I have an iOS app that takes use of SQLite. I use FireFox and the plugin SQLite Manager for managing the database.
Now I have a table like this:
CREATE TABLE "someTable" ("id" INTEGER NOT NULL , "timeOfEvent" DATETIME NOT NULL)
I am however able to input practically any value I want into the DateTime column like so:
INSERT INTO sometable (id, timeOfEvent) VALUES (1,'2012-99-99')
INSERT INTO sometable (id, timeOfEvent) VALUES (2,'yyyy-mm-dd')
...etc
Why is this possible?
As per the documentation: SQLite- Data Types
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Thus SQLite relies on methods to convert the values. It doesn't have it's own data type to restrict date/time type.
SQLite is dynamic. From SQLite Query Language - CREATE TABLE
Unlike most SQL databases, SQLite does not restrict the type of data that may be inserted into a column based on the columns declared type. Instead, SQLite uses dynamic typing. The declared type of a column is used to determine the affinity of the column only.
Related
I have two tables both of which have a timestamp field [TIMESTAMP_TZ] and when I perform a join based on this timestamp field the plan in snowflake DB shows an auto conversion on these timestamps into LTZ. Ex
(TO_TIMESTAMP_LTZ(CAG.LOAD_DATE_UTC) = TO_TIMESTAMP_LTZ(PIT.CSAT_AGREEMENT_LDTS))
Any reason why this is happening?
TIMESTAMP_TZ means your timestamp is linked to a time zone and TIMESTAMP_LTZ is your local timezone. Probably the timezones of your two timestamps are different and thus Snowflake converts them automatically to your local timezone to match them correctly.
I am building a rails app, where the user picks up a date from a date picker and a time from the time picker. Both the date and time have been formatted using moment js to show the date and time in the following way:
moment().format('LL'); //January 23,2017
moment().format('LTS'); //1:17:54 PM
I read this answer with guidelines about selection of a proper column type.
Is there documentation for the Rails column types?
Ideally, I should be using :date, :time or :timestamp for this. But since the dates are formatted, should I be using :string instead?
Which would be the correct and appropriate column type to use in this situation?
If you want to store a time reference in your database you should use one of the types the database offers you. I'll explain this using MySQL (which is the one I have used the most) but the explanation should be similar in other database servers.
If you use a timestamp column you will be using just 4 bytes of storage, which is always a good new since it makes smaller indexes, uses less memory in temporal tables during the internal database operations and so on. However, timestamp has a smaller range than datetime so you will only be able to store values from year 1970 up to year 2038 more or less
If you use datetime you will be able to store a wider range (from year 1001 to year 9999) with the same precision (second). The bad consequence is that a higher range needs more memory, making it a bit slower.
There are some other differences between these two column types that don't fit in this answer, but you should keep an eye on before deciding.
If you use varchar, which is the default column type for text attributes in Ruby on Rails, you will be forced to convert from text to datetime and vice-versa every time you need to use that field. In addition, ordering or filtering on that column will be very inefficient because the database will need to convert all strings into dates before filtering or sorting, making it impossible to use indexes on that column.
If you need sub-second precision, you can use bigint to meet your requirements, as MySQL does not provide a date specific type for this purpose
In general, I recommend using timestamp if your application requirements fit the timestamp limitation. Otherwise, use datetime, but I strongly discourage you to use varchar for this purpose.
EDIT: Formatting
The way you store dates in database is completely different from the way you display it to the user. You can create a DateTime object using DateTime.new(year, month, day, hour, minute, second) and assign that object to your model. By the time you save it into database, ActiveRecord will be in charge of converting the DateTime object into the appropiate database format.
In order to display a value that is already stored in database in a specific format (in a view, API response, etc.) you can hava a look at other posts like this one.
You can have a timestamp column in your database, and then parse the request to a ruby datetime object like this:
d = Time.parse(params[:date])
t = Time.new(params[:time])
dt = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec, t.zone)
#now simply use dt to your datetime column
On Postgres you can save a ruby DateTime object straight into a postgres timestamp field, e.g
User.first.update_attribute('updated_at', dt )
Another option is to concatenate your date and time strings into one and then u can do a one-liner:
User.last.update_attribute('created_at', Time.parse('January 23,2017 1:17:54 PM'))
I'm pretty sure this will work on MySQL datetime or timestamp as well.
Credit to david grayson Ruby: combine Date and Time objects into a DateTime
Change this date format which is in sqlite db 12/10/11 to 12-10-11 (mm-dd-yy) I am unable to do so .I am a noob in sqlite and have to parse this value SELECT strftime('%d-%m-%Y',Date) from report but I am getting null as sqlite db excepts value in mm-dd-yy so How do I convert format 12/10/11 to 12-10-11 (mm-dd-yy) .Thanks in advance .Really appreciate the help.
The short answer:
If you have a text string stored as "12/10/11" that you want reported as "12-10-11", you should use the replace(X,Y,Z) function, to replace occurrences of Y in X with Z. Thus:
SELECT replace('12/24/11','/','-');
will return:
12-10-11
The long answer:
First, dates do not actually exist as a proper datatype in SQLite. They're stored as either TEXT, REAL, or INTEGER values. See date and time datatype in SQLite. So it depends upon how your date was stored in the database.
Second, you seem to be implying that you stored the date in a "mm/dd/yy" format. That's not a valid/useful TEXT format to be storing date/time values (as the date cannot be sorted, cannot used in "greater than" and "less than" operations, cannot be used in SQLite date functions, etc.). You really want to store datetime values in one of the formats listed in the "Time strings" section of the date and time functions document.
So, generally you should store your date/time values in one of those formats, use NSDateFormatter to convert that to a NSDate when you retrieve it from the database. And when you want to display the date value in your app, use whatever format you want for output.
But, if you don't care that the dates are stored as text strings and are not effectively usable as dates in SQLite, then just treat it as a plain old TEXT string and use TEXT functions, such as replace(X,Y,Z) to replace occurrences of "/" with "-", as outlined above.
I use rails for version 2.3.5, when i update or save a record, the created_at and updated_at fields can be filled in automatically in the format like '2011-05-17 23:54:53', however i want to store the second int value of time to these fields automatically, what should i do?
Thank you in advance.
Within your database engine the storage method for dates, times, datetimes, and timestamps can vary but the presentation through the SQL layer is often similar. You can transform the request from integer to time if you like using some of the built in functions.
For example, in MySQL you can use the UNIX_TIMESTAMP function to return integer times:
SELECT UNIX_TIMESTAMP(created_at) FROM users
You can also insert integers and convert to times:
UPDATE users SET updated_at=FROM_UNIXTIME(1111885200) WHERE id=1
This sort of thing is not supported natively within ActiveRecord, but you can do conversions using the DateTime class:
User.first.created_at.to_i
You can also convert from an integer to a DateTime:
user.updated_at = Time.at(1111885200)
In my database migration file I inserted the line:
t.timestamps
Two columns, as I expected, were created: "updated_at" and "created_at". However, their type is "datetime" and not "timestamp".
I am using MySQL and the "timestamp" type, as I understand, is designed exactly for such cases, as it uses less space and is independent of timezone.
So, is there any reason, why Rails 3 uses "datetime" and not "timestamp"? Should I try to fix that? If yes, is there any way to do this besides not using "t.timestamps" and defining "updated_at" and "created_at" columns separately every time for each new table?
From memory, the mysql timestamp column type behaves similar to updated_at in that it is updated with the current time whenever the record is updated.
While this is useful for the updated_at column, this is not the desired behaviour for created_at.
In addition, Rails handles the timezone as specified in your app's settings (should would normally be set to UTC), so using mysql's time may be inconsistent with other datetime records.
timestamp columns have a limited range which begins in 1970 and ends in 2038. You can google "Unix Millennium Bug" for more information, but it's basically because unix timestamps are stored as a 32-bit signed integer. A timestamp is expressed in seconds since Jan. 1, 1970, and the number wraps on itself in 2038. For this reason, I typically use datetime even when timestamp seems like an easier solution, especially to represent historical or forecasted data further off into the past or future.