Swift-Kuery icon indicating copy to clipboard operation
Swift-Kuery copied to clipboard

Using "now()" in an insert?

Open NocturnalSolutions opened this issue 6 years ago • 3 comments

I'm basically trying to do something like

    let i = Insert(into: postsTable,
                   columns: [postsTable.id, postsTable.date, postsTable.title, postsTable.body],
                   values: [uuid, now(), titleText, bodyText])
    db.execute(query: i) { queryResult in //…

I also tried

    let i = Insert(into: postsTable,
                   columns: [postsTable.id, postsTable.date, postsTable.title, postsTable.body],
                   values: [uuid, Parameter(), titleText, bodyText])
    db.execute(query: i, parameters: [now()]) { queryResult in // …

Neither of these work as expected. The former builds a query like INSERT INTO posts (id, date, title, body) VALUES ('1E417162-256C-40E0-8FDF-87A89A285B33', ScalarColumnExpression(alias: nil, function: SwiftKuery.ScalarColumnExpression.ScalarFunction.now), 'asdf', 'asdf') - so the expression is being flatly converted to a string rather than having its .build(queryBuilder: QueryBuilder) method called. The latter ultimately fails because it appears the parameter binding code is expecting simple variable types (String, Int, etc).

Is there a correct way to do this? If so, what is it? If not, can I hack one together and make a PR?

NocturnalSolutions avatar Jan 04 '18 23:01 NocturnalSolutions

From what I can tell from a somewhat naive look through the code now() and the corresponding ScalarColumnExpression it creates are intended for use as filters in queries.

I'm not sure on how to specify that you would like to use the database/SQL NOW() on an insert, however (as you are probably aware), if you don't mind using the date-time according to your Swift program, then I believe you can pass a Date object created with Date() which should represent the current time/date.

I will do some more experiments to see if there is a reasonable way to make this work with the current implementation.

tunniclm avatar Jan 05 '18 13:01 tunniclm

Yeah, this is pretty much the conclusion I had come to as well.

The problem with just formatting a date on the Swift side is that theoretically different underlying RDBMSes could require different date formats. Not so much a worry with my project since I'm only using SQLite anyway, but it's the principle of the thing, ya know?

NocturnalSolutions avatar Jan 05 '18 17:01 NocturnalSolutions

It looks like the queryBuilder supports substitutions for NOW() so I don't see why we couldn't implement support for using NOW() outside filters. I am going to mark this as a potential enhancement and leave it as an item for future consideration.

kilnerm avatar Sep 03 '18 12:09 kilnerm