@umituz/web-database 0.0.0-stage → 1.0.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 +59 -2
- package/package.json +69 -4
- package/src/driver.ts +17 -0
- package/src/index.ts +9 -0
- package/src/lifecycle.ts +108 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 umituz
|
|
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
CHANGED
|
@@ -1,3 +1,60 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @umituz/web-database
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The database layer for the fleet — and the **single vendor-coupled module** in the entire ecosystem. Every other package and app speaks drizzle; only this one knows that the database behind it is Neon (serverless HTTP driver today). Swapping or adding a vendor later means changing this package, nothing else.
|
|
4
|
+
|
|
5
|
+
The package is **source-distributed** (published as raw TypeScript in `src/`). Wrangler, Vite, and tsc all compile it alongside your app; no prebuilt bundle ships.
|
|
6
|
+
|
|
7
|
+
## Why it exists
|
|
8
|
+
|
|
9
|
+
Before this package, `neon()` + `drizzle(neon(url))` boilerplate (and the `@neondatabase/serverless` dependency) was scattered across `web-hono` internals and every fleet app's scripts. A vendor change would have meant touching all of them. Now the vendor touch surface is one file: `src/driver.ts`.
|
|
10
|
+
|
|
11
|
+
## What's inside
|
|
12
|
+
|
|
13
|
+
| Export | What it is | Entry |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `createDb(url, schema?)` | drizzle factory over the vendor driver — the only sanctioned way to build a `db` | `.` or `/driver` |
|
|
16
|
+
| `sql(url)` | raw vendor executor (tagged-template queries) for scripts that shouldn't go through drizzle | `.` or `/driver` |
|
|
17
|
+
| `Db` | the database type alias used across the fleet (`web-hono`'s `CrudDb`, `SnapshotDb` derive from it) | `.` or `/driver` |
|
|
18
|
+
| `resetTables` / `snapshotToSeed` / `seedFromSnapshot` / `snapshotToBytes` | lifecycle tooling: prefix-guarded drops, snapshot export, snapshot import | `.` or `/lifecycle` |
|
|
19
|
+
|
|
20
|
+
`resetTables` keeps the fleet's shared-database safety: it drops only tables carrying your project prefix and hard-stops the moment it sees a prefix-less table.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @umituz/web-database
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Peer dependencies (install alongside): `drizzle-orm ^0.45`. The `@neondatabase/serverless` driver ships as a regular dependency — it is this package's implementation detail.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { createDb } from '@umituz/web-database';
|
|
34
|
+
import * as schema from './schema';
|
|
35
|
+
|
|
36
|
+
export const db = createDb(process.env.DATABASE_URL!, schema);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
A reset/seed script:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { resetTables, seedFromSnapshot } from '@umituz/web-database/lifecycle';
|
|
43
|
+
|
|
44
|
+
await resetTables({ specs, prefix: 'hg_', url });
|
|
45
|
+
await seedFromSnapshot({ specs, url, inPath: new URL('./seed.sql.gz', import.meta.url) });
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Rules of engagement
|
|
49
|
+
|
|
50
|
+
- Apps and packages import **only** this package for driver creation and lifecycle work — never `@neondatabase/serverless` directly.
|
|
51
|
+
- Schema stays per-app: this package owns transport and lifecycle, not your tables.
|
|
52
|
+
- A vendor swap (or a second vendor) is implemented here and released as a major/minor of this package; consumers keep importing `createDb`/`sql`.
|
|
53
|
+
|
|
54
|
+
## Development
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npm run typecheck && npm run lint && npm test
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Tests run against an in-memory PGlite instance (`@electric-sql/pglite`); no database credentials needed.
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-database",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Database layer for the fleet — the single vendor-coupled module (Neon serverless HTTP driver today): sql(url) raw executor, createDb(url, schema) drizzle factory, Db type alias, and db lifecycle tooling (reset / snapshot / seed)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"sideEffects": false,
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./src/index.ts",
|
|
11
|
+
"./driver": "./src/driver.ts",
|
|
12
|
+
"./lifecycle": "./src/lifecycle.ts",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"lint": "eslint .",
|
|
23
|
+
"test": "vitest run",
|
|
24
|
+
"test:watch": "vitest",
|
|
25
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm test",
|
|
26
|
+
"version:patch": "npm version patch -m 'chore: release v%s'",
|
|
27
|
+
"version:minor": "npm version minor -m 'chore: release v%s'",
|
|
28
|
+
"version:major": "npm version major -m 'chore: release v%s'"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"drizzle-orm": "^0.45.4"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@neondatabase/serverless": "^1.2.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@electric-sql/pglite": "^0.5.9",
|
|
38
|
+
"@eslint/js": "^9.32.0",
|
|
39
|
+
"@types/node": "~22.13.10",
|
|
40
|
+
"drizzle-orm": "^0.45.4",
|
|
41
|
+
"eslint": "^9.32.0",
|
|
42
|
+
"typescript": "~5.9.2",
|
|
43
|
+
"typescript-eslint": "^8.58.0",
|
|
44
|
+
"vitest": "3.2.4"
|
|
45
|
+
},
|
|
46
|
+
"keywords": [
|
|
47
|
+
"database",
|
|
48
|
+
"postgres",
|
|
49
|
+
"neon",
|
|
50
|
+
"drizzle",
|
|
51
|
+
"driver",
|
|
52
|
+
"vendor-isolation",
|
|
53
|
+
"lifecycle",
|
|
54
|
+
"snapshot",
|
|
55
|
+
"seed",
|
|
56
|
+
"reset"
|
|
57
|
+
],
|
|
58
|
+
"author": "umituz",
|
|
59
|
+
"license": "MIT",
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public"
|
|
62
|
+
},
|
|
63
|
+
"repository": {
|
|
64
|
+
"type": "git",
|
|
65
|
+
"url": "git+https://github.com/umituz/web-database.git"
|
|
66
|
+
},
|
|
67
|
+
"bugs": {
|
|
68
|
+
"url": "https://github.com/umituz/web-database/issues"
|
|
69
|
+
},
|
|
70
|
+
"homepage": "https://github.com/umituz/web-database#readme"
|
|
71
|
+
}
|
package/src/driver.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { drizzle } from 'drizzle-orm/neon-http';
|
|
2
|
+
import type { NeonHttpDatabase } from 'drizzle-orm/neon-http';
|
|
3
|
+
import { neon } from '@neondatabase/serverless';
|
|
4
|
+
|
|
5
|
+
export type Db<TSchema extends Record<string, unknown> = Record<string, never>> = NeonHttpDatabase<TSchema>;
|
|
6
|
+
|
|
7
|
+
export function sql(url: string) {
|
|
8
|
+
return neon(url);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function createDb<TSchema extends Record<string, unknown>>(
|
|
12
|
+
url: string,
|
|
13
|
+
schema?: TSchema,
|
|
14
|
+
): Db<TSchema> {
|
|
15
|
+
const client = neon(url);
|
|
16
|
+
return schema === undefined ? drizzle(client) : drizzle(client, { schema });
|
|
17
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { createDb, sql } from './driver';
|
|
2
|
+
export type { Db } from './driver';
|
|
3
|
+
export {
|
|
4
|
+
resetTables,
|
|
5
|
+
seedFromSnapshot,
|
|
6
|
+
snapshotToBytes,
|
|
7
|
+
snapshotToSeed,
|
|
8
|
+
} from './lifecycle';
|
|
9
|
+
export type { SeedSnapshot, SnapshotBytesResult, SnapshotDb, TableSpec } from './lifecycle';
|
package/src/lifecycle.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { getTableName, getTableColumns } from 'drizzle-orm';
|
|
2
|
+
import type { PgTable } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
5
|
+
import { createDb, sql } from './driver';
|
|
6
|
+
import type { Db } from './driver';
|
|
7
|
+
|
|
8
|
+
export interface TableSpec {
|
|
9
|
+
name: string;
|
|
10
|
+
table: PgTable;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SeedSnapshot {
|
|
14
|
+
generatedAt: string;
|
|
15
|
+
tables: Record<string, Record<string, unknown>[]>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type SnapshotDb = Pick<Db, 'select'>;
|
|
19
|
+
|
|
20
|
+
export interface SnapshotBytesResult {
|
|
21
|
+
generatedAt: string;
|
|
22
|
+
bytes: Uint8Array;
|
|
23
|
+
total: number;
|
|
24
|
+
rawBytes: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function snapshotToBytes(opts: { specs: TableSpec[]; db: SnapshotDb }): Promise<SnapshotBytesResult> {
|
|
28
|
+
const tables: Record<string, unknown[]> = {};
|
|
29
|
+
let total = 0;
|
|
30
|
+
for (const { name, table } of opts.specs) {
|
|
31
|
+
const rows = (await opts.db.select().from(table)) as unknown[];
|
|
32
|
+
tables[name] = rows;
|
|
33
|
+
total += rows.length;
|
|
34
|
+
}
|
|
35
|
+
const generatedAt = new Date().toISOString();
|
|
36
|
+
const payload = JSON.stringify({ generatedAt, tables });
|
|
37
|
+
const gzipped = new Blob([payload]).stream().pipeThrough(new CompressionStream('gzip'));
|
|
38
|
+
const bytes = new Uint8Array(await new Response(gzipped).arrayBuffer());
|
|
39
|
+
return { generatedAt, bytes, total, rawBytes: payload.length };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function resetTables(opts: { specs: TableSpec[]; prefix: string; url: string }): Promise<string[]> {
|
|
43
|
+
const client = sql(opts.url);
|
|
44
|
+
|
|
45
|
+
const names = opts.specs.map((spec) => getTableName(spec.table));
|
|
46
|
+
const unsafe = names.find((n) => !n.startsWith(opts.prefix));
|
|
47
|
+
if (unsafe !== undefined) throw new Error(`Safety stop: '${unsafe}' does not carry prefix '${opts.prefix}' — refusing to drop.`);
|
|
48
|
+
|
|
49
|
+
const dropped: string[] = [];
|
|
50
|
+
for (const name of [...names].reverse()) {
|
|
51
|
+
await client`DROP TABLE IF EXISTS ${client.unsafe(`"${name}"`)} CASCADE`;
|
|
52
|
+
dropped.push(name);
|
|
53
|
+
console.log(`dropped: ${name}`);
|
|
54
|
+
}
|
|
55
|
+
console.log(`\n${names.length} '${opts.prefix}*' tables dropped.`);
|
|
56
|
+
return dropped;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function snapshotToSeed(opts: { specs: TableSpec[]; url: string; outPath: string | URL }): Promise<{ total: number; rawBytes: number }> {
|
|
60
|
+
const db = createDb(opts.url);
|
|
61
|
+
|
|
62
|
+
const tables: Record<string, unknown[]> = {};
|
|
63
|
+
let total = 0;
|
|
64
|
+
for (const { name, table } of opts.specs) {
|
|
65
|
+
const rows = (await db.select().from(table)) as unknown[];
|
|
66
|
+
tables[name] = rows;
|
|
67
|
+
total += rows.length;
|
|
68
|
+
console.log(`${name.padEnd(20)} ${rows.length}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const payload = JSON.stringify({ generatedAt: new Date().toISOString(), tables });
|
|
72
|
+
writeFileSync(opts.outPath, gzipSync(Buffer.from(payload, 'utf8')));
|
|
73
|
+
console.log(`\nSnapshot: ${total} rows → ${opts.outPath} (${(payload.length / 1024).toFixed(0)} KiB raw)`);
|
|
74
|
+
return { total, rawBytes: payload.length };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
type Row = Record<string, unknown>;
|
|
78
|
+
|
|
79
|
+
function reviveRow(table: PgTable, row: Row): Row {
|
|
80
|
+
const out: Row = { ...row };
|
|
81
|
+
for (const [key, col] of Object.entries(getTableColumns(table))) {
|
|
82
|
+
const v = out[key];
|
|
83
|
+
if (v === null || v === undefined) continue;
|
|
84
|
+
if (col.columnType.includes('Timestamp')) out[key] = new Date(v as string);
|
|
85
|
+
else if (col.columnType.toLowerCase().includes('date')) out[key] = String(v).slice(0, 10);
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function seedFromSnapshot(opts: { specs: TableSpec[]; url: string; inPath: string | URL }): Promise<number> {
|
|
91
|
+
const db = createDb(opts.url);
|
|
92
|
+
|
|
93
|
+
const snapshot = JSON.parse(gunzipSync(readFileSync(opts.inPath)).toString('utf8')) as SeedSnapshot;
|
|
94
|
+
console.log(`Snapshot generated at ${snapshot.generatedAt}`);
|
|
95
|
+
|
|
96
|
+
let inserted = 0;
|
|
97
|
+
for (const { name, table } of opts.specs) {
|
|
98
|
+
const rows = (snapshot.tables[name] ?? []).map((r) => reviveRow(table, r));
|
|
99
|
+
for (let i = 0; i < rows.length; i += 200) {
|
|
100
|
+
const chunk = rows.slice(i, i + 200);
|
|
101
|
+
const res = (await db.insert(table).values(chunk as never).onConflictDoNothing().returning()) as unknown[];
|
|
102
|
+
inserted += res.length;
|
|
103
|
+
}
|
|
104
|
+
console.log(`${name.padEnd(20)} ${rows.length} offered`);
|
|
105
|
+
}
|
|
106
|
+
console.log(`\nSeed complete: ${inserted} rows inserted (existing ids skipped).`);
|
|
107
|
+
return inserted;
|
|
108
|
+
}
|