SQLite User Forum

Change access to readonly
Login

Change access to readonly

(1) By Baruch (baruch) on 2022-07-20 12:21:33 [link] [source]

Is it possible to change an open db connection to be readonly? I am creating a ":memory:" database, and need to make it readonly after adding some initial data to it. Is this possible?

(2.1) By Ryan Smith (cuz) on 2022-07-20 13:06:48 edited from 2.0 in reply to 1 [link] [source]

The simple answer is NO... but,

A DB created using :memory: exists necessarily only in the scope of your own connection to it (or with shared-memory connections you must control), why on Earth would you need to police yourself? Just do not write to it again.

EDIT: If you wish to curtail DB writes regardless, the best bet is to use the Authorizer API. You can set that up so that it allows all queries or just specific types, allowing you to limit querying based on your own rules.

(7) By Baruch (baruch) on 2022-07-24 20:28:56 in reply to 2.1 [link] [source]

As for why I would want this - my application uses a database that is readonly. For unit testing, I want to use in-memory databases setup in various states. I want to set it to be readonly to catch any attempts to write to it (which are errors)

(3) By David Raymond (dvdraymond) on 2022-07-20 13:04:55 in reply to 1 [link] [source]

Not a true read only, but there's always the option for the query_only pragma

PRAGMA query_only;

PRAGMA query_only = boolean;

The query_only pragma prevents data changes on database files when enabled. When this pragma is enabled, any attempt to CREATE, DELETE, DROP, INSERT, or UPDATE will result in an SQLITE_READONLY error. However, the database is not truly read-only. You can still run a checkpoint or a COMMIT and the return value of the sqlite3_db_readonly() routine is not affected.

(5) By Simon Slavin (slavin) on 2022-07-20 16:32:54 in reply to 3 [link] [source]

Is this not the right answer ? Seems to be exactly what the OP wanted.

(6) By Baruch (baruch) on 2022-07-24 20:22:40 in reply to 3 [source]

Thank you. This is good enough for my needs

(4) By Stephan Beal (stephan) on 2022-07-20 13:10:34 in reply to 1 [link] [source]

Is it possible to change an open db connection to be readonly?

Another option is to install an "authorizer" function which denies all non-read-only access:

An example authorizer from the fossil source tree:

https://fossil-scm.org/home/file?name=src/db.c&ln=485-531