@astrojs/db 0.7.1 → 0.8.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.
@@ -1,143 +0,0 @@
1
- import { SQL } from "drizzle-orm";
2
- import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
3
- import { z } from "zod";
4
- import { SERIALIZED_SQL_KEY } from "../runtime/types.js";
5
- import { errorMap } from "./integration/error-map.js";
6
- const sqlite = new SQLiteAsyncDialect();
7
- const sqlSchema = z.instanceof(SQL).transform(
8
- (sqlObj) => ({
9
- [SERIALIZED_SQL_KEY]: true,
10
- sql: sqlite.sqlToQuery(sqlObj).sql
11
- })
12
- );
13
- const baseColumnSchema = z.object({
14
- label: z.string().optional(),
15
- optional: z.boolean().optional().default(false),
16
- unique: z.boolean().optional().default(false),
17
- deprecated: z.boolean().optional().default(false),
18
- // Defined when `defineReadableTable()` is called
19
- name: z.string().optional(),
20
- // TODO: rename to `tableName`. Breaking schema change
21
- collection: z.string().optional()
22
- });
23
- const booleanColumnSchema = z.object({
24
- type: z.literal("boolean"),
25
- schema: baseColumnSchema.extend({
26
- default: z.union([z.boolean(), sqlSchema]).optional()
27
- })
28
- });
29
- const numberColumnBaseSchema = baseColumnSchema.omit({ optional: true }).and(
30
- z.union([
31
- z.object({
32
- primaryKey: z.literal(false).optional().default(false),
33
- optional: baseColumnSchema.shape.optional,
34
- default: z.union([z.number(), sqlSchema]).optional()
35
- }),
36
- z.object({
37
- // `integer primary key` uses ROWID as the default value.
38
- // `optional` and `default` do not have an effect,
39
- // so disable these config options for primary keys.
40
- primaryKey: z.literal(true),
41
- optional: z.literal(false).optional(),
42
- default: z.literal(void 0).optional()
43
- })
44
- ])
45
- );
46
- const numberColumnOptsSchema = numberColumnBaseSchema.and(
47
- z.object({
48
- references: z.function().returns(z.lazy(() => numberColumnSchema)).optional().transform((fn) => fn?.())
49
- })
50
- );
51
- const numberColumnSchema = z.object({
52
- type: z.literal("number"),
53
- schema: numberColumnOptsSchema
54
- });
55
- const textColumnBaseSchema = baseColumnSchema.omit({ optional: true }).extend({
56
- default: z.union([z.string(), sqlSchema]).optional(),
57
- multiline: z.boolean().optional()
58
- }).and(
59
- z.union([
60
- z.object({
61
- primaryKey: z.literal(false).optional().default(false),
62
- optional: baseColumnSchema.shape.optional
63
- }),
64
- z.object({
65
- // text primary key allows NULL values.
66
- // NULL values bypass unique checks, which could
67
- // lead to duplicate URLs per record in Astro Studio.
68
- // disable `optional` for primary keys.
69
- primaryKey: z.literal(true),
70
- optional: z.literal(false).optional()
71
- })
72
- ])
73
- );
74
- const textColumnOptsSchema = textColumnBaseSchema.and(
75
- z.object({
76
- references: z.function().returns(z.lazy(() => textColumnSchema)).optional().transform((fn) => fn?.())
77
- })
78
- );
79
- const textColumnSchema = z.object({
80
- type: z.literal("text"),
81
- schema: textColumnOptsSchema
82
- });
83
- const dateColumnSchema = z.object({
84
- type: z.literal("date"),
85
- schema: baseColumnSchema.extend({
86
- default: z.union([
87
- sqlSchema,
88
- // transform to ISO string for serialization
89
- z.date().transform((d) => d.toISOString())
90
- ]).optional()
91
- })
92
- });
93
- const jsonColumnSchema = z.object({
94
- type: z.literal("json"),
95
- schema: baseColumnSchema.extend({
96
- default: z.unknown().optional()
97
- })
98
- });
99
- const columnSchema = z.union([
100
- booleanColumnSchema,
101
- numberColumnSchema,
102
- textColumnSchema,
103
- dateColumnSchema,
104
- jsonColumnSchema
105
- ]);
106
- const referenceableColumnSchema = z.union([textColumnSchema, numberColumnSchema]);
107
- const columnsSchema = z.record(columnSchema);
108
- const indexSchema = z.object({
109
- on: z.string().or(z.array(z.string())),
110
- unique: z.boolean().optional()
111
- });
112
- const foreignKeysSchema = z.object({
113
- columns: z.string().or(z.array(z.string())),
114
- references: z.function().returns(z.lazy(() => referenceableColumnSchema.or(z.array(referenceableColumnSchema)))).transform((fn) => fn())
115
- });
116
- const tableSchema = z.object({
117
- columns: columnsSchema,
118
- indexes: z.record(indexSchema).optional(),
119
- foreignKeys: z.array(foreignKeysSchema).optional(),
120
- deprecated: z.boolean().optional().default(false)
121
- });
122
- const tablesSchema = z.preprocess((rawTables) => {
123
- const tables = z.record(z.any()).parse(rawTables, { errorMap });
124
- for (const [tableName, table] of Object.entries(tables)) {
125
- const { columns } = z.object({ columns: z.record(z.any()) }).parse(table, { errorMap });
126
- for (const [columnName, column] of Object.entries(columns)) {
127
- column.schema.name = columnName;
128
- column.schema.collection = tableName;
129
- }
130
- }
131
- return rawTables;
132
- }, z.record(tableSchema));
133
- const dbConfigSchema = z.object({
134
- tables: tablesSchema.optional()
135
- });
136
- export {
137
- columnSchema,
138
- dbConfigSchema,
139
- indexSchema,
140
- referenceableColumnSchema,
141
- tableSchema,
142
- tablesSchema
143
- };
@@ -9,7 +9,7 @@ function getRemoteDatabaseUrl() {
9
9
  }
