@hamur/db 0.0.0-stage → 0.0.2

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.
Files changed (125) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
  4. package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
  5. package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
  6. package/dist/chunks/browser-d1-a16d23f0.js +8 -0
  7. package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
  8. package/dist/chunks/browser-index-kf697bfy.js +113 -0
  9. package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
  10. package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
  11. package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
  12. package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
  13. package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
  14. package/dist/chunks/bun-index-06tj00dn.js +11 -0
  15. package/dist/chunks/bun-index-9na2zkqq.js +224 -0
  16. package/dist/chunks/bun-index-b47nngck.js +352 -0
  17. package/dist/chunks/bun-index-hrx1eqma.js +29 -0
  18. package/dist/chunks/bun-index-pd6k99dv.js +114 -0
  19. package/dist/src/cli.js +1692 -0
  20. package/dist/src/devtools.js +153 -0
  21. package/dist/src/index.js +1491 -0
  22. package/dist/src/server/index.js +584 -0
  23. package/dist/src/storage/define.js +7 -0
  24. package/dist/types/src/build/connections.d.ts +8 -0
  25. package/dist/types/src/build/databases.d.ts +20 -0
  26. package/dist/types/src/build/factories.d.ts +6 -0
  27. package/dist/types/src/build/migrations.d.ts +21 -0
  28. package/dist/types/src/build/queue.d.ts +7 -0
  29. package/dist/types/src/build/schema.d.ts +50 -0
  30. package/dist/types/src/build/tables.d.ts +7 -0
  31. package/dist/types/src/build/types.d.ts +4 -0
  32. package/dist/types/src/cli.d.ts +26 -0
  33. package/dist/types/src/connectors/bun-sql.d.ts +3 -0
  34. package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
  35. package/dist/types/src/connectors/client-fakes.d.ts +57 -0
  36. package/dist/types/src/connectors/client.d.ts +3 -0
  37. package/dist/types/src/connectors/d1-fake.d.ts +32 -0
  38. package/dist/types/src/connectors/d1.d.ts +26 -0
  39. package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
  40. package/dist/types/src/connectors/node-test.d.ts +17 -0
  41. package/dist/types/src/connectors/suite.d.ts +13 -0
  42. package/dist/types/src/devtools.d.ts +6 -0
  43. package/dist/types/src/index.d.ts +25 -0
  44. package/dist/types/src/module.d.ts +6 -0
  45. package/dist/types/src/options.d.ts +9 -0
  46. package/dist/types/src/runtime/connector.d.ts +53 -0
  47. package/dist/types/src/runtime/database.d.ts +15 -0
  48. package/dist/types/src/runtime/migrate.d.ts +56 -0
  49. package/dist/types/src/runtime/query.d.ts +12 -0
  50. package/dist/types/src/runtime/queue-process.d.ts +1 -0
  51. package/dist/types/src/runtime/queue.d.ts +85 -0
  52. package/dist/types/src/runtime/registry.d.ts +16 -0
  53. package/dist/types/src/server/client.d.ts +3 -0
  54. package/dist/types/src/server/databases.d.ts +4 -0
  55. package/dist/types/src/server/define-factory.d.ts +9 -0
  56. package/dist/types/src/server/devtools-routes.d.ts +4 -0
  57. package/dist/types/src/server/devtools.d.ts +26 -0
  58. package/dist/types/src/server/door-dev.d.ts +3 -0
  59. package/dist/types/src/server/door.d.ts +2 -0
  60. package/dist/types/src/server/factory-core.d.ts +12 -0
  61. package/dist/types/src/server/factory.d.ts +6 -0
  62. package/dist/types/src/server/fake.d.ts +35 -0
  63. package/dist/types/src/server/index.d.ts +12 -0
  64. package/dist/types/src/server/migrations.d.ts +5 -0
  65. package/dist/types/src/server/page.d.ts +26 -0
  66. package/dist/types/src/server/plugin.d.ts +1 -0
  67. package/dist/types/src/server/queue.d.ts +6 -0
  68. package/dist/types/src/server/table-entities.d.ts +33 -0
  69. package/dist/types/src/server/task.d.ts +6 -0
  70. package/dist/types/src/storage/define.d.ts +12 -0
  71. package/dist/types/src/storage/driver.d.ts +36 -0
  72. package/dist/types/src/storage/index.d.ts +3 -0
  73. package/dist/types/src/types.d.ts +103 -0
  74. package/package.json +55 -4
  75. package/src/build/connections.ts +225 -0
  76. package/src/build/databases.ts +101 -0
  77. package/src/build/factories.ts +135 -0
  78. package/src/build/migrations.ts +247 -0
  79. package/src/build/queue.ts +29 -0
  80. package/src/build/schema.ts +636 -0
  81. package/src/build/tables.ts +20 -0
  82. package/src/build/types.ts +46 -0
  83. package/src/cli.ts +153 -0
  84. package/src/connectors/bun-sql.ts +68 -0
  85. package/src/connectors/bun-sqlite.ts +69 -0
  86. package/src/connectors/client-fakes.ts +257 -0
  87. package/src/connectors/client.ts +161 -0
  88. package/src/connectors/d1-fake.ts +92 -0
  89. package/src/connectors/d1.ts +151 -0
  90. package/src/connectors/node-sqlite.ts +83 -0
  91. package/src/connectors/node-test.ts +31 -0
  92. package/src/connectors/suite.ts +406 -0
  93. package/src/devtools.ts +264 -0
  94. package/src/env.d.ts +28 -0
  95. package/src/index.ts +46 -0
  96. package/src/module.ts +36 -0
  97. package/src/options.ts +104 -0
  98. package/src/runtime/connector.ts +87 -0
  99. package/src/runtime/database.ts +353 -0
  100. package/src/runtime/migrate.ts +307 -0
  101. package/src/runtime/query.ts +82 -0
  102. package/src/runtime/queue-process.ts +39 -0
  103. package/src/runtime/queue.ts +380 -0
  104. package/src/runtime/registry.ts +61 -0
  105. package/src/server/client.ts +6 -0
  106. package/src/server/databases.ts +24 -0
  107. package/src/server/define-factory.ts +22 -0
  108. package/src/server/devtools-routes.ts +34 -0
  109. package/src/server/devtools.ts +205 -0
  110. package/src/server/door-dev.ts +6 -0
  111. package/src/server/door.ts +4 -0
  112. package/src/server/factory-core.ts +91 -0
  113. package/src/server/factory.ts +19 -0
  114. package/src/server/fake.ts +348 -0
  115. package/src/server/index.ts +17 -0
  116. package/src/server/migrations.ts +26 -0
  117. package/src/server/page.ts +181 -0
  118. package/src/server/plugin.ts +14 -0
  119. package/src/server/queue.ts +38 -0
  120. package/src/server/table-entities.ts +29 -0
  121. package/src/server/task.ts +15 -0
  122. package/src/storage/define.ts +12 -0
  123. package/src/storage/driver.ts +419 -0
  124. package/src/storage/index.ts +7 -0
  125. package/src/types.ts +101 -0
@@ -0,0 +1,205 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { migrations } from "#hamur/db/migrations"
3
+ import { migrationStatus, mysqlStatements } from "../runtime/migrate.ts"
4
+ import type { Database, Dialect } from "../types.ts"
5
+ import { active, databases } from "./databases.ts"
6
+
7
+ /** Rows per page of the Database tab. */
8
+ export const PAGE_SIZE = 50
9
+ /** The rows one SQL run answers at most. */
10
+ export const QUERY_ROWS_MAX = 500
11
+ export const SQL_MAX_LENGTH = 100_000
12
+ const BODY_MAX_BYTES = 1024 * 1024
13
+
14
+ const JSON_HEADERS = {
15
+ "content-type": "application/json",
16
+ "cache-control": "no-store",
17
+ "x-content-type-options": "nosniff",
18
+ }
19
+
20
+ const answer = (body: unknown, status = 200, headers: Record<string, string> = {}): Response =>
21
+ new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } })
22
+
23
+ const failure = (message: string, status: number, headers: Record<string, string> = {}): Response =>
24
+ answer({ error: message }, status, headers)
25
+
26
+ const wrongMethod = (name: string, method: string): Response =>
27
+ failure(`Devtools data route ${JSON.stringify(name)} answers ${method}`, 405, { allow: method })
28
+
29
+ const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error))
30
+
31
+ /** The router decodes escapes, so `/_hamur/devtool%73/…` reaches these handlers too; only the literal path is answered. */
32
+ function notLiteral(request: Request, name: string): Response | undefined {
33
+ const { pathname } = new URL(request.url)
34
+ return pathname.endsWith(`/_hamur/devtools/api/db/${name}`)
35
+ ? undefined
36
+ : failure(`No devtools data route ${JSON.stringify(`db/${name}`)}`, 404)
37
+ }
38
+
39
+ const TABLES: Record<Dialect, string> = {
40
+ sqlite: "select name from sqlite_master where type in ('table', 'view') and name not like 'sqlite_%' order by name",
41
+ postgres:
42
+ "select table_name as name from information_schema.tables where table_schema = current_schema() order by table_name",
43
+ mysql: "select table_name as name from information_schema.tables where table_schema = database() order by table_name",
44
+ }
45
+
46
+ /** A template of one string, so a statement typed in the tab runs through `db.sql` with no value bound. */
47
+ const statement = (text: string): TemplateStringsArray =>
48
+ Object.assign([text], { raw: [text] }) as unknown as TemplateStringsArray
49
+
50
+ const quoted = (dialect: Dialect, name: string): string =>
51
+ dialect === "mysql" ? `\`${name.replaceAll("`", "``")}\`` : `"${name.replaceAll('"', '""')}"`
52
+
53
+ /** A row as JSON: a bigint as its digits, bytes as `0x<hex>`. */
54
+ export function jsonRow(row: Record<string, unknown>): Record<string, unknown> {
55
+ const cell = (value: unknown): unknown => {
56
+ if (typeof value === "bigint") return value.toString()
57
+ if (value instanceof Uint8Array)
58
+ return `0x${Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("")}`
59
+ return value
60
+ }
61
+ return Object.fromEntries(Object.entries(row).map(([key, value]) => [key, cell(value)]))
62
+ }
63
+
64
+ function connectionOf(url: URL): Database | Response {
65
+ const name = url.searchParams.get("connection") || "default"
66
+ if (!Object.hasOwn(active, name))
67
+ return failure(`No database ${JSON.stringify(name)}: set db.connections.${name} in hamur.config.ts`, 404)
68
+ return databases.use(name)
69
+ }
70
+
71
+ async function tableNames(db: Database): Promise<string[]> {
72
+ const rows = await db.sql<{ name: unknown }>(statement(TABLES[db.dialect]))
73
+ return rows.map((row) => String(row.name))
74
+ }
75
+
76
+ /** `GET api/db/tables?connection=<c>`: `{ connection, connections, dialect, tables }`. */
77
+ export async function answerTables(request: Request): Promise<Response> {
78
+ const refused = notLiteral(request, "tables")
79
+ if (refused) return refused
80
+ if (request.method !== "GET") return wrongMethod("db/tables", "GET")
81
+ const db = connectionOf(new URL(request.url))
82
+ if (db instanceof Response) return db
83
+ try {
84
+ return answer({
85
+ connection: db.name,
86
+ connections: Object.keys(active),
87
+ dialect: db.dialect,
88
+ tables: await tableNames(db),
89
+ })
90
+ } catch (error) {
91
+ return failure(messageOf(error), 500)
92
+ }
93
+ }
94
+
95
+ /** `GET api/db/rows?connection=<c>&table=<t>&page=<n>`: one page of 50 rows of a table the connection lists, and its row count. */
96
+ export async function answerRows(request: Request): Promise<Response> {
97
+ const refused = notLiteral(request, "rows")
98
+ if (refused) return refused
99
+ if (request.method !== "GET") return wrongMethod("db/rows", "GET")
100
+ const url = new URL(request.url)
101
+ const db = connectionOf(url)
102
+ if (db instanceof Response) return db
103
+ const table = url.searchParams.get("table") ?? ""
104
+ const page = Number(url.searchParams.get("page") ?? "1")
105
+ if (!Number.isSafeInteger(page) || page < 1)
106
+ return failure(`page must be a whole number from 1 (got ${JSON.stringify(url.searchParams.get("page"))})`, 400)
107
+ try {
108
+ if (!(await tableNames(db)).includes(table))
109
+ return failure(`No table ${JSON.stringify(table)} in database ${JSON.stringify(db.name)}`, 404)
110
+ const name = quoted(db.dialect, table)
111
+ const [count] = await db.sql<{ n: unknown }>(statement(`select count(*) as n from ${name}`))
112
+ const rows = await db.sql(statement(`select * from ${name} limit ${PAGE_SIZE} offset ${(page - 1) * PAGE_SIZE}`))
113
+ return answer({
114
+ table,
115
+ page,
116
+ pageSize: PAGE_SIZE,
117
+ total: Number(count?.n ?? 0),
118
+ columns: Object.keys(rows[0] ?? {}),
119
+ rows: rows.map(jsonRow),
120
+ })
121
+ } catch (error) {
122
+ return failure(messageOf(error), 500)
123
+ }
124
+ }
125
+
126
+ /** The one statement of `sql`, or the message of why it is refused. */
127
+ export function oneStatement(sql: unknown): string | { error: string } {
128
+ if (typeof sql !== "string") return { error: "The body must be { sql: string, connection?: string }" }
129
+ if (sql.length > SQL_MAX_LENGTH) return { error: `A statement is at most ${SQL_MAX_LENGTH} characters` }
130
+ const statements = mysqlStatements(sql)
131
+ if (!statements.length) return { error: "The SQL box holds no statement" }
132
+ if (statements.length > 1) return { error: `The SQL box runs one statement at a time (got ${statements.length})` }
133
+ return statements[0]!
134
+ }
135
+
136
+ const READ = /^\s*(select|with)\b/i
137
+
138
+ /**
139
+ * The rows of `sql`, at most `QUERY_ROWS_MAX + 1`: no connector reads rows one at a time, so a `select` or `with` runs wrapped in
140
+ * `select * from (…) limit <n>` and the database stops at the cap. One that does not parse wrapped (a `with … insert`) runs as typed;
141
+ * a parse error runs nothing, so the statement runs once.
142
+ */
143
+ export async function capped(db: Database, sql: string): Promise<Array<Record<string, unknown>>> {
144
+ if (!READ.test(sql)) return db.sql(statement(sql))
145
+ let rows: Array<Record<string, unknown>>
146
+ try {
147
+ rows = await db.sql(statement(`select * from (${sql}) as hamur_devtools_query limit ${QUERY_ROWS_MAX + 1}`))
148
+ } catch {
149
+ return db.sql(statement(sql))
150
+ }
151
+ return rows
152
+ }
153
+
154
+ /** `POST api/db/query` `{ sql, connection? }`: runs one statement and answers `{ columns, rows, truncated, ms }`, at most 500 rows. */
155
+ export async function answerQuery(request: Request): Promise<Response> {
156
+ const refused = notLiteral(request, "query")
157
+ if (refused) return refused
158
+ if (request.method !== "POST") return wrongMethod("db/query", "POST")
159
+ if (request.headers.get("content-type")?.split(";")[0]!.trim().toLowerCase() !== "application/json")
160
+ return failure("The body must be JSON", 400)
161
+ if (Number(request.headers.get("content-length") ?? 0) > BODY_MAX_BYTES)
162
+ return failure(`The body is over ${BODY_MAX_BYTES} bytes`, 413)
163
+ const bytes = await request.arrayBuffer()
164
+ if (bytes.byteLength > BODY_MAX_BYTES) return failure(`The body is over ${BODY_MAX_BYTES} bytes`, 413)
165
+ let body: { sql?: unknown; connection?: unknown }
166
+ try {
167
+ body = JSON.parse(new TextDecoder().decode(bytes)) ?? {}
168
+ } catch {
169
+ return failure("The body must be JSON", 400)
170
+ }
171
+ if (body.connection !== undefined && typeof body.connection !== "string")
172
+ return failure("connection must be a string", 400)
173
+ const url = new URL(request.url)
174
+ if (body.connection) url.searchParams.set("connection", body.connection)
175
+ const db = connectionOf(url)
176
+ if (db instanceof Response) return db
177
+ const sql = oneStatement(body.sql)
178
+ if (typeof sql !== "string") return failure(sql.error, 400)
179
+ const started = performance.now()
180
+ try {
181
+ const rows = await capped(db, sql)
182
+ return answer({
183
+ columns: Object.keys(rows[0] ?? {}),
184
+ rows: rows.slice(0, QUERY_ROWS_MAX).map(jsonRow),
185
+ truncated: rows.length > QUERY_ROWS_MAX,
186
+ ms: Math.round(performance.now() - started),
187
+ })
188
+ } catch (error) {
189
+ return failure(messageOf(error), 400)
190
+ }
191
+ }
192
+
193
+ /** `GET api/db/migrations?connection=<c>`: each migration with its state, as `hamur db status` reads it. */
194
+ export async function answerMigrations(request: Request): Promise<Response> {
195
+ const refused = notLiteral(request, "migrations")
196
+ if (refused) return refused
197
+ if (request.method !== "GET") return wrongMethod("db/migrations", "GET")
198
+ const db = connectionOf(new URL(request.url))
199
+ if (db instanceof Response) return db
200
+ try {
201
+ return answer(await migrationStatus(db, migrations[db.name] ?? []))
202
+ } catch (error) {
203
+ return failure(messageOf(error), 500)
204
+ }
205
+ }
@@ -0,0 +1,6 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { dbPlugin } from "./plugin.ts"
3
+
4
+ export { devtoolsDbMigrations, devtoolsDbQuery, devtoolsDbRows, devtoolsDbTables } from "./devtools-routes.ts"
5
+
6
+ export default defineServer({ plugins: [dbPlugin] })
@@ -0,0 +1,4 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { dbPlugin } from "./plugin.ts"
3
+
4
+ export default defineServer({ plugins: [dbPlugin] })
@@ -0,0 +1,91 @@
1
+ import type { DatabaseName, DefaultDatabase, Insert, Row, TableName } from "../index.ts"
2
+ import type { Database, SqlValue } from "../types.ts"
3
+ import type { Factory } from "./define-factory.ts"
4
+ import { createFake, fakeSeed, seedOf } from "./fake.ts"
5
+ import { quote } from "./page.ts"
6
+
7
+ type Overrides<T extends TableName<C>, C extends DatabaseName> =
8
+ Partial<Insert<T, C>> | ((n: number) => Partial<Insert<T, C>>)
9
+
10
+ /** What `factory(table)` returns. */
11
+ export interface TableFactory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase> {
12
+ make(count?: number, overrides?: Overrides<T, C>): Insert<T, C>[]
13
+ create(count?: number, overrides?: Overrides<T, C>): Promise<Row<T, C>[]>
14
+ }
15
+
16
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
17
+
18
+ function template(head: string, glue: string, tail: string, slots: number): TemplateStringsArray {
19
+ const parts = slots === 0 ? [head + tail] : [head, ...Array<string>(slots - 1).fill(glue), tail]
20
+ return Object.assign(parts, { raw: parts }) as TemplateStringsArray
21
+ }
22
+
23
+ function insertOf(db: Database, table: string, row: Record<string, unknown>) {
24
+ const columns = Object.keys(row).filter((column) => row[column] !== undefined)
25
+ for (const column of columns) {
26
+ if (!IDENTIFIER.test(column)) throw new TypeError(`factory("${table}"): "${column}" is not a column name`)
27
+ }
28
+ const into = `INSERT INTO ${quote(db.dialect, [table])}`
29
+ const returning = db.dialect === "mysql" ? "" : " RETURNING *"
30
+ const strings = columns.length
31
+ ? template(
32
+ `${into} (${columns.map((column) => quote(db.dialect, [column])).join(", ")}) VALUES (`,
33
+ ", ",
34
+ `)${returning}`,
35
+ columns.length,
36
+ )
37
+ : template(db.dialect === "mysql" ? `${into} () VALUES ()` : `${into} DEFAULT VALUES`, "", returning, 0)
38
+ const values = columns.map((column) => row[column] as SqlValue)
39
+ return db.dialect === "mysql" ? db.run(strings, ...values) : db.sql<Record<string, unknown>>(strings, ...values)
40
+ }
41
+
42
+ /** `insert`s in one `batch`; mysql has no `returning`, so its rows are selected by id afterwards. */
43
+ async function insertRows(db: Database, table: string, rows: Array<Record<string, unknown>>) {
44
+ const results = await db.batch(rows.map((row) => insertOf(db, table, row)))
45
+ if (db.dialect !== "mysql") return (results as Array<Array<Record<string, unknown>>>).flat()
46
+ const ids = (results as Array<{ lastInsertId?: number | string }>).map((result, index) => {
47
+ const id = rows[index]!.id ?? result.lastInsertId
48
+ if (id === undefined || id === null || id === 0)
49
+ throw new Error(`factory("${table}").create: row ${index + 1} has no id to select it by; give it an id`)
50
+ return id as SqlValue
51
+ })
52
+ const found = await db.sql<Record<string, unknown>>(
53
+ template(
54
+ `SELECT * FROM ${quote(db.dialect, [table])} WHERE ${quote(db.dialect, ["id"])} IN (`,
55
+ ", ",
56
+ ")",
57
+ ids.length,
58
+ ),
59
+ ...ids,
60
+ )
61
+ const byId = new Map(found.map((row) => [String(row.id), row]))
62
+ return ids.map((id) => byId.get(String(id))!)
63
+ }
64
+
65
+ /** `n` counts from 1 per value, and the values of `fake` follow `HAMUR_FAKE_SEED` and the table. */
66
+ export function createFactory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase>(
67
+ table: T,
68
+ connection: string,
69
+ definition: Factory<T, C>,
70
+ open: () => Database,
71
+ ): TableFactory<T, C> {
72
+ const fake = createFake(seedOf(fakeSeed(), `${connection}\0${table}`))
73
+ let made = 0
74
+ const make = (count = 1, overrides?: Overrides<T, C>): Insert<T, C>[] => {
75
+ if (!Number.isSafeInteger(count) || count < 0)
76
+ throw new TypeError(`factory("${table}") count must be an integer from 0`)
77
+ return Array.from({ length: count }, () => {
78
+ const n = ++made
79
+ const given = typeof overrides === "function" ? overrides(n) : overrides
80
+ return { ...(definition.make(n, fake) as object), ...(given as object | undefined) } as Insert<T, C>
81
+ })
82
+ }
83
+ return {
84
+ make,
85
+ async create(count, overrides) {
86
+ const rows = make(count, overrides)
87
+ if (rows.length === 0) return []
88
+ return (await insertRows(open(), table, rows as Array<Record<string, unknown>>)) as Row<T, C>[]
89
+ },
90
+ }
91
+ }
@@ -0,0 +1,19 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { factories } from "#hamur/db/factories"
3
+ import type { DatabaseName, DefaultDatabase, TableName } from "../index.ts"
4
+ import { isFactory } from "./define-factory.ts"
5
+ import { createFactory, type TableFactory } from "./factory-core.ts"
6
+ import { databases } from "./databases.ts"
7
+
8
+ /** The factory of `server/db/factories/<table>.ts` (`<connection>/<table>.ts` for another connection). */
9
+ export function factory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase>(
10
+ table: T,
11
+ options?: { connection?: C },
12
+ ): TableFactory<T, C> {
13
+ const connection: string = options?.connection ?? "default"
14
+ const file = `server/db/factories/${connection === "default" ? "" : `${connection}/`}${table}.ts`
15
+ const definition = (factories as Record<string, Record<string, unknown> | undefined>)[connection]?.[table]
16
+ if (definition === undefined) throw new Error(`No factory for "${table}" in db "${connection}"; write ${file}`)
17
+ if (!isFactory(definition)) throw new TypeError(`${file} must export default defineFactory(...)`)
18
+ return createFactory<T, C>(table, connection, definition as never, () => databases.use(connection))
19
+ }
@@ -0,0 +1,348 @@
1
+ const FIRST_NAMES = [
2
+ "Ada",
3
+ "Alan",
4
+ "Amara",
5
+ "Anders",
6
+ "Beatriz",
7
+ "Bruno",
8
+ "Carla",
9
+ "Chidi",
10
+ "Dara",
11
+ "Diego",
12
+ "Elif",
13
+ "Emil",
14
+ "Farah",
15
+ "Felix",
16
+ "Greta",
17
+ "Hana",
18
+ "Hugo",
19
+ "Ines",
20
+ "Ivan",
21
+ "Jana",
22
+ "Jonas",
23
+ "Kai",
24
+ "Leila",
25
+ "Liam",
26
+ "Maya",
27
+ "Mateo",
28
+ "Nadia",
29
+ "Noah",
30
+ "Olga",
31
+ "Omar",
32
+ "Priya",
33
+ "Quinn",
34
+ "Rosa",
35
+ "Ravi",
36
+ "Sara",
37
+ "Sven",
38
+ "Tara",
39
+ "Theo",
40
+ "Uma",
41
+ "Viktor",
42
+ "Wren",
43
+ "Xavier",
44
+ "Yara",
45
+ "Yusuf",
46
+ "Zoe",
47
+ "Zane",
48
+ "Mira",
49
+ "Luca",
50
+ "Nina",
51
+ "Oscar",
52
+ ]
53
+
54
+ const LAST_NAMES = [
55
+ "Almeida",
56
+ "Andersen",
57
+ "Bauer",
58
+ "Bianchi",
59
+ "Castillo",
60
+ "Chen",
61
+ "Dubois",
62
+ "Eriksen",
63
+ "Fischer",
64
+ "Garcia",
65
+ "Haddad",
66
+ "Ivanov",
67
+ "Jensen",
68
+ "Kaya",
69
+ "Kowalski",
70
+ "Larsen",
71
+ "Lopez",
72
+ "Moreau",
73
+ "Nakamura",
74
+ "Novak",
75
+ "Okafor",
76
+ "Petrov",
77
+ "Quist",
78
+ "Rossi",
79
+ "Santos",
80
+ "Silva",
81
+ "Tanaka",
82
+ "Ulrich",
83
+ "Varga",
84
+ "Weber",
85
+ "Yilmaz",
86
+ "Zhang",
87
+ "Brandt",
88
+ "Costa",
89
+ "Demir",
90
+ "Evans",
91
+ "Foster",
92
+ "Grant",
93
+ "Hughes",
94
+ "Iqbal",
95
+ "Jones",
96
+ "Keller",
97
+ "Lindgren",
98
+ "Mendes",
99
+ "Nolan",
100
+ "Ortega",
101
+ "Patel",
102
+ "Reyes",
103
+ "Singh",
104
+ "Walker",
105
+ ]
106
+
107
+ const WORDS = [
108
+ "able",
109
+ "acorn",
110
+ "amber",
111
+ "anchor",
112
+ "apple",
113
+ "arrow",
114
+ "autumn",
115
+ "badge",
116
+ "basket",
117
+ "beacon",
118
+ "bridge",
119
+ "bright",
120
+ "brook",
121
+ "candle",
122
+ "canvas",
123
+ "cedar",
124
+ "cherry",
125
+ "cliff",
126
+ "cloud",
127
+ "clover",
128
+ "copper",
129
+ "coral",
130
+ "crystal",
131
+ "dawn",
132
+ "delta",
133
+ "desert",
134
+ "dove",
135
+ "dream",
136
+ "eagle",
137
+ "ember",
138
+ "falcon",
139
+ "feather",
140
+ "field",
141
+ "flint",
142
+ "forest",
143
+ "fox",
144
+ "garden",
145
+ "glacier",
146
+ "granite",
147
+ "harbor",
148
+ "hazel",
149
+ "hill",
150
+ "horizon",
151
+ "island",
152
+ "ivory",
153
+ "jade",
154
+ "jasmine",
155
+ "juniper",
156
+ "kettle",
157
+ "lake",
158
+ "lantern",
159
+ "lemon",
160
+ "lily",
161
+ "maple",
162
+ "meadow",
163
+ "mist",
164
+ "moon",
165
+ "morning",
166
+ "moss",
167
+ "mountain",
168
+ "needle",
169
+ "north",
170
+ "oak",
171
+ "ocean",
172
+ "olive",
173
+ "orchard",
174
+ "paper",
175
+ "pearl",
176
+ "pebble",
177
+ "pine",
178
+ "planet",
179
+ "pond",
180
+ "prairie",
181
+ "quartz",
182
+ "rain",
183
+ "raven",
184
+ "reef",
185
+ "ridge",
186
+ "river",
187
+ "robin",
188
+ "saffron",
189
+ "sage",
190
+ "sand",
191
+ "silver",
192
+ "sky",
193
+ "slate",
194
+ "snow",
195
+ "spark",
196
+ "spring",
197
+ "stone",
198
+ "storm",
199
+ "summer",
200
+ "sun",
201
+ "thistle",
202
+ "thunder",
203
+ "tide",
204
+ "timber",
205
+ "tulip",
206
+ "valley",
207
+ "velvet",
208
+ "violet",
209
+ "water",
210
+ "willow",
211
+ "wind",
212
+ "winter",
213
+ "wolf",
214
+ "yarrow",
215
+ "zephyr",
216
+ "quiet",
217
+ "swift",
218
+ ]
219
+
220
+ type Instant = Date | string | number
221
+
222
+ /** The seeded generator a factory's `make` gets. */
223
+ export interface Fake {
224
+ name(): string
225
+ firstName(): string
226
+ lastName(): string
227
+ /** `<word><n>@example.com`, unique per `n`; without `n`, `<word>@example.com`. */
228
+ email(n?: number): string
229
+ word(): string
230
+ words(k: number): string
231
+ sentence(): string
232
+ paragraph(): string
233
+ /** An integer from `min` to `max`, both included. */
234
+ int(min: number, max: number): number
235
+ /** A number from `min` up to, not including, `max`. */
236
+ float(min: number, max: number): number
237
+ /** `true` with probability `p` (default 0.5). */
238
+ bool(p?: number): boolean
239
+ pick<T>(list: readonly T[]): T
240
+ /** A date from `from` to `to`, both included. */
241
+ date(range: { from: Instant; to: Instant }): Date
242
+ uuid(): string
243
+ slug(): string
244
+ url(): string
245
+ }
246
+
247
+ const rotl = (value: number, shift: number) => ((value << shift) | (value >>> (32 - shift))) >>> 0
248
+
249
+ /** xoshiro128** over a state that splitmix32 fills from `seed`. */
250
+ function xoshiro(seed: number): () => number {
251
+ let mix = seed >>> 0
252
+ const split = () => {
253
+ mix = (mix + 0x9e3779b9) >>> 0
254
+ let z = mix
255
+ z = Math.imul(z ^ (z >>> 16), 0x85ebca6b)
256
+ z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35)
257
+ return (z ^ (z >>> 16)) >>> 0
258
+ }
259
+ const state = new Uint32Array([split(), split(), split(), split()])
260
+ return () => {
261
+ const result = Math.imul(rotl(Math.imul(state[1]!, 5), 7), 9) >>> 0
262
+ const shifted = state[1]! << 9
263
+ state[2]! ^= state[0]!
264
+ state[3]! ^= state[1]!
265
+ state[1]! ^= state[2]!
266
+ state[0]! ^= state[3]!
267
+ state[2]! ^= shifted
268
+ state[3] = rotl(state[3]!, 11)
269
+ return result
270
+ }
271
+ }
272
+
273
+ function instant(name: string, value: Instant): number {
274
+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime()
275
+ if (Number.isNaN(time)) throw new TypeError(`fake.date ${name} is not a date`)
276
+ return time
277
+ }
278
+
279
+ const capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)
280
+
281
+ /** The same `seed` gives the same values in the same order. */
282
+ export function createFake(seed: number): Fake {
283
+ const next = xoshiro(seed)
284
+ const unit = () => next() / 0x100000000
285
+ const int = (min: number, max: number) => {
286
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max)) throw new TypeError("fake.int takes integers")
287
+ if (min > max) throw new TypeError("fake.int min must not exceed max")
288
+ return min + Math.floor(unit() * (max - min + 1))
289
+ }
290
+ const pick = <T>(list: readonly T[]): T => {
291
+ if (list.length === 0) throw new TypeError("fake.pick needs a non-empty list")
292
+ return list[int(0, list.length - 1)]!
293
+ }
294
+ const word = () => pick(WORDS)
295
+ const words = (k: number) => {
296
+ if (!Number.isSafeInteger(k) || k < 1) throw new TypeError("fake.words k must be an integer from 1")
297
+ return Array.from({ length: k }, word).join(" ")
298
+ }
299
+ const sentence = () => `${capitalize(words(int(5, 10)))}.`
300
+ const slug = () => words(3).replaceAll(" ", "-")
301
+ const hex = (digits: number) => Array.from({ length: digits }, () => int(0, 15).toString(16)).join("")
302
+ return {
303
+ name: () => `${pick(FIRST_NAMES)} ${pick(LAST_NAMES)}`,
304
+ firstName: () => pick(FIRST_NAMES),
305
+ lastName: () => pick(LAST_NAMES),
306
+ email: (n) => `${word()}${n ?? ""}@example.com`,
307
+ word,
308
+ words,
309
+ sentence,
310
+ paragraph: () => Array.from({ length: int(3, 6) }, sentence).join(" "),
311
+ int,
312
+ float(min, max) {
313
+ if (!Number.isFinite(min) || !Number.isFinite(max)) throw new TypeError("fake.float takes finite numbers")
314
+ if (min > max) throw new TypeError("fake.float min must not exceed max")
315
+ return min + unit() * (max - min)
316
+ },
317
+ bool: (p = 0.5) => unit() < p,
318
+ pick,
319
+ date(range) {
320
+ const from = instant("from", range.from)
321
+ const to = instant("to", range.to)
322
+ if (from > to) throw new TypeError("fake.date from must not be after to")
323
+ return new Date(from + Math.floor(unit() * (to - from + 1)))
324
+ },
325
+ uuid: () => `${hex(8)}-${hex(4)}-4${hex(3)}-${pick(["8", "9", "a", "b"])}${hex(3)}-${hex(12)}`,
326
+ slug,
327
+ url: () => `https://example.com/${slug()}`,
328
+ }
329
+ }
330
+
331
+ const SEED_ENV = "HAMUR_FAKE_SEED"
332
+
333
+ /** `HAMUR_FAKE_SEED` or 1. */
334
+ export function fakeSeed(): number {
335
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env
336
+ const text = env?.[SEED_ENV]
337
+ if (text === undefined || text === "") return 1
338
+ const seed = Number(text)
339
+ if (!Number.isSafeInteger(seed)) throw new TypeError(`${SEED_ENV} must be an integer (got ${JSON.stringify(text)})`)
340
+ return seed
341
+ }
342
+
343
+ /** One 32-bit seed per factory, so a table's rows do not depend on which other factories ran first. */
344
+ export function seedOf(seed: number, key: string): number {
345
+ let hash = (seed ^ 0x811c9dc5) >>> 0
346
+ for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193) >>> 0
347
+ return hash
348
+ }
@@ -0,0 +1,17 @@
1
+ import type { DatabaseName, Database } from "../index.ts"
2
+ import { databases } from "./databases.ts"
3
+
4
+ export type { DatabaseName, Insert, Row, TableName } from "../index.ts"
5
+ export { defineDatabaseClient } from "./client.ts"
6
+
7
+ /** The connection `name` (default `"default"`) of `db.connections`, one per process, opened at its first query. */
8
+ export function useDatabase(name?: DatabaseName | (string & {})): Database {
9
+ return databases.use(name)
10
+ }
11
+ export { cursorQuery, offsetQuery } from "./page.ts"
12
+ export { tableEntities } from "./table-entities.ts"
13
+ export { defineFactory } from "./define-factory.ts"
14
+ export type { Factory } from "./define-factory.ts"
15
+ export type { Fake } from "./fake.ts"
16
+ export { factory } from "./factory.ts"
17
+ export type { TableFactory } from "./factory-core.ts"