A database migration can finish without a syntax error and still leave an application broken. A copied table may have lost an index. A new constraint may reject a value that an older worker still writes. A rollback script may restore the old column names while discarding records created after the release. These are different failures, and asking an AI assistant to “make this migration safe” does not give you a way to distinguish them.
Use DeepSeek to develop and challenge a migration plan, then use your database and application tests to decide whether the plan works. Give it a bounded schema, an explicit change contract and synthetic counterexamples. Require every proposed operation to explain what it preserves, what it rejects and which check would catch a mistake. Keep execution under the control of your normal migration process.
This guide develops that approach through a small SQLite example: a task tracker needs to restrict task status to open or done without changing existing task identities or project relationships. The accompanying Python lab uses only the standard library and disposable databases. It demonstrates a deliberately narrow table rebuild, precondition checks and rollback testing. It is a rehearsal pattern, not a general migration framework or a production deployment script.
Testing boundary: the executable example and its tests were run locally. The prompts are reusable templates written for this guide; no paid DeepSeek API call, model-quality benchmark, live application deployment or production database test was performed. Technical references were checked on October 4, 2026. Your SQLite runtime and application requirements still need their own verification.
1. Write the change contract before requesting SQL
The first useful artifact is a short statement of permitted changes. For our task tracker, the old schema allows a task to have a missing or arbitrary status. The new rule requires every task to contain one of two exact strings. Existing valid rows must retain their task ID, project ID, title and status. A project must still exist for every task. The application must retain the named index used to find tasks within a project.
That sounds small, but several business decisions are hidden inside it. Should a blank status mean open? Is OPEN equivalent to open? Can an archived task be converted to done? Does a missing project indicate an import error or a legitimate orphan that should be preserved elsewhere? This guide deliberately answers none of those questions by guessing. A source row that violates the target rule stops the rehearsal. An owner must approve any remediation separately.
Write preservation requirements in terms of things a test can compare. “Keep the data” is too vague. “Before and after the migration, the ordered tuples of task ID, project ID, title and status are identical” is useful for this tiny fixture. “Retain performance” is also vague. “Recreate the project lookup index, then measure the named lookup on a representative rehearsal dataset” describes two independently checkable tasks.
Separate schema requirements from operational requirements. The schema contract may require a non-null status and a membership check. The operational contract may require a maximum maintenance window, a known owner for abort decisions and a tested restore procedure. Neither contract can substitute for the other. A logically correct migration that takes longer than the available window can still be unsuitable for release.
Also name what must remain unsupported. Our lab has two ordinary tables and one explicit index. It has no views, triggers, generated columns, virtual tables or tables referring to tasks. It rejects unexpected schema objects rather than silently dropping them. This narrowness is a useful design decision: the exercise produces strong evidence about one well-defined change instead of weak evidence about many possible databases.
If the request includes data normalization as well as a schema change, split those decisions into reviewable steps. The reversible data-cleaning workflow explains how to record proposed transformations without hiding the original values. A migration should not become an accidental policy for resolving ambiguous business data.