10
10
  function getAstroStudioUrl() {
11
11
  const env = getAstroStudioEnv();
12
- return env.ASTRO_STUDIO_URL || "https://stardate.astro.build";
12
+ return env.ASTRO_STUDIO_URL || "https://studio.astro.build";
13
13
  }
14
14
  function getDbDirectoryUrl(root) {
15
15
  return new URL("db/", root);
@@ -5,14 +5,7 @@ export { sql };
5
5
  export type SqliteDB = LibSQLDatabase;
6
6
  export type { Table } from './types.js';
7
7
  export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
8
- export declare function seedLocal({ userSeedGlob, integrationSeedImports, }: {
9
- userSeedGlob: Record<string, {
10
- default?: () => Promise<void>;
11
- }>;
12
- integrationSeedImports: Array<() => Promise<{
13
- default: () => Promise<void>;
14
- }>>;
15
- }): Promise<void>;
8
+ export { seedLocal } from './seed-local.js';
16
9
  export declare function hasPrimaryKey(column: DBColumn): boolean;
17
10
  export declare const NOW: import("drizzle-orm").SQL<unknown>;
18
11
  export declare const TRUE: import("drizzle-orm").SQL<unknown>;
@@ -1,4 +1,3 @@
1
- import { LibsqlError } from "@libsql/client";
2
1
  import { sql } from "drizzle-orm";
3
2
  import {
4
3
  customType,
@@ -7,40 +6,10 @@ import {
7
6
  sqliteTable,
8
7
  text
9
8
  } from "drizzle-orm/sqlite-core";
10
- import { SEED_DEFAULT_EXPORT_ERROR, SEED_ERROR } from "../core/errors.js";
11
9
  import {} from "../core/types.js";
12
10
  import { isSerializedSQL } from "./types.js";
13
11
  import { createRemoteDatabaseClient, createLocalDatabaseClient } from "./db-client.js";
14
- async function seedLocal({
15
- // Glob all potential seed files to catch renames and deletions.
16
- userSeedGlob,
17
- integrationSeedImports
18
- }) {
19
- const seedFilePath = Object.keys(userSeedGlob)[0];
20
- if (seedFilePath) {
21
- const mod = userSeedGlob[seedFilePath];
22
- if (!mod.default) {
23
- throw new Error(SEED_DEFAULT_EXPORT_ERROR(seedFilePath));
24
- }
25
- try {
26
- await mod.default();
27
- } catch (e) {
28
- if (e instanceof LibsqlError) {
29
- throw new Error(SEED_ERROR(e.message));
30
- }
31
- throw e;
32
- }
33
- }
34
- for (const importModule of integrationSeedImports) {
35
- const mod = await importModule();
36
- await mod.default().catch((e) => {
37
- if (e instanceof LibsqlError) {
38
- throw new Error(SEED_ERROR(e.message));
39
- }
40
- throw e;
41
- });
42
- }
43
- }
12
+ import { seedLocal } from "./seed-local.js";
44
13
  function hasPrimaryKey(column) {
45
14
  return "primaryKey" in column.schema && !!column.schema.primaryKey;
46
15
  }
@@ -0,0 +1,10 @@
1
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
+ import { type DBTables } from '../core/types.js';
3
+ export declare function seedLocal({ db, tables, userSeedGlob, integrationSeedFunctions, }: {
4
+ db: LibSQLDatabase;
5
+ tables: DBTables;
6
+ userSeedGlob: Record<string, {
7
+ default?: () => Promise<void>;
8
+ }>;
9
+ integrationSeedFunctions: Array<() => Promise<void>>;
10
+ }): Promise<void>;
@@ -0,0 +1,53 @@
1
+ import { LibsqlError } from "@libsql/client";
2
+ import { sql } from "drizzle-orm";
3
+ import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
4
+ import { SEED_DEFAULT_EXPORT_ERROR, SEED_ERROR } from "../core/errors.js";
5
+ import {} from "../core/types.js";
6
+ import { getCreateIndexQueries, getCreateTableQuery } from "./queries.js";
7
+ const sqlite = new SQLiteAsyncDialect();
8
+ async function seedLocal({
9
+ db,
10
+ tables,
11
+ // Glob all potential seed files to catch renames and deletions.
12
+ userSeedGlob,
13
+ integrationSeedFunctions
14
+ }) {
15
+ await recreateTables({ db, tables });
16
+ const seedFunctions = [];
17
+ const seedFilePath = Object.keys(userSeedGlob)[0];
18
+ if (seedFilePath) {
19
+ const mod = userSeedGlob[seedFilePath];
20
+ if (!mod.default)
21
+ throw new Error(SEED_DEFAULT_EXPORT_ERROR(seedFilePath));
22
+ seedFunctions.push(mod.default);
23
+ }
24
+ for (const seedFn of integrationSeedFunctions) {
25
+ seedFunctions.push(seedFn);
26
+ }
27
+ for (const seed of seedFunctions) {
28
+ try {
29
+ await seed();
30
+ } catch (e) {
31
+ if (e instanceof LibsqlError) {
32
+ throw new Error(SEED_ERROR(e.message));
33
+ }
34
+ throw e;
35
+ }
36
+ }
37
+ }
38
+ async function recreateTables({ db, tables }) {
39
+ const setupQueries = [];
40
+ for (const [name, table] of Object.entries(tables)) {
41
+ const dropQuery = sql.raw(`DROP TABLE IF EXISTS ${sqlite.escapeName(name)}`);
42
+ const createQuery = sql.raw(getCreateTableQuery(name, table));
43
+ const indexQueries = getCreateIndexQueries(name, table);
44
+ setupQueries.push(dropQuery, createQuery, ...indexQueries.map((s) => sql.raw(s)));
45
+ }
46
+ await db.batch([
47
+ db.run(sql`pragma defer_foreign_keys=true;`),
48
+ ...setupQueries.map((q) => db.run(q))
49
+ ]);
50
+ }
51
+ export {
52
+ seedLocal
53
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrojs/db",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,10 +20,13 @@
20
20
  "types": "./dist/runtime/index.d.ts",
21
21
  "import": "./dist/runtime/index.js"
22
22
  },
23
- "./runtime/config": {
24
- "types": "./dist/runtime/config.d.ts",
23
+ "./dist/runtime/config.js": {
25
24
  "import": "./dist/runtime/config.js"
26
25
  },
26
+ "./types": {
27
+ "types": "./dist/core/types.d.ts",
28
+ "import": "./dist/core/types.js"
29
+ },
27
30
  "./package.json": "./package.json"
28
31
  },
29
32
  "typesVersions": {
@@ -31,14 +34,14 @@
31
34
  ".": [
32
35
  "./index.d.ts"
33
36
  ],
37
+ "types": [
38
+ "./dist/types.d.ts"
39
+ ],
34
40
  "utils": [
35
41
  "./dist/utils.d.ts"
36
42
  ],
37
43
  "runtime": [
38
44
  "./dist/runtime/index.d.ts"
39
- ],
40
- "runtime/config": [
41
- "./dist/runtime/config.d.ts"
42
45
  ]
43
46
  }
44
47
  },
@@ -52,7 +55,7 @@
52
55
  "astro-integration"
53
56
  ],
