Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid inserting the wrong data type in SQLite tables?

SQLite has this "feature" whereas even when you create a column of type INTEGER or REAL, it allows you to insert a string into it, even a string without numbers in it, like "the quick fox jumped over the lazy dog".

How do you prevent this kind of insertions to happen in your projects?

I mean, when my code has an error that leads to that kind of insertions or updates, I want the program to give an error, so I can debug it, not simply insert garbage in my database silently.

like image 379
Tulains Córdova Avatar asked Apr 06 '15 18:04

Tulains Córdova


People also ask

When using SQLite what datatypes can you assign?

SQLite only has four primitive data types: INTEGER, REAL, TEXT, and BLOB.

Does SQLite apply strict types?

For this latter group, SQLite supports a strict typing mode, as of version 3.37. 0 (2021-11-27), that is enabled separately for each table.

What does insert or ignore do SQLite?

insert or ignore ... will insert the row(s) and ignore rows which violation any constraint (other than foreign key constraints).


1 Answers

You can implement this using the CHECK constraint (see previous answer here). This would look like

   CREATE TABLE T (
       N   INTEGER CHECK(TYPEOF(N) = 'integer'),
       Str TEXT CHECK(TYPEOF(Str) = 'text'),
       Dt  DATETIME CHECK(JULIANDAY(Dt) IS NOT NULL)
   );
like image 90
Seth Avatar answered Oct 14 '22 01:10

Seth