ISSUE DESCRIPTION alter col leaves sqlitesequence table behind note that i'm unsure of…
- User
ISSUE DESCRIPTION
alter col leaves sqlite_sequence table behind note that i'm unsure of alter column rules, i was not able to find any docs or rules around this, but my expectation is when we change a autoincrement col to plain text there shouldn't be a stale sqlite_sequence.
sqlturso> CREATE TABLE t(a INTEGER PRIMARY KEY AUTOINCREMENT, b TEXT); INSERT INTO t(b) VALUES('x'),('y'); ALTER TABLE t ALTER COLUMN a TO a2 TEXT; SELECT * FROM sqlite_sequence; SELECT sql FROM sqlite_schema WHERE name='t'; ┌──────┬─────┐ │ name │ seq │ ├──────┼─────┤ │ t │ 2 │ └──────┴─────┘ ┌──────────────────────────────────┐ │ sql │ ├──────────────────────────────────┤ │ CREATE TABLE t (a2 TEXT, b TEXT) │ └──────────────────────────────────┘ turso> select * from sqlite_schema; ┌───────┬─────────────────┬─────────────────┬──────────┬────────────────────────────────────────┐ │ type │ name │ tbl_name │ rootpage │ sql │ ├───────┼─────────────────┼─────────────────┼──────────┼────────────────────────────────────────┤ │ table │ sqlite_sequence │ sqlite_sequence │ 2 │ CREATE TABLE sqlite_sequence(name,seq) │ ├───────┼─────────────────┼─────────────────┼──────────┼────────────────────────────────────────┤ │ table │ t │ t │ 3 │ CREATE TABLE t (a2 TEXT, b TEXT) │ └───────┴─────────────────┴─────────────────┴──────────┴────────────────────────────────────────┘Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository using command. Additionally, you can use and to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted. Assistant
Let me start by exploring the repository structure to understand what we're working with.
Assistant
This is a Rust repository (Turso SQL). Let me explore the core directory which should have the main logic for the SQL engine.
Assistant
Let me search for the AlterColumn logic specifically:
Assistant
Now let me find the
AlterColumninstruction handler:Assistant
Let me look at how sqlite_sequence is created/managed in the codebase:
Assistant
Let me look at how sqlite_sequence is created when AUTOINCREMENT is used:
Assistant
Let me look at the schema.rs around the area where the sqlite_sequence table is created to understand the schema:
Assistant
Let me now look at the context around
op_alter_column:Assistant
Let me search for what code creates the sqlite_sequence and when it's deleted:
Assistant
Let me first build the project and reproduce the issue:
Assistant
Let me check whether the project has been built and try to reproduce the issue:
Assistant
Let me check what SQLite does in this case to understand the correct behavior:
Assistant
Let me search for where the sqlite_sequence entry is cleaned up during DROP TABLE:
Assistant
Let me look at how the table being auto-increment is determined:
Assistant
Let me also check how the column constraint "PRIMARY KEY" and "AUTOINCREMENT" are stored:
Assistant
Let me search for where the AUTOINCREMENT column constraint is set:
Assistant
Now I need to understand the existing logic in
op_alter_columnbetter and figure out where to add the sqlite_sequence cleanup. Looking at the code in core/vdbe/execute.rs around line 12924, whenop_alter_columnis called, it updates the column in the schema, but doesn't update thebtree.has_autoincrementflag.Let me also look at how btree.has_autoincrement is set when altering:
Assistant
Let me look at the Column struct for the AUTOINCREMENT related fields:
Assistant
Now let me understand the relation between
has_autoincrementon the BTreeTable and the column definitions. Looking at the schema.rs:has_autoincrementis a field on the BTreeTable struct.- It's used to determine if the SQL should include "AUTOINCREMENT" in
to_sql().
The has_autoincrement flag is set based on the column constraints during CREATE TABLE. But it seems like it's not tied to a specific column; rather, it's just a flag on the table saying "this table has at least one autoincrement column".
Wait, but the column constraints themselves don't store whether they have AUTOINCREMENT. Looking at the code in alter.rs line 12924:
- It modifies
btree.columns_mut()[*column_index] = new_column.clone(); - The new_column is constructed from the column definition, which is parsed via
Column::try_from(&definition)?.
Let me check Column::try_from:
Assistant
Let me check the parser for AUTOINCREMENT:
Assistant
So
auto_incrementis a flag on thePrimaryKeyconstraint. Since ALTER COLUMN can't add PRIMARY KEY, AUTOINCREMENT can't be added either.But wait, looking at parse_column_constraint (looking for AUTOINCREMENT without PRIMARY KEY):
Assistant
Let me look at how the alter column accepts the new type:
Assistant
Let me check the Insn::Delete implementation:
Assistant
OK, sqlite_sequence table uses Insn::Insert too. Let me check how Insn::Delete works in MVCC mode and non-MVCC mode:
Looking at
emit_rename_sqlite_sequence_entry:rust// In MVCC mode, we need to delete before insert to properly // end the old version (Hekaton-style UPDATE = DELETE + INSERT) if database_uses_mvcc(connection, database_id) { program.emit_insn(Insn::Delete { cursor_id: seq_cursor_id, table_name: crate::schema::SQLITE_SEQUENCE_TABLE_NAME.to_string(), is_part_of_update: true, }); } program.emit_insn(Insn::Insert { cursor: seq_cursor_id, ... });So in MVCC mode, delete-then-insert is needed. Otherwise, just insert (which acts as update for the rowid-keyed record).
For our case, we need to actually delete the entry. Let me look at the Insn::Delete code to understand:
Assistant
Now let me look at how the alter column handles its MVCC mode operation:
Assistant
Let me look at how the Column struct relates to has_autoincrement:
Assistant
OK so the column has
primary_keyandis_rowid_aliasflags. AUTOINCREMENT is not stored in the column - only at the table level.Now let me think about the design more concretely. Let me look at the alter.rs code more carefully around the column change and understand where to insert the logic:
Assistant
Let me check how SQLite handles DROP TABLE with respect to sqlite_sequence:
Assistant
Let me check the cursor_loop function to understand how to iterate and delete:
Assistant
Now let me look at the structure of the existing alter.rs code in more detail, focusing on the alter column operation:
Assistant
Now let me design and implement the fix. The plan is:
-
In
op_alter_column(execute.rs): When the altered column was the AUTOINCREMENT column and is no longer rowid-alias, setbtree.has_autoincrement = false. -
In the alter.rs translator: When the above condition is detected at translation time, emit bytecode to delete the sqlite_sequence row for this table.
Let me start with the implementation:
-
Assistant
Now let me look at the end of
emit_rename_sqlite_sequence_entryto understand its full structure:Assistant
Let me look for examples of Delete within cursor_loop:
Assistant
Let me look at where deleting rows happens in a loop:
Assistant
Let me look at the existing code that uses DELETE in a loop, particularly in build.rs or other related code:
Assistant
Let me check the index drop code which uses DELETE in a loop pattern:
Assistant
Let me look at the btree delete + next implementation:
Assistant
Let me now look at where ALTER COLUMN logic is in the alter.rs file to find a good place for the new code:
Assistant
Let me look at exactly where to add the sqlite_sequence delete logic. Let me look at the surrounding code:
Assistant
Now I have a good understanding. Let me implement the fix. First, let me add a helper function for deleting the sqlite_sequence entry. I'll add it after
emit_rename_sqlite_sequence_entry:Assistant
Now let me look at the whole structure more carefully to determine where to make the changes:
Assistant
Now I'll implement the fix. First, let me add the
emit_delete_sqlite_sequence_entry_for_tablefunction:Assistant
Now I have all the context I need. Let me start implementing the fix.
First, add the new helper function
emit_delete_sqlite_sequence_entry_for_tableafteremit_rename_sqlite_sequence_entry:Assistant
I see some duplication. Let me clean it up:
Assistant
Now I need to call this function from the alter.rs translator. Let me find where to add the call:
Assistant
Now let me look at the existing op_alter_column more carefully:
Assistant
Now let me modify execute.rs to update
has_autoincrement:Assistant
Let me look at the structure of the AlterColumn block to find a good place for the call:
Assistant
Let me modify the code to compute the flag and call our function. First, let me understand the code structure better:
Assistant
Let me modify alter.rs to detect the case where the alter will lose autoincrement:
Assistant
Now let me find a good place to insert the call. Let me find the
program.emit_insn(Insn::SetCookiefordb: database_id:Assistant
Now let me add the call to delete the sqlite_sequence entry after the schema updates but before the AlterColumn instruction:
Assistant
Let me check that
normalized_table_nameis in scope:Assistant
normalized_table_nameis not defined. I need to add it. Let me check what's available:Assistant
Looking at the code,
table_nameisqualified_name.name.as_str()(un-normalized). I need to use a normalized version for the comparison with sqlite_sequence.Assistant
Let me update the code to use the proper normalized table name:
Assistant
Now let me also clean up the execute.rs change. The
let _ = lost_autoincrement;is unused. Let me check if it compiles:Assistant
Build succeeded. Now let me test the fix:
Assistant
The fix works. Let me test more scenarios:
Assistant
Wait, Test 2 shows the issue isn't fully fixed - t2 still appears in sqlite_sequence after alter to INTEGER. Let me investigate:
Assistant
Wait, looking again - "After alter" returned no rows. Let me re-run the more complex tests:
Assistant
Let me debug the issue more. The sequence shows it incremented to 3, which means the INSERT is still treating the table as autoincrement:
Assistant
After alter, sqlite_sequence is correctly empty. So the delete logic works. But after INSERT, the row reappears. Let me check the INSERT path:
Assistant
Let me check where the INSERT logic checks for autoincrement:
Assistant
So the
init_autoincrementreads from sqlite_sequence and sets up the autoincrement state. If the table is still treated as having autoincrement (i.e.,ctx.table.has_autoincrementis true), then this will run. But we just removed the row from sqlite_sequence, so this might do strange things.Let me look at line 322 in insert.rs to see what
ensure_sequence_initializeddoes:Assistant
Let me also verify that the schema update (in op_alter_column) actually changes has_autoincrement. Let me check more code:
Assistant
I see the bug!
was_rowid_aliasis read AFTER the column has been replaced with new_column. Let me fix this:Assistant
Now let me also update the second block to use the captured value:
Assistant
Now after the alter, sqlite_sequence is empty and INSERT works. Let me also verify this works with the original issue and check the data preservation:
Assistant
Let me test more edge cases:
Assistant
Looking at the test outputs more carefully:
- Test 2 (alter non-AUTOINCREMENT): t2 is preserved correctly. ✓
- Test 3 (multiple AUTOINCREMENT): t3 removed, t4 preserved. ✓
But Test 1 (rename only) doesn't show the expected output. Let me verify:
Assistant
Hmm, the schema shows "a1" without a type, and ALTER COLUMN rename only behaves incorrectly here.
Actually wait, looking at this more carefully - the schema is
CREATE TABLE t1 (a1, b TEXT). This means after renaming to "a1", the column has no type info. This is wrong.But looking at the existing
to_sql()code:rustif self.has_autoincrement && column.is_rowid_alias() { sql.push_str(" AUTOINCREMENT"); }It only adds AUTOINCREMENT when has_autoincrement && column.is_rowid_alias(). So if the column has been renamed but is still rowid_alias, the AUTOINCREMENT keyword should be there.
Let me look at the to_sql() more thoroughly:
Assistant
Let me check this rename-only behavior on master (without my changes):
Assistant
Master output shows the same missing type. This is an existing issue, not related to my changes. Let me restore my changes:
Assistant
Hmm, the rename-only test is now exiting with code 0 but producing no output. Let me try a different approach to ensure the input is being read correctly.
Assistant
Let me check the CLI behavior:
Assistant
Hmm, it appears that the ALTER TABLE statement is causing some failure but no error output. Let me try different approaches.
Assistant
The CLI exits with code 0 but produces no output. This is strange. Let me check if it actually ran the statements.
Assistant
Something is wrong with my CLI usage. The CLI seems to be running and exiting silently when there's ALTER TABLE. Let me look at the CLI command line args:
Assistant
Hmm, the SQL argument mode seems to require single quotes. Let me try differently.
Assistant
The output shows no seq after rename - but rename should preserve AUTOINCREMENT! Let me investigate:
Assistant
Let me check master behavior:
Assistant
On master, the rename preserves the AUTOINCREMENT. But after my change, the rename incorrectly deletes the entry. Let me restore my changes and investigate:
Assistant
Let me add some debug output:
Assistant
Wait, the debug says
rename = falsefor what should be a rename! Let me check the parser:Assistant
Let me look at how the alter.rs handles the rename vs alter distinction:
Assistant
Let me check the existing master behavior:
Assistant
Let me restore my changes and think about this:
Assistant
Let me re-think the design. The schema change in the existing code already changes
is_rowid_aliasto false. So if the column is no longer a rowid alias, it makes sense that AUTOINCREMENT is lost too.But to be conservative and match the user's expectation, let me think about whether to detect the "rename-like" case specifically.
Let me check what
RENAME COLUMNdoes to understand:Assistant
The RENAME COLUMN syntax preserves everything correctly. Now let me remove the debug output and consider edge cases more carefully. I'll consider detecting "rename-like" AlterColumn operations where the user just wants to change the name:
Assistant
Let me verify what happens if user explicitly tries to keep PRIMARY KEY:
Assistant
Now let me also verify that the persistence behavior is correct - that reopening the DB shows no stale entry:
Assistant
Hmm, the reopen shows the sqlite_sequence still has t. Let me check if the persistence is working:
Assistant
Wait, the delete is not working in this test. Let me rebuild and investigate:
Assistant
Let me re-run the test cleanly:
Assistant
The fix works in memory. Let me test persistence:
Assistant
Excellent! The fix persists properly across DB reopen. Let me now check that existing tests still pass:
Assistant
There don't seem to be tests for ALTER COLUMN (the alter column type change syntax) - just ALTER TABLE ADD/DROP COLUMN and RENAME COLUMN. Let me look for any tests that test changing column types:
Assistant
Let me look for tests that test column type changes:
Assistant
There are existing sqltests for ALTER COLUMN. Let me run them to make sure my changes don't break anything.
Assistant
All 57 alter_column tests pass. Now let me run trigger tests that test ALTER TABLE:
Assistant
All 1775 tests pass. Let me also run the integration tests:
Assistant
Let me also test that even when the user uses ALTER COLUMN to just rename (no type change), the behavior is consistent:
Assistant
Let me verify behavior for an ALTER COLUMN that adds a NOT NULL constraint:
Assistant
The schema is unchanged because there's a parsing error due to the duplicate column name (since I didn't change the name). But the sequence advanced to 3 (because of the earlier insert and the rollback). Wait, actually:
- INSERT INTO t1(b) VALUES('z') failed because the ALTER failed (rollback? or did it succeed?).
- The seq advanced to 3.
Wait, looking at this output:
- before: seq=2
- alter failed with duplicate column error
- after alter_column type-preserving: seq=2 (so the alter didn't apply, sqlite_sequence unchanged)
- schema: still
CREATE TABLE t1 (a INTEGER PRIMARY KEY AUTOINCREMENT, b TEXT) - after insert: seq=3 (so the insert succeeded and advanced seq)
OK that's reasonable. The alter failed because the new definition has the same name as the old column. The seq advanced on insert.
Now let me look at a real ALTER COLUMN that adds NOT NULL (but renames the column):
Assistant
Let me do a final review of the diff:
Assistant
Let me check the MVCC handling for DELETE in the current code:
Assistant
Looking at the existing code, MVCC mode is used for things like Delete-then-Insert (Hekaton-style). For pure Delete, it doesn't seem to be needed.
Actually, let me look more carefully at line 2209:
Assistant
Let me also test with STRICT tables:
Assistant
Let me also verify by checking the persisted DB:
Assistant
Let me also check related tests:
Assistant
Let me also run the cli tests:
Assistant
Let me look for any sqlite_sequence specific tests:
Assistant
All sqlite_sequence related tests pass.
Let me also run the trigger tests:
Assistant
All tests work as expected. Let me do a final review of my changes:
Assistant
The diff looks clean. Let me make sure everything compiles cleanly and there are no warnings:
Assistant
No warnings. Let me also run a clippy check:
Assistant
No warnings or errors. Let me also run formatting checks:
Assistant
Formatting is clean. Let me also test the same scenario from the user's issue to confirm:
Assistant
The user's expectation is met. Let me also think about whether to drop the entire sqlite_sequence table itself. Looking at the original issue title: "alter col leaves sqlite_sequence table behind". The user might be referring to the row in the table, not the table itself.
Looking at SQLite's behavior - the sqlite_sequence table is kept but is unused when no AUTOINCREMENT tables exist. My fix removes the row, which matches the user's main concern.
Let me also verify the fix works correctly with the issue's exact reproduction:
Assistant
Excellent! The fix correctly resolves the issue. Let me also do a final review by checking my changes meet the requirements from the issue:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.