drizzle-orm
Drizzle ORM for type-safe SQL with PostgreSQL, MySQL, and SQLite. Use when defining schemas, writing queries, managing relations, running migrations, or using drizzle-kit. Use for drizzle, orm, schema, query, migration, pgTable, relations, drizzle-kit, drizzle-zod.
What this skill does
# Drizzle ORM
## Overview
Drizzle ORM is a lightweight, type-safe TypeScript ORM that maps directly to SQL for PostgreSQL, MySQL, and SQLite. It provides both a SQL-like query builder and a relational queries API, with zero dependencies and full serverless compatibility. Use Drizzle when you need compile-time type safety with SQL-level control; avoid it when you need a full active-record ORM with automatic migrations (use Prisma) or when working with MongoDB/NoSQL databases.
## Quick Reference
| Pattern | API | Key Points |
| ------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------- |
| Schema definition | `pgTable('name', { columns }, (t) => [indexes])` | Third arg returns array of indexes/constraints |
| Column types | `text()`, `integer()`, `boolean()`, `timestamp()` | Import from `drizzle-orm/pg-core` |
| Type inference | `typeof table.$inferSelect`, `$inferInsert` | Derive TS types directly from schema |
| Relational queries | `db.query.table.findMany({ with, where })` | Requires schema passed to `drizzle()` client |
| SQL-like queries | `db.select().from(table).where()` | Chainable, returns array of rows |
| Insert | `db.insert(table).values({}).returning()` | `.returning()` for getting inserted rows |
| Update | `db.update(table).set({}).where().returning()` | Always include `.where()` to avoid full-table updates |
| Delete | `db.delete(table).where()` | Always include `.where()` to avoid full-table deletes |
| Upsert | `.onConflictDoUpdate({ target, set })` | Chain after `.insert().values()` |
| Transactions | `db.transaction(async (tx) => { ... })` | Auto-rollback on thrown errors |
| Filters | `eq()`, `and()`, `or()`, `inArray()`, `sql\`\`` | Import operators from `drizzle-orm` |
| Relations | `relations(table, ({ one, many }) => ({}))` | Declares logical relations for relational queries |
| Generate migrations | `drizzle-kit generate` | Creates SQL migration files from schema diff |
| Apply migrations | `drizzle-kit migrate` or `migrate()` in code | Applies pending migrations to database |
| Push schema | `drizzle-kit push` | Direct schema push without migration files |
| Prepared statements | `db.select().from(t).where(eq(t.id, sql.placeholder('id'))).prepare()` | Reusable parameterized queries |
| Views | `pgView('name').as(qb => ...)` | Regular and materialized views |
| $count utility | `db.$count(table, filter?)` | Shorthand count, usable as subquery |
| Generated columns | `text().generatedAlwaysAs(() => sql\`...\`)` | Computed columns (virtual or stored) |
| Check constraints | `check('name', sql\`condition\`)` | Row-level validation at database level |
## Common Mistakes
| Mistake | Correct Pattern |
| -------------------------------------------------- | --------------------------------------------------------------------- |
| Missing `.returning()` on insert/update | Chain `.returning()` to get back inserted/updated rows |
| Omitting `.where()` on update/delete | Always provide `.where()` to avoid affecting all rows |
| Using `any` for query result types | Use `$inferSelect` / `$inferInsert` for type-safe results |
| Not passing `schema` to `drizzle()` client | Pass `{ schema }` to enable `db.query` relational API |
| Forgetting indexes on foreign key columns | Add explicit indexes for columns used in joins/lookups |
| Wrapping related writes without a transaction | Use `db.transaction()` for multi-table mutations |
| Using raw column names with `casing: 'snake_case'` | With casing option, define columns in camelCase without name arg |
| Declaring relations but missing the inverse | Both sides of a relation need declarations for relational queries |
| Using `serial()` in new PostgreSQL schemas | Prefer `integer().generatedAlwaysAsIdentity()` (modern approach) |
| Not handling `findFirst` returning `undefined` | Check for `undefined` before accessing properties |
| Importing column types from wrong dialect module | Use `drizzle-orm/pg-core` for PostgreSQL, `mysql-core`, `sqlite-core` |
| Using `.references()` instead of `relations()` | `.references()` is SQL foreign key; `relations()` is for query API |
## Delegation
> If the `tanstack-query` skill is available, delegate client-side caching and server state management to it.
> Otherwise, recommend: `npx skills add oakoss/agent-skills --skill tanstack-query`
>
> If the `tanstack-start` skill is available, delegate server function patterns for database access to it.
> Otherwise, recommend: `npx skills add oakoss/agent-skills --skill tanstack-start`
>
> If the `electricsql` skill is available, delegate Electric setup, shape configuration, and write patterns to it.
> Otherwise, recommend: `pnpm dlx skills add oakoss/agent-skills -s electricsql -a claude-code -y`
>
> If the `pglite` skill is available, delegate PGlite-specific configuration, extensions, and browser storage patterns to it.
> Otherwise, recommend: `pnpm dlx skills add oakoss/agent-skills -s pglite -a claude-code -y`
- **Schema validation**: Use `drizzle-zod` to generate Zod schemas from Drizzle tables for input validation
- **Query pattern discovery**: Use `Explore` agent
- **Code review**: Delegate to `code-reviewer` agent
## References
- [Schema definition, column types, constraints, indexes, and type inference](references/schema-definition.md)
- [Relational queries, SQL-like API, joins, subqueries, and aggregations](references/queries.md)
- [Insert, update, delete, upsert, and transactions](references/mutations.md)
- [Relations: one, many, nested with clauses, self-referencing](references/relations.md)
- [Migrations: drizzle-kit generate, migrate, push, pull, studio](references/migrations.md)
- [Filter operators: eq, ne, gt, lt, like, inArray, sql template](references/filters-and-operators.md)
- [Views, materialized views, generated columns, check constraints, $count, batch API](references/views-and-advanced.md)
- [ElectricSQL + PGlite integration: driver setup, schema-to-shape mapping, type inference, local sync](references/electric-integration.md)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.