@astrojs/db 0.0.0-db-export-bug-20240307130354

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 (63) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +38 -0
  3. package/dist/core/cli/commands/execute/index.d.ts +8 -0
  4. package/dist/core/cli/commands/execute/index.js +32 -0
  5. package/dist/core/cli/commands/link/index.d.ts +20 -0
  6. package/dist/core/cli/commands/link/index.js +238 -0
  7. package/dist/core/cli/commands/login/index.d.ts +8 -0
  8. package/dist/core/cli/commands/login/index.js +55 -0
  9. package/dist/core/cli/commands/logout/index.d.ts +1 -0
  10. package/dist/core/cli/commands/logout/index.js +9 -0
  11. package/dist/core/cli/commands/push/index.d.ts +8 -0
  12. package/dist/core/cli/commands/push/index.js +77 -0
  13. package/dist/core/cli/commands/shell/index.d.ts +8 -0
  14. package/dist/core/cli/commands/shell/index.js +17 -0
  15. package/dist/core/cli/commands/verify/index.d.ts +8 -0
  16. package/dist/core/cli/commands/verify/index.js +46 -0
  17. package/dist/core/cli/index.d.ts +6 -0
  18. package/dist/core/cli/index.js +77 -0
  19. package/dist/core/cli/migration-queries.d.ts +22 -0
  20. package/dist/core/cli/migration-queries.js +366 -0
  21. package/dist/core/consts.d.ts +7 -0
  22. package/dist/core/consts.js +19 -0
  23. package/dist/core/errors.d.ts +11 -0
  24. package/dist/core/errors.js +65 -0
  25. package/dist/core/integration/error-map.d.ts +6 -0
  26. package/dist/core/integration/error-map.js +79 -0
  27. package/dist/core/integration/file-url.d.ts +2 -0
  28. package/dist/core/integration/file-url.js +81 -0
  29. package/dist/core/integration/index.d.ts +2 -0
  30. package/dist/core/integration/index.js +112 -0
  31. package/dist/core/integration/typegen.d.ts +5 -0
  32. package/dist/core/integration/typegen.js +31 -0
  33. package/dist/core/integration/vite-plugin-db.d.ts +29 -0
  34. package/dist/core/integration/vite-plugin-db.js +111 -0
  35. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +11 -0
  36. package/dist/core/integration/vite-plugin-inject-env-ts.js +53 -0
  37. package/dist/core/load-file.d.ts +31 -0
  38. package/dist/core/load-file.js +98 -0
  39. package/dist/core/tokens.d.ts +11 -0
  40. package/dist/core/tokens.js +131 -0
  41. package/dist/core/types.d.ts +3901 -0
  42. package/dist/core/types.js +143 -0
  43. package/dist/core/utils.d.ts +6 -0
  44. package/dist/core/utils.js +22 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +6 -0
  47. package/dist/runtime/config.d.ts +148 -0
  48. package/dist/runtime/config.js +87 -0
  49. package/dist/runtime/db-client.d.ts +5 -0
  50. package/dist/runtime/db-client.js +64 -0
  51. package/dist/runtime/drizzle.d.ts +1 -0
  52. package/dist/runtime/drizzle.js +48 -0
  53. package/dist/runtime/index.d.ts +31 -0
  54. package/dist/runtime/index.js +126 -0
  55. package/dist/runtime/queries.d.ts +81 -0
  56. package/dist/runtime/queries.js +206 -0
  57. package/dist/runtime/types.d.ts +69 -0
  58. package/dist/runtime/types.js +8 -0
  59. package/dist/utils.d.ts +1 -0
  60. package/dist/utils.js +4 -0
  61. package/index.d.ts +3 -0
  62. package/package.json +90 -0
  63. package/virtual.d.ts +9 -0
