Add a primary key to a sqlite table
This example demonstrates a SQLite migration technique that adds a primary key to an existing table without losing its data. The code defines three functions: `get_create_table_string` retrieves the original `CREATE TABLE` statement from the `sqlite_master` system table, `add_pk_to_create_table_string` uses the `re` module’s `re.sub` to insert the `PRIMARY KEY` constraint into that string for a specified column, and `add_pk_to_sqlite_table` orchestrates the migration. It executes an SQL `BEGIN TRANSACTION` block that renames the original table, creates a new table using the modified schema, copies rows via `INSERT INTO ... SELECT *`, and drops the old table. The example uses Python’s `sqlite3` connection API and `executescript` to run the multi-statement transaction.
AI-generated description