Drizzle keeps SQL close to TypeScript while providing typed query construction. The types improve development feedback, but they do not replace database constraints, runtime validation, or migration review.
Let the schema describe invariants
Define nullability, unique constraints, foreign keys, and indexes in the schema where the database can enforce them for every writer. Validate external input before it reaches persistence. Prefer the query builder or parameterized SQL for values; never interpolate untrusted text into a raw SQL string.
Use transactions when several writes represent one domain operation, such as creating a record and its audit event. Keep transaction scopes short and do not perform slow network calls while holding locks. Make conflict behavior explicit: upsert is appropriate only when the update fields are intentionally owned by the operation.
Treat migrations as production code
Generate migrations from the schema, then inspect the SQL before applying it. Consider table size, lock duration, default-value behavior, and whether a change needs a staged rollout. A destructive migration should include a verified backup and a rollback or recovery plan. Do not use schema push as a substitute for reviewed production migrations.
Test queries against the real database engine when behavior depends on constraints, isolation, or SQL details. Check query plans for important read paths and avoid selecting columns the caller does not need. Drizzle helps express data access; good production behavior still depends on SQL and operational discipline.
Let the database enforce the production invariant
Drizzle exposes transactions through db.transaction and supplies a transaction object to each callback. Use that same object for every dependent write. If an article and its revision must appear together, inserting the article through db and the revision through tx would split ownership of the transaction. Define a database unique rule for keys whose correctness matters under retries. Drizzle transaction API · PostgreSQL unique indexes
Review the actual generated SQL alongside the TypeScript schema. Check names of indexes and columns, whether table rewrites or long locks are likely, and how existing rows satisfy new constraints. Apply schema changes to a disposable copy first. In the application's test, verify both the committed result and the failure path where the second write raises an error. Typed query builders make it easier to express the intended values, while PostgreSQL still supplies concurrency and transaction behavior.
Worked example
This service sketch assumes your own typed schema and validated inputs. Force the second insert to fail in an integration test; the article insert should roll back with it.
tsawait database.transaction(async (tx) => { await tx.insert(articles).values(article); await tx.insert(articleTags).values(tags); });




Community
Discussion
Loading comments…