@@ -0,0 +1,143 @@
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
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];
3
+ export declare function getAstroStudioEnv(envMode?: string): Record<`ASTRO_STUDIO_${string}`, string>;
4
+ export declare function getRemoteDatabaseUrl(): string;
5
+ export declare function getAstroStudioUrl(): string;
6
+ export declare function getDbDirectoryUrl(root: URL | string): URL;
@@ -0,0 +1,22 @@
1
+ import { loadEnv } from "vite";
2
+ function getAstroStudioEnv(envMode = "") {
3
+ const env = loadEnv(envMode, process.cwd(), "ASTRO_STUDIO_");
4
+ return env;
5
+ }
6
+ function getRemoteDatabaseUrl() {
7
+ const env = getAstroStudioEnv();
8
+ return env.ASTRO_STUDIO_REMOTE_DB_URL || "https://db.services.astro.build";
9
+ }
10
+ function getAstroStudioUrl() {
11
+ const env = getAstroStudioEnv();
12
+ return env.ASTRO_STUDIO_URL || "https://stardate.astro.build";
13
+ }
14
+ function getDbDirectoryUrl(root) {
15
+ return new URL("db/", root);
16
+ }
17
+ export {
18
+ getAstroStudioEnv,
19
+ getAstroStudioUrl,
20
+ getDbDirectoryUrl,
21
+ getRemoteDatabaseUrl
22
+ };
@@ -0,0 +1,3 @@
1
+ export type { ResolvedCollectionConfig, TableConfig } from './core/types.js';
2
+ export { cli } from './core/cli/index.js';
3
+ export { integration as default } from './core/integration/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import { cli } from "./core/cli/index.js";
2
+ import { integration } from "./core/integration/index.js";
3
+ export {
4
+ cli,
5
+ integration as default
6
+ };
@@ -0,0 +1,148 @@
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';
@@ -0,0 +1,87 @@
1
+ function createColumn(type, schema) {
2
+ return {
3
+ type,
4
+ /**
5
+ * @internal
6
+ */
7
+ schema
8
+ };
9
+ }
10
+ const column = {
11
+ number: (opts = {}) => {
12
+ return createColumn("number", opts);
13
+ },
14
+ boolean: (opts = {}) => {
15
+ return createColumn("boolean", opts);
16
+ },
17
+ text: (opts = {}) => {
18
+ return createColumn("text", opts);
19
+ },
20
+ date(opts = {}) {
21
+ return createColumn("date", opts);
22
+ },
23
+ json(opts = {}) {
24
+ return createColumn("json", opts);
25
+ }
26
+ };
27
+ function defineTable(userConfig) {
28
+ return userConfig;
29
+ }
30
+ function defineDB(userConfig) {
31
+ return userConfig;
32
+ }
33
+ import { NOW, TRUE, FALSE } from "./index.js";
34
+ import {
35
+ sql,
36
+ eq,
37
+ gt,
38
+ gte,
39
+ lt,
40
+ lte,
41
+ ne,
42
+ isNull,
43
+ isNotNull,
44
+ inArray,
45
+ notInArray,
46
+ exists,
47
+ notExists,
48
+ between,
49
+ notBetween,
50
+ like,
51
+ notIlike,
52
+ not,
53
+ asc,
54
+ desc,
55
+ and,
56
+ or
57
+ } from "drizzle-orm";
58
+ export {
59
+ FALSE,
60
+ NOW,
61
+ TRUE,
62
+ and,
63
+ asc,
64
+ between,
65
+ column,
66
+ defineDB,
67
+ defineTable,
68
+ desc,
69
+ eq,
70
+ exists,
71
+ gt,
72
+ gte,
73
+ inArray,
74
+ isNotNull,
75
+ isNull,
76
+ like,
77
+ lt,
78
+ lte,
79
+ ne,
80
+ not,
81
+ notBetween,
82
+ notExists,
83
+ notIlike,
84
+ notInArray,
85
+ or,
86
+ sql
87
+ };
@@ -0,0 +1,5 @@
1
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
+ export declare function createLocalDatabaseClient({ dbUrl }: {
3
+ dbUrl: string;
4
+ }): LibSQLDatabase;
5
+ export declare function createRemoteDatabaseClient(appToken: string, remoteDbURL: string): import("drizzle-orm/sqlite-proxy").SqliteRemoteDatabase<Record<string, never>>;
@@ -0,0 +1,64 @@
1
+ import { createClient } from "@libsql/client";
2
+ import { drizzle as drizzleLibsql } from "drizzle-orm/libsql";
3
+ import { drizzle as drizzleProxy } from "drizzle-orm/sqlite-proxy";
4
+ import { z } from "zod";
5
+ const isWebContainer = !!process.versions?.webcontainer;
6
+ function createLocalDatabaseClient({ dbUrl }) {
7
+ const url = isWebContainer ? "file:content.db" : dbUrl;
8
+ const client = createClient({ url: process.env.TEST_IN_MEMORY_DB ? ":memory:" : url });
9
+ const db = drizzleLibsql(client);
10
+ return db;
11
+ }
12
+ function createRemoteDatabaseClient(appToken, remoteDbURL) {
13
+ const url = new URL("/db/query", remoteDbURL);
14
+ const db = drizzleProxy(async (sql, parameters, method) => {
15
+ const requestBody = { sql, args: parameters };
16
+ const res = await fetch(url, {
17
+ method: "POST",
18
+ headers: {
19
+ Authorization: `Bearer ${appToken}`,
20
+ "Content-Type": "application/json"
21
+ },
22
+ body: JSON.stringify(requestBody)
23
+ });
24
+ if (!res.ok) {
25
+ throw new Error(
26
+ `Failed to execute query.
27
+ Query: ${sql}
28
+ Full error: ${res.status} ${await res.text()}}`
29
+ );
30
+ }
31
+ const queryResultSchema = z.object({
32
+ rows: z.array(z.unknown())
33
+ });
34
+ let rows;
35
+ try {
36
+ const json = await res.json();
37
+ rows = queryResultSchema.parse(json).rows;
38
+ } catch (e) {
39
+ throw new Error(
40
+ `Failed to execute query.
41
+ Query: ${sql}
42
+ Full error: Unexpected JSON response. ${e instanceof Error ? e.message : String(e)}`
43
+ );
44
+ }
45
+ const rowValues = [];
46
+ for (const row of rows) {
47
+ if (row != null && typeof row === "object") {
48
+ rowValues.push(Object.values(row));
49
+ }
50
+ }
51
+ if (method === "get") {
52
+ return { rows: rowValues[0] };
53
+ }
54
+ return { rows: rowValues };
55
+ });
56
+ db.batch = (_drizzleQueries) => {
57
+ throw new Error("db.batch() is not currently supported.");
58
+ };
59
+ return db;
60
+ }
61
+ export {
62
+ createLocalDatabaseClient,
63
+ createRemoteDatabaseClient
64
+ };
@@ -0,0 +1 @@
1
+ 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';
@@ -0,0 +1,48 @@
1
+ import {
2
+ sql,
3
+ eq,
4
+ gt,
5
+ gte,
6
+ lt,
7
+ lte,
8
+ ne,
9
+ isNull,
10
+ isNotNull,
11
+ inArray,
12
+ notInArray,
13
+ exists,
14
+ notExists,
15
+ between,
16
+ notBetween,
17
+ like,
18
+ notIlike,
19
+ not,
20
+ asc,
21
+ desc,
22
+ and,
23
+ or
24
+ } from "drizzle-orm";
25
+ export {
26
+ and,
27
+ asc,
28
+ between,
29
+ desc,
30
+ eq,
31
+ exists,
32
+ gt,
33
+ gte,
34
+ inArray,
35
+ isNotNull,
36
+ isNull,
37
+ like,
38
+ lt,
39
+ lte,
40
+ ne,
41
+ not,
42
+ notBetween,
43
+ notExists,
44
+ notIlike,
45
+ notInArray,
46
+ or,
47
+ sql
48
+ };
@@ -0,0 +1,31 @@
1
+ import { type ColumnDataType, sql } from 'drizzle-orm';
2
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
3
+ import { type DBColumn, type DBTable } from '../core/types.js';
4
+ export { sql };
5
+ export type SqliteDB = LibSQLDatabase;
6
+ export type { Table } from './types.js';
7
+ export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
8
+ export { seedLocal } from './queries.js';
9
+ export declare function hasPrimaryKey(column: DBColumn): boolean;
10
+ export declare const NOW: import("drizzle-orm").SQL<unknown>;
11
+ export declare const TRUE: import("drizzle-orm").SQL<unknown>;
12
+ export declare const FALSE: import("drizzle-orm").SQL<unknown>;
13
+ export declare function asDrizzleTable(name: string, table: DBTable): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
14
+ name: string;
15
+ schema: undefined;
16
+ columns: {
17
+ [x: string]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
18
+ name: string;
19
+ tableName: string;
20
+ dataType: ColumnDataType;
21
+ columnType: string;
22
+ data: unknown;
23
+ driverParam: unknown;
24
+ notNull: false;
25
+ hasDefault: false;
26
+ enumValues: string[] | undefined;
27
+ baseColumn: never;
28
+ }, object>;
29
+ };
30
+ dialect: "sqlite";
31
+ }>;
@@ -0,0 +1,126 @@
1
+ import { sql } from "drizzle-orm";
2
+ import {
3
+ customType,
4
+ index,
5
+ integer,
6
+ sqliteTable,
7
+ text
8
+ } from "drizzle-orm/sqlite-core";
9
+ import {} from "../core/types.js";
10
+ import { isSerializedSQL } from "./types.js";
11
+ import { createRemoteDatabaseClient, createLocalDatabaseClient } from "./db-client.js";
12
+ import { seedLocal } from "./queries.js";
13
+ function hasPrimaryKey(column) {
14
+ return "primaryKey" in column.schema && !!column.schema.primaryKey;
15
+ }
16
+ const NOW = sql`CURRENT_TIMESTAMP`;
17
+ const TRUE = sql`TRUE`;
18
+ const FALSE = sql`FALSE`;
19
+ const dateType = customType({
20
+ dataType() {
21
+ return "text";
22
+ },
23
+ toDriver(value) {
24
+ return value.toISOString();
25
+ },
26
+ fromDriver(value) {
27
+ return new Date(value);
28
+ }
29
+ });
30
+ const jsonType = customType({
31
+ dataType() {
32
+ return "text";
33
+ },
34
+ toDriver(value) {
35
+ return JSON.stringify(value);
36
+ },
37
+ fromDriver(value) {
38
+ return JSON.parse(value);
39
+ }
40
+ });
41
+ function asDrizzleTable(name, table) {
42
+ const columns = {};
43
+ if (!Object.entries(table.columns).some(([, column]) => hasPrimaryKey(column))) {
44
+ columns["_id"] = integer("_id").primaryKey();
45
+ }
46
+ for (const [columnName, column] of Object.entries(table.columns)) {
47
+ columns[columnName] = columnMapper(columnName, column);
48
+ }
49
+ const drizzleTable = sqliteTable(name, columns, (ormTable) => {
50
+ const indexes = {};
51
+ for (const [indexName, indexProps] of Object.entries(table.indexes ?? {})) {
52
+ const onColNames = Array.isArray(indexProps.on) ? indexProps.on : [indexProps.on];
53
+ const onCols = onColNames.map((colName) => ormTable[colName]);
54
+ if (!atLeastOne(onCols))
55
+ continue;
56
+ indexes[indexName] = index(indexName).on(...onCols);
57
+ }
58
+ return indexes;
59
+ });
60
+ return drizzleTable;
61
+ }
62
+ function atLeastOne(arr) {
63
+ return arr.length > 0;
64
+ }
65
+ function columnMapper(columnName, column) {
66
+ let c;
67
+ switch (column.type) {
68
+ case "text": {
69
+ c = text(columnName);
70
+ if (column.schema.default !== void 0)
71
+ c = c.default(handleSerializedSQL(column.schema.default));
72
+ if (column.schema.primaryKey === true)
73
+ c = c.primaryKey();
74
+ break;
75
+ }
76
+ case "number": {
77
+ c = integer(columnName);
78
+ if (column.schema.default !== void 0)
79
+ c = c.default(handleSerializedSQL(column.schema.default));
80
+ if (column.schema.primaryKey === true)
81
+ c = c.primaryKey();
82
+ break;
83
+ }
84
+ case "boolean": {
85
+ c = integer(columnName, { mode: "boolean" });
86
+ if (column.schema.default !== void 0)
87
+ c = c.default(handleSerializedSQL(column.schema.default));
88
+ break;
89
+ }
90
+ case "json":
91
+ c = jsonType(columnName);
92
+ if (column.schema.default !== void 0)
93
+ c = c.default(column.schema.default);
94
+ break;
95
+ case "date": {
96
+ c = dateType(columnName);
97
+ if (column.schema.default !== void 0) {
98
+ const def = handleSerializedSQL(column.schema.default);
99
+ c = c.default(typeof def === "string" ? new Date(def) : def);
100
+ }
101
+ break;
102
+ }
103
+ }
104
+ if (!column.schema.optional)
105
+ c = c.notNull();
106
+ if (column.schema.unique)
107
+ c = c.unique();
108
+ return c;
109
+ }
110
+ function handleSerializedSQL(def) {
111
+ if (isSerializedSQL(def)) {
112
+ return sql.raw(def.sql);
113
+ }
114
+ return def;
115
+ }
116
+ export {
117
+ FALSE,
118
+ NOW,
119
+ TRUE,
120
+ asDrizzleTable,
121
+ createLocalDatabaseClient,
122
+ createRemoteDatabaseClient,
123
+ hasPrimaryKey,
124
+ seedLocal,
125
+ sql
126
+ };