Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite allows insert of string data into datetime column

Tags:

sql

sqlite

Table:

CREATE TABLE logaction
(
  actype varchar(8) not null,
  actime DATETIME not null,
  devid int not null
);

SQL:

insert into logaction values ('TEST', '2013-08-22', 1);
insert into logaction values ('TEST', '2013-08-22 09:45:30', 1);
insert into logaction values ('TEST', 'xyz', 2); // shouldn't this fail?

The last record does make it into the table regardless of the non-datetime value for the actime column. Why and how can I enforce that only good data go in?

Here is a SQL Fiddle.

like image 584
amphibient Avatar asked Dec 12 '22 12:12

amphibient


2 Answers

Well, there's just no DATETIME type in Sqlite...

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 ("YYYY-MM-DD HH:MM:SS.SSS").
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. 

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

see doc

You could have created your table like that, it wouldn't have changed anything.

CREATE TABLE logaction
(
  actype varchar(8) not null,
  actime NonexistingType not null,
  devid int not null
);
like image 129
Raphaël Althaus Avatar answered Jan 01 '23 05:01

Raphaël Althaus


Unfortunately, not really in sqlite - it doesn't have a datetime type - see section 1.2 in here

like image 33
Oliver Matthews Avatar answered Jan 01 '23 06:01

Oliver Matthews