@cslug/database 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/docs/README.md +28 -0
- package/docs/api.md +153 -0
- package/package.json +31 -4
- package/src/columns.ts +169 -0
- package/src/commands.ts +186 -0
- package/src/database.ts +333 -0
- package/src/encryption.ts +44 -0
- package/src/errors.ts +40 -0
- package/src/factory.ts +112 -0
- package/src/fake.ts +115 -0
- package/src/index.ts +42 -0
- package/src/migrator.ts +194 -0
- package/src/operators.ts +28 -0
- package/src/provider.ts +28 -0
- package/src/query.ts +234 -0
- package/src/relations.ts +79 -0
- package/src/repository.ts +241 -0
- package/src/sql.ts +110 -0
- package/src/table.ts +135 -0
- package/src/write.ts +10 -0
- package/stubs/factory.stub +6 -0
- package/stubs/migration.create.stub +9 -0
- package/stubs/migration.stub +5 -0
- package/stubs/repository.stub +6 -0
- package/stubs/seeder.stub +5 -0
- package/stubs/table.stub +9 -0
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/database
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
PostgreSQL on `Bun.sql`, with no ORM: typed tables, the `sql` tag, ambient transactions and advisory locks, a
|
|
4
|
+
query builder, repositories, `preload`, SQL-file migrations, factories, seeders, `idempotent()` and encrypted
|
|
5
|
+
columns.
|
|
6
|
+
|
|
7
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
8
|
+
[guide 09](../../guides/09-database.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# @cslug/database
|
|
2
|
+
|
|
3
|
+
PostgreSQL on `Bun.sql`, with no ORM and no dependency. Typed tables, the `sql` tag, ambient transactions and
|
|
4
|
+
advisory locks, the single-table query builder, repositories, `preload`, SQL-file migrations, factories,
|
|
5
|
+
seeders, `idempotent()` and encrypted columns.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { amount, currency, date, id, sql, table, text, timestamps, type Row } from '@cslug/database'
|
|
9
|
+
|
|
10
|
+
export const bookings = table('bookings', {
|
|
11
|
+
id: id(), // UUIDv7, generated by the app
|
|
12
|
+
status: text().oneOf(['requested', 'deposit_paid']).default('requested'),
|
|
13
|
+
startDate: date(), // 'YYYY-MM-DD'
|
|
14
|
+
currency: currency(),
|
|
15
|
+
deposit: amount(), // bigint minor units
|
|
16
|
+
...timestamps(),
|
|
17
|
+
})
|
|
18
|
+
export type Booking = Row<typeof bookings>
|
|
19
|
+
|
|
20
|
+
await db.transaction(async () => {
|
|
21
|
+
const booking = await db.one(sql`select * from ${bookings} where ${bookings.c.id} = ${id} for update`, bookings)
|
|
22
|
+
await db.exec(sql`update ${bookings} set status = 'deposit_paid' where ${bookings.c.id} = ${id}`)
|
|
23
|
+
await SendReceiptJob.dispatch({ bookingId: id }) // sent only after COMMIT
|
|
24
|
+
})
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- Full reference: [api.md](./api.md)
|
|
28
|
+
- Guide: [09 Database](../../../guides/09-database.md)
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# @cslug/database: API
|
|
2
|
+
|
|
3
|
+
## Columns
|
|
4
|
+
|
|
5
|
+
| Builder | SQL | TS type |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| `id()` | `uuid` primary key | `string`, UUIDv7 generated on insert |
|
|
8
|
+
| `uuid()` | `uuid` | `string` |
|
|
9
|
+
| `text()` / `varchar(n)` | `text` / `varchar(n)` | `string`; `.oneOf([...])` → union + CHECK |
|
|
10
|
+
| `integer()` / `bigint()` | | `number` / `bigint` |
|
|
11
|
+
| `numeric(p, s)` | | `string` (exact) |
|
|
12
|
+
| `boolean()` | | `boolean` |
|
|
13
|
+
| `date()` | `date` | `'YYYY-MM-DD'` |
|
|
14
|
+
| `timestamp()` | `timestamptz` | `Date` |
|
|
15
|
+
| `jsonb<T>()` / `translated()` | `jsonb` | `T` / `{ fr?, en?, … }` |
|
|
16
|
+
| `amount()` / `currency()` | `bigint` / `char(3)` | money |
|
|
17
|
+
| `shortCode('ALB')` | `text unique` | `ALB-7K2Q9F`, generated |
|
|
18
|
+
| `timestamps()` / `softDeletes()` | `created_at`, `updated_at` / `deleted_at` | `Date` / `Date \| null` |
|
|
19
|
+
|
|
20
|
+
Modifiers: `.nullable()` (columns are NOT NULL otherwise), `.default(v)`, `.defaultSql('now()')`, `.unique()`,
|
|
21
|
+
`.references(() => table, { onDelete })`, `.check(sql\`…\`)`.
|
|
22
|
+
|
|
23
|
+
## Tables
|
|
24
|
+
|
|
25
|
+
`table(name, columns, { indexes: (t) => [t.index('a', 'b'), t.unique('c')] })` → `Table` with:
|
|
26
|
+
`c.<key>` (column refs for the sql tag), `star`, `sqlNames`, `primaryKey`, `softDeletes`, `fromDb(row)`,
|
|
27
|
+
`toDb(values)`. Types: `Row<typeof t>`, `NewRow<typeof t>`. Keys are camelCase in TS, snake_case in SQL.
|
|
28
|
+
|
|
29
|
+
Reading converts driver values: `date` → `'YYYY-MM-DD'`, `bigint` → bigint, `numeric` → string, `char(n)` trimmed.
|
|
30
|
+
|
|
31
|
+
## The `sql` tag
|
|
32
|
+
|
|
33
|
+
| | |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `` sql`… ${value} …` `` | Values become `$n` parameters; tables and column refs become quoted identifiers; fragments nest |
|
|
36
|
+
| `sql.join(items, separator?)` | `in (${sql.join(ids)})` → `in ($1, $2, $3)` (Bun.sql has no array parameters) |
|
|
37
|
+
| `sql.ident('name')` | Quoted identifier |
|
|
38
|
+
| `sql.raw('desc')` | Trusted constant text |
|
|
39
|
+
| `sql.json(value)` | jsonb parameter (`($n::text)::jsonb`; bigint as string) |
|
|
40
|
+
| `fragment.compile()` | `{ text, params }` |
|
|
41
|
+
|
|
42
|
+
## `Database`
|
|
43
|
+
|
|
44
|
+
| | |
|
|
45
|
+
|---|---|
|
|
46
|
+
| `new Database({ url, pool?: { max, idleTimeout, connectTimeout }, slowQueryMs? }, logger?)` | `Bun.sql` pool with `bigint: true` |
|
|
47
|
+
| `many(q, table?)` / `one(q, table?)` / `maybeOne(q, table?)` | Rows typed by the table, or camelCased; `one` throws `RowCountError` unless exactly one |
|
|
48
|
+
| `value(q)` / `exec(q)` | First column of the first row / affected rows |
|
|
49
|
+
| `transaction(fn, { isolation?, retry? })` | Ambient: every `db` call inside uses it; nested = savepoint; `retry` on 40001/40P01 |
|
|
50
|
+
| `afterCommit` | `tx.afterCommit(fn)`, or core's `afterCommit(fn)`: runs after the outermost commit, never on rollback; hooks of a failed savepoint are dropped |
|
|
51
|
+
| `withoutTransaction(fn)` | Run on the pool inside a transaction |
|
|
52
|
+
| `advisoryLock(key, fn)` | Cluster-wide mutex (xact lock inside a transaction, session lock on a reserved connection outside) |
|
|
53
|
+
| `ping()` / `close()` | |
|
|
54
|
+
| `current` | The transaction open in this context |
|
|
55
|
+
|
|
56
|
+
Postgres aggregate types apply: `count(*)` is bigint (cast `::int`), `sum(bigint)` is numeric (cast `::bigint`).
|
|
57
|
+
|
|
58
|
+
**Implementation note:** `Bun.sql` runs `begin()`/`savepoint()` callbacks outside the caller's async context;
|
|
59
|
+
`transaction()` re-enters the context (and sets `tx` in it), so request ids, locale and the transaction itself are
|
|
60
|
+
visible inside. Tested with 200 concurrent units.
|
|
61
|
+
|
|
62
|
+
## Errors
|
|
63
|
+
|
|
64
|
+
`QueryError` (`sqlState`, `constraint`, original error as `cause`, SQL text but never parameters in the message),
|
|
65
|
+
`UniqueViolationError` (23505), `SerializationError` (40001/40P01), `RowCountError`.
|
|
66
|
+
|
|
67
|
+
## `DatabaseProvider`
|
|
68
|
+
|
|
69
|
+
Binds `Database` from `config('database')`, pings at boot, closes at shutdown.
|
|
70
|
+
|
|
71
|
+
## Query builder (one table)
|
|
72
|
+
|
|
73
|
+
`repo.where({...})` / `repo.query()` → `Query<T, R>` (immutable).
|
|
74
|
+
|
|
75
|
+
| | |
|
|
76
|
+
|---|---|
|
|
77
|
+
| `where({ key: value \| null \| op })` | AND of conditions; `null` → IS NULL; `undefined` keys ignored (so `...(cond && {…})` works). Keys and value types are checked against the table |
|
|
78
|
+
| operators | `eq ne gt gte lt lte between inList notIn like ilike isNull notNull not(op)`. `inList([])` matches nothing |
|
|
79
|
+
| `orWhere({...})` / `whereSql(sql\`…\`)` | OR group / raw condition |
|
|
80
|
+
| `orderBy(key, 'asc' \| 'desc', { nulls: 'first' \| 'last' })` | Chainable |
|
|
81
|
+
| `limit`, `offset`, `select(...keys)` | `select` narrows the row type to `Pick<Row, K>` |
|
|
82
|
+
| `lockForUpdate({ skipLocked?, noWait? })` | Must be inside a transaction (clear error otherwise) |
|
|
83
|
+
| `withTrashed()` / `onlyTrashed()` | Soft-deleted rows are hidden by default when the table has `deletedAt` |
|
|
84
|
+
| `all()`, `first()`, `count()`, `exists()` | |
|
|
85
|
+
| `update(values)` / `delete()` / `forceDelete()` | Bulk; return the number of rows; `updatedAt` refreshed; `delete` is soft when possible |
|
|
86
|
+
| `paginate(page, perPage)` | `{ data, meta: { page, perPage, total, lastPage } }` |
|
|
87
|
+
| `cursor({ after?, limit, orderBy? })` | Keyset pagination → `{ data, next }` |
|
|
88
|
+
| `each({ batch? })` | Async iterator over every matching row |
|
|
89
|
+
| `toSql()` | The SELECT as a fragment |
|
|
90
|
+
|
|
91
|
+
## `Repository(table)`
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
@inject()
|
|
95
|
+
export class BookingRepository extends Repository(bookings) { /* domain queries */ }
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The base resolves `Database` itself. Methods: `find`, `findOrFail` (`NotFoundError`, code `<singular>.not_found`),
|
|
99
|
+
`findBy`, `findByOrFail`, `existsBy`, `count`, `all`, `create` / `createMany` (generated ids, short codes,
|
|
100
|
+
timestamps, defaults; `RETURNING *`), `update(id, values)`, `upsert(values, { conflict, update? })`,
|
|
101
|
+
`delete` (soft if possible), `forceDelete`, `restore`, `lockForUpdate(id, opts)`, `paginate({ page, perPage, where, orderBy, dir })`,
|
|
102
|
+
`where`, `query`, `withTrashed`, `onlyTrashed`, `using(tx)` (explicit transaction), `table`, `db`.
|
|
103
|
+
|
|
104
|
+
## `preload`
|
|
105
|
+
|
|
106
|
+
`preload(rows, { operator: belongsTo(operators, 'operatorId'), todos: hasMany(todos, 'operatorId', { orderBy }) })`:
|
|
107
|
+
one query per relation, typed results (`Row | null` for belongsTo, `Row[]` for hasMany).
|
|
108
|
+
|
|
109
|
+
## Migrations
|
|
110
|
+
|
|
111
|
+
SQL files `database/migrations/YYYYMMDD_HHMMSS_name.sql` with `-- up` / `-- down` sections (several statements
|
|
112
|
+
and `$$` bodies are fine). A first line `-- cslug:no-transaction` runs the file outside a transaction (needed for
|
|
113
|
+
`create index concurrently`).
|
|
114
|
+
|
|
115
|
+
| `Migrator(db, { paths?, env?, log?, packageMigrations? })` | `packageMigrations` defaults to the folders added with `addMigrations()` |
|
|
116
|
+
|---|---|
|
|
117
|
+
| `migrate()` | Pending migrations, each in its own transaction, recorded in `cslug_migrations` with a batch number. The whole run holds an advisory lock: concurrent runs execute each migration **once** |
|
|
118
|
+
| `rollback({ steps? })` | Undo the last `steps` batches (default 1), newest first; fails clearly without a `-- down` |
|
|
119
|
+
| `status()` | `{ name, ran, batch?, ranAt? }[]` |
|
|
120
|
+
| `fresh()` | Drop the public schema and migrate; **refused when `env` is `production`** |
|
|
121
|
+
| `Migrator.create(dir, name)` | Writes an empty, timestamped file |
|
|
122
|
+
| `FRAMEWORK_MIGRATIONS` | cslug's own (e.g. `cslug_idempotency`), always run first |
|
|
123
|
+
|
|
124
|
+
A failing migration is rolled back entirely and the error names the file. (`cslug migrate*` commands arrive
|
|
125
|
+
with `@cslug/cli` in M3. The table differ, `--from-tables`, comes later.)
|
|
126
|
+
|
|
127
|
+
## Factories and seeders
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
export const TodoFactory = factory(todos, ({ seq, fake, clock }) => ({
|
|
131
|
+
userId: () => UserFactory.create().then((u) => u.id), // lazy, may be async
|
|
132
|
+
title: `Todo ${seq}`,
|
|
133
|
+
})).state('done', ({ clock }) => ({ completedAt: clock.now() }))
|
|
134
|
+
|
|
135
|
+
await TodoFactory.for({ userId: me.id }).state('done').createMany(3)
|
|
136
|
+
await TodoFactory.make() // attributes only
|
|
137
|
+
await TodoFactory.on(db).create() // a specific database
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`fake` (`Fake`, seeded, deterministic): `name firstName lastName company email word words sentence int bool pick
|
|
141
|
+
digits phone(country) date(from, to) passwordHash(plain)`. `seeder(async () => …)` marks a seeder for `cslug db:seed`.
|
|
142
|
+
|
|
143
|
+
## `db.idempotent(key, fn, { scope? })`
|
|
144
|
+
|
|
145
|
+
Runs `fn` once per key under an advisory lock; the result is stored as JSON and every call, the first one
|
|
146
|
+
included, returns it as `Json<T>` (bigint and Date as strings). Inside a transaction the record commits or rolls
|
|
147
|
+
back with your changes.
|
|
148
|
+
|
|
149
|
+
## Encrypted columns
|
|
150
|
+
|
|
151
|
+
`text().encrypted()`: AES-256-GCM, key derived from `APP_KEY` (set by `DatabaseProvider` from `config('app.key')`,
|
|
152
|
+
or `setEncryptionKey()`), random IV per value, stored as `v1.<iv>.<tag>.<ciphertext>`. Decrypted on read; using
|
|
153
|
+
the column in `where` throws (random IVs make it unsearchable). A wrong key fails loudly (`db.decrypt_failed`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/database",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "PostgreSQL on Bun.sql: typed tables, query builder, sql tag, repositories, migrations.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/database"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/database",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"docs",
|
|
24
|
+
"stubs",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@cslug/core": "0.2.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/columns.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { SqlFragment } from './sql'
|
|
2
|
+
|
|
3
|
+
export type ColumnKind =
|
|
4
|
+
| 'uuid'
|
|
5
|
+
| 'text'
|
|
6
|
+
| 'varchar'
|
|
7
|
+
| 'integer'
|
|
8
|
+
| 'bigint'
|
|
9
|
+
| 'numeric'
|
|
10
|
+
| 'boolean'
|
|
11
|
+
| 'date'
|
|
12
|
+
| 'timestamp'
|
|
13
|
+
| 'jsonb'
|
|
14
|
+
| 'char'
|
|
15
|
+
|
|
16
|
+
export type ColumnDef = {
|
|
17
|
+
kind: ColumnKind
|
|
18
|
+
sqlType: string
|
|
19
|
+
nullable: boolean
|
|
20
|
+
primary?: boolean
|
|
21
|
+
unique?: boolean
|
|
22
|
+
/** A value the app generates on insert (UUIDv7 ids, short codes, timestamps). */
|
|
23
|
+
generate?: () => unknown
|
|
24
|
+
/** SQL default (for migrations). */
|
|
25
|
+
defaultSql?: string
|
|
26
|
+
/** Static default used on insert when the value is missing. */
|
|
27
|
+
defaultValue?: unknown
|
|
28
|
+
oneOf?: readonly string[]
|
|
29
|
+
references?: { table: () => { name: string }; column: string; onDelete?: string }
|
|
30
|
+
check?: SqlFragment<unknown>
|
|
31
|
+
/** Set on update automatically (updatedAt). */
|
|
32
|
+
touch?: boolean
|
|
33
|
+
/** Stored encrypted (AES-256-GCM with APP_KEY); decrypted on read; cannot be queried by value. */
|
|
34
|
+
encrypted?: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A column. `T` is its TypeScript value type; `N` whether it accepts null; `D` whether inserts may omit it
|
|
39
|
+
* (it has a default or is generated).
|
|
40
|
+
*/
|
|
41
|
+
export class Column<T, N extends boolean = false, D extends boolean = false> {
|
|
42
|
+
declare readonly _type: T
|
|
43
|
+
declare readonly _nullable: N
|
|
44
|
+
declare readonly _hasDefault: D
|
|
45
|
+
|
|
46
|
+
constructor(readonly def: ColumnDef) {}
|
|
47
|
+
|
|
48
|
+
private with<T2 = T, N2 extends boolean = N, D2 extends boolean = D>(patch: Partial<ColumnDef>): Column<T2, N2, D2> {
|
|
49
|
+
return new Column<T2, N2, D2>({ ...this.def, ...patch })
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Columns are NOT NULL unless marked nullable. */
|
|
53
|
+
nullable(): Column<T, true, true> {
|
|
54
|
+
return this.with<T, true, true>({ nullable: true })
|
|
55
|
+
}
|
|
56
|
+
/** Default used on insert when the value is missing (also written into migrations). */
|
|
57
|
+
default(value: T): Column<T, N, true> {
|
|
58
|
+
return this.with<T, N, true>({ defaultValue: value })
|
|
59
|
+
}
|
|
60
|
+
/** SQL default, e.g. `defaultSql('now()')`, for migrations; inserts may omit the column. */
|
|
61
|
+
defaultSql(expression: string): Column<T, N, true> {
|
|
62
|
+
return this.with<T, N, true>({ defaultSql: expression })
|
|
63
|
+
}
|
|
64
|
+
unique(): this {
|
|
65
|
+
return this.with({ unique: true }) as this
|
|
66
|
+
}
|
|
67
|
+
references(
|
|
68
|
+
table: () => { name: string },
|
|
69
|
+
options: { column?: string; onDelete?: 'cascade' | 'restrict' | 'set null' } = {},
|
|
70
|
+
): this {
|
|
71
|
+
return this.with({ references: { table, column: options.column ?? 'id', onDelete: options.onDelete } }) as this
|
|
72
|
+
}
|
|
73
|
+
check(expression: SqlFragment<unknown>): this {
|
|
74
|
+
return this.with({ check: expression }) as this
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A text column restricted to values: typed as the union and checked by a CHECK constraint. */
|
|
79
|
+
export class TextColumn<T extends string = string, N extends boolean = false, D extends boolean = false> extends Column<
|
|
80
|
+
T,
|
|
81
|
+
N,
|
|
82
|
+
D
|
|
83
|
+
> {
|
|
84
|
+
oneOf<const V extends readonly string[]>(values: V): TextColumn<V[number], N, D> {
|
|
85
|
+
return new TextColumn<V[number], N, D>({ ...this.def, oneOf: values })
|
|
86
|
+
}
|
|
87
|
+
override nullable(): TextColumn<T, true, true> {
|
|
88
|
+
return new TextColumn<T, true, true>({ ...this.def, nullable: true })
|
|
89
|
+
}
|
|
90
|
+
override default(value: T): TextColumn<T, N, true> {
|
|
91
|
+
return new TextColumn<T, N, true>({ ...this.def, defaultValue: value })
|
|
92
|
+
}
|
|
93
|
+
/** Store encrypted at rest (AES-256-GCM with APP_KEY). Values are decrypted on read and cannot be searched. */
|
|
94
|
+
encrypted(): TextColumn<T, N, D> {
|
|
95
|
+
return new TextColumn<T, N, D>({ ...this.def, encrypted: true })
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const col = <T>(kind: ColumnKind, sqlType: string, extra: Partial<ColumnDef> = {}) =>
|
|
100
|
+
new Column<T>({ kind, sqlType, nullable: false, ...extra })
|
|
101
|
+
|
|
102
|
+
/** Primary key: UUIDv7 generated by the app (ids exist before insert; good index locality). */
|
|
103
|
+
export const id = () =>
|
|
104
|
+
new Column<string, false, true>({
|
|
105
|
+
kind: 'uuid',
|
|
106
|
+
sqlType: 'uuid',
|
|
107
|
+
nullable: false,
|
|
108
|
+
primary: true,
|
|
109
|
+
generate: () => Bun.randomUUIDv7(),
|
|
110
|
+
})
|
|
111
|
+
export const uuid = () => col<string>('uuid', 'uuid')
|
|
112
|
+
export const text = () => new TextColumn<string>({ kind: 'text', sqlType: 'text', nullable: false })
|
|
113
|
+
export const varchar = (length: number) =>
|
|
114
|
+
new TextColumn<string>({ kind: 'varchar', sqlType: `varchar(${length})`, nullable: false })
|
|
115
|
+
export const integer = () => col<number>('integer', 'integer')
|
|
116
|
+
export const bigint = () => col<bigint>('bigint', 'bigint')
|
|
117
|
+
/** Exact decimal, returned as a string (`'12.50'`). */
|
|
118
|
+
export const numeric = (precision: number, scale: number) => col<string>('numeric', `numeric(${precision},${scale})`)
|
|
119
|
+
export const boolean = () => col<boolean>('boolean', 'boolean')
|
|
120
|
+
/** A calendar date, as `'YYYY-MM-DD'`. */
|
|
121
|
+
export const date = () => col<string>('date', 'date')
|
|
122
|
+
/** An instant, `timestamptz` (stored in UTC), as a `Date`. */
|
|
123
|
+
export const timestamp = () => col<Date>('timestamp', 'timestamptz')
|
|
124
|
+
export const jsonb = <T>() => col<T>('jsonb', 'jsonb')
|
|
125
|
+
/** Money in minor units. */
|
|
126
|
+
export const amount = () => col<bigint>('bigint', 'bigint')
|
|
127
|
+
/** ISO 4217 code. */
|
|
128
|
+
export const currency = () => new TextColumn<string>({ kind: 'char', sqlType: 'char(3)', nullable: false })
|
|
129
|
+
/** Translated content: `{ fr, en, it }` as jsonb. */
|
|
130
|
+
export const translated = () => col<Partial<Record<string, string>>>('jsonb', 'jsonb')
|
|
131
|
+
|
|
132
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
|
|
133
|
+
/** A short public reference, generated on insert: `shortCode('ALB')` → `ALB-7K2Q9F`. Unique. */
|
|
134
|
+
export const shortCode = (prefix: string, length = 6) =>
|
|
135
|
+
new Column<string, false, true>({
|
|
136
|
+
kind: 'text',
|
|
137
|
+
sqlType: 'text',
|
|
138
|
+
nullable: false,
|
|
139
|
+
unique: true,
|
|
140
|
+
generate: () => {
|
|
141
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length))
|
|
142
|
+
return `${prefix}-${[...bytes].map((b) => CROCKFORD[b % 32]).join('')}`
|
|
143
|
+
},
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
/** `createdAt` and `updatedAt` (timestamptz), set by the app; `updatedAt` is refreshed on every update. */
|
|
147
|
+
export const timestamps = () => ({
|
|
148
|
+
createdAt: new Column<Date, false, true>({
|
|
149
|
+
kind: 'timestamp',
|
|
150
|
+
sqlType: 'timestamptz',
|
|
151
|
+
nullable: false,
|
|
152
|
+
defaultSql: 'now()',
|
|
153
|
+
generate: () => new Date(),
|
|
154
|
+
}),
|
|
155
|
+
updatedAt: new Column<Date, false, true>({
|
|
156
|
+
kind: 'timestamp',
|
|
157
|
+
sqlType: 'timestamptz',
|
|
158
|
+
nullable: false,
|
|
159
|
+
defaultSql: 'now()',
|
|
160
|
+
generate: () => new Date(),
|
|
161
|
+
touch: true,
|
|
162
|
+
}),
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
/** `deletedAt` (nullable timestamptz): repositories soft-delete and hide deleted rows. */
|
|
166
|
+
export const softDeletes = () => ({ deletedAt: timestamp().nullable() })
|
|
167
|
+
|
|
168
|
+
// biome-ignore lint/suspicious/noExplicitAny: any column
|
|
169
|
+
export type AnyColumn = Column<any, boolean, boolean>
|
package/src/commands.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { arg, Command, flag, names } from '@cslug/core'
|
|
4
|
+
import { Database } from './database'
|
|
5
|
+
import { isSeeder } from './factory'
|
|
6
|
+
import { Migrator } from './migrator'
|
|
7
|
+
|
|
8
|
+
const STUBS = join(import.meta.dir, '../stubs')
|
|
9
|
+
|
|
10
|
+
abstract class DatabaseCommand extends Command {
|
|
11
|
+
protected migrator(): Migrator {
|
|
12
|
+
return new Migrator(this.app.resolve(Database), {
|
|
13
|
+
paths: [join(this.app.rootDir, 'database/migrations')],
|
|
14
|
+
env: String(this.app.config('app.env') ?? 'development'),
|
|
15
|
+
log: this.log,
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
protected get production(): boolean {
|
|
19
|
+
return this.app.config('app.env') === 'production'
|
|
20
|
+
}
|
|
21
|
+
/** Destructive commands in production need `--force`. */
|
|
22
|
+
protected guard(force: boolean, what: string): boolean {
|
|
23
|
+
if (this.production && !force) {
|
|
24
|
+
this.error(`${what} in production: add --force if you really mean it`)
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
return true
|
|
28
|
+
}
|
|
29
|
+
protected async seed(only?: string): Promise<number> {
|
|
30
|
+
const dir = join(this.app.rootDir, 'database/seeders')
|
|
31
|
+
if (!existsSync(dir)) {
|
|
32
|
+
this.warn('No database/seeders folder')
|
|
33
|
+
return 0
|
|
34
|
+
}
|
|
35
|
+
// database-seeder.ts runs alone (it calls the others) unless one is named
|
|
36
|
+
const files = readdirSync(dir).filter((f) => f.endsWith('.ts'))
|
|
37
|
+
const chosen = only
|
|
38
|
+
? files.filter((f) => f === `${names(only, 'seeder').file}.ts` || f === `${only}.ts`)
|
|
39
|
+
: files.includes('database-seeder.ts')
|
|
40
|
+
? ['database-seeder.ts']
|
|
41
|
+
: files.sort()
|
|
42
|
+
if (!chosen.length) {
|
|
43
|
+
this.error(`No seeder ${only}`)
|
|
44
|
+
return 1
|
|
45
|
+
}
|
|
46
|
+
for (const f of chosen) {
|
|
47
|
+
const mod = await import(join(dir, f))
|
|
48
|
+
if (!isSeeder(mod.default)) throw new Error(`${f} must \`export default seeder(async () => { … })\``)
|
|
49
|
+
await this.app.resolve(Database).transaction(() => mod.default.run())
|
|
50
|
+
this.success(`seeded ${f.replace(/\.ts$/, '')}`)
|
|
51
|
+
}
|
|
52
|
+
return 0
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** `cslug migrate`: run pending migrations (advisory-locked: concurrent runs execute each once). */
|
|
57
|
+
export class MigrateCommand extends DatabaseCommand {
|
|
58
|
+
static signature = 'migrate'
|
|
59
|
+
static description = 'Run pending migrations'
|
|
60
|
+
static args = {
|
|
61
|
+
seed: flag.boolean().describe('Run the seeders afterwards'),
|
|
62
|
+
force: flag.boolean().describe('Required with --seed in production'),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async handle({ seed, force }: Command.Args<typeof MigrateCommand>) {
|
|
66
|
+
const ran = await this.migrator().migrate()
|
|
67
|
+
if (!ran.length) this.info('Nothing to migrate')
|
|
68
|
+
for (const name of ran) this.success(name)
|
|
69
|
+
if (seed) return this.guard(force, 'Seeding') ? this.seed() : 1
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class MigrateStatusCommand extends DatabaseCommand {
|
|
74
|
+
static signature = 'migrate:status'
|
|
75
|
+
static description = 'Which migrations ran, in which batch'
|
|
76
|
+
static args = { json: flag.boolean() }
|
|
77
|
+
|
|
78
|
+
async handle({ json }: Command.Args<typeof MigrateStatusCommand>) {
|
|
79
|
+
const status = await this.migrator().status()
|
|
80
|
+
if (json) return this.line(JSON.stringify(status))
|
|
81
|
+
this.table(
|
|
82
|
+
status.map((s) => ({ migration: s.name, ran: s.ran ? 'yes' : 'pending', batch: s.batch ?? '', at: s.ranAt })),
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export class MigrateRollbackCommand extends DatabaseCommand {
|
|
88
|
+
static signature = 'migrate:rollback'
|
|
89
|
+
static description = 'Roll back the last batch (or --step n migrations)'
|
|
90
|
+
static args = { step: flag.number().optional().describe('Number of migrations'), force: flag.boolean() }
|
|
91
|
+
|
|
92
|
+
async handle({ step, force }: Command.Args<typeof MigrateRollbackCommand>) {
|
|
93
|
+
if (!this.guard(force, 'Rolling back')) return 1
|
|
94
|
+
const rolled = await this.migrator().rollback({ steps: step })
|
|
95
|
+
if (!rolled.length) this.info('Nothing to roll back')
|
|
96
|
+
for (const name of rolled) this.success(`rolled back ${name}`)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export class MigrateFreshCommand extends DatabaseCommand {
|
|
101
|
+
static signature = 'migrate:fresh'
|
|
102
|
+
static description = 'Drop every table and migrate from scratch (refused in production)'
|
|
103
|
+
static args = { seed: flag.boolean().describe('Run the seeders afterwards') }
|
|
104
|
+
|
|
105
|
+
async handle({ seed }: Command.Args<typeof MigrateFreshCommand>) {
|
|
106
|
+
if (this.production) {
|
|
107
|
+
this.error('migrate:fresh drops every table; it is refused in production')
|
|
108
|
+
return 1
|
|
109
|
+
}
|
|
110
|
+
for (const name of await this.migrator().fresh()) this.success(name)
|
|
111
|
+
if (seed) return this.seed()
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class DbSeedCommand extends DatabaseCommand {
|
|
116
|
+
static signature = 'db:seed'
|
|
117
|
+
static description = 'Run database/seeders/database-seeder.ts (or the one named)'
|
|
118
|
+
static args = {
|
|
119
|
+
seeder: arg.string().optional().describe('e.g. pilot (database/seeders/pilot-seeder.ts)'),
|
|
120
|
+
force: flag.boolean(),
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
handle({ seeder, force }: Command.Args<typeof DbSeedCommand>) {
|
|
124
|
+
return this.guard(force, 'Seeding') ? this.seed(seeder) : 1
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** `cslug make:migration add_claims_index` → database/migrations/20261126_101500_add_claims_index.sql. */
|
|
129
|
+
export class MakeMigrationCommand extends Command {
|
|
130
|
+
static signature = 'make:migration'
|
|
131
|
+
static description = 'Create an empty SQL migration'
|
|
132
|
+
static boot = false
|
|
133
|
+
static args = { name: arg.string().describe('snake_case, e.g. create_claims') }
|
|
134
|
+
|
|
135
|
+
handle({ name }: Command.Args<typeof MakeMigrationCommand>) {
|
|
136
|
+
const now = this.clock.now()
|
|
137
|
+
const pad = (n: number) => String(n).padStart(2, '0')
|
|
138
|
+
const stamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}_${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`
|
|
139
|
+
const snakeName = names(name).snake
|
|
140
|
+
const table = /^create_(\w+)$/.exec(snakeName)?.[1]
|
|
141
|
+
return this.generate(
|
|
142
|
+
STUBS,
|
|
143
|
+
table ? 'migration.create.stub' : 'migration.stub',
|
|
144
|
+
`database/migrations/${stamp}_${snakeName}.sql`,
|
|
145
|
+
{ table: table ?? '' },
|
|
146
|
+
)
|
|
147
|
+
? 0
|
|
148
|
+
: 1
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const makeArgs = { name: arg.string().describe('e.g. Claim'), force: flag.boolean() }
|
|
153
|
+
const make = (kind: 'table' | 'repository' | 'factory' | 'seeder', dir: string) =>
|
|
154
|
+
class extends Command {
|
|
155
|
+
static signature = `make:${kind}`
|
|
156
|
+
static description = `Create a ${kind}`
|
|
157
|
+
static boot = false
|
|
158
|
+
static args = makeArgs
|
|
159
|
+
handle({ name, force }: Command.Args<{ args: typeof makeArgs }>) {
|
|
160
|
+
const n = names(name, kind)
|
|
161
|
+
const plural = n.snake.endsWith('s') ? n.snake : `${n.snake}s`
|
|
162
|
+
const tableName = names(name, 'table')
|
|
163
|
+
return this.generate(
|
|
164
|
+
STUBS,
|
|
165
|
+
`${kind}.stub`,
|
|
166
|
+
`${dir}/${n.file}.ts`,
|
|
167
|
+
{ ...n, plural, tableVar: `${tableName.camel}s`.replace(/ss$/, 's'), tableFile: tableName.file },
|
|
168
|
+
force,
|
|
169
|
+
)
|
|
170
|
+
? 0
|
|
171
|
+
: 1
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export const databaseCommands = [
|
|
176
|
+
MigrateCommand,
|
|
177
|
+
MigrateStatusCommand,
|
|
178
|
+
MigrateRollbackCommand,
|
|
179
|
+
MigrateFreshCommand,
|
|
180
|
+
DbSeedCommand,
|
|
181
|
+
MakeMigrationCommand,
|
|
182
|
+
make('table', 'app/tables'),
|
|
183
|
+
make('repository', 'app/repositories'),
|
|
184
|
+
make('factory', 'database/factories'),
|
|
185
|
+
make('seeder', 'database/seeders'),
|
|
186
|
+
]
|