Skip to content

Commit 9ff56bd

Browse files
committed
add check for columns declared as NOT NULL without a DEFAULT value
1 parent 63faf9c commit 9ff56bd

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/dbutils.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,15 @@ bool dbutils_table_sanity_check (sqlite3 *db, sqlite3_context *context, const ch
416416
}
417417
}
418418

419+
// check for columns declared as NOT NULL without a DEFAULT value.
420+
// Otherwise, col_merge_stmt would fail if changes to other columns are inserted first.
421+
sql = sqlite3_snprintf((int)blen, buffer, "SELECT count(*) FROM pragma_table_info('%w') WHERE pk=0 AND \"notnull\"=1 AND \"dflt_value\" IS NULL;", name);
422+
sqlite3_int64 count3 = dbutils_int_select(db, sql);
423+
if (count3 > 0) {
424+
dbutils_context_result_error(context, "All non-primary key columns declared as NOT NULL must have a DEFAULT value. (table %s)", name);
425+
return false;
426+
}
427+
419428
return true;
420429
}
421430

test/unit.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1674,7 +1674,9 @@ bool do_test_dbutils (void) {
16741674
const char *sql = "CREATE TABLE IF NOT EXISTS foo (name TEXT PRIMARY KEY NOT NULL, age INTEGER, note TEXT, stamp TEXT DEFAULT CURRENT_TIME);"
16751675
"CREATE TABLE IF NOT EXISTS bar (name TEXT PRIMARY KEY NOT NULL, age INTEGER, note TEXT, stamp TEXT DEFAULT CURRENT_TIME);"
16761676
"CREATE TABLE IF NOT EXISTS rowid_table (name TEXT, age INTEGER);"
1677-
"CREATE TABLE IF NOT EXISTS nonnull_prikey_table (name TEXT PRIMARY KEY, age INTEGER);";
1677+
"CREATE TABLE IF NOT EXISTS nonnull_prikey_table (name TEXT PRIMARY KEY, age INTEGER);"
1678+
"CREATE TABLE IF NOT EXISTS nonnull_nodefault_table (name TEXT PRIMARY KEY NOT NULL, stamp TEXT NOT NULL);"
1679+
"CREATE TABLE IF NOT EXISTS nonnull_default_table (name TEXT PRIMARY KEY NOT NULL, stamp TEXT NOT NULL DEFAULT CURRENT_TIME);";
16781680

16791681
rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
16801682
if (rc != SQLITE_OK) goto finalize;
@@ -1731,6 +1733,10 @@ bool do_test_dbutils (void) {
17311733
if (b == true) goto finalize;
17321734
b = dbutils_table_sanity_check(db, NULL, "nonnull_prikey_table");
17331735
if (b == true) goto finalize;
1736+
b = dbutils_table_sanity_check(db, NULL, "nonnull_nodefault_table");
1737+
if (b == true) goto finalize;
1738+
b = dbutils_table_sanity_check(db, NULL, "nonnull_default_table");
1739+
if (b == false) goto finalize;
17341740

17351741
// create huge dummy_table table
17361742
rc = sqlite3_exec(db, build_huge_table(), NULL, NULL, NULL);

0 commit comments

Comments
 (0)