@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.
@@ -0,0 +1,241 @@
1
+ import { CslugError, NotFoundError, resolve } from '@cslug/core'
2
+ import { Database, type Queryable, type Transaction } from './database'
3
+ import { Query, setClause, type Where, whereSql } from './query'
4
+ import { sql } from './sql'
5
+ import type { NewRow, Row, Table } from './table'
6
+ import { writeValue } from './write'
7
+
8
+ const singular = (name: string) =>
9
+ name.endsWith('ies') ? `${name.slice(0, -3)}y` : name.endsWith('s') ? name.slice(0, -1) : name
10
+
11
+ /** The repository API for one table (what `Repository(table)` classes inherit). */
12
+ export interface RepositoryApi<T extends Table> {
13
+ readonly table: T
14
+ readonly db: Database
15
+ where(where: Where<T>): Query<T>
16
+ query(): Query<T>
17
+ withTrashed(): Query<T>
18
+ onlyTrashed(): Query<T>
19
+ find(id: unknown): Promise<Row<T> | null>
20
+ findOrFail(id: unknown): Promise<Row<T>>
21
+ findBy(where: Where<T>): Promise<Row<T> | null>
22
+ findByOrFail(where: Where<T>): Promise<Row<T>>
23
+ existsBy(where: Where<T>): Promise<boolean>
24
+ count(where?: Where<T>): Promise<number>
25
+ all(where?: Where<T>): Promise<Row<T>[]>
26
+ create(values: NewRow<T>): Promise<Row<T>>
27
+ createMany(values: NewRow<T>[]): Promise<Row<T>[]>
28
+ update(id: unknown, values: Partial<Row<T>>): Promise<Row<T>>
29
+ upsert(
30
+ values: NewRow<T>,
31
+ options: { conflict: (keyof Row<T> & string)[]; update?: (keyof Row<T> & string)[] },
32
+ ): Promise<Row<T>>
33
+ delete(id: unknown): Promise<void>
34
+ forceDelete(id: unknown): Promise<void>
35
+ restore(id: unknown): Promise<Row<T>>
36
+ lockForUpdate(id: unknown, options?: { skipLocked?: boolean; noWait?: boolean }): Promise<Row<T>>
37
+ paginate(options?: {
38
+ page?: number
39
+ perPage?: number
40
+ where?: Where<T>
41
+ orderBy?: keyof Row<T> & string
42
+ dir?: 'asc' | 'desc'
43
+ }): ReturnType<Query<T>['paginate']>
44
+ using(tx: Transaction): this
45
+ }
46
+
47
+ /**
48
+ * The base of a repository for one table:
49
+ *
50
+ * ```ts
51
+ * @inject()
52
+ * export class BookingRepository extends Repository(bookings) {
53
+ * upcomingFor(travellerId: string, today: string) {
54
+ * return this.where({ travellerId, startDate: gte(today) }).orderBy('startDate').all()
55
+ * }
56
+ * }
57
+ * ```
58
+ *
59
+ * The `Database` is resolved by the base class, so subclasses only `@inject` what they add.
60
+ */
61
+ export function Repository<T extends Table>(table: T) {
62
+ abstract class BaseRepository implements RepositoryApi<T> {
63
+ readonly table = table
64
+ /** The database (queries use the ambient transaction automatically). */
65
+ readonly db: Database = resolve(Database)
66
+ /** Set by `using(tx)`: an explicit transaction instead of the ambient one. */
67
+ protected explicit?: Transaction
68
+
69
+ /** The resource name used in NotFoundError codes (`booking.not_found`). */
70
+ protected get resource(): string {
71
+ return singular(table.name)
72
+ }
73
+
74
+ protected get exec(): Queryable & Pick<Database, 'current'> {
75
+ if (!this.explicit) return this.db
76
+ const tx = this.explicit
77
+ return Object.assign(Object.create(tx) as Transaction, { current: tx })
78
+ }
79
+
80
+ query(): Query<T> {
81
+ return new Query(table, () => this.exec)
82
+ }
83
+ where(where: Where<T>): Query<T> {
84
+ return this.query().where(where)
85
+ }
86
+ withTrashed(): Query<T> {
87
+ return this.query().withTrashed()
88
+ }
89
+ onlyTrashed(): Query<T> {
90
+ return this.query().onlyTrashed()
91
+ }
92
+
93
+ protected byId(id: unknown): Where<T> {
94
+ return { [table.primaryKey]: id } as Where<T>
95
+ }
96
+
97
+ find(id: unknown) {
98
+ return this.query().where(this.byId(id)).first()
99
+ }
100
+ async findOrFail(id: unknown) {
101
+ const row = await this.find(id)
102
+ if (!row) throw new NotFoundError(this.resource, String(id))
103
+ return row
104
+ }
105
+ findBy(where: Where<T>) {
106
+ return this.where(where).first()
107
+ }
108
+ async findByOrFail(where: Where<T>) {
109
+ const row = await this.findBy(where)
110
+ if (!row) throw new NotFoundError(this.resource)
111
+ return row
112
+ }
113
+ existsBy(where: Where<T>) {
114
+ return this.where(where).exists()
115
+ }
116
+ count(where: Where<T> = {}) {
117
+ return this.where(where).count()
118
+ }
119
+ all(where: Where<T> = {}) {
120
+ return this.where(where).all()
121
+ }
122
+
123
+ /** Fill generated and default values (ids, short codes, timestamps). */
124
+ protected prepare(values: Record<string, unknown>): Record<string, unknown> {
125
+ const out = { ...values }
126
+ for (const [key, column] of Object.entries(table.columns)) {
127
+ if (out[key] !== undefined) continue
128
+ if (column.def.generate) out[key] = column.def.generate()
129
+ else if (column.def.defaultValue !== undefined) out[key] = column.def.defaultValue
130
+ }
131
+ return out
132
+ }
133
+
134
+ async create(values: NewRow<T>) {
135
+ const [row] = await this.createMany([values])
136
+ return row as Row<T>
137
+ }
138
+
139
+ async createMany(list: NewRow<T>[]) {
140
+ if (!list.length) return []
141
+ const prepared = list.map((v) => this.prepare(v as Record<string, unknown>))
142
+ const keys = Object.keys(table.columns).filter((k) => prepared.some((p) => p[k] !== undefined))
143
+ const names = sql.join(keys.map((k) => sql.ident(table.sqlNames.get(k) as string)))
144
+ const rows = prepared.map(
145
+ (p) =>
146
+ sql`(${sql.join(
147
+ keys.map((k) => (p[k] === undefined ? sql`default` : writeValue(p[k], table.columns[k] as never))),
148
+ )})`,
149
+ )
150
+ return this.exec.many(sql`insert into ${table} (${names}) values ${sql.join(rows)} returning *`, table)
151
+ }
152
+
153
+ async update(id: unknown, values: Partial<Row<T>>) {
154
+ const where = whereSql(table, this.byId(id))
155
+ const row = await this.exec.maybeOne(
156
+ sql`update ${table} set ${setClause(table, values as Record<string, unknown>)} where ${where} returning *`,
157
+ table,
158
+ )
159
+ if (!row) throw new NotFoundError(this.resource, String(id))
160
+ return row
161
+ }
162
+
163
+ async upsert(
164
+ values: NewRow<T>,
165
+ options: { conflict: (keyof Row<T> & string)[]; update?: (keyof Row<T> & string)[] },
166
+ ) {
167
+ const p = this.prepare(values as Record<string, unknown>)
168
+ const keys = Object.keys(table.columns).filter((k) => p[k] !== undefined)
169
+ const conflict = sql.join(options.conflict.map((k) => sql.ident(table.sqlNames.get(k) as string)))
170
+ const updatable = (options.update ??
171
+ keys.filter(
172
+ (k) => !options.conflict.includes(k as never) && k !== table.primaryKey && k !== 'createdAt',
173
+ )) as string[]
174
+ const touch = Object.entries(table.columns).find(([, c]) => c.def.touch)?.[0]
175
+ const sets = [...new Set([...updatable, ...(touch ? [touch] : [])])].map((k) => {
176
+ const name = sql.ident(table.sqlNames.get(k) as string)
177
+ return sql`${name} = excluded.${name}`
178
+ })
179
+ const action = sets.length ? sql`do update set ${sql.join(sets)}` : sql`do nothing`
180
+ const row = await this.exec.maybeOne(
181
+ sql`insert into ${table} (${sql.join(keys.map((k) => sql.ident(table.sqlNames.get(k) as string)))})
182
+ values (${sql.join(keys.map((k) => writeValue(p[k], table.columns[k] as never)))})
183
+ on conflict (${conflict}) ${action} returning *`,
184
+ table,
185
+ )
186
+ return (
187
+ row ??
188
+ (this.where(Object.fromEntries(options.conflict.map((k) => [k, p[k]])) as Where<T>).first() as Promise<Row<T>>)
189
+ )
190
+ }
191
+
192
+ /** Soft-deletes when the table has `deletedAt`, deletes otherwise. */
193
+ async delete(id: unknown) {
194
+ const n = await this.query().where(this.byId(id)).delete()
195
+ if (!n) throw new NotFoundError(this.resource, String(id))
196
+ }
197
+
198
+ async forceDelete(id: unknown) {
199
+ const n = await this.withTrashed().where(this.byId(id)).forceDelete()
200
+ if (!n) throw new NotFoundError(this.resource, String(id))
201
+ }
202
+
203
+ async restore(id: unknown) {
204
+ if (!table.softDeletes) throw new CslugError('db.not_soft_deletable', `${table.name} has no deletedAt column`)
205
+ const n = await this.onlyTrashed()
206
+ .where(this.byId(id))
207
+ .update({ deletedAt: null } as Partial<Row<T>>)
208
+ if (!n) throw new NotFoundError(this.resource, String(id))
209
+ return this.findOrFail(id)
210
+ }
211
+
212
+ /** The row, locked `FOR UPDATE` until the transaction ends. Throws NotFoundError. */
213
+ async lockForUpdate(id: unknown, options: { skipLocked?: boolean; noWait?: boolean } = {}) {
214
+ const row = await this.query().where(this.byId(id)).lockForUpdate(options).first()
215
+ if (!row) throw new NotFoundError(this.resource, String(id))
216
+ return row
217
+ }
218
+
219
+ paginate(
220
+ options: {
221
+ page?: number
222
+ perPage?: number
223
+ where?: Where<T>
224
+ orderBy?: keyof Row<T> & string
225
+ dir?: 'asc' | 'desc'
226
+ } = {},
227
+ ) {
228
+ let q = this.where(options.where ?? {})
229
+ if (options.orderBy) q = q.orderBy(options.orderBy, options.dir)
230
+ return q.paginate(options.page ?? 1, options.perPage ?? 20)
231
+ }
232
+
233
+ /** This repository bound to an explicit transaction (instead of the ambient one). */
234
+ using(tx: Transaction): this {
235
+ const copy = Object.create(this) as this & { explicit?: Transaction }
236
+ copy.explicit = tx
237
+ return copy
238
+ }
239
+ }
240
+ return BaseRepository
241
+ }
package/src/sql.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The `sql` tag: SQL text with bound parameters. Interpolated values always become `$n` parameters; tables and
3
+ * columns become quoted identifiers; nested fragments are inlined. There is no API that takes a SQL string, so
4
+ * user input cannot be concatenated into a query.
5
+ */
6
+ export const IDENT: unique symbol = Symbol('cslug.sql.identifier')
7
+
8
+ /** Something that renders as SQL text (a table, a column reference, an identifier). */
9
+ export interface SqlIdentifier {
10
+ readonly [IDENT]: string
11
+ }
12
+
13
+ export const isIdentifier = (v: unknown): v is SqlIdentifier => typeof v === 'object' && v !== null && IDENT in v
14
+
15
+ /** Quote an identifier: `booking"s` → `"booking""s"`. */
16
+ export const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`
17
+
18
+ /** A piece of SQL with its parameters. `T` is the row type when the fragment is a whole query. */
19
+ export class SqlFragment<T = Record<string, unknown>> {
20
+ declare readonly _row: T
21
+ constructor(
22
+ readonly parts: readonly string[],
23
+ readonly values: readonly unknown[],
24
+ ) {}
25
+
26
+ /** Compile to text with `$1…$n` and the parameter list. */
27
+ compile(offset = 0): { text: string; params: unknown[] } {
28
+ const params: unknown[] = []
29
+ let text = ''
30
+ const walk = (fragment: SqlFragment<unknown>) => {
31
+ fragment.parts.forEach((part, i) => {
32
+ text += part
33
+ if (i >= fragment.values.length) return
34
+ const value = fragment.values[i]
35
+ if (value instanceof SqlFragment) walk(value)
36
+ else if (isIdentifier(value)) text += value[IDENT]
37
+ else if (value instanceof Raw) text += value.text
38
+ else if (value instanceof JsonParam) {
39
+ params.push(value.json)
40
+ text += `($${offset + params.length}::text)::jsonb`
41
+ } else {
42
+ params.push(value === undefined ? null : value)
43
+ text += `$${offset + params.length}`
44
+ }
45
+ })
46
+ }
47
+ walk(this as SqlFragment<unknown>)
48
+ return { text, params }
49
+ }
50
+
51
+ toString(): string {
52
+ return this.compile().text
53
+ }
54
+ }
55
+
56
+ /** Trusted SQL text, inserted as is. Only for constants written in code (lint-flagged). */
57
+ export class Raw {
58
+ constructor(readonly text: string) {}
59
+ }
60
+
61
+ /** A JSON value bound as a jsonb parameter (Bun.sql would double-encode a string, and mangle arrays). */
62
+ export class JsonParam {
63
+ readonly json: string
64
+ constructor(value: unknown) {
65
+ this.json = JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))
66
+ }
67
+ }
68
+
69
+ type SqlTag = {
70
+ <T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: unknown[]): SqlFragment<T>
71
+ /** Join fragments or values with a separator fragment: `sql.join(ids, sql\`, \`)`. */
72
+ join(items: readonly unknown[], separator?: SqlFragment<unknown>): SqlFragment<unknown>
73
+ /** Trusted SQL text (constants only). */
74
+ raw(text: string): Raw
75
+ /** A quoted identifier from a name, e.g. a schema. */
76
+ ident(...names: string[]): SqlIdentifier
77
+ /** A JSON value for a jsonb column or parameter. */
78
+ json(value: unknown): JsonParam
79
+ /** Empty fragment. */
80
+ empty: SqlFragment<unknown>
81
+ }
82
+
83
+ /** Tagged template: values become bound parameters, `SqlIdentifier`s and fragments are inlined. */
84
+ export const sql: SqlTag = Object.assign(
85
+ <T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: unknown[]) =>
86
+ new SqlFragment<T>([...strings], values),
87
+ {
88
+ join(
89
+ items: readonly unknown[],
90
+ separator: SqlFragment<unknown> = new SqlFragment([', '], []),
91
+ ): SqlFragment<unknown> {
92
+ if (!items.length) return new SqlFragment([''], [])
93
+ const parts: string[] = ['']
94
+ const values: unknown[] = []
95
+ items.forEach((item, i) => {
96
+ if (i > 0) {
97
+ values.push(separator)
98
+ parts.push('')
99
+ }
100
+ values.push(item)
101
+ parts.push('')
102
+ })
103
+ return new SqlFragment(parts, values)
104
+ },
105
+ raw: (text: string) => new Raw(text),
106
+ ident: (...names: string[]): SqlIdentifier => ({ [IDENT]: names.map(quote).join('.') }),
107
+ json: (value: unknown) => new JsonParam(value),
108
+ empty: new SqlFragment<unknown>([''], []),
109
+ },
110
+ )
package/src/table.ts ADDED
@@ -0,0 +1,135 @@
1
+ import type { AnyColumn, Column } from './columns'
2
+ import { decrypt } from './encryption'
3
+ import { IDENT, quote, type SqlIdentifier } from './sql'
4
+
5
+ export type Columns = Record<string, AnyColumn>
6
+
7
+ type ValueOf<C> = C extends Column<infer T, infer N, boolean> ? (N extends true ? T | null : T) : never
8
+ type Flatten<T> = { [K in keyof T]: T[K] } & {}
9
+ type OptionalKeys<C extends Columns> = {
10
+ [K in keyof C]: C[K] extends Column<unknown, boolean, true> ? K : never
11
+ }[keyof C]
12
+
13
+ /** What a SELECT returns: every column, nullable ones as `T | null`. */
14
+ export type Row<T extends Table> = Flatten<{ [K in keyof T['columns']]: ValueOf<T['columns'][K]> }>
15
+
16
+ /** What an INSERT needs: NOT NULL columns without a default are required; the rest optional. */
17
+ export type NewRow<T extends Table> = Flatten<
18
+ { [K in Exclude<keyof T['columns'], OptionalKeys<T['columns']>>]: ValueOf<T['columns'][K]> } & {
19
+ [K in OptionalKeys<T['columns']>]?: ValueOf<T['columns'][K]>
20
+ }
21
+ >
22
+
23
+ /** `fooBar` → `foo_bar` */
24
+ export const snake = (s: string) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)
25
+
26
+ /** A column reference that renders as `"table"."column"` in the sql tag. */
27
+ export type ColumnRef = SqlIdentifier & { readonly name: string; readonly key: string; readonly table: string }
28
+
29
+ export type IndexDef = { columns: string[]; unique: boolean; name: string }
30
+
31
+ type IndexBuilder<C extends Columns> = {
32
+ index(...keys: (keyof C & string)[]): IndexDef
33
+ unique(...keys: (keyof C & string)[]): IndexDef
34
+ }
35
+
36
+ /** A typed table: columns, keys and indexes; `table()` creates one. */
37
+ export class Table<C extends Columns = Columns> implements SqlIdentifier {
38
+ readonly [IDENT]: string
39
+ /** Column references for the sql tag: `${bookings.c.startDate}` → `"bookings"."start_date"`. */
40
+ readonly c: { readonly [K in keyof C]: ColumnRef }
41
+ /** `${bookings.star}` → `"bookings".*` */
42
+ readonly star: SqlIdentifier
43
+ /** TS key → SQL column name. */
44
+ readonly sqlNames: ReadonlyMap<string, string>
45
+ readonly indexes: IndexDef[]
46
+ readonly primaryKey: string
47
+
48
+ constructor(
49
+ readonly name: string,
50
+ readonly columns: C,
51
+ options: { indexes?: (t: IndexBuilder<C>) => IndexDef[] } = {},
52
+ ) {
53
+ this[IDENT] = quote(name)
54
+ const names = new Map<string, string>()
55
+ const refs: Record<string, ColumnRef> = {}
56
+ for (const key of Object.keys(columns)) {
57
+ const column = snake(key)
58
+ names.set(key, column)
59
+ refs[key] = { [IDENT]: `${quote(name)}.${quote(column)}`, name: column, key, table: name }
60
+ }
61
+ this.sqlNames = names
62
+ this.c = refs as Table<C>['c']
63
+ this.star = { [IDENT]: `${quote(name)}.*` }
64
+ this.primaryKey = Object.entries(columns).find(([, c]) => c.def.primary)?.[0] ?? 'id'
65
+ const builder: IndexBuilder<C> = {
66
+ index: (...keys) => ({
67
+ columns: keys.map(snake),
68
+ unique: false,
69
+ name: `${name}_${keys.map(snake).join('_')}_idx`,
70
+ }),
71
+ unique: (...keys) => ({
72
+ columns: keys.map(snake),
73
+ unique: true,
74
+ name: `${name}_${keys.map(snake).join('_')}_key`,
75
+ }),
76
+ }
77
+ this.indexes = options.indexes?.(builder) ?? []
78
+ }
79
+
80
+ /** True when the table has `deletedAt` (soft deletes). */
81
+ get softDeletes(): boolean {
82
+ return 'deletedAt' in this.columns
83
+ }
84
+
85
+ /** A database row (snake_case, driver types) → the app row (camelCase, cslug types). */
86
+ fromDb(raw: Record<string, unknown>): Row<this> {
87
+ const out: Record<string, unknown> = {}
88
+ for (const [key, column] of Object.entries(this.columns)) {
89
+ const name = this.sqlNames.get(key) as string
90
+ if (!(name in raw)) continue
91
+ const value = raw[name]
92
+ out[key] =
93
+ column.def.encrypted && typeof value === 'string' ? decrypt(value) : convertFromDb(value, column.def.kind)
94
+ }
95
+ return out as Row<this>
96
+ }
97
+
98
+ /** App values (camelCase) → `[sqlName, value]` pairs, for known columns only. */
99
+ toDb(values: Record<string, unknown>): [string, unknown, AnyColumn][] {
100
+ const out: [string, unknown, AnyColumn][] = []
101
+ for (const [key, value] of Object.entries(values)) {
102
+ const column = this.columns[key]
103
+ if (!column || value === undefined) continue
104
+ out.push([this.sqlNames.get(key) as string, value, column])
105
+ }
106
+ return out
107
+ }
108
+ }
109
+
110
+ function convertFromDb(value: unknown, kind: string): unknown {
111
+ if (value === null || value === undefined) return null
112
+ switch (kind) {
113
+ case 'date':
114
+ return value instanceof Date ? value.toISOString().slice(0, 10) : String(value)
115
+ case 'bigint':
116
+ return typeof value === 'bigint' ? value : BigInt(value as string)
117
+ case 'integer':
118
+ return typeof value === 'number' ? value : Number(value)
119
+ case 'numeric':
120
+ return String(value)
121
+ case 'char':
122
+ return String(value).trimEnd()
123
+ default:
124
+ return value
125
+ }
126
+ }
127
+
128
+ /** Define a table: `export const bookings = table('bookings', { id: id(), … })`. */
129
+ export function table<C extends Columns>(
130
+ name: string,
131
+ columns: C,
132
+ options: { indexes?: (t: IndexBuilder<C>) => IndexDef[] } = {},
133
+ ): Table<C> {
134
+ return new Table(name, columns, options)
135
+ }
package/src/write.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { AnyColumn } from './columns'
2
+ import { encrypt } from './encryption'
3
+ import { sql } from './sql'
4
+
5
+ /** A value as written to the database: jsonb columns are bound as JSON. */
6
+ export function writeValue(value: unknown, column: AnyColumn): unknown {
7
+ if (value === null || value === undefined) return null
8
+ if (column.def.encrypted) return encrypt(String(value))
9
+ return column.def.kind === 'jsonb' ? sql.json(value) : value
10
+ }
@@ -0,0 +1,6 @@
1
+ import { factory } from '@cslug/database'
2
+ import { {{ tableVar }} } from '#app/tables/{{ tableFile }}'
3
+
4
+ export const {{ class }} = factory({{ tableVar }}, ({ seq, fake }) => ({
5
+ // name: `{{ base }} ${seq}`,
6
+ }))
@@ -0,0 +1,9 @@
1
+ -- up
2
+ create table {{ table }} (
3
+ id uuid primary key,
4
+ created_at timestamptz not null default now(),
5
+ updated_at timestamptz not null default now()
6
+ );
7
+
8
+ -- down
9
+ drop table {{ table }};
@@ -0,0 +1,5 @@
1
+ -- up
2
+
3
+
4
+ -- down
5
+
@@ -0,0 +1,6 @@
1
+ import { inject } from '@cslug/core'
2
+ import { Repository } from '@cslug/database'
3
+ import { {{ tableVar }} } from '#app/tables/{{ tableFile }}'
4
+
5
+ @inject()
6
+ export class {{ class }} extends Repository({{ tableVar }}) {}
@@ -0,0 +1,5 @@
1
+ import { seeder } from '@cslug/database'
2
+
3
+ export default seeder(async () => {
4
+ // await SomethingFactory.createMany(10)
5
+ })
@@ -0,0 +1,9 @@
1
+ import { id, type NewRow, type Row, table, timestamps } from '@cslug/database'
2
+
3
+ export const {{ tableVar }} = table('{{ plural }}', {
4
+ id: id(),
5
+ ...timestamps(),
6
+ })
7
+
8
+ export type {{ base }} = Row<typeof {{ tableVar }}>
9
+ export type New{{ base }} = NewRow<typeof {{ tableVar }}>