2. Give DeepSeek an evidence packet, not a database dump
A useful request contains the current schema, the intended schema, the exact engine version and a few carefully chosen examples. Include the connection behavior and migration runner as well. SQL does not run in a vacuum: a framework may start a transaction before your code does, a connection pool may apply different settings, and a deployment system may retry a job whose first outcome was uncertain.
For the task tracker, the packet should identify the two tables and the project lookup index, list each field that must survive, and show several invented rows. Add an explicit inventory statement: tasks is a leaf table in this fixture, so no other table refers to it. Include the actual runtime value of sqlite3.sqlite_version, not merely the Python version or a developer’s installed command-line client. Different entry points can use different SQLite builds.
Give the model the reason for the change. Suppose a new application release expects status filters to work with two supported values. That helps it notice that an old import worker might still create a missing status. Without that context, the assistant may focus on fitting the new table definition and ignore the writer that can immediately violate the new rule.
Keep secrets and real customer records out of the packet. Schema names, internal descriptions and sample values can expose business information even when there is no obvious password. Replace identities and free-text fields with synthetic equivalents, and share only the context approved for the model service you use. The DeepSeek data-minimization guide offers a practical way to reduce unnecessary disclosure before a request leaves your application.
If your organization allows DeepSeek through an API or approved coding tool, treat generated SQL as a candidate artifact. You do not need to connect the model to a database to follow this workflow. A text-only exchange containing sanitized schema and test results is enough to ask for a plan, identify missing assumptions and refine test cases. The official DeepSeek API reference supports conversation input, but this article does not depend on a particular model name or claim that any model reliably prevents migration mistakes.
Record the evidence packet alongside the proposed migration. A later reviewer should be able to tell which schema the advice was based on. If the actual database now has an additional trigger or a different index, the old proposal has lost a key assumption. A fresh request can help investigate the difference, but a new chat answer should never silently authorize widening the release scope.
3. Build a small fixture that exposes meaningful mistakes
Our example uses projects and tasks. Each task has an explicit integer ID, a project ID, a title and a status. The target keeps those same fields while tightening status. This is intentionally different from adding a new derived column: there is no reason for a valid row’s values to change, so exact value comparison becomes a particularly strong check.
A tiny fixture should be small enough to inspect by eye while still exposing the likely failure modes. Use nonconsecutive task IDs so a careless copy that regenerates IDs becomes visible. Include tasks in different projects so a swapped project mapping becomes visible. Extend the fixture with multiple tasks in one project when testing project-level lookups. Include both allowed status values, and include a title with punctuation or Unicode so a home-grown serialization step cannot quietly simplify the data.
Keep the invalid cases separate. One fixture can contain a missing status; another can contain an unsupported string. A third can contain an orphan project reference inserted only while building a deliberately corrupted test fixture. That does not model a permitted application action. It models a database inherited from an older bug, an import or a connection that failed to enforce its intended rules.
Make an empty database a first-class case too. A migration can accidentally depend on the first row to infer a column mapping, or confuse “nothing to copy” with “nothing to validate.” The correct outcome for an empty but expected schema is still a correctly constrained target with its required index. Schema correctness should not depend on whether today’s customer happens to have data.
The examples should also include conditions the migration refuses before changing anything: an unexpected view, a new index, a schema version it does not recognize, or an already active caller-owned transaction. Refusal is informative when it names a violated precondition and leaves the source unchanged. A test suite made exclusively of valid rows cannot establish this boundary.
Do not let an AI assistant expand this into hundreds of arbitrary records while leaving the important distinctions untested. Start with a case matrix: valid, empty, missing status, unsupported status, orphan reference, unexpected schema and interrupted rebuild. The synthetic test-data guide explains how to connect fixtures to the behaviors they are meant to prove.

