Postgres con Drizzle: cliente compartido, esquemas por módulo, transacciones e IDs ULID
Instalar
genpm add @core/dbQué obtienes
- Código en src/lib/db/, 8 archivos. (8,2 kB)
- Reglas de IA en src/lib/db/AGENTS.md, más archivos de reglas para tu IDE.
- Variables añadidas a .env.example: DATABASE_URL.
README
@core/db
Postgres with Drizzle: shared client, per-module schemas, transactions and ULID ids
A GenPM module: source code + AI rules + MCP config, injected into your project instead of hidden in node_modules. The code lands in src/lib/db, pinned to a verified commit, and you own it.
Install
genpm add @core/dbNo genpm yet? curl -fsSL https://genpm.net/install.sh | sh (macOS/Linux), irm https://genpm.net/install.ps1 | iex (Windows), or one-off with npx @genpm-net/cli add @core/db.
Or let your AI agent do it: run genpm mcp setup once, then ask "add @core/db with genpm" in Claude Code, Cursor, VS Code, Windsurf, Codex or Gemini CLI. It shows you a dry-run plan before writing anything.
What it does
Shared Postgres access for every module: one Drizzle client, per-module schemas, transactions, ULID ids and standard timestamps. It owns no tables itself. Not an ORM wrapper: use Drizzle's query builder directly.
Setup
After genpm add, follow these steps (your AI agent finds the same steps in src/lib/db/AGENTS.md and can do them for you):
- Set
DATABASE_URL(any Postgres: local, Neon, Supabase, RDS). - GenPM modules import each other with
.tsextensions: make suretsconfig.jsonhas"allowImportingTsExtensions": true(requires"noEmit": true, the default in Next.js, Vite and tsx projects). - Install the npm deps if GenPM did not:
drizzle-orm,postgres, anddrizzle-kitas a dev dependency. - Add scripts to
package.json:"db:generate": "drizzle-kit generate --config src/lib/db/drizzle.config.ts","db:migrate": "drizzle-kit migrate --config src/lib/db/drizzle.config.ts". - Run
db:generatethendb:migrateafter installing any module that has aschema.ts.drizzle-kitreadsDATABASE_URLfrom the environment or.env, not.env.local: runnode --env-file=.env.local node_modules/drizzle-kit/bin.cjs migrate --config …(the real entry point: with pnpm.bin/drizzle-kitis a shell script). Same fortsxscripts:npx tsx --env-file=.env.local <script>(or export the variable) when the value lives there. - Query from app code:
import { getDb } from './lib/db/index.ts'; const rows = await getDb().select().from(users); - Another driver (Neon serverless, PGlite in tests): build it with Drizzle and call
setDb(db)once at startup.
What's inside
Paths are relative to src/lib/db.
index.ts— public API:getDb,createDb,setDb,withTransaction,primaryId,timestamps,newId,ulid; typesDb,Tx,Executor.client.ts— lazy client fromDATABASE_URL(postgres-js).columns.ts—primaryId(prefix)andtimestampscolumn helpers.drizzle.config.ts— drizzle-kit config that collectssrc/lib/*/schema.ts.
At a glance
- npm dependencies (proposed, never installed without asking):
drizzle-orm,postgres - Environment variables (added to
.env.example):DATABASE_URL - AI rules:
AGENTS.md, loaded by your agent only when it works insrc/lib/db
Security
GenPM installs a 40-character commit SHA (never a branch), verifies an Ed25519-signed manifest, never runs install scripts and scans AI rules for prompt injection. Details: genpm.net/docs/security.
License
Esto es exactamente lo que lee tu IA cuando trabaja en src/lib/db. No se añade nada más a su contexto.
@core/db — rules for AI agents
Purpose
Shared Postgres access for every module: one Drizzle client, per-module schemas, transactions, ULID ids and standard timestamps. It owns no tables itself. Not an ORM wrapper: use Drizzle's query builder directly.
Map
index.ts— public API:getDb,createDb,setDb,withTransaction,primaryId,timestamps,newId,ulid; typesDb,Tx,Executor.client.ts— lazy client fromDATABASE_URL(postgres-js).columns.ts—primaryId(prefix)andtimestampscolumn helpers.drizzle.config.ts— drizzle-kit config that collectssrc/lib/*/schema.ts.
Integration
- Set
DATABASE_URL(any Postgres: local, Neon, Supabase, RDS). - GenPM modules import each other with
.tsextensions: make suretsconfig.jsonhas"allowImportingTsExtensions": true(requires"noEmit": true, the default in Next.js, Vite and tsx projects). - Install the npm deps if GenPM did not:
drizzle-orm,postgres, anddrizzle-kitas a dev dependency. - Add scripts to
package.json:"db:generate": "drizzle-kit generate --config src/lib/db/drizzle.config.ts","db:migrate": "drizzle-kit migrate --config src/lib/db/drizzle.config.ts". - Run
db:generatethendb:migrateafter installing any module that has aschema.ts.drizzle-kitreadsDATABASE_URLfrom the environment or.env, not.env.local: runnode --env-file=.env.local node_modules/drizzle-kit/bin.cjs migrate --config …(the real entry point: with pnpm.bin/drizzle-kitis a shell script). Same fortsxscripts:npx tsx --env-file=.env.local <script>(or export the variable) when the value lives there. - Query from app code:
import { getDb } from './lib/db/index.ts'; const rows = await getDb().select().from(users); - Another driver (Neon serverless, PGlite in tests): build it with Drizzle and call
setDb(db)once at startup.
Conventions
- Each module defines its tables in its own
src/lib/<module>/schema.ts. Never put tables insrc/lib/db. - Table names are prefixed with the module when ambiguous (
auth_sessions, notsessions). - Primary keys:
id: primaryId('<3-4 letter prefix>'); spread...timestampsin every table. - Functions that write accept an optional
Executor(dbortx) so callers can compose them inwithTransaction. - Money as integer minor units; times as
timestamp with time zone.
Don't
- Don't edit or reference another module's tables except through that module's exported functions.
- Don't create a second client or connection pool; use
getDb(). - Don't log
DATABASE_URLor query parameters that may hold secrets. - Don't use
drizzle-kit pushagainst production; generate and review migrations.
# @core/db — rules for AI agents
## Purpose
Shared Postgres access for every module: one Drizzle client, per-module schemas, transactions, ULID ids and standard
timestamps. It owns no tables itself. Not an ORM wrapper: use Drizzle's query builder directly.
## Map
- `index.ts` — public API: `getDb`, `createDb`, `setDb`, `withTransaction`, `primaryId`, `timestamps`, `newId`, `ulid`; types `Db`, `Tx`, `Executor`.
- `client.ts` — lazy client from `DATABASE_URL` (postgres-js).
- `columns.ts` — `primaryId(prefix)` and `timestamps` column helpers.
- `drizzle.config.ts` — drizzle-kit config that collects `src/lib/*/schema.ts`.
## Integration
1. Set `DATABASE_URL` (any Postgres: local, Neon, Supabase, RDS).
2. GenPM modules import each other with `.ts` extensions: make sure `tsconfig.json` has `"allowImportingTsExtensions": true`
(requires `"noEmit": true`, the default in Next.js, Vite and tsx projects).
3. Install the npm deps if GenPM did not: `drizzle-orm`, `postgres`, and `drizzle-kit` as a dev dependency.
4. Add scripts to `package.json`:
`"db:generate": "drizzle-kit generate --config src/lib/db/drizzle.config.ts"`,
`"db:migrate": "drizzle-kit migrate --config src/lib/db/drizzle.config.ts"`.
5. Run `db:generate` then `db:migrate` after installing any module that has a `schema.ts`. `drizzle-kit` reads
`DATABASE_URL` from the environment or `.env`, not `.env.local`: run `node --env-file=.env.local node_modules/drizzle-kit/bin.cjs migrate --config …`
(the real entry point: with pnpm `.bin/drizzle-kit` is a shell script). Same for `tsx` scripts: `npx tsx --env-file=.env.local <script>`
(or export the variable) when the value lives there.
6. Query from app code:
```ts
import { getDb } from './lib/db/index.ts';
const rows = await getDb().select().from(users);
```
7. Another driver (Neon serverless, PGlite in tests): build it with Drizzle and call `setDb(db)` once at startup.
## Conventions
- Each module defines its tables in its own `src/lib/<module>/schema.ts`. Never put tables in `src/lib/db`.
- Table names are prefixed with the module when ambiguous (`auth_sessions`, not `sessions`).
- Primary keys: `id: primaryId('<3-4 letter prefix>')`; spread `...timestamps` in every table.
- Functions that write accept an optional `Executor` (`db` or `tx`) so callers can compose them in `withTransaction`.
- Money as integer minor units; times as `timestamp with time zone`.
## Don't
- Don't edit or reference another module's tables except through that module's exported functions.
- Don't create a second client or connection pool; use `getDb()`.
- Don't log `DATABASE_URL` or query parameters that may hold secrets.
- Don't use `drizzle-kit push` against production; generate and review migrations.
El árbol exacto que se inyectará, tras aplicar .genpmignore. Anclado a
// Configuración de drizzle-kit para TODA la app: recoge el `schema.ts` de cada módulo de src/lib, así que añadir un
// módulo no exige editar este archivo. Uso: `npx drizzle-kit generate --config src/lib/db/drizzle.config.ts`.
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'postgresql',
schema: './src/lib/*/schema.ts',
out: './drizzle',
dbCredentials: { url: process.env.DATABASE_URL ?? '' },
strict: true,
verbose: true,
});
Este paquete no declara servidores MCP.
- genpm
- ninguno
- propuesta
- GenPM propone el comando npm y solo lo ejecuta si dices que sí.
- Usado por (29)
- @core/admin ^1.0.0@core/ai ^1.0.0@core/antispam ^1.0.0@core/auth ^1.0.0@core/billing ^1.0.0@core/blocks ^1.0.0@core/blog ^1.0.0@core/cart ^1.0.0@core/catalog ^1.0.0@core/comments ^1.0.0@core/consent ^1.0.0@core/content ^1.0.0@core/discounts ^1.0.0@core/experiments ^1.0.0@core/forms ^1.0.0@core/invoices ^1.0.0@core/jobs ^1.0.0@core/media ^1.0.0@core/newsletter ^1.0.0@core/orders ^1.0.0
- escaneo
- escaneo superado · 0 hallazgos
- commit
- v1.0.3 → 25313384ee33df13103f8ecd8698781c866cbd43 · verificado tras la descarga
- scripts
- Ninguno. GenPM nunca ejecuta código del paquete.
- licencia
- MIT
- Calidad
- 100/100
- Licencia reconocidacumplido
- AGENTS.md explica su propósitocumplido
- AGENTS.md tiene pasos de integracióncumplido
- AGENTS.md lista convenciones o prohibicionescumplido
- Incluye testscumplido
- Escaneo de seguridad superadocumplido
- Publicado en los últimos 6 mesescumplido
- Publicador verificadocumplido
- Resumen y palabras clavecumplido
- reporte
- ¿Ves algo raro?