@cslug/database 0.0.0-stage → 0.1.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 +43 -0
- package/src/errors.ts +39 -0
- package/src/factory.ts +111 -0
- package/src/fake.ts +114 -0
- package/src/index.ts +42 -0
- package/src/migrator.ts +188 -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 +109 -0
- package/src/table.ts +134 -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
|
@@ -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,109 @@
|
|
|
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
|
+
export const sql: SqlTag = Object.assign(
|
|
84
|
+
<T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: unknown[]) =>
|
|
85
|
+
new SqlFragment<T>([...strings], values),
|
|
86
|
+
{
|
|
87
|
+
join(
|
|
88
|
+
items: readonly unknown[],
|
|
89
|
+
separator: SqlFragment<unknown> = new SqlFragment([', '], []),
|
|
90
|
+
): SqlFragment<unknown> {
|
|
91
|
+
if (!items.length) return new SqlFragment([''], [])
|
|
92
|
+
const parts: string[] = ['']
|
|
93
|
+
const values: unknown[] = []
|
|
94
|
+
items.forEach((item, i) => {
|
|
95
|
+
if (i > 0) {
|
|
96
|
+
values.push(separator)
|
|
97
|
+
parts.push('')
|
|
98
|
+
}
|
|
99
|
+
values.push(item)
|
|
100
|
+
parts.push('')
|
|
101
|
+
})
|
|
102
|
+
return new SqlFragment(parts, values)
|
|
103
|
+
},
|
|
104
|
+
raw: (text: string) => new Raw(text),
|
|
105
|
+
ident: (...names: string[]): SqlIdentifier => ({ [IDENT]: names.map(quote).join('.') }),
|
|
106
|
+
json: (value: unknown) => new JsonParam(value),
|
|
107
|
+
empty: new SqlFragment<unknown>([''], []),
|
|
108
|
+
},
|
|
109
|
+
)
|
package/src/table.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
37
|
+
readonly [IDENT]: string
|
|
38
|
+
/** Column references for the sql tag: `${bookings.c.startDate}` → `"bookings"."start_date"`. */
|
|
39
|
+
readonly c: { readonly [K in keyof C]: ColumnRef }
|
|
40
|
+
/** `${bookings.star}` → `"bookings".*` */
|
|
41
|
+
readonly star: SqlIdentifier
|
|
42
|
+
/** TS key → SQL column name. */
|
|
43
|
+
readonly sqlNames: ReadonlyMap<string, string>
|
|
44
|
+
readonly indexes: IndexDef[]
|
|
45
|
+
readonly primaryKey: string
|
|
46
|
+
|
|
47
|
+
constructor(
|
|
48
|
+
readonly name: string,
|
|
49
|
+
readonly columns: C,
|
|
50
|
+
options: { indexes?: (t: IndexBuilder<C>) => IndexDef[] } = {},
|
|
51
|
+
) {
|
|
52
|
+
this[IDENT] = quote(name)
|
|
53
|
+
const names = new Map<string, string>()
|
|
54
|
+
const refs: Record<string, ColumnRef> = {}
|
|
55
|
+
for (const key of Object.keys(columns)) {
|
|
56
|
+
const column = snake(key)
|
|
57
|
+
names.set(key, column)
|
|
58
|
+
refs[key] = { [IDENT]: `${quote(name)}.${quote(column)}`, name: column, key, table: name }
|
|
59
|
+
}
|
|
60
|
+
this.sqlNames = names
|
|
61
|
+
this.c = refs as Table<C>['c']
|
|
62
|
+
this.star = { [IDENT]: `${quote(name)}.*` }
|
|
63
|
+
this.primaryKey = Object.entries(columns).find(([, c]) => c.def.primary)?.[0] ?? 'id'
|
|
64
|
+
const builder: IndexBuilder<C> = {
|
|
65
|
+
index: (...keys) => ({
|
|
66
|
+
columns: keys.map(snake),
|
|
67
|
+
unique: false,
|
|
68
|
+
name: `${name}_${keys.map(snake).join('_')}_idx`,
|
|
69
|
+
}),
|
|
70
|
+
unique: (...keys) => ({
|
|
71
|
+
columns: keys.map(snake),
|
|
72
|
+
unique: true,
|
|
73
|
+
name: `${name}_${keys.map(snake).join('_')}_key`,
|
|
74
|
+
}),
|
|
75
|
+
}
|
|
76
|
+
this.indexes = options.indexes?.(builder) ?? []
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** True when the table has `deletedAt` (soft deletes). */
|
|
80
|
+
get softDeletes(): boolean {
|
|
81
|
+
return 'deletedAt' in this.columns
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A database row (snake_case, driver types) → the app row (camelCase, cslug types). */
|
|
85
|
+
fromDb(raw: Record<string, unknown>): Row<this> {
|
|
86
|
+
const out: Record<string, unknown> = {}
|
|
87
|
+
for (const [key, column] of Object.entries(this.columns)) {
|
|
88
|
+
const name = this.sqlNames.get(key) as string
|
|
89
|
+
if (!(name in raw)) continue
|
|
90
|
+
const value = raw[name]
|
|
91
|
+
out[key] =
|
|
92
|
+
column.def.encrypted && typeof value === 'string' ? decrypt(value) : convertFromDb(value, column.def.kind)
|
|
93
|
+
}
|
|
94
|
+
return out as Row<this>
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** App values (camelCase) → `[sqlName, value]` pairs, for known columns only. */
|
|
98
|
+
toDb(values: Record<string, unknown>): [string, unknown, AnyColumn][] {
|
|
99
|
+
const out: [string, unknown, AnyColumn][] = []
|
|
100
|
+
for (const [key, value] of Object.entries(values)) {
|
|
101
|
+
const column = this.columns[key]
|
|
102
|
+
if (!column || value === undefined) continue
|
|
103
|
+
out.push([this.sqlNames.get(key) as string, value, column])
|
|
104
|
+
}
|
|
105
|
+
return out
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function convertFromDb(value: unknown, kind: string): unknown {
|
|
110
|
+
if (value === null || value === undefined) return null
|
|
111
|
+
switch (kind) {
|
|
112
|
+
case 'date':
|
|
113
|
+
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value)
|
|
114
|
+
case 'bigint':
|
|
115
|
+
return typeof value === 'bigint' ? value : BigInt(value as string)
|
|
116
|
+
case 'integer':
|
|
117
|
+
return typeof value === 'number' ? value : Number(value)
|
|
118
|
+
case 'numeric':
|
|
119
|
+
return String(value)
|
|
120
|
+
case 'char':
|
|
121
|
+
return String(value).trimEnd()
|
|
122
|
+
default:
|
|
123
|
+
return value
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Define a table: `export const bookings = table('bookings', { id: id(), … })`. */
|
|
128
|
+
export function table<C extends Columns>(
|
|
129
|
+
name: string,
|
|
130
|
+
columns: C,
|
|
131
|
+
options: { indexes?: (t: IndexBuilder<C>) => IndexDef[] } = {},
|
|
132
|
+
): Table<C> {
|
|
133
|
+
return new Table(name, columns, options)
|
|
134
|
+
}
|
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
|
+
}
|
package/stubs/table.stub
ADDED
|
@@ -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 }}>
|