54
57
  "dependencies": {
55
- "@libsql/client": "^0.4.3",
58
+ "@libsql/client": "^0.5.5",
56
59
  "async-listen": "^3.0.1",
57
60
  "deep-diff": "^1.0.2",
58
61
  "drizzle-orm": "^0.29.5",
@@ -77,8 +80,8 @@
77
80
  "mocha": "^10.2.0",
78
81
  "typescript": "^5.2.2",
79
82
  "vite": "^5.1.4",
80
- "astro": "4.5.0",
81
- "astro-scripts": "0.0.14"
83
+ "astro-scripts": "0.0.14",
84
+ "astro": "4.5.2"
82
85
  },
83
86
  "scripts": {
84
87
  "build": "astro-scripts build \"src/**/*.ts\" && tsc",
@@ -1,148 +0,0 @@
1
- import type { ColumnsConfig, DBConfigInput, TableConfig } from '../core/types.js';
2
- export declare const column: {
3
- number: <T extends ({
4
- name?: string | undefined;
5
- label?: string | undefined;
6
- unique?: boolean | undefined;
7
- deprecated?: boolean | undefined;
8
- collection?: string | undefined;
9
- } & ({
10
- primaryKey?: false | undefined;
11
- optional?: boolean | undefined;
12
- default?: number | import("drizzle-orm").SQL<any> | undefined;
13
- } | {
14
- primaryKey: true;
15
- optional?: false | undefined;
16
- default?: undefined;
17
- })) & {
18
- references?: (() => {
19
- type: "number";
20
- schema: ({
21
- name?: string | undefined;
22
- label?: string | undefined;
23
- unique?: boolean | undefined;
24
- deprecated?: boolean | undefined;
25
- collection?: string | undefined;
26
- } & {
27
- primaryKey?: false | undefined;
28
- optional?: boolean | undefined;
29
- default?: number | import("drizzle-orm").SQL<any> | undefined;
30
- } & any) | ({
31
- name?: string | undefined;
32
- label?: string | undefined;
33
- unique?: boolean | undefined;
34
- deprecated?: boolean | undefined;
35
- collection?: string | undefined;
36
- } & {
37
- primaryKey: true;
38
- optional?: false | undefined;
39
- default?: undefined;
40
- } & any);
41
- }) | undefined;
42
- }>(opts?: T) => {
43
- type: "number";
44
- /**
45
- * @internal
46
- */
47
- schema: T;
48
- };
49
- boolean: <T_1 extends {
50
- name?: string | undefined;
51
- label?: string | undefined;
52
- optional?: boolean | undefined;
53
- unique?: boolean | undefined;
54
- deprecated?: boolean | undefined;
55
- collection?: string | undefined;
56
- default?: boolean | import("drizzle-orm").SQL<any> | undefined;
57
- }>(opts?: T_1) => {
58
- type: "boolean";
59
- /**
60
- * @internal
61
- */
62
- schema: T_1;
63
- };
64
- text: <T_2 extends ({
65
- name?: string | undefined;
66
- label?: string | undefined;
67
- unique?: boolean | undefined;
68
- deprecated?: boolean | undefined;
69
- collection?: string | undefined;
70
- default?: string | import("drizzle-orm").SQL<any> | undefined;
71
- multiline?: boolean | undefined;
72
- } & ({
73
- primaryKey?: false | undefined;
74
- optional?: boolean | undefined;
75
- } | {
76
- primaryKey: true;
77
- optional?: false | undefined;
78
- })) & {
79
- references?: (() => {
80
- type: "text";
81
- schema: ({
82
- name?: string | undefined;
83
- label?: string | undefined;
84
- unique?: boolean | undefined;
85
- deprecated?: boolean | undefined;
86
- collection?: string | undefined;
87
- default?: string | import("drizzle-orm").SQL<any> | undefined;
88
- multiline?: boolean | undefined;
89
- } & {
90
- primaryKey?: false | undefined;
91
- optional?: boolean | undefined;
92
- } & any) | ({
93
- name?: string | undefined;
94
- label?: string | undefined;
95
- unique?: boolean | undefined;
96
- deprecated?: boolean | undefined;
97
- collection?: string | undefined;
98
- default?: string | import("drizzle-orm").SQL<any> | undefined;
99
- multiline?: boolean | undefined;
100
- } & {
101
- primaryKey: true;
102
- optional?: false | undefined;
103
- } & any);
104
- }) | undefined;
105
- }>(opts?: T_2) => {
106
- type: "text";
107
- /**
108
- * @internal
109
- */
110
- schema: T_2;
111
- };
112
- date<T_3 extends {
113
- name?: string | undefined;
114
- label?: string | undefined;
115
- optional?: boolean | undefined;
116
- unique?: boolean | undefined;
117
- deprecated?: boolean | undefined;
118
- collection?: string | undefined;
119
- default?: Date | import("drizzle-orm").SQL<any> | undefined;
120
- }>(opts?: T_3): {
121
- type: "date";
122
- /**
123
- * @internal
124
- */
125
- schema: T_3;
126
- };
127
- json<T_4 extends {
128
- name?: string | undefined;
129
- label?: string | undefined;
130
- optional?: boolean | undefined;
131
- unique?: boolean | undefined;
132
- deprecated?: boolean | undefined;
133
- collection?: string | undefined;
134
- default?: unknown;
135
- }>(opts?: T_4): {
136
- type: "json";
137
- /**
138
- * @internal
139
- */
140
- schema: T_4;
141
- };
142
- };
143
- export declare function defineTable<TColumns extends ColumnsConfig>(userConfig: TableConfig<TColumns>): TableConfig<TColumns>;
144
- export declare function defineDb(userConfig: DBConfigInput): {
145
- tables?: unknown;
146
- };
147
- export { NOW, TRUE, FALSE } from './index.js';
148
- export { sql, eq, gt, gte, lt, lte, ne, isNull, isNotNull, inArray, notInArray, exists, notExists, between, notBetween, like, notIlike, not, asc, desc, and, or, } from 'drizzle-orm';