storesafe / cordova-sqlite-storage

A Cordova/PhoneGap plugin to open and use sqlite databases on Android, iOS and Windows with HTML5/Web SQL API
Other
2.15k stars 715 forks source link

Test & document date/time handling along with pitfalls #546

Open brodycj opened 8 years ago

brodycj commented 8 years ago

From discussion in https://groups.google.com/forum/#!topic/phonegap/za7z51_fKRw I suspect date/time handling with JavaScript and SQLite databases can be a bit tricky. (I am not sure about IndexedDB but suspect similar issues with LocalStorage.) I can think of the following ways to store date/time in a SQLite database:

If someone just uses something like Date.now() in a SQL parameter list, its toString() function is called and the plugin would simply store the string value. (I am 99.9% sure that this would be the case for Web SQL as well.) I suspect that it is possible to use the valueOf() member function to get the numeric value.

It can also be tricky to figure out how to use date comparisons when selecting data.

From https://groups.google.com/d/msg/phonegap/za7z51_fKRw/gMCypOCwBQAJ:

There's actually two tricks to solving this.

First, if you declare your field as a datetime (which is nothing more than an integer) you will NEVER get this to work. Not under iOS 9.x, not under Android and not on Chrome 52.x (64-bit) on Windows 10.

What you have to do is store your date as a TEXT field and store your datetime as a string like this:

tx.executeSql("CREATE TABLE IF NOT EXISTS mytable (msg_id UNSIGNED INT PRIMARY KEY ASC, msg_when TEXT, msg_read INTEGER, title TEXT, msg_text TEXT)",

Next, you have to wrap your comparison in (parenthesis) so that sqlite treats it as a formula and does the math conversions for you... like this:

tx.executeSql(DELETE FROM mytable WHERE (msg_when <= datetime('now', '-4 days'))",

Notice the parenthesis before the (msg_when column and after the closing parenthesis on the datetime)) function.

(Note that he gave the JavaScript samples with the callback functions cut off.)

I personally think it should be possible and perhaps a little more efficient to use numeric "DATETIME" fields but may well be mistaken here. Unfortunately I cannot promise when I will have a chance to test this.

brodycj commented 8 years ago

From further discussion in https://groups.google.com/forum/#!topic/phonegap/za7z51_fKRw I think the following SQLite date/time pitfalls can be identified:

Additional SQLite pitfall(s) in general:

I can identify the following TODOs:

In general I would really like to see these items clearly documented by the SQLite project.

P.S. I found http://stackoverflow.com/questions/26978342/how-to-store-datetime-in-sqlite through reference at: http://stackoverflow.com/questions/17227110/what-is-the-best-way-to-save-datetime-type-in-sqlite

brodycj commented 7 years ago

Also linking to #415 with another pitfall: no explicit handling of JavaScript Date object