Database becomes malformed if set key in transaction


#1

Hi.

I caught the issue on Mac that a database sometimes becomes malformed. After spending hours of debugging to understand the problem I noticed that key is set after the transaction is initiated to perform table updates. After moving sqlite3_key after begin exclusive transaction the issue is gone.

Could this really be the reason?

Objective-C FMDB wrapper around SQLite is used.

Works fine.

[dbQueue inDatabase:^(FMDatabase *db) {
	[db setKeySafe:[DBManager getPragmaKey]];

	[db beginTransaction];
	...
];

The reason is that a database becomes malformed.

[dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
	[db setKeySafe:[DBManager getPragmaKey]];
	...
];

#2

Hi @Vladislav,

You guessed it exactly:

SQLCipher uses just-in-time key derivation at the point it is first needed for an operation. This means that the key (and any options) must be set before the first operation on the database.

That’s the same whether you use sqlite3_key or PRAGMA key, and it applies to BEGIN as well as other calls like UPDATE, INSERT, etc. I should also note that ATTACH operations (with or without a key parameter) cannot be executed in a transaction either.


#3

@wgray thanks for your immediate reply. :slight_smile: