@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.
- package/LICENSE +22 -0
- package/README.md +38 -2
- package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
- package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
- package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
- package/dist/chunks/browser-d1-a16d23f0.js +8 -0
- package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
- package/dist/chunks/browser-index-kf697bfy.js +113 -0
- package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
- package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
- package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
- package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
- package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
- package/dist/chunks/bun-index-06tj00dn.js +11 -0
- package/dist/chunks/bun-index-9na2zkqq.js +224 -0
- package/dist/chunks/bun-index-b47nngck.js +352 -0
- package/dist/chunks/bun-index-hrx1eqma.js +29 -0
- package/dist/chunks/bun-index-pd6k99dv.js +114 -0
- package/dist/src/cli.js +1692 -0
- package/dist/src/devtools.js +153 -0
- package/dist/src/index.js +1491 -0
- package/dist/src/server/index.js +584 -0
- package/dist/src/storage/define.js +7 -0
- package/dist/types/src/build/connections.d.ts +8 -0
- package/dist/types/src/build/databases.d.ts +20 -0
- package/dist/types/src/build/factories.d.ts +6 -0
- package/dist/types/src/build/migrations.d.ts +21 -0
- package/dist/types/src/build/queue.d.ts +7 -0
- package/dist/types/src/build/schema.d.ts +50 -0
- package/dist/types/src/build/tables.d.ts +7 -0
- package/dist/types/src/build/types.d.ts +4 -0
- package/dist/types/src/cli.d.ts +26 -0
- package/dist/types/src/connectors/bun-sql.d.ts +3 -0
- package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/client-fakes.d.ts +57 -0
- package/dist/types/src/connectors/client.d.ts +3 -0
- package/dist/types/src/connectors/d1-fake.d.ts +32 -0
- package/dist/types/src/connectors/d1.d.ts +26 -0
- package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/node-test.d.ts +17 -0
- package/dist/types/src/connectors/suite.d.ts +13 -0
- package/dist/types/src/devtools.d.ts +6 -0
- package/dist/types/src/index.d.ts +25 -0
- package/dist/types/src/module.d.ts +6 -0
- package/dist/types/src/options.d.ts +9 -0
- package/dist/types/src/runtime/connector.d.ts +53 -0
- package/dist/types/src/runtime/database.d.ts +15 -0
- package/dist/types/src/runtime/migrate.d.ts +56 -0
- package/dist/types/src/runtime/query.d.ts +12 -0
- package/dist/types/src/runtime/queue-process.d.ts +1 -0
- package/dist/types/src/runtime/queue.d.ts +85 -0
- package/dist/types/src/runtime/registry.d.ts +16 -0
- package/dist/types/src/server/client.d.ts +3 -0
- package/dist/types/src/server/databases.d.ts +4 -0
- package/dist/types/src/server/define-factory.d.ts +9 -0
- package/dist/types/src/server/devtools-routes.d.ts +4 -0
- package/dist/types/src/server/devtools.d.ts +26 -0
- package/dist/types/src/server/door-dev.d.ts +3 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/factory-core.d.ts +12 -0
- package/dist/types/src/server/factory.d.ts +6 -0
- package/dist/types/src/server/fake.d.ts +35 -0
- package/dist/types/src/server/index.d.ts +12 -0
- package/dist/types/src/server/migrations.d.ts +5 -0
- package/dist/types/src/server/page.d.ts +26 -0
- package/dist/types/src/server/plugin.d.ts +1 -0
- package/dist/types/src/server/queue.d.ts +6 -0
- package/dist/types/src/server/table-entities.d.ts +33 -0
- package/dist/types/src/server/task.d.ts +6 -0
- package/dist/types/src/storage/define.d.ts +12 -0
- package/dist/types/src/storage/driver.d.ts +36 -0
- package/dist/types/src/storage/index.d.ts +3 -0
- package/dist/types/src/types.d.ts +103 -0
- package/package.json +55 -4
- package/src/build/connections.ts +225 -0
- package/src/build/databases.ts +101 -0
- package/src/build/factories.ts +135 -0
- package/src/build/migrations.ts +247 -0
- package/src/build/queue.ts +29 -0
- package/src/build/schema.ts +636 -0
- package/src/build/tables.ts +20 -0
- package/src/build/types.ts +46 -0
- package/src/cli.ts +153 -0
- package/src/connectors/bun-sql.ts +68 -0
- package/src/connectors/bun-sqlite.ts +69 -0
- package/src/connectors/client-fakes.ts +257 -0
- package/src/connectors/client.ts +161 -0
- package/src/connectors/d1-fake.ts +92 -0
- package/src/connectors/d1.ts +151 -0
- package/src/connectors/node-sqlite.ts +83 -0
- package/src/connectors/node-test.ts +31 -0
- package/src/connectors/suite.ts +406 -0
- package/src/devtools.ts +264 -0
- package/src/env.d.ts +28 -0
- package/src/index.ts +46 -0
- package/src/module.ts +36 -0
- package/src/options.ts +104 -0
- package/src/runtime/connector.ts +87 -0
- package/src/runtime/database.ts +353 -0
- package/src/runtime/migrate.ts +307 -0
- package/src/runtime/query.ts +82 -0
- package/src/runtime/queue-process.ts +39 -0
- package/src/runtime/queue.ts +380 -0
- package/src/runtime/registry.ts +61 -0
- package/src/server/client.ts +6 -0
- package/src/server/databases.ts +24 -0
- package/src/server/define-factory.ts +22 -0
- package/src/server/devtools-routes.ts +34 -0
- package/src/server/devtools.ts +205 -0
- package/src/server/door-dev.ts +6 -0
- package/src/server/door.ts +4 -0
- package/src/server/factory-core.ts +91 -0
- package/src/server/factory.ts +19 -0
- package/src/server/fake.ts +348 -0
- package/src/server/index.ts +17 -0
- package/src/server/migrations.ts +26 -0
- package/src/server/page.ts +181 -0
- package/src/server/plugin.ts +14 -0
- package/src/server/queue.ts +38 -0
- package/src/server/table-entities.ts +29 -0
- package/src/server/task.ts +15 -0
- package/src/storage/define.ts +12 -0
- package/src/storage/driver.ts +419 -0
- package/src/storage/index.ts +7 -0
- package/src/types.ts +101 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DatabaseName, DefaultDatabase, Insert, Row, TableName } from "../index.ts";
|
|
2
|
+
import type { Database } from "../types.ts";
|
|
3
|
+
import type { Factory } from "./define-factory.ts";
|
|
4
|
+
type Overrides<T extends TableName<C>, C extends DatabaseName> = Partial<Insert<T, C>> | ((n: number) => Partial<Insert<T, C>>);
|
|
5
|
+
/** What `factory(table)` returns. */
|
|
6
|
+
export interface TableFactory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase> {
|
|
7
|
+
make(count?: number, overrides?: Overrides<T, C>): Insert<T, C>[];
|
|
8
|
+
create(count?: number, overrides?: Overrides<T, C>): Promise<Row<T, C>[]>;
|
|
9
|
+
}
|
|
10
|
+
/** `n` counts from 1 per value, and the values of `fake` follow `HAMUR_FAKE_SEED` and the table. */
|
|
11
|
+
export declare function createFactory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase>(table: T, connection: string, definition: Factory<T, C>, open: () => Database): TableFactory<T, C>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { DatabaseName, DefaultDatabase, TableName } from "../index.ts";
|
|
2
|
+
import { type TableFactory } from "./factory-core.ts";
|
|
3
|
+
/** The factory of `server/db/factories/<table>.ts` (`<connection>/<table>.ts` for another connection). */
|
|
4
|
+
export declare function factory<T extends TableName<C>, C extends DatabaseName = DefaultDatabase>(table: T, options?: {
|
|
5
|
+
connection?: C;
|
|
6
|
+
}): TableFactory<T, C>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
type Instant = Date | string | number;
|
|
2
|
+
/** The seeded generator a factory's `make` gets. */
|
|
3
|
+
export interface Fake {
|
|
4
|
+
name(): string;
|
|
5
|
+
firstName(): string;
|
|
6
|
+
lastName(): string;
|
|
7
|
+
/** `<word><n>@example.com`, unique per `n`; without `n`, `<word>@example.com`. */
|
|
8
|
+
email(n?: number): string;
|
|
9
|
+
word(): string;
|
|
10
|
+
words(k: number): string;
|
|
11
|
+
sentence(): string;
|
|
12
|
+
paragraph(): string;
|
|
13
|
+
/** An integer from `min` to `max`, both included. */
|
|
14
|
+
int(min: number, max: number): number;
|
|
15
|
+
/** A number from `min` up to, not including, `max`. */
|
|
16
|
+
float(min: number, max: number): number;
|
|
17
|
+
/** `true` with probability `p` (default 0.5). */
|
|
18
|
+
bool(p?: number): boolean;
|
|
19
|
+
pick<T>(list: readonly T[]): T;
|
|
20
|
+
/** A date from `from` to `to`, both included. */
|
|
21
|
+
date(range: {
|
|
22
|
+
from: Instant;
|
|
23
|
+
to: Instant;
|
|
24
|
+
}): Date;
|
|
25
|
+
uuid(): string;
|
|
26
|
+
slug(): string;
|
|
27
|
+
url(): string;
|
|
28
|
+
}
|
|
29
|
+
/** The same `seed` gives the same values in the same order. */
|
|
30
|
+
export declare function createFake(seed: number): Fake;
|
|
31
|
+
/** `HAMUR_FAKE_SEED` or 1. */
|
|
32
|
+
export declare function fakeSeed(): number;
|
|
33
|
+
/** One 32-bit seed per factory, so a table's rows do not depend on which other factories ran first. */
|
|
34
|
+
export declare function seedOf(seed: number, key: string): number;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DatabaseName, Database } from "../index.ts";
|
|
2
|
+
export type { DatabaseName, Insert, Row, TableName } from "../index.ts";
|
|
3
|
+
export { defineDatabaseClient } from "./client.ts";
|
|
4
|
+
/** The connection `name` (default `"default"`) of `db.connections`, one per process, opened at its first query. */
|
|
5
|
+
export declare function useDatabase(name?: DatabaseName | (string & {})): Database;
|
|
6
|
+
export { cursorQuery, offsetQuery } from "./page.ts";
|
|
7
|
+
export { tableEntities } from "./table-entities.ts";
|
|
8
|
+
export { defineFactory } from "./define-factory.ts";
|
|
9
|
+
export type { Factory } from "./define-factory.ts";
|
|
10
|
+
export type { Fake } from "./fake.ts";
|
|
11
|
+
export { factory } from "./factory.ts";
|
|
12
|
+
export type { TableFactory } from "./factory-core.ts";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Logger } from "hamur/server";
|
|
2
|
+
/** What a server run applied: each connection's file names, in order. */
|
|
3
|
+
export type AppliedMigrations = Record<string, string[]>;
|
|
4
|
+
/** The server's run over every bundled connection, or `only`; the plugin at start and the task `db:migrate` share it. */
|
|
5
|
+
export declare function applyMigrations(log: Pick<Logger, "info" | "warn">, only?: string): Promise<AppliedMigrations>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CursorPage, OffsetPage } from "hamur/server";
|
|
2
|
+
import type { Dialect, SqlFragment } from "../types.ts";
|
|
3
|
+
type Direction = "asc" | "desc";
|
|
4
|
+
export declare const quote: (dialect: Dialect, segments: string[]) => string;
|
|
5
|
+
/** The keyset parts of a page query. */
|
|
6
|
+
export declare function cursorQuery<R extends Record<string, unknown>>(input: {
|
|
7
|
+
cursor?: string;
|
|
8
|
+
limit: number;
|
|
9
|
+
}, options: {
|
|
10
|
+
orderBy: ReadonlyArray<readonly [column: string, direction: Direction]>;
|
|
11
|
+
}): {
|
|
12
|
+
where: SqlFragment;
|
|
13
|
+
orderBy: SqlFragment;
|
|
14
|
+
limit: number;
|
|
15
|
+
page(rows: R[]): CursorPage<R>;
|
|
16
|
+
};
|
|
17
|
+
/** The `limit`, `offset` and page of an offset-paginated query. */
|
|
18
|
+
export declare function offsetQuery<R>(input: {
|
|
19
|
+
page: number;
|
|
20
|
+
perPage: number;
|
|
21
|
+
}): {
|
|
22
|
+
limit: number;
|
|
23
|
+
offset: number;
|
|
24
|
+
page(rows: R[], total: number): OffsetPage<R>;
|
|
25
|
+
};
|
|
26
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const dbPlugin: import("hamur/server").ServerPlugin;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { HamurServer } from "hamur/server";
|
|
2
|
+
/**
|
|
3
|
+
* With `tasks.queue: { driver: "db" }`, `enqueue` inserts a row and this process runs a worker once the plugins ran.
|
|
4
|
+
* Its `close` hook goes before the one that closes the connections: the worker stops claiming and its runs end first.
|
|
5
|
+
*/
|
|
6
|
+
export declare function startQueue(server: HamurServer): void;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { EntityData, EntitySource, EntityTypeName } from "hamur/server";
|
|
2
|
+
import type { DatabaseName, DefaultDatabase, Row, TableName } from "../index.ts";
|
|
3
|
+
type ColumnOf<C extends DatabaseName, Tbl extends TableName<C>> = keyof Row<Tbl, C> & string;
|
|
4
|
+
/** An entity source that loads from a table, and that `authorizedWhere` turns into SQL. */
|
|
5
|
+
export declare function tableEntities<T extends EntityTypeName, Tbl extends TableName<C>, C extends DatabaseName = DefaultDatabase>(options: {
|
|
6
|
+
table: Tbl;
|
|
7
|
+
connection?: C;
|
|
8
|
+
id?: ColumnOf<C, Tbl>;
|
|
9
|
+
attributes: {
|
|
10
|
+
[K in keyof EntityData<T>["attrs"]]: ColumnOf<C, Tbl> | {
|
|
11
|
+
column: ColumnOf<C, Tbl>;
|
|
12
|
+
entity?: EntityTypeName;
|
|
13
|
+
boolean?: true;
|
|
14
|
+
} | {
|
|
15
|
+
join: {
|
|
16
|
+
table: string;
|
|
17
|
+
key: string;
|
|
18
|
+
value: string;
|
|
19
|
+
};
|
|
20
|
+
entity?: EntityTypeName;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
parents?: {
|
|
24
|
+
[K in ColumnOf<C, Tbl>]?: EntityTypeName;
|
|
25
|
+
};
|
|
26
|
+
ancestors?: {
|
|
27
|
+
table: string;
|
|
28
|
+
id: string;
|
|
29
|
+
type: string;
|
|
30
|
+
ancestor: string;
|
|
31
|
+
};
|
|
32
|
+
}): EntitySource<T>;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type AppliedMigrations } from "./migrations.ts";
|
|
2
|
+
/** `db:migrate`, the run of the server's start, on demand: `runTask`, `tasks.runOnStart`, `scheduledTasks`, the CLI. */
|
|
3
|
+
declare const _default: import("hamur/server").Task<{
|
|
4
|
+
connection?: string;
|
|
5
|
+
} | undefined, AppliedMigrations>;
|
|
6
|
+
export default _default;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** A storage mount on a `db.connections` table: `storage: { sessions: dbStorage({ connection: "main" }) }`. */
|
|
2
|
+
export declare const dbStorage: (options?: ({
|
|
3
|
+
connection?: string | import("hamur").EnvRef<string> | undefined;
|
|
4
|
+
table?: string | import("hamur").EnvRef<string> | undefined;
|
|
5
|
+
} & {
|
|
6
|
+
encrypt?: import("hamur").EnvRef<string | readonly string[]>;
|
|
7
|
+
}) | undefined) => import("hamur").StorageMount<{
|
|
8
|
+
connection?: string | import("hamur").EnvRef<string> | undefined;
|
|
9
|
+
table?: string | import("hamur").EnvRef<string> | undefined;
|
|
10
|
+
} & {
|
|
11
|
+
encrypt?: import("hamur").EnvRef<string | readonly string[]>;
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Database } from "../types.ts";
|
|
2
|
+
export interface DbStorageOptions {
|
|
3
|
+
/** Connection name of `db.connections` (default `"default"`). */
|
|
4
|
+
connection?: string;
|
|
5
|
+
/** Table name (default `hamur_storage`). */
|
|
6
|
+
table?: string;
|
|
7
|
+
}
|
|
8
|
+
/** The storage driver (`StorageDriver` of `hamur/server`) with every optional method this driver implements. */
|
|
9
|
+
export interface DbStorageDriver {
|
|
10
|
+
getItem(key: string): Promise<Uint8Array | undefined>;
|
|
11
|
+
setItem(key: string, value: Uint8Array, expires?: number): Promise<void>;
|
|
12
|
+
hasItem(key: string): Promise<boolean>;
|
|
13
|
+
removeItem(key: string): Promise<void>;
|
|
14
|
+
getKeys(prefix: string): Promise<string[]>;
|
|
15
|
+
clear(prefix: string): Promise<void>;
|
|
16
|
+
getItems(keys: string[]): Promise<Array<Uint8Array | undefined>>;
|
|
17
|
+
setItems(items: Array<{
|
|
18
|
+
key: string;
|
|
19
|
+
value: Uint8Array | undefined;
|
|
20
|
+
expires?: number;
|
|
21
|
+
}>): Promise<void>;
|
|
22
|
+
getMeta(key: string): Promise<{
|
|
23
|
+
size?: number;
|
|
24
|
+
mtime?: Date;
|
|
25
|
+
expires?: number;
|
|
26
|
+
} | undefined>;
|
|
27
|
+
increment(key: string, by: number, expires?: number): Promise<number | undefined>;
|
|
28
|
+
}
|
|
29
|
+
/** Bytes of a stored key on every dialect: the mount's part, the key and the `$` of its metadata record. */
|
|
30
|
+
export declare const MAX_KEY_BYTES = 1024;
|
|
31
|
+
/**
|
|
32
|
+
* One table, `(key, value, expires, mtime)` (`BYTEA` and `BIGINT` on postgres, a binary `key` and `LONGBLOB` on mysql),
|
|
33
|
+
* written in the SQL of the connection's dialect; the table is created at first use. A mount's keys are stored as
|
|
34
|
+
* `<mount>|<key>`, so mounts that share a table never see each other's rows.
|
|
35
|
+
*/
|
|
36
|
+
export declare function dbStorageDriver(database: () => Database, options?: DbStorageOptions, mount?: string): DbStorageDriver;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type DbStorageDriver, type DbStorageOptions } from "./driver.ts";
|
|
2
|
+
/** The storage driver of a `dbStorage({ connection?, table? })` mount, given the mount's name; the connection opens at the mount's first use. */
|
|
3
|
+
export default function db(options?: DbStorageOptions, mount?: string): DbStorageDriver;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { HamurContext } from "hamur/kit";
|
|
2
|
+
import type { Secret } from "hamur/server";
|
|
3
|
+
import type { createSqlFragment } from "hamur/server/internal";
|
|
4
|
+
export type Dialect = "sqlite" | "postgres" | "mysql";
|
|
5
|
+
export type { Secret };
|
|
6
|
+
/** `hamur/server`'s `SqlFragment`, named through the entry that holds its symbol so both resolve to one declaration. */
|
|
7
|
+
export type SqlFragment = ReturnType<typeof createSqlFragment>;
|
|
8
|
+
export type Connection = ({
|
|
9
|
+
connector: "bun-sql";
|
|
10
|
+
url?: Secret;
|
|
11
|
+
dialect?: Dialect;
|
|
12
|
+
} | {
|
|
13
|
+
connector: "bun-sqlite";
|
|
14
|
+
path: string;
|
|
15
|
+
} | {
|
|
16
|
+
connector: "node-sqlite";
|
|
17
|
+
path: string;
|
|
18
|
+
} | {
|
|
19
|
+
connector: "d1";
|
|
20
|
+
binding: string;
|
|
21
|
+
} | {
|
|
22
|
+
connector: "client";
|
|
23
|
+
dialect: Dialect;
|
|
24
|
+
client: string;
|
|
25
|
+
}) & {
|
|
26
|
+
dev?: Connection;
|
|
27
|
+
};
|
|
28
|
+
export interface DbConfig {
|
|
29
|
+
migrate?: "dev" | "start" | "build" | false;
|
|
30
|
+
connections?: Record<string, Connection>;
|
|
31
|
+
}
|
|
32
|
+
/** One connection as the build resolved it: the connector, its dialect and the options the connector opens with. */
|
|
33
|
+
export interface ResolvedConnection {
|
|
34
|
+
connector: Connection["connector"];
|
|
35
|
+
dialect: Dialect;
|
|
36
|
+
url?: Secret;
|
|
37
|
+
path?: string;
|
|
38
|
+
binding?: string;
|
|
39
|
+
/** The client file as configured, relative to `rootDir`. */
|
|
40
|
+
client?: string;
|
|
41
|
+
/** Replaces this connection under `hamur dev` and in the prerender; the build reads it and does not pass it on. */
|
|
42
|
+
dev?: ResolvedConnection;
|
|
43
|
+
}
|
|
44
|
+
export interface ResolvedDbOptions {
|
|
45
|
+
migrate: "dev" | "start" | "build" | false;
|
|
46
|
+
/** The configured connections; `default` is added by `setupConnections` when the preset has a database of its own. */
|
|
47
|
+
connections: Record<string, ResolvedConnection>;
|
|
48
|
+
}
|
|
49
|
+
export type DbSetup = (options: ResolvedDbOptions, hamur: HamurContext) => void | Promise<void>;
|
|
50
|
+
export type SqlValue = string | number | bigint | boolean | null | Date | Uint8Array | readonly SqlValue[];
|
|
51
|
+
export interface RunResult {
|
|
52
|
+
changes: number;
|
|
53
|
+
lastInsertId?: number | string;
|
|
54
|
+
}
|
|
55
|
+
export interface Query<R> extends PromiseLike<R> {
|
|
56
|
+
/** The statement with the dialect's placeholders: `$1 … $n` on postgres, `?` on sqlite and mysql. */
|
|
57
|
+
readonly text: string;
|
|
58
|
+
readonly values: readonly SqlValue[];
|
|
59
|
+
}
|
|
60
|
+
export interface Database {
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly dialect: Dialect;
|
|
63
|
+
sql<T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: Array<SqlValue | SqlFragment>): Query<T[]>;
|
|
64
|
+
first<T = Record<string, unknown>>(strings: TemplateStringsArray, ...values: Array<SqlValue | SqlFragment>): Query<T | undefined>;
|
|
65
|
+
run(strings: TemplateStringsArray, ...values: Array<SqlValue | SqlFragment>): Query<RunResult>;
|
|
66
|
+
exec(text: string): Promise<void>;
|
|
67
|
+
batch<const Q extends readonly Query<unknown>[]>(queries: Q): Promise<{
|
|
68
|
+
[K in keyof Q]: Awaited<Q[K]>;
|
|
69
|
+
}>;
|
|
70
|
+
transaction<R>(fn: (tx: Transaction) => Promise<R>): Promise<R>;
|
|
71
|
+
close(): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
export type Transaction = Omit<Database, "transaction" | "close">;
|
|
74
|
+
/** The app's own driver adapted to one shape; `text` holds the dialect's placeholders and `params` the values in order. */
|
|
75
|
+
export interface DatabaseClient {
|
|
76
|
+
query(text: string, params: unknown[]): Promise<{
|
|
77
|
+
rows: Record<string, unknown>[];
|
|
78
|
+
changes?: number;
|
|
79
|
+
lastInsertId?: number | string;
|
|
80
|
+
}>;
|
|
81
|
+
/**
|
|
82
|
+
* One connection held until `release`; `transaction` and `batch` run on it, since a `BEGIN` sent to a pool lands on any connection.
|
|
83
|
+
* `release(error)` gets the error that left the connection in an unknown state (a failed `ROLLBACK`, a failed migration run):
|
|
84
|
+
* the pool should drop it, not hand it out again.
|
|
85
|
+
*/
|
|
86
|
+
reserve?(): Promise<{
|
|
87
|
+
query: DatabaseClient["query"];
|
|
88
|
+
release(error?: Error): void | Promise<void>;
|
|
89
|
+
}>;
|
|
90
|
+
end?(): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
declare module "hamur" {
|
|
93
|
+
interface HamurModuleOptions {
|
|
94
|
+
db?: DbConfig;
|
|
95
|
+
}
|
|
96
|
+
interface HamurHooks {
|
|
97
|
+
/** A module adds a directory of `<number>_<name>.sql` files for a connection. */
|
|
98
|
+
"db:migrations:dirs": (dirs: Array<{
|
|
99
|
+
connection: string;
|
|
100
|
+
dir: string;
|
|
101
|
+
}>) => void | Promise<void>;
|
|
102
|
+
}
|
|
103
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hamur/db",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/productdevbook/hamur.git",
|
|
9
|
+
"directory": "packages/db"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/types/src/index.d.ts",
|
|
14
|
+
"bun": "./src/index.ts",
|
|
15
|
+
"hamur-source": "./src/index.ts",
|
|
16
|
+
"node": "./dist/src/index.js",
|
|
17
|
+
"default": "./src/index.ts"
|
|
18
|
+
},
|
|
19
|
+
"./server": {
|
|
20
|
+
"types": "./dist/types/src/server/index.d.ts",
|
|
21
|
+
"bun": "./src/server/index.ts",
|
|
22
|
+
"hamur-source": "./src/server/index.ts",
|
|
23
|
+
"node": "./dist/src/server/index.js",
|
|
24
|
+
"default": "./src/server/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"./storage": {
|
|
27
|
+
"types": "./dist/types/src/storage/define.d.ts",
|
|
28
|
+
"bun": "./src/storage/define.ts",
|
|
29
|
+
"hamur-source": "./src/storage/define.ts",
|
|
30
|
+
"node": "./dist/src/storage/define.js",
|
|
31
|
+
"default": "./src/storage/define.ts"
|
|
32
|
+
},
|
|
33
|
+
"./cli": {
|
|
34
|
+
"types": "./dist/types/src/cli.d.ts",
|
|
35
|
+
"bun": "./src/cli.ts",
|
|
36
|
+
"hamur-source": "./src/cli.ts",
|
|
37
|
+
"node": "./dist/src/cli.js",
|
|
38
|
+
"default": "./src/cli.ts"
|
|
39
|
+
},
|
|
40
|
+
"./devtools": {
|
|
41
|
+
"types": "./dist/types/src/devtools.d.ts",
|
|
42
|
+
"bun": "./src/devtools.ts",
|
|
43
|
+
"hamur-source": "./src/devtools.ts",
|
|
44
|
+
"node": "./dist/src/devtools.js",
|
|
45
|
+
"default": "./src/devtools.ts"
|
|
46
|
+
},
|
|
47
|
+
"./package.json": "./package.json"
|
|
48
|
+
},
|
|
49
|
+
"files": [
|
|
50
|
+
"dist",
|
|
51
|
+
"src"
|
|
52
|
+
],
|
|
53
|
+
"dependencies": {},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"hamur": "~0.0.2"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { join } from "node:path"
|
|
2
|
+
import {
|
|
3
|
+
DiagnosticError,
|
|
4
|
+
addServer,
|
|
5
|
+
addTemplate,
|
|
6
|
+
createResolver,
|
|
7
|
+
diagnostic,
|
|
8
|
+
useLogger,
|
|
9
|
+
type HamurContext,
|
|
10
|
+
} from "hamur/kit"
|
|
11
|
+
import { CONNECTORS } from "../options.ts"
|
|
12
|
+
import { dbStorage } from "../storage/define.ts"
|
|
13
|
+
import type { DbStorageOptions } from "../storage/driver.ts"
|
|
14
|
+
import { asBun, clientFile, clientLoaders, devConnections, LOADERS } from "./databases.ts"
|
|
15
|
+
import type { DbSetup, ResolvedConnection } from "../types.ts"
|
|
16
|
+
|
|
17
|
+
const SERVER = "@hamur/db/server"
|
|
18
|
+
const PRERENDER_CONNECTIONS = "__HAMUR_DB_PRERENDER__"
|
|
19
|
+
const BUN_DATABASE = {
|
|
20
|
+
connector: "bun-sqlite",
|
|
21
|
+
dialect: "sqlite",
|
|
22
|
+
path: ".data/db.sqlite",
|
|
23
|
+
} as const satisfies ResolvedConnection
|
|
24
|
+
/** The preset's own database when `db.connections` has no `default`; under `hamur dev` it is `bun-sqlite`. */
|
|
25
|
+
const PRESET_DATABASES: Record<string, ResolvedConnection> = {
|
|
26
|
+
bun: BUN_DATABASE,
|
|
27
|
+
static: BUN_DATABASE,
|
|
28
|
+
node: { connector: "node-sqlite", dialect: "sqlite", path: ".data/db.sqlite" },
|
|
29
|
+
cloudflare: { connector: "d1", dialect: "sqlite", binding: "DB" },
|
|
30
|
+
}
|
|
31
|
+
const NO_KEPT_FILES = ["vercel", "netlify"]
|
|
32
|
+
const WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"]
|
|
33
|
+
|
|
34
|
+
function hasPassword(url: string): boolean {
|
|
35
|
+
try {
|
|
36
|
+
return new URL(url).password !== ""
|
|
37
|
+
} catch {
|
|
38
|
+
return false
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
43
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The `d1_databases[].binding` names of the app's wrangler config, with `cloudflare.env`'s block over the top level as the preset
|
|
47
|
+
* writes it, and the preset's errors for a file that does not parse or an env it does not have.
|
|
48
|
+
*/
|
|
49
|
+
async function declaredD1Bindings(rootDir: string, env: string | undefined): Promise<string[]> {
|
|
50
|
+
let config: Record<string, unknown> = {}
|
|
51
|
+
for (const name of WRANGLER_FILES) {
|
|
52
|
+
const file = Bun.file(join(rootDir, name))
|
|
53
|
+
if (!(await file.exists())) continue
|
|
54
|
+
let parsed: unknown
|
|
55
|
+
try {
|
|
56
|
+
parsed = Bun.JSONC.parse(await file.text())
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new DiagnosticError(
|
|
59
|
+
"HAMUR_E5512",
|
|
60
|
+
`Cannot parse ${name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
if (!isObject(parsed)) throw new DiagnosticError("HAMUR_E5513", `${name} must contain a JSON object`)
|
|
64
|
+
config = parsed
|
|
65
|
+
break
|
|
66
|
+
}
|
|
67
|
+
const envs = isObject(config.env) ? config.env : {}
|
|
68
|
+
if (env !== undefined && !(Object.hasOwn(envs, env) && isObject(envs[env]))) {
|
|
69
|
+
throw new DiagnosticError(
|
|
70
|
+
"HAMUR_E5514",
|
|
71
|
+
`cloudflare.env ${JSON.stringify(env)} is not in wrangler.json (envs: ${Object.keys(envs).sort().join(", ") || "none"})`,
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
const chosen = env !== undefined ? { ...config, ...(envs[env] as Record<string, unknown>) } : config
|
|
75
|
+
const databases = Array.isArray(chosen.d1_databases) ? chosen.d1_databases : []
|
|
76
|
+
return databases.flatMap((database) =>
|
|
77
|
+
isObject(database) && typeof database.binding === "string" ? [database.binding] : [],
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const idVariable = (binding: string): string => `HAMUR_CF_${binding.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_ID`
|
|
82
|
+
|
|
83
|
+
/** `cloudflare.bindings.<NAME>.id`, else env `HAMUR_CF_<NAME>_ID` with the name upper-cased and each character outside `A-Z0-9_` turned into `_`. */
|
|
84
|
+
export const cloudflareId = (hamur: HamurContext, binding: string): string | undefined =>
|
|
85
|
+
hamur.options.cloudflare.bindings?.[binding]?.id || process.env[idVariable(binding)] || undefined
|
|
86
|
+
|
|
87
|
+
/** The top-level key of the finalized `.output/wrangler.json` that names `name` as a binding (`binding`, a durable object's `name`, a `vars` key), as `bindingKey` of the preset finds it. */
|
|
88
|
+
export function bindingKey(config: Record<string, unknown>, name: string): string | undefined {
|
|
89
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
90
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
91
|
+
const names = (value: unknown, inDurableObjects: boolean): boolean => {
|
|
92
|
+
if (Array.isArray(value)) return value.some((item) => names(item, inDurableObjects))
|
|
93
|
+
if (!isRecord(value)) return false
|
|
94
|
+
if (value.binding === name || (inDurableObjects && value.name === name)) return true
|
|
95
|
+
return Object.values(value).some((item) => names(item, inDurableObjects))
|
|
96
|
+
}
|
|
97
|
+
for (const [key, value] of Object.entries(config)) {
|
|
98
|
+
if (key === "env") continue
|
|
99
|
+
if (key === "vars" ? isRecord(value) && Object.hasOwn(value, name) : names(value, key === "durable_objects"))
|
|
100
|
+
return key
|
|
101
|
+
}
|
|
102
|
+
return undefined
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const withoutDev = ({ dev: _, ...connection }: ResolvedConnection): ResolvedConnection => connection
|
|
106
|
+
|
|
107
|
+
/** The preset's own `default`, each connection's `dev` under `hamur dev` and in the prerender, `node-sqlite` as `bun-sqlite` under `hamur dev`, the connector and binding checks, the import guard, `#hamur/db/connections` and the close plugin. */
|
|
108
|
+
export const setupConnections: DbSetup = (options, hamur) => {
|
|
109
|
+
const { preset, dev } = hamur.options
|
|
110
|
+
const { connections } = options
|
|
111
|
+
const presetDatabase = dev ? BUN_DATABASE : PRESET_DATABASES[preset]
|
|
112
|
+
if (!connections.default && presetDatabase) connections.default = { ...presetDatabase }
|
|
113
|
+
if (dev) {
|
|
114
|
+
for (const [name, connection] of Object.entries(connections))
|
|
115
|
+
connections[name] = asBun(connection.dev ?? connection)
|
|
116
|
+
}
|
|
117
|
+
const served = Object.fromEntries(
|
|
118
|
+
Object.entries(connections).map(([name, connection]) => [name, withoutDev(connection)]),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
const { rootDir } = hamur.options
|
|
122
|
+
const missing = Object.entries(connections)
|
|
123
|
+
.flatMap(([name, { client, dev: own }]) => [
|
|
124
|
+
[`db.connections.${name}`, client] as const,
|
|
125
|
+
[`db.connections.${name}.dev`, own?.client] as const,
|
|
126
|
+
])
|
|
127
|
+
.flatMap(([at, client]) =>
|
|
128
|
+
client !== undefined && !clientFile(rootDir, client)
|
|
129
|
+
? [`Cannot find database client ${JSON.stringify(client)} for ${at}`]
|
|
130
|
+
: [],
|
|
131
|
+
)
|
|
132
|
+
if (missing.length) throw new DiagnosticError("HAMUR_E5515", missing.join("\n"))
|
|
133
|
+
const clients = Object.fromEntries(
|
|
134
|
+
Object.entries(served).flatMap(([name, { client }]) =>
|
|
135
|
+
client === undefined ? [] : [[name, clientFile(rootDir, client)!]],
|
|
136
|
+
),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
for (const [name, connection] of Object.entries(connections)) {
|
|
140
|
+
if (typeof connection.url === "string" && hasPassword(connection.url))
|
|
141
|
+
useLogger("hamur").warn(
|
|
142
|
+
diagnostic("HAMUR_W5520", `db.connections.${name}.url holds a password; read it from the env with env("NAME")`),
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const protection = hamur.options.build.importProtection
|
|
147
|
+
const client = (protection.client ??= {})
|
|
148
|
+
;(client.deny ??= []).push(SERVER)
|
|
149
|
+
|
|
150
|
+
const r = createResolver(import.meta.url)
|
|
151
|
+
const used = [...new Set(Object.values(served).map((connection) => connection.connector))]
|
|
152
|
+
addTemplate({
|
|
153
|
+
filename: "db/connections",
|
|
154
|
+
getContents: () =>
|
|
155
|
+
`export const connections = ${JSON.stringify(served)};\nexport const connectors = {\n${used
|
|
156
|
+
.map(
|
|
157
|
+
(connector) =>
|
|
158
|
+
` ${JSON.stringify(connector)}: () => import(${JSON.stringify(r.resolve(`../connectors/${connector}.ts`))}),`,
|
|
159
|
+
)
|
|
160
|
+
.join("\n")}\n};\nexport const clients = {\n${Object.entries(clients)
|
|
161
|
+
.map(([name, file]) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),`)
|
|
162
|
+
.join("\n")}\n};\n`,
|
|
163
|
+
})
|
|
164
|
+
addServer(r.resolve(dev ? "../server/door-dev.ts" : "../server/door.ts"))
|
|
165
|
+
// setup, not build:before, which hamur dev never calls
|
|
166
|
+
const unknown: string[] = []
|
|
167
|
+
const driver = dbStorage({}).driver
|
|
168
|
+
for (const [mount, config] of Object.entries(hamur.options.storage)) {
|
|
169
|
+
if (config.driver !== driver) continue
|
|
170
|
+
const connection = (config.options as DbStorageOptions).connection ?? "default"
|
|
171
|
+
if (typeof connection !== "string" || !Object.hasOwn(connections, connection)) {
|
|
172
|
+
unknown.push(
|
|
173
|
+
`Storage mount "${mount}" uses the db driver with connection ${JSON.stringify(connection)}, which db.connections does not have`,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (unknown.length) throw new DiagnosticError("HAMUR_E5516", unknown.join("\n"))
|
|
178
|
+
|
|
179
|
+
// The prerender runs the built server in this process; its dev connections are handed over here so the bundle holds neither them nor their connectors.
|
|
180
|
+
if (!dev) {
|
|
181
|
+
hamur.hooks.hook("prerender:routes", () => {
|
|
182
|
+
const overrides = devConnections(connections)
|
|
183
|
+
const scope = globalThis as Record<string, unknown>
|
|
184
|
+
if (Object.keys(overrides).length)
|
|
185
|
+
scope[PRERENDER_CONNECTIONS] = {
|
|
186
|
+
connections: overrides,
|
|
187
|
+
loaders: LOADERS,
|
|
188
|
+
clients: clientLoaders(hamur, overrides),
|
|
189
|
+
}
|
|
190
|
+
else delete scope[PRERENDER_CONNECTIONS]
|
|
191
|
+
})
|
|
192
|
+
hamur.hooks.hook("build:done", () => void delete (globalThis as Record<string, unknown>)[PRERENDER_CONNECTIONS])
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
hamur.hooks.hook("build:before", async () => {
|
|
196
|
+
const problems: string[] = []
|
|
197
|
+
if (!connections.default && NO_KEPT_FILES.includes(preset)) {
|
|
198
|
+
problems.push(
|
|
199
|
+
`@hamur/db needs db.connections.default on the ${preset} preset: its file system does not keep files`,
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
for (const [name, connection] of Object.entries(dev ? {} : connections)) {
|
|
203
|
+
const { presets } = CONNECTORS[connection.connector]
|
|
204
|
+
if (!presets.includes(preset)) {
|
|
205
|
+
problems.push(
|
|
206
|
+
`Database "${name}" uses the "${connection.connector}" connector, which the "${preset}" preset cannot run (it runs on: ${presets.join(", ")})`,
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const d1 = Object.entries(connections).filter(
|
|
211
|
+
([, connection]) => !dev && connection.connector === "d1" && preset === "cloudflare",
|
|
212
|
+
)
|
|
213
|
+
if (d1.length) {
|
|
214
|
+
const declared = await declaredD1Bindings(hamur.options.rootDir, hamur.options.cloudflare.env)
|
|
215
|
+
for (const [name, { binding }] of d1) {
|
|
216
|
+
if (!declared.includes(binding!) && !cloudflareId(hamur, binding!)) {
|
|
217
|
+
problems.push(
|
|
218
|
+
`db.connections.${name} uses the d1 binding "${binding}", which the app's wrangler config does not declare; add a d1_databases entry with binding "${binding}"`,
|
|
219
|
+
)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (problems.length) throw new DiagnosticError("HAMUR_E5517", problems.join("\n"))
|
|
224
|
+
})
|
|
225
|
+
}
|