diff --git a/core/schema.rs b/core/schema.rs index 0bf9f464c..2bfe9dfc8 100644 --- a/core/schema.rs +++ b/core/schema.rs @@ -1553,6 +1553,12 @@ pub fn create_table(tbl_name: &str, body: &CreateTableBody, root_page: i64) -> R foreign_keys.push(Arc::new(fk)); } } + + // Due to a bug in SQLite, this check is needed to maintain backwards compatibility with rowid alias + // SQLite docs: https://sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key + // Issue: https://github.com/tursodatabase/turso/issues/3665 + let mut primary_key_desc_columns_constraint = false; + for ast::ColumnDefinition { col_name, col_type, @@ -1690,6 +1696,9 @@ pub fn create_table(tbl_name: &str, body: &CreateTableBody, root_page: i64) -> R if primary_key { primary_key_columns.push((name.clone(), order)); + if order == SortOrder::Desc { + primary_key_desc_columns_constraint = true; + } } else if primary_key_columns .iter() .any(|(col_name, _)| col_name == &name) @@ -1702,7 +1711,9 @@ pub fn create_table(tbl_name: &str, body: &CreateTableBody, root_page: i64) -> R ty, ty_str, primary_key, - is_rowid_alias: typename_exactly_integer && primary_key, + is_rowid_alias: typename_exactly_integer + && primary_key + && !primary_key_desc_columns_constraint, notnull, default, unique, diff --git a/testing/insert.test b/testing/insert.test index 4419bcafb..05c03329f 100755 --- a/testing/insert.test +++ b/testing/insert.test @@ -678,4 +678,20 @@ do_execsql_test_on_specific_db {:memory:} insert-rowid-select-rowid-success { INSERT INTO t(a) SELECT rowid FROM t; SELECT * FROM t; } {2 -1} \ No newline at end of file +1} + + +# Due to a bug in SQLite, this check is needed to maintain backwards compatibility with rowid alias +# SQLite docs: https://sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key +# Issue: https://github.com/tursodatabase/turso/issues/3665 +do_execsql_test_on_specific_db {:memory:} insert-rowid-backwards-compability { + CREATE TABLE t(a INTEGER PRIMARY KEY DESC); + INSERT INTO t(a) VALUES (123); + SELECT rowid, * FROM t; +} {1|123} + +do_execsql_test_on_specific_db {:memory:} insert-rowid-backwards-compability-2 { + CREATE TABLE t(a INTEGER, PRIMARY KEY (a DESC)); + INSERT INTO t(a) VALUES (123); + SELECT rowid, * FROM t; +} {123|123} \ No newline at end of file