@neon-pixels/db 0.0.0 → 0.4.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/LICENSE +21 -0
- package/README.md +95 -0
- package/dist/errors-Gu1ri858.js +11 -0
- package/dist/index.d.ts +78 -0
- package/dist/index.js +116 -0
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +64 -0
- package/dist/types-BmZi9Qzv.d.ts +3 -0
- package/package.json +51 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Neon Pixels Studio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# @neon-pixels/db
|
|
2
|
+
|
|
3
|
+
A drizzle client on the Neon HTTP driver, URL resolvers, a batch helper, audit timestamp columns, offset pagination helpers, and an in-memory Postgres (PGlite) test database. Schema, migrations, and seed scripts stay in your app. Nothing here reads `process.env` or a framework's runtime config; you pass values in.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @neon-pixels/db drizzle-orm @neondatabase/serverless
|
|
9
|
+
pnpm add -D @electric-sql/pglite # only for @neon-pixels/db/testing
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`drizzle-orm` and `@neondatabase/serverless` are peer dependencies. `@electric-sql/pglite` is an optional peer, needed only by `./testing`.
|
|
13
|
+
|
|
14
|
+
## Client
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import {
|
|
18
|
+
createCachedDatabase,
|
|
19
|
+
createDatabase,
|
|
20
|
+
resolveDatabaseUrl,
|
|
21
|
+
} from "@neon-pixels/db";
|
|
22
|
+
import * as schema from "./schema";
|
|
23
|
+
|
|
24
|
+
// One-off client
|
|
25
|
+
const database = createDatabase(process.env.DATABASE_URL ?? "", schema);
|
|
26
|
+
|
|
27
|
+
// Built on first call, then reused. The resolver is yours.
|
|
28
|
+
export const getDatabase = createCachedDatabase(
|
|
29
|
+
() => resolveDatabaseUrl(process.env),
|
|
30
|
+
schema,
|
|
31
|
+
);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`createDatabase` throws a `DatabaseError` with `code: "missing-database-url"` when the URL is empty.
|
|
35
|
+
|
|
36
|
+
`resolveDatabaseUrl(env)` returns `E2E_DATABASE_URL`, else `DATABASE_URL`. `resolveMigrationDatabaseUrl(env)` returns `E2E_DATABASE_URL`, else `DATABASE_URL_UNPOOLED`, else `DATABASE_URL`. Both return `""` when nothing is set.
|
|
37
|
+
|
|
38
|
+
`runBatch(database, statements)` runs a list of statements as one batch, and returns `[]` without calling the database when the list is empty.
|
|
39
|
+
|
|
40
|
+
## Audit timestamps
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { auditTimestamps } from "@neon-pixels/db";
|
|
44
|
+
|
|
45
|
+
export const users = pgTable("users", {
|
|
46
|
+
id: uuid("id").primaryKey(),
|
|
47
|
+
...auditTimestamps(),
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Adds `created_at` and `updated_at`: `timestamptz`, not null, default now, with `updated_at` refreshed on update through drizzle.
|
|
52
|
+
|
|
53
|
+
## Pagination
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import {
|
|
57
|
+
parsePageNumber,
|
|
58
|
+
parsePageSize,
|
|
59
|
+
probeLimit,
|
|
60
|
+
splitPage,
|
|
61
|
+
toLimitOffset,
|
|
62
|
+
} from "@neon-pixels/db";
|
|
63
|
+
|
|
64
|
+
const page = parsePageNumber(query.page);
|
|
65
|
+
const { limit, offset } = toLimitOffset(page, parsePageSize(query.pageSize));
|
|
66
|
+
const rows = await database
|
|
67
|
+
.select()
|
|
68
|
+
.from(posts)
|
|
69
|
+
.limit(probeLimit(limit))
|
|
70
|
+
.offset(offset);
|
|
71
|
+
const { items, hasMore } = splitPage(rows, limit);
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`parsePageNumber(value, maxPage = 1000)` falls back to 1 for anything missing, non-integer, or out of range. `parsePageSize(value, { fallback = 20, max = 100 })` clamps to `1..max`.
|
|
75
|
+
|
|
76
|
+
## Testing
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import {
|
|
80
|
+
applyMigration,
|
|
81
|
+
createMigratedDatabase,
|
|
82
|
+
PGLITE_BOOT_TIMEOUT_MS,
|
|
83
|
+
truncateAllTables,
|
|
84
|
+
} from "@neon-pixels/db/testing";
|
|
85
|
+
|
|
86
|
+
const { client, database } = await createMigratedDatabase({
|
|
87
|
+
migrationsFolder: "server/db/migrations",
|
|
88
|
+
schema,
|
|
89
|
+
stopBefore: "0007_rewrite_slugs", // optional
|
|
90
|
+
});
|
|
91
|
+
await client.exec("INSERT ...");
|
|
92
|
+
await applyMigration(client, "server/db/migrations", "0007_rewrite_slugs");
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Migrations run in `meta/_journal.json` order, each in a transaction. They are not recorded in drizzle's migrations table, so do not pass this database to drizzle's `migrate()`. Boot one instance per test file in `beforeAll` (give it `PGLITE_BOOT_TIMEOUT_MS`) and call `truncateAllTables(client)` in `beforeEach`.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
/** Thrown for invalid database setup, with a stable `code`. */
|
|
3
|
+
var DatabaseError = class extends Error {
|
|
4
|
+
name = "DatabaseError";
|
|
5
|
+
code;
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
export { DatabaseError as t };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { NeonHttpDatabase } from "drizzle-orm/neon-http";
|
|
2
|
+
import { BatchItem } from "drizzle-orm/batch";
|
|
3
|
+
import { t as Schema } from "./types-BmZi9Qzv.js";
|
|
4
|
+
/**
|
|
5
|
+
* Builds a drizzle client on the Neon HTTP driver from an explicit
|
|
6
|
+
* connection string. Throws a `DatabaseError` when the string is empty.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createDatabase<TSchema extends Schema>(databaseUrl: string, schema: TSchema): NeonHttpDatabase<TSchema>;
|
|
9
|
+
/**
|
|
10
|
+
* Returns a getter that builds the client on first call and reuses it. The
|
|
11
|
+
* resolver runs only once, so it is where an app reads its own config.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createCachedDatabase<TSchema extends Schema>(resolveUrl: () => string, schema: TSchema): () => NeonHttpDatabase<TSchema>;
|
|
14
|
+
/**
|
|
15
|
+
* Runs a variable-length list of statements as one batch (one transaction on
|
|
16
|
+
* the Neon HTTP driver). Drizzle types `batch()` as a non-empty tuple, so the
|
|
17
|
+
* cast and the empty-list guard live here: no statements means no call.
|
|
18
|
+
*/
|
|
19
|
+
export declare function runBatch(database: Pick<NeonHttpDatabase<never>, "batch">, statements: BatchItem<"pg">[]): Promise<unknown[]>;
|
|
20
|
+
type DatabaseErrorCode = "missing-database-url" | "unknown-migration";
|
|
21
|
+
/** Thrown for invalid database setup, with a stable `code`. */
|
|
22
|
+
export declare class DatabaseError extends Error {
|
|
23
|
+
name: string;
|
|
24
|
+
readonly code: DatabaseErrorCode;
|
|
25
|
+
constructor(code: DatabaseErrorCode, message: string);
|
|
26
|
+
}
|
|
27
|
+
type DatabaseEnvironment = Record<string, string | undefined>;
|
|
28
|
+
/** `E2E_DATABASE_URL`, else `DATABASE_URL`, else an empty string. */
|
|
29
|
+
export declare function resolveDatabaseUrl(env: DatabaseEnvironment): string;
|
|
30
|
+
/**
|
|
31
|
+
* `E2E_DATABASE_URL`, else `DATABASE_URL_UNPOOLED`, else `DATABASE_URL`, else
|
|
32
|
+
* an empty string. Migrations want the direct (unpooled) connection.
|
|
33
|
+
*/
|
|
34
|
+
export declare function resolveMigrationDatabaseUrl(env: DatabaseEnvironment): string;
|
|
35
|
+
export declare const MAX_PAGE = 1000;
|
|
36
|
+
export declare const DEFAULT_PAGE_SIZE = 20;
|
|
37
|
+
export declare const MAX_PAGE_SIZE = 100;
|
|
38
|
+
interface PageSizeOptions {
|
|
39
|
+
fallback?: number;
|
|
40
|
+
max?: number;
|
|
41
|
+
}
|
|
42
|
+
interface LimitOffset {
|
|
43
|
+
limit: number;
|
|
44
|
+
offset: number;
|
|
45
|
+
}
|
|
46
|
+
interface PageSlice<TRow> {
|
|
47
|
+
items: TRow[];
|
|
48
|
+
hasMore: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Coerces an untrusted 1-based page number. Anything missing, non-integer, or
|
|
52
|
+
* outside `1..maxPage` becomes page 1.
|
|
53
|
+
*/
|
|
54
|
+
export declare function parsePageNumber(value: unknown, maxPage?: number): number;
|
|
55
|
+
/**
|
|
56
|
+
* Coerces an untrusted page size. Missing or non-integer values use the
|
|
57
|
+
* fallback; everything else is clamped to `1..max`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function parsePageSize(value: unknown, { fallback, max }?: PageSizeOptions): number;
|
|
60
|
+
/** Converts a 1-based page and a page size into SQL `limit` and `offset`. */
|
|
61
|
+
export declare function toLimitOffset(page: number, pageSize: number): LimitOffset;
|
|
62
|
+
/** The row count to request so `splitPage` can tell whether more exist. */
|
|
63
|
+
export declare function probeLimit(limit: number): number;
|
|
64
|
+
/**
|
|
65
|
+
* Trims a `probeLimit(limit)` read back to `limit` rows. `hasMore` is true
|
|
66
|
+
* when the extra row came back, so no COUNT query is needed.
|
|
67
|
+
*/
|
|
68
|
+
export declare function splitPage<TRow>(rows: TRow[], limit: number): PageSlice<TRow>;
|
|
69
|
+
/**
|
|
70
|
+
* `created_at` and `updated_at` columns for a table whose rows are edited in
|
|
71
|
+
* place. A function so every table gets its own column builders.
|
|
72
|
+
* `updated_at` is refreshed by drizzle on update.
|
|
73
|
+
*/
|
|
74
|
+
export declare function auditTimestamps(): {
|
|
75
|
+
createdAt: import("drizzle-orm").NotNull<import("drizzle-orm").HasDefault<import("drizzle-orm/pg-core").PgTimestampBuilderInitial<"created_at">>>;
|
|
76
|
+
updatedAt: import("drizzle-orm").HasDefault<import("drizzle-orm").NotNull<import("drizzle-orm").HasDefault<import("drizzle-orm/pg-core").PgTimestampBuilderInitial<"updated_at">>>>;
|
|
77
|
+
};
|
|
78
|
+
export type { DatabaseEnvironment, DatabaseErrorCode, LimitOffset, PageSizeOptions, PageSlice };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { neon } from "@neondatabase/serverless";
|
|
2
|
+
import { drizzle } from "drizzle-orm/neon-http";
|
|
3
|
+
import { t as DatabaseError } from "./errors-Gu1ri858.js";
|
|
4
|
+
import { timestamp } from "drizzle-orm/pg-core";
|
|
5
|
+
// src/client.ts
|
|
6
|
+
/**
|
|
7
|
+
* Builds a drizzle client on the Neon HTTP driver from an explicit
|
|
8
|
+
* connection string. Throws a `DatabaseError` when the string is empty.
|
|
9
|
+
*/
|
|
10
|
+
function createDatabase(databaseUrl, schema) {
|
|
11
|
+
if (!databaseUrl.trim()) throw new DatabaseError("missing-database-url", "Cannot create a database client: the database URL is empty.");
|
|
12
|
+
return drizzle(neon(databaseUrl), { schema });
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Returns a getter that builds the client on first call and reuses it. The
|
|
16
|
+
* resolver runs only once, so it is where an app reads its own config.
|
|
17
|
+
*/
|
|
18
|
+
function createCachedDatabase(resolveUrl, schema) {
|
|
19
|
+
let cached;
|
|
20
|
+
return () => {
|
|
21
|
+
cached ??= createDatabase(resolveUrl(), schema);
|
|
22
|
+
return cached;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Runs a variable-length list of statements as one batch (one transaction on
|
|
27
|
+
* the Neon HTTP driver). Drizzle types `batch()` as a non-empty tuple, so the
|
|
28
|
+
* cast and the empty-list guard live here: no statements means no call.
|
|
29
|
+
*/
|
|
30
|
+
async function runBatch(database, statements) {
|
|
31
|
+
if (statements.length === 0) return [];
|
|
32
|
+
return database.batch(statements);
|
|
33
|
+
}
|
|
34
|
+
// src/env.ts
|
|
35
|
+
function firstSet(env, names) {
|
|
36
|
+
return names.map((name) => env[name]?.trim()).find(Boolean) ?? "";
|
|
37
|
+
}
|
|
38
|
+
/** `E2E_DATABASE_URL`, else `DATABASE_URL`, else an empty string. */
|
|
39
|
+
function resolveDatabaseUrl(env) {
|
|
40
|
+
return firstSet(env, ["E2E_DATABASE_URL", "DATABASE_URL"]);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* `E2E_DATABASE_URL`, else `DATABASE_URL_UNPOOLED`, else `DATABASE_URL`, else
|
|
44
|
+
* an empty string. Migrations want the direct (unpooled) connection.
|
|
45
|
+
*/
|
|
46
|
+
function resolveMigrationDatabaseUrl(env) {
|
|
47
|
+
return firstSet(env, [
|
|
48
|
+
"E2E_DATABASE_URL",
|
|
49
|
+
"DATABASE_URL_UNPOOLED",
|
|
50
|
+
"DATABASE_URL"
|
|
51
|
+
]);
|
|
52
|
+
}
|
|
53
|
+
// src/pagination.ts
|
|
54
|
+
const DECIMAL_INTEGER = /^[+-]?\d+$/;
|
|
55
|
+
const MAX_PAGE = 1e3;
|
|
56
|
+
const DEFAULT_PAGE_SIZE = 20;
|
|
57
|
+
const MAX_PAGE_SIZE = 100;
|
|
58
|
+
function toSafeInteger(value) {
|
|
59
|
+
if (typeof value !== "number" && typeof value !== "string") return;
|
|
60
|
+
if (typeof value === "string" && value.trim() === "") return;
|
|
61
|
+
if (typeof value === "string" && !DECIMAL_INTEGER.test(value.trim())) return;
|
|
62
|
+
const parsed = Number(value);
|
|
63
|
+
return Number.isSafeInteger(parsed) ? parsed : void 0;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Coerces an untrusted 1-based page number. Anything missing, non-integer, or
|
|
67
|
+
* outside `1..maxPage` becomes page 1.
|
|
68
|
+
*/
|
|
69
|
+
function parsePageNumber(value, maxPage = MAX_PAGE) {
|
|
70
|
+
const parsed = toSafeInteger(value);
|
|
71
|
+
if (parsed === void 0 || parsed < 1 || parsed > maxPage) return 1;
|
|
72
|
+
return parsed;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Coerces an untrusted page size. Missing or non-integer values use the
|
|
76
|
+
* fallback; everything else is clamped to `1..max`.
|
|
77
|
+
*/
|
|
78
|
+
function parsePageSize(value, { fallback = 20, max = 100 } = {}) {
|
|
79
|
+
const parsed = toSafeInteger(value);
|
|
80
|
+
if (parsed === void 0) return Math.min(Math.max(fallback, 1), max);
|
|
81
|
+
return Math.min(Math.max(parsed, 1), max);
|
|
82
|
+
}
|
|
83
|
+
/** Converts a 1-based page and a page size into SQL `limit` and `offset`. */
|
|
84
|
+
function toLimitOffset(page, pageSize) {
|
|
85
|
+
return {
|
|
86
|
+
limit: pageSize,
|
|
87
|
+
offset: (page - 1) * pageSize
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** The row count to request so `splitPage` can tell whether more exist. */
|
|
91
|
+
function probeLimit(limit) {
|
|
92
|
+
return limit + 1;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Trims a `probeLimit(limit)` read back to `limit` rows. `hasMore` is true
|
|
96
|
+
* when the extra row came back, so no COUNT query is needed.
|
|
97
|
+
*/
|
|
98
|
+
function splitPage(rows, limit) {
|
|
99
|
+
return {
|
|
100
|
+
items: rows.slice(0, limit),
|
|
101
|
+
hasMore: rows.length > limit
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
// src/timestamps.ts
|
|
105
|
+
/**
|
|
106
|
+
* `created_at` and `updated_at` columns for a table whose rows are edited in
|
|
107
|
+
* place. A function so every table gets its own column builders.
|
|
108
|
+
* `updated_at` is refreshed by drizzle on update.
|
|
109
|
+
*/
|
|
110
|
+
function auditTimestamps() {
|
|
111
|
+
return {
|
|
112
|
+
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
|
113
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull().$onUpdate(() => /* @__PURE__ */ new Date())
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export { DEFAULT_PAGE_SIZE, DatabaseError, MAX_PAGE, MAX_PAGE_SIZE, auditTimestamps, createCachedDatabase, createDatabase, parsePageNumber, parsePageSize, probeLimit, resolveDatabaseUrl, resolveMigrationDatabaseUrl, runBatch, splitPage, toLimitOffset };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { t as Schema } from "./types-BmZi9Qzv.js";
|
|
2
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
3
|
+
import { PgliteDatabase } from "drizzle-orm/pglite";
|
|
4
|
+
/**
|
|
5
|
+
* Booting PGlite (WASM Postgres) is CPU heavy. Boot one instance per test
|
|
6
|
+
* file in `beforeAll`, truncate in `beforeEach`, and give the `beforeAll`
|
|
7
|
+
* this budget instead of vitest's 10s default.
|
|
8
|
+
*/
|
|
9
|
+
export declare const PGLITE_BOOT_TIMEOUT_MS = 30000;
|
|
10
|
+
export interface CreateMigratedDatabaseOptions<TSchema extends Schema> {
|
|
11
|
+
/** The folder drizzle-kit writes: `*.sql` files plus `meta/_journal.json`. */
|
|
12
|
+
migrationsFolder: string;
|
|
13
|
+
schema?: TSchema;
|
|
14
|
+
/** Stop before this migration tag (for example `0007_rewrite_slugs`). */
|
|
15
|
+
stopBefore?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface MigratedDatabase<TSchema extends Schema> {
|
|
18
|
+
client: PGlite;
|
|
19
|
+
database: PgliteDatabase<TSchema>;
|
|
20
|
+
}
|
|
21
|
+
/** Applies one migration by tag, for the step after `stopBefore`. */
|
|
22
|
+
export declare function applyMigration(client: PGlite, migrationsFolder: string, tag: string): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Boots an in-memory Postgres and applies an app's migrations in journal
|
|
25
|
+
* order. With `stopBefore`, applies only the migrations ahead of that tag so a
|
|
26
|
+
* test can seed rows, call `applyMigration`, and assert on the result.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createMigratedDatabase<TSchema extends Schema = Record<string, never>>(options: CreateMigratedDatabaseOptions<TSchema>): Promise<MigratedDatabase<TSchema>>;
|
|
29
|
+
/**
|
|
30
|
+
* Empties every public table and resets identities, so each test starts
|
|
31
|
+
* clean without paying for a fresh boot.
|
|
32
|
+
*/
|
|
33
|
+
export declare function truncateAllTables(client: PGlite): Promise<void>;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { t as DatabaseError } from "./errors-Gu1ri858.js";
|
|
4
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
5
|
+
import { drizzle } from "drizzle-orm/pglite";
|
|
6
|
+
// src/testing.ts
|
|
7
|
+
const STATEMENT_BREAKPOINT = "--> statement-breakpoint";
|
|
8
|
+
/**
|
|
9
|
+
* Booting PGlite (WASM Postgres) is CPU heavy. Boot one instance per test
|
|
10
|
+
* file in `beforeAll`, truncate in `beforeEach`, and give the `beforeAll`
|
|
11
|
+
* this budget instead of vitest's 10s default.
|
|
12
|
+
*/
|
|
13
|
+
const PGLITE_BOOT_TIMEOUT_MS = 3e4;
|
|
14
|
+
async function readJournalTags(migrationsFolder) {
|
|
15
|
+
const journalPath = join(migrationsFolder, "meta", "_journal.json");
|
|
16
|
+
return JSON.parse(await readFile(journalPath, "utf8")).entries.map((entry) => entry.tag);
|
|
17
|
+
}
|
|
18
|
+
function assertKnownTag(tags, tag) {
|
|
19
|
+
if (!tags.includes(tag)) throw new DatabaseError("unknown-migration", `Migration "${tag}" is not in the migrations journal.`);
|
|
20
|
+
}
|
|
21
|
+
async function runMigrationFile(client, migrationsFolder, tag) {
|
|
22
|
+
const statements = (await readFile(join(migrationsFolder, `${tag}.sql`), "utf8")).split(STATEMENT_BREAKPOINT).filter((statement) => statement.trim());
|
|
23
|
+
await client.transaction(async (transaction) => {
|
|
24
|
+
for (const statement of statements) await transaction.exec(statement);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/** Applies one migration by tag, for the step after `stopBefore`. */
|
|
28
|
+
async function applyMigration(client, migrationsFolder, tag) {
|
|
29
|
+
assertKnownTag(await readJournalTags(migrationsFolder), tag);
|
|
30
|
+
await runMigrationFile(client, migrationsFolder, tag);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Boots an in-memory Postgres and applies an app's migrations in journal
|
|
34
|
+
* order. With `stopBefore`, applies only the migrations ahead of that tag so a
|
|
35
|
+
* test can seed rows, call `applyMigration`, and assert on the result.
|
|
36
|
+
*/
|
|
37
|
+
async function createMigratedDatabase(options) {
|
|
38
|
+
const { migrationsFolder, stopBefore } = options;
|
|
39
|
+
const tags = await readJournalTags(migrationsFolder);
|
|
40
|
+
if (stopBefore !== void 0) assertKnownTag(tags, stopBefore);
|
|
41
|
+
const stopIndex = stopBefore === void 0 ? tags.length : tags.indexOf(stopBefore);
|
|
42
|
+
const client = new PGlite();
|
|
43
|
+
try {
|
|
44
|
+
for (const tag of tags.slice(0, stopIndex)) await runMigrationFile(client, migrationsFolder, tag);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
await client.close();
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
client,
|
|
51
|
+
database: drizzle(client, { schema: options.schema })
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Empties every public table and resets identities, so each test starts
|
|
56
|
+
* clean without paying for a fresh boot.
|
|
57
|
+
*/
|
|
58
|
+
async function truncateAllTables(client) {
|
|
59
|
+
const { rows } = await client.query("SELECT tablename FROM pg_tables WHERE schemaname = 'public'");
|
|
60
|
+
if (rows.length === 0) return;
|
|
61
|
+
const tableList = rows.map((row) => `"${row.tablename.replaceAll("\"", "\"\"")}"`).join(", ");
|
|
62
|
+
await client.exec(`TRUNCATE ${tableList} RESTART IDENTITY CASCADE`);
|
|
63
|
+
}
|
|
64
|
+
export { PGLITE_BOOT_TIMEOUT_MS, applyMigration, createMigratedDatabase, truncateAllTables };
|
package/package.json
CHANGED
|
@@ -1 +1,51 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@neon-pixels/db",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Neon HTTP drizzle client, URL resolvers, batch helper, audit timestamps, offset pagination, and a PGlite test database.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/neonpixels-studio/packages.git",
|
|
10
|
+
"directory": "packages/db"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./testing": {
|
|
18
|
+
"types": "./dist/testing.d.ts",
|
|
19
|
+
"default": "./dist/testing.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": "^22.17.0 || ^24.0.0 || >=26.0.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@electric-sql/pglite": "^0.5.16",
|
|
34
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
35
|
+
"drizzle-orm": "^0.45.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"@electric-sql/pglite": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@electric-sql/pglite": "^0.5.16",
|
|
44
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
45
|
+
"drizzle-orm": "^0.45.4"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsdown",
|
|
49
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
50
|
+
}
|
|
51
|
+
}
|