Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only fields in SQLite3 database table?

I'm a beginner when it comes to databases and have been reading through the SQLite3 documentation. However, I can't find the answer to the following:

Is it possible to create a SQLite3 database table that has some read-only fields (i.e. not the whole of the table is read-only)?. I know I can stop people writing to the fields via some extra code, but I was wondering if can define a constraint or something similar.

Thanks!

like image 471
Umbungu Avatar asked Sep 06 '25 03:09

Umbungu


2 Answers

You can create a trigger to prevent updates of specific columns:

CREATE TRIGGER ro_columns
BEFORE UPDATE OF col1, col2 ON mytable
BEGIN
    SELECT raise(abort, 'don''t do this!');
END
like image 104
CL. Avatar answered Sep 07 '25 19:09

CL.


Sadly, constraints cannot be added after table creation in SQLite;

It is not possible to rename a column, remove a column, or add or remove constraints from a table.

In other words, no, you cannot make a column read only using a constraint, since creating the table with the (CHECK) constraint would make it impossible to add the read only values to the table in the first place.

like image 41
Joachim Isaksson Avatar answered Sep 07 '25 19:09

Joachim Isaksson