4. Ask DeepSeek for a plan before a runnable migration
The first prompt should produce questions and a proposed sequence, not a command to execute. This gives the reviewer an opportunity to reject an incorrect assumption before it becomes embedded in code. State that missing information is a reason to stop. An assistant that invents an index name or assumes a table has no inbound relationships has not filled a harmless gap; it has changed the scope of the migration.
Review this SQLite migration proposal. Do not execute anything.
Goal: restrict tasks.status to the exact values open and done,
with no NULLs. Preserve every valid row's id, project_id, title
and status. Preserve the named project lookup index.
I will provide:
- SQLite and Python runtime versions
- current CREATE statements and schema-object inventory
- target requirements and synthetic fixtures
- application readers/writers and deployment constraints
Return:
1. Missing facts that block a safe plan
2. Preconditions that can be checked mechanically
3. A candidate operation sequence with reasons
4. Failure cases and expected unchanged state
5. Application compatibility questions
Do not repair invalid rows, disable safeguards, invent schema
objects or assume a production rollout is authorized.
Next, ask it to turn each assumption into a test. If the plan says that a copied table retains all rows, require a comparison that would fail when values are swapped between rows. If it says the index survives, require an inventory check. If it says failure is reversible, require a deliberate failure after the old table has been dropped but before the transaction commits.
A separate review pass can be useful, especially when the reviewer receives the original contract and proposed code rather than a glowing summary of the first answer. The aim is to reduce anchoring, not to create an illusion of independent certification. Two model responses may share the same blind spot. Treat agreement as another suggestion to inspect, not as a replacement for a database test.
Challenge this migration against the original contract.
For each suspected defect, give:
- the relevant operation or assumption
- a concrete synthetic counterexample
- the exact invariant that would fail
- a test that distinguishes correct from incorrect behavior
Pay special attention to transaction boundaries, schema drift,
foreign keys, index recreation, ID preservation, dirty source
rows, repeat execution and application compatibility.
Label uncertain claims as questions. Do not claim a test passed
unless I supply its actual output.
Bring back the smallest meaningful test failure. A useful follow-up says that a named test inserted a missing status and the migration unexpectedly committed, then supplies the relevant schema and traceback. An unhelpful follow-up says only “it failed, fix everything.” The smaller report makes it easier to review the proposed correction and confirm that it addresses the failing invariant without weakening another one.
Preserve the candidate before requesting revisions. Otherwise it becomes difficult to know whether a passing test followed a real fix, a changed expectation or a deleted assertion. A normal version-control diff is enough for this. For a structured review of those changes, use the evidence-based code-review workflow.
5. Run a bounded SQLite migration rehearsal
The lab below operates on a database it creates for the demonstration. It never accepts a production path. It uses explicit SQL transaction statements on a connection configured for explicit control, checks the expected starting schema and version, copies named columns, verifies the result and commits only after its checks pass. The test suite then challenges the same migration function with invalid and interrupted cases.
The target combines a non-null requirement with a check restricting status. Current SQLite documentation includes direct operations for setting and dropping a column’s NOT NULL constraint, added in SQLite 3.53.0. Do not repeat the outdated blanket claim that SQLite can never make that change directly. This example uses a rebuild for the combined target definition and to expose the preservation work that a rebuild requires.
SQLite’s documented generalized rebuild procedure covers more complicated schemas and includes carefully ordered handling of foreign keys and dependent objects. Our lab is narrower: tasks is the child table, no other table points to it, and unknown schema objects cause a stop. Within that declared fixture, foreign-key enforcement remains enabled throughout. Do not transplant this shortcut into a parent-table rebuild or a database with unexamined dependencies.
The central sequence is easy to describe: establish a write transaction, validate the source, create the replacement table, copy explicit columns, replace the original name, rebuild the known index, compare preserved values and check integrity. Every statement executes individually. That makes the transaction boundary and injected failure points visible to the reader instead of hiding them inside an opaque script runner.
Run the example: save the following code as article_demo.py and run python article_demo.py with Python 3.12 or later. It creates only in-memory databases. The strict schema checks may refuse other runtime behavior; investigate a refusal rather than removing the checks.
Complete runnable Python example (132 lines)
"""Python 3.12+; run this file. It creates only disposable in-memory databases."""
import platform
import sqlite3
PROJECTS = "CREATE TABLE projects (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
TASKS = ("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT NOT NULL, "
"status TEXT, project_id INTEGER NOT NULL REFERENCES projects(id))")
NEW = ("CREATE TABLE tasks_new (id INTEGER PRIMARY KEY, title TEXT NOT NULL, "
"status TEXT NOT NULL CHECK (status IN ('open', 'done')), "
"project_id INTEGER NOT NULL REFERENCES projects(id))")
INDEX = "CREATE INDEX tasks_project_id_idx ON tasks(project_id)"
TARGET = NEW.replace("CREATE TABLE tasks_new", 'CREATE TABLE "tasks"', 1)
def require(condition, message):
if not condition:
raise RuntimeError(message)
def inventory(c):
return tuple(c.execute(
"SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name"))
def expected(target=False):
return (("table", "projects", "projects", PROJECTS),
("table", "tasks", "tasks", TARGET if target else TASKS),
("index", "tasks_project_id_idx", "tasks", INDEX))
def data(c):
return (tuple(c.execute("SELECT id, typeof(id), name, typeof(name) "
"FROM main.projects ORDER BY id")),
tuple(c.execute("SELECT id, typeof(id), title, typeof(title), "
"status, typeof(status), project_id, typeof(project_id) "
"FROM main.tasks ORDER BY id")))
def snapshot(c):
return inventory(c), data(c), c.execute("PRAGMA user_version").fetchone()
def health(c):
require(not list(c.execute("PRAGMA main.foreign_key_check")), "Foreign key violation")
require(list(c.execute("PRAGMA main.integrity_check")) == [("ok",)], "Integrity failure")
def fresh():
c = sqlite3.connect(":memory:", isolation_level=None,
autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
c.execute("PRAGMA foreign_keys=ON")
c.execute("PRAGMA ignore_check_constraints=OFF")
require(c.execute("PRAGMA foreign_keys").fetchone() == (1,), "FK support required")
for sql in (PROJECTS, TASKS, INDEX):
c.execute(sql)
c.executemany("INSERT INTO projects VALUES (?, ?)", [(1, "Web"), (2, "Docs")])
c.executemany("INSERT INTO tasks VALUES (?, ?, ?, ?)",
[(7, "Draft café guide", "open", 1), (42, "Review ", "done", 2)])
return c
def migrate(c, fail_after_drop=False):
require(not c.in_transaction, "Existing transaction: refused")
require(c.isolation_level is None and
c.autocommit == sqlite3.LEGACY_TRANSACTION_CONTROL, "Connection mode: refused")
require(c.row_factory is None and c.text_factory is str, "Custom factories: refused")
for name, value in (("foreign_keys", 1), ("ignore_check_constraints", 0),
("writable_schema", 0), ("legacy_alter_table", 0),
("defer_foreign_keys", 0), ("journal_mode", "memory")):
require(c.execute(f"PRAGMA {name}").fetchone() == (value,), f"Unsafe {name}")
require(all(row[1] in ("main", "temp") and not row[2]
for row in c.execute("PRAGMA database_list")), "Only in-memory demo allowed")
require(not list(c.execute("SELECT name FROM temp.sqlite_schema")), "Temp objects: refused")
c.execute("BEGIN IMMEDIATE")
try:
require(inventory(c) == expected(), "Schema drift or repeat run: refused")
require(c.execute("PRAGMA user_version").fetchone() == (0,), "Version: refused")
invalid = list(c.execute("SELECT id, status FROM main.tasks WHERE status IS NULL "
"OR status NOT IN ('open', 'done') ORDER BY id"))
require(not invalid, f"Invalid status rows; no cleanup: {invalid!r}")
health(c)
before = data(c)
c.execute(NEW)
c.execute("INSERT INTO tasks_new (id, title, status, project_id) "
"SELECT id, title, status, project_id FROM tasks ORDER BY id")
c.execute("DROP TABLE tasks")
if fail_after_drop:
raise RuntimeError("Injected failure after DROP")
c.execute("ALTER TABLE tasks_new RENAME TO tasks")
c.execute(INDEX)
require(inventory(c) == expected(True), "Unexpected target schema")
require(data(c) == before, "Values or storage classes changed")
health(c)
c.execute("PRAGMA user_version=1")
c.execute("COMMIT")
except BaseException:
if c.in_transaction:
c.execute("ROLLBACK")
raise
def main():
print(f"Python {platform.python_version()} / SQLite {sqlite3.sqlite_version}")
for scenario in ("valid", "dirty", "injected"):
c = fresh()
try:
if scenario == "dirty":
c.execute("UPDATE tasks SET status=NULL WHERE id=7")
before = snapshot(c)
try:
migrate(c, fail_after_drop=(scenario == "injected"))
except RuntimeError as error:
require(scenario != "valid", f"Unexpected failure: {error}")
require(snapshot(c) == before, "Rollback verification failed")
print(f"{scenario}: refused; original schema/data preserved")
else:
require(scenario == "valid", "Expected refusal did not occur")
print("valid: migrated; values/types equal; FK and integrity checks passed")
migrated = snapshot(c)
try:
migrate(c)
except RuntimeError:
require(snapshot(c) == migrated, "Repeat run changed database")
print("repeat: refused; migrated schema/data preserved")
else:
raise RuntimeError("Repeat unexpectedly succeeded")
finally:
c.close()
if __name__ == "__main__":
main()
Download the SQLite migration lab and tests for the self-contained example, the expanded rehearsal, test modules, actual local output and usage notes. All examples use synthetic disposable databases.
Read this as an executable explanation of a contract, not an invitation to point it at an important file. A production implementation needs integration with its actual migration ledger, logging, access controls, backup system, maintenance process and application release. An exact-schema check is intentionally strict here: semantically similar but differently formatted schema text may be refused. That is preferable to this teaching lab guessing whether a broader schema is equivalent.
The local runner uses Python’s sqlite3 module. With the transaction-control configuration shown in the code, the rebuild statements share one explicitly opened transaction, committed only after validation. Avoid casually replacing that sequence with executescript(): its transaction behavior depends on Python’s connection configuration and can include committing a pending transaction under legacy control. If your framework owns the connection, first establish which layer owns begin, commit and rollback.
Parameter binding is appropriate for row values. It does not turn an arbitrary table name from a model response into a safe SQL identifier. The lab uses fixed, reviewed identifiers and explicit column lists. A general-purpose migration generator needs its own identifier-validation and schema-mapping rules, which are outside the small contract proved here.
6. Interpret the evidence instead of counting green tests
A successful case should demonstrate several separate facts. The migration accepted the expected starting schema. The resulting rows preserved every contract field. The new constraints reject missing and unsupported statuses. The project relationship is still enforced. The known lookup index exists. The recorded schema version changed as intended. A single “migration succeeded” message does not tell you all of that.
Row count is a useful early warning, but it is insufficient evidence of preservation. Three rows before and three rows after can conceal one duplicate and one missing record. A checksum can also hide a poor comparison method if serialization drops type information or uses ambiguous delimiters. For this fixture, ordered row tuples provide a simple, inspectable comparison. For a large database, design a scalable reconciliation method with explicit type, ordering and collision assumptions.
SQLite’s integrity check and foreign-key check answer different structural questions. Passing integrity checking does not replace checking foreign-key relationships. Neither one knows that task 7 must keep its original title or that a business rule requires a particular status meaning. Run the checks you need, but describe their coverage precisely rather than treating “integrity” as a universal correctness certificate.
Dirty-data refusal deserves the same attention as the happy path. After a missing status is detected, verify that the original rows, original table definition, index and schema version remain unchanged. After an unsupported status is detected, ensure the code did not silently convert it. The error should identify enough of the issue for a reviewer to investigate without dumping unnecessary sensitive data into deployment logs.
Failure injection should exercise the dangerous middle, not only an error before work begins. The embedded article example injects one exception after dropping the old table; its tests verify restoration of the expected logical schema and values. The expanded implementation in the optional download tests additional failure stages. This is a useful local observation. It is not a test of power loss, operating-system crashes, disk failure, backup restoration or the behavior of a different database engine.
Repeat execution also needs a defined outcome. The lab refuses a second run because its starting version and schema no longer match. That is an intentional fail-closed choice, not an idempotence claim. A real runner may instead recognize an already recorded migration and return success without reapplying it. The dangerous behavior is guessing from a partially familiar table name and continuing after an uncertain previous attempt.
Observed local results: the exact article example printed the following output on Python 3.12.14 with SQLite 3.53.1. The complete downloadable lab contains 41 passing unittest methods: 13 cover the article implementation and 28 cover the expanded rehearsal. The suite also passed with Python optimization enabled. These counts describe this local test run, not model accuracy or production readiness.
Python 3.12.14 / SQLite 3.53.1
valid: migrated; values/types equal; FK and integrity checks passed
repeat: refused; migrated schema/data preserved
dirty: refused; original schema/data preserved
injected: refused; original schema/data preserved
Keep the test report attached to the exact candidate that produced it. Record Python and SQLite versions, fixture definitions, the test command and the source revision or hash. If any of these changes, rerun the relevant checks. A screenshot of green output without the tested source is weak release evidence because another person cannot establish what actually passed.
7. Treat locks, duration and copies as a separate rehearsal
The small lab establishes logical behavior on a tiny dataset. It says little about the duration of copying millions of rows, the space required for a replacement table and index, or the experience of a busy application during the write window. Those concerns require a second rehearsal with representative size, shape and contention. Keep the two evidence sets separate so a fast unit test cannot be mistaken for a capacity result.
SQLite allows a single writer at a time. Beginning an immediate transaction attempts to acquire the write transaction early; it can fail when another writer is active. That can be useful because the migration learns about contention before it starts rebuilding. It is not a promise that the entire operation will encounter no later error or that readers and other processes will behave as your application expects.
Write down an operational stop rule before measuring. For example, the owner might require aborting if the migration cannot acquire its write window within the approved budget. The specific budget belongs to the application owner and measured workload; this guide does not invent a universal safe timeout. Report lock-acquisition delay separately from copy time, index creation and post-copy verification so the next decision has useful detail.
Use a database-aware copying or backup method and prove that the copy can be opened and used. SQLite provides a backup API, exposed by Python’s connection backup method, that is suitable for creating a consistent destination through the database engine. A byte copy made casually while a database is active is not the same evidence. In WAL mode, committed work can reside in the WAL file, so handling only the main database file can omit relevant state.
A representative rehearsal copy also needs a privacy decision. A full copy may contain information that does not belong on a developer laptop or in a model prompt. Keep database execution in an approved environment and give DeepSeek only the sanitized observations necessary for analysis. For example, a histogram of status values and a redacted schema can be enough to discuss a failed precondition without sending individual task titles.
When measuring, include the application checks that matter after the change: project task listing, filtering by status, creating a task and updating its status. Compare the important lookup behavior under realistic parameters. Merely seeing an index name in the catalog proves that an object exists; it does not prove that the query planner will choose it or that the application’s workload remains acceptable.
8. Check old and new application behavior explicitly
A schema change is part of an application release, even when the SQL is short. List all writers, including import scripts, scheduled jobs, background workers and older mobile or desktop clients. The main web application may write valid status values while an overlooked nightly importer still writes a missing value. Tightening the database constraint exposes that mismatch immediately.
Build a compatibility matrix using the versions you actually expect to coexist. Can the old application read the new schema? Can it write valid records? Can the new application run before the migration? Are old workers still draining queued jobs while the new release starts? Each “yes” needs a test or an explicitly documented limitation. A schema version number alone does not answer these questions.
For the status example, an application-first step might make every writer supply a valid explicit status while continuing to tolerate old stored rows. A separately approved cleanup could then resolve invalid historical records. Only after both conditions are established would the constraint-tightening migration be eligible. This sequencing is a design option, not a claim that all systems can deploy the same way.
Ask DeepSeek to challenge the compatibility matrix with concrete paths: an old worker retries yesterday’s queued payload; a user submits an older cached form; an import uses a positional insert statement; a report expects columns in a particular order. These scenarios reveal assumptions that are easy to miss when reviewing only the target CREATE TABLE statement.
Be especially careful with positional inserts and broad SELECT projections in surrounding code. The demonstration uses explicit column names to make its intended mapping visible. The application should be examined for the same dependency. A migration can preserve every database value and still break a caller that assumed a different column count or order.
If the application needs genuinely online, multi-step compatibility, design that process with its actual database engine and deployment tools. Patterns often described as expand, migrate and contract involve more than adding a column: they need rules for which representation is authoritative, how backfills interact with concurrent writes and when an old representation can be removed. Do not label the single-transaction lab as a zero-downtime migration.

9. Distinguish transaction rollback, application rollback and restore
The word rollback is often used for three different operations. A transaction rollback undoes uncommitted database work. An application rollback deploys an earlier program version. A restore replaces or reconstructs database state from a recovery source. Each operation has different prerequisites, and succeeding at one says little about the others.
The lab proves a bounded transaction-rollback property when a deliberate Python exception interrupts the migration before commit. After a successful commit, executing ROLLBACK does not reverse that completed migration. Reversing a committed change requires a separately designed operation or a restore decision, and it must account for records written since the change.
Consider an application rollback after the new status constraint is live. If the previous program sometimes writes missing statuses, deploying it again may restart the original incompatibility. The correct response might be a forward application fix rather than a schema reversal. Decide based on the tested compatibility matrix and the incident’s facts, not on a reflex to run whichever script is named down.
A down migration that removes a restriction may be less destructive than one that removes a column, but it still deserves review. Does it preserve records written by the newer application? Does it recreate the old index and version marker correctly? Does it require the same maintenance window? A plausible reverse sequence is not evidence that it has been rehearsed against the post-release state.
Restore planning must include the fate of new writes. If a backup predates the release and people have created tasks since then, restoring it can lose those tasks unless another recovery mechanism captures them. State the acceptable recovery point, the source of any replayable changes and who decides whether the tradeoff is permitted. This is a business decision as well as a technical one.
Finally, rehearse the human steps. Who stops writers, chooses the artifact, checks that the database identity is correct and decides whether to reopen traffic? An assistant can help turn those questions into a checklist. It cannot establish that the organization has the necessary authorization, recovery access or tested operational capacity merely by generating a well-written runbook.
10. Turn the proposal into a reviewable release runbook
A useful runbook starts with identity and scope. Name the migration artifact, expected starting schema version, intended target version and the approved database environment. Include a check that distinguishes the intended target from a similarly named test or production database. The lab avoids this problem by creating its own temporary database; a deployment cannot rely on that simplification.
Next, list prerequisites in the order someone can verify them: backup or recovery evidence, compatible application versions, resolved dirty data, expected schema inventory, available space and approved write window. Attach the actual rehearsal evidence. A checked box saying “backup exists” is weaker than a record that the named recovery source was opened and its relevant application behavior verified.
Record the execution sequence and the boundaries at which an operator must stop. Distinguish a precondition refusal from a mid-transaction exception and from an uncertain commit outcome. If the outcome is uncertain, inspect the authoritative database state and migration ledger before retrying. Repeatedly issuing the same destructive statements because a console disconnected is not a recovery strategy.
Specify post-change acceptance checks. For this example, they include expected schema and version, preservation reconciliation, constraint rejection tests, project relationship checks, index presence and the application paths identified earlier. Use a disposable or otherwise approved test record for any live write checks; do not invent real customer data or alter a user’s task just to prove the migration worked.
End with ownership and recovery decisions. Name the person or role that can approve reopening writes, the signal that calls for investigation and the procedure for collecting evidence without leaking sensitive records. Include a bounded observation plan based on the application’s actual traffic cycle. A background job that runs once each night will not be covered by checking the home page immediately after release.
DeepSeek is most helpful here when asked to find omissions. Give it the contract and draft runbook, then ask which prerequisite has no evidence and which acceptance check has no failure response. You remain responsible for resolving those gaps with real measurements and the people who own the system.
Frequently asked questions
Can I give DeepSeek read-only database access instead?
Read-only access reduces some write risks but does not eliminate disclosure, load or query-cost concerns. It also does not make a generated migration correct. This workflow works with a sanitized text packet, so start there unless a separately approved integration has a concrete benefit. Keep permissions, data handling and query limits appropriate to that integration.
Should every SQLite constraint change rebuild a table?
No. Choose an operation supported by your actual SQLite version and the particular change. Current SQLite documentation includes more ALTER TABLE capabilities than older guides may describe. The rebuild here teaches a combined target definition and its preservation obligations; it is not a recommendation to replace a simpler supported operation without a reason.
Are passing offline tests enough to release?
No. They establish evidence about the fixtures, runtime and assertions that actually ran. A real release also needs representative data, application compatibility, capacity and recovery checks. Keep the local test report useful by stating these limits instead of inflating it into a claim about production safety.
What should I do when the model suggests automatic data repair?
Ask it to separate the repair proposal from the schema migration and show affected cases. A missing value may have several legitimate meanings. Have the appropriate owner approve the mapping, preserve a review trail and test the repaired dataset before tightening the constraint. The model’s preferred interpretation is not a business decision.
The practical takeaway
A good AI-assisted migration leaves a trail another engineer can inspect: a specific change contract, bounded context, a candidate artifact, tests that can reject it and a release plan grounded in measured behavior. DeepSeek can help develop each artifact and challenge its assumptions. The database engine, application tests and authorized operator establish what actually happened.
Start with the small SQLite rehearsal, then replace each simplification with evidence from your real system. Preserve identities explicitly, refuse ambiguous source data, test the failure path and distinguish uncommitted rollback from recovery after a release. Those habits make model assistance useful even when a generated answer is incomplete.
Sources & References
Official documentation checked October 4, 2026. These sources support the platform-specific statements; the task-tracker example, prompts, diagrams, contract and review workflow are original instructional material.
- DeepSeek: Chat Completions API — conversation inputs and API request reference; no live model result is claimed here.
- SQLite: ALTER TABLE — supported changes, version-specific NOT NULL operations and the generalized table-rebuild procedure.
- SQLite: Foreign Key Support — connection-level enforcement and relationship constraints.
- SQLite: Transactions — explicit transaction behavior and immediate write transactions.
- Python: sqlite3 module — runtime version reporting, connection transaction control, executescript and backup.
- SQLite: PRAGMA statements — schema inspection, version metadata, integrity checks and foreign-key checks.
- SQLite: Online Backup API — database-aware backup behavior and consistency.
- SQLite: Write-Ahead Logging — concurrent access and the role of the WAL file.
- SQLite: CREATE TABLE — table and column constraints used in the example.
