Skip to content

Commit 692696f

Browse files
committed
implement SQL_SCHEMA_VERSION with app_schema_version table and event trigger
1 parent bcfff0c commit 692696f

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/postgresql/sql_postgresql.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,20 @@ const char * const SQL_SETTINGS_LOAD_TABLE =
4343
"SELECT lower(tbl_name), lower(col_name), key, value FROM cloudsync_table_settings ORDER BY tbl_name;";
4444

4545
const char * const SQL_CREATE_SETTINGS_TABLE =
46-
"CREATE TABLE IF NOT EXISTS cloudsync_settings (key TEXT PRIMARY KEY NOT NULL, value TEXT);";
46+
"CREATE TABLE IF NOT EXISTS cloudsync_settings (key TEXT PRIMARY KEY NOT NULL, value TEXT);"
47+
"CREATE TABLE IF NOT EXISTS app_schema_version ("
48+
"version BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY"
49+
");"
50+
"CREATE OR REPLACE FUNCTION bump_app_schema_version() "
51+
"RETURNS event_trigger AS $$ "
52+
"BEGIN "
53+
"INSERT INTO app_schema_version DEFAULT VALUES; "
54+
"END;"
55+
"$$ LANGUAGE plpgsql;"
56+
"DROP EVENT TRIGGER IF EXISTS app_schema_change;"
57+
"CREATE EVENT TRIGGER app_schema_change "
58+
"ON ddl_command_end "
59+
"EXECUTE FUNCTION bump_app_schema_version();";
4760

4861
// format strings (snprintf) are also static SQL templates
4962
const char * const SQL_INSERT_SETTINGS_STR_FORMAT =
@@ -150,7 +163,7 @@ const char * const SQL_DATA_VERSION =
150163
"SELECT txid_snapshot_xmin(txid_current_snapshot());"; // was "PRAGMA data_version"
151164

152165
const char * const SQL_SCHEMA_VERSION =
153-
"SELECT 1;"; // TODO: PostgreSQL equivalent of sqlite "PRAGMA schema_version", "SELECT current_schema();" is not equivalent
166+
"SELECT COALESCE(max(version), 0) FROM app_schema_version;"; // was "PRAGMA schema_version"
154167

155168
const char * const SQL_SITEID_GETSET_ROWID_BY_SITEID =
156169
"INSERT INTO cloudsync_site_id (site_id) VALUES ($1) "

0 commit comments

Comments
 (0)