@astrojs/db 0.1.14 → 0.1.16

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,8 +1,9 @@
1
+ import { createClient } from "@libsql/client";
1
2
  import deepDiff from "deep-diff";
2
3
  import { eq, sql } from "drizzle-orm";
3
4
  import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
4
5
  import { appTokenError } from "../../../errors.js";
5
- import { collectionToTable, createLocalDatabaseClient } from "../../../internal.js";
6
+ import { drizzle } from "drizzle-orm/sqlite-proxy";
6
7
  import {
7
8
  createCurrentSnapshot,
8
9
  createEmptySnapshot,
@@ -20,6 +21,7 @@ import {
20
21
  migrationsTable
21
22
  } from "../../../utils.js";
22
23
  import { getMigrationQueries } from "../../queries.js";
24
+ import { setupDbTables } from "../../../internal.js";
23
25
  const { diff } = deepDiff;
24
26
  const sqliteDialect = new SQLiteAsyncDialect();
25
27
  async function cmd({ config, flags }) {
@@ -91,26 +93,34 @@ async function pushData({
91
93
  appToken,
92
94
  isDryRun
93
95
  }) {
94
- const db = await createLocalDatabaseClient({
95
- collections: config.db.collections,
96
- dbUrl: ":memory:",
97
- seeding: true
98
- });
99
96
  const queries = [];
100
- for (const [name, collection] of Object.entries(config.db.collections)) {
101
- if (collection.writable || !collection.data)
102
- continue;
103
- const table = collectionToTable(name, collection);
104
- const insert = db.insert(table).values(await collection.data());
105
- queries.push(insert.toSQL());
97
+ if (config.db?.data) {
98
+ const libsqlClient = createClient({ url: ":memory:" });
99
+ const db = await drizzle(async (sqlQuery, params, method) => {
100
+ const stmt = { sql: sqlQuery, args: params };
101
+ queries.push(stmt);
102
+ const { rows } = await libsqlClient.execute(stmt);
103
+ const rowValues = [];
104
+ for (const row of rows) {
105
+ if (row != null && typeof row === "object") {
106
+ rowValues.push(Object.values(row));
107
+ }
108
+ }
109
+ if (method === "get") {
110
+ return { rows: rowValues[0] };
111
+ }
112
+ return { rows: rowValues };
113
+ });
114
+ await setupDbTables({
115
+ db,
116
+ mode: "build",
117
+ collections: config.db.collections ?? {},
118
+ data: config.db.data
119
+ });
106
120
  }
107
121
  const url = new URL("/db/query", getRemoteDatabaseUrl());
108
- const requestBody = queries.map((q) => ({
109
- sql: q.sql,
110
- args: q.params
111
- }));
112
122
  if (isDryRun) {
113
- console.info("[DRY RUN] Batch data seed:", JSON.stringify(requestBody, null, 2));
123
+ console.info("[DRY RUN] Batch data seed:", JSON.stringify(queries, null, 2));
114
124
  return new Response(null, { status: 200 });
115
125
  }
116
126
  return await fetch(url, {
@@ -118,7 +128,7 @@ async function pushData({
118
128
  headers: new Headers({
119
129
  Authorization: `Bearer ${appToken}`
120
130
  }),
121
- body: JSON.stringify(requestBody)
131
+ body: JSON.stringify(queries)
122
132
  });
123
133
  }
124
134
  async function runBatchQuery({
@@ -2,7 +2,13 @@ import * as color from "kleur/colors";
2
2
  import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
3
3
  import { customAlphabet } from "nanoid";
4
4
  import prompts from "prompts";
5
- import { getCreateTableQuery, getModifiers, hasDefault, hasPrimaryKey, schemaTypeToSqlType } from "../internal.js";
5
+ import {
6
+ getCreateTableQuery,
7
+ getModifiers,
8
+ hasDefault,
9
+ hasPrimaryKey,
10
+ schemaTypeToSqlType
11
+ } from "../internal.js";
6
12
  const sqlite = new SQLiteAsyncDialect();
7
13
  const genTempTableName = customAlphabet("abcdefghijklmnopqrstuvwxyz", 10);
8
14
  async function getMigrationQueries({
@@ -115,12 +121,8 @@ async function getCollectionChangeQueries({
115
121
  process.exit(0);
116
122
  }
117
123
  }
118
- const addedPrimaryKey = Object.entries(added).find(
119
- ([, field]) => hasPrimaryKey(field)
120
- );
121
- const droppedPrimaryKey = Object.entries(dropped).find(
122
- ([, field]) => hasPrimaryKey(field)
123
- );
124
+ const addedPrimaryKey = Object.entries(added).find(([, field]) => hasPrimaryKey(field));
125
+ const droppedPrimaryKey = Object.entries(dropped).find(([, field]) => hasPrimaryKey(field));
124
126
  const updatedPrimaryKey = Object.entries(updated).find(
125
127
  ([, field]) => hasPrimaryKey(field.old) || hasPrimaryKey(field.new)
126
128
  );
package/dist/config.d.ts CHANGED
@@ -1,5 +1,15 @@
1
- import { type BooleanField, type DBFieldInput, type DateFieldInput, type JsonField, type NumberField, type TextField, type collectionSchema, type MaybePromise } from './types.js';
1
+ import type { SQLiteInsertValue } from 'drizzle-orm/sqlite-core';
2
+ import type { SqliteDB, Table } from './internal.js';
3
+ import type { MaybeArray, collectionSchema } from './types.js';
4
+ import { type BooleanField, type DBFieldInput, type DateFieldInput, type JsonField, type NumberField, type TextField, type MaybePromise } from './types.js';
2
5
  import { z } from 'zod';
6
+ export type DBFieldsConfig = z.input<typeof collectionSchema>['fields'];
7
+ export type DBDataContext = {
8
+ db: SqliteDB;
9
+ seed<TFields extends DBFieldsConfig>(collection: ResolvedCollectionConfig<TFields>, data: MaybeArray<SQLiteInsertValue<Table<string,
10
+ /** TODO: true type inference */ Record<Extract<keyof TFields, string>, DBFieldsConfig[number]>>>>): Promise<any> /** TODO: type output */;
11
+ mode: 'dev' | 'build';
12
+ };
3
13
  export declare const dbConfigSchema: z.ZodObject<{
4
14
  studio: z.ZodOptional<z.ZodBoolean>;
5
15
  collections: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
@@ -103,8 +113,9 @@ export declare const dbConfigSchema: z.ZodObject<{
103
113
  unique?: boolean | undefined;
104
114
  default?: unknown;
105
115
  }>]>>;
106
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
107
116
  writable: z.ZodLiteral<false>;
117
+ table: z.ZodAny;
118
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
108
119
  }, "strip", z.ZodTypeAny, {
109
120
  fields: Record<string, {
110
121
  type: "boolean";
@@ -141,7 +152,8 @@ export declare const dbConfigSchema: z.ZodObject<{
141
152
  default?: unknown;
142
153
  }>;
143
154
  writable: false;
144
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
155
+ table?: any;
156
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
145
157
  }, {
146
158
  fields: Record<string, {
147
159
  type: "boolean";
@@ -178,7 +190,8 @@ export declare const dbConfigSchema: z.ZodObject<{
178
190
  default?: unknown;
179
191
  }>;
180
192
  writable: false;
181
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
193
+ table?: any;
194
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
182
195
  }>, z.ZodObject<{
183
196
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
184
197
  label: z.ZodOptional<z.ZodString>;
@@ -280,8 +293,9 @@ export declare const dbConfigSchema: z.ZodObject<{
280
293
  unique?: boolean | undefined;
281
294
  default?: unknown;
282
295
  }>]>>;
283
- seed: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
284
296
  writable: z.ZodLiteral<true>;
297
+ table: z.ZodAny;
298
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
285
299
  }, "strip", z.ZodTypeAny, {
286
300
  fields: Record<string, {
287
301
  type: "boolean";
@@ -318,7 +332,8 @@ export declare const dbConfigSchema: z.ZodObject<{
318
332
  default?: unknown;
319
333
  }>;
320
334
  writable: true;
321
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
335
+ table?: any;
336
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
322
337
  }, {
323
338
  fields: Record<string, {
324
339
  type: "boolean";
@@ -355,9 +370,10 @@ export declare const dbConfigSchema: z.ZodObject<{
355
370
  default?: unknown;
356
371
  }>;
357
372
  writable: true;
358
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
373
+ table?: any;
374
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
359
375
  }>]>>>;
360
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodUnknown>>;
376
+ data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodVoid, z.ZodPromise<z.ZodVoid>]>>>;
361
377
  }, "strip", z.ZodTypeAny, {
362
378
  studio?: boolean | undefined;
363
379
  collections?: Record<string, {
@@ -396,7 +412,8 @@ export declare const dbConfigSchema: z.ZodObject<{
396
412
  default?: unknown;
397
413
  }>;
398
414
  writable: false;
399
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
415
+ table?: any;
416
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
400
417
  } | {
401
418
  fields: Record<string, {
402
419
  type: "boolean";
@@ -433,9 +450,10 @@ export declare const dbConfigSchema: z.ZodObject<{
433
450
  default?: unknown;
434
451
  }>;
435
452
  writable: true;
436
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
453
+ table?: any;
454
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
437
455
  }> | undefined;
438
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
456
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
439
457
  }, {
440
458
  studio?: boolean | undefined;
441
459
  collections?: Record<string, {
@@ -474,7 +492,8 @@ export declare const dbConfigSchema: z.ZodObject<{
474
492
  default?: unknown;
475
493
  }>;
476
494
  writable: false;
477
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
495
+ table?: any;
496
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
478
497
  } | {
479
498
  fields: Record<string, {
480
499
  type: "boolean";
@@ -511,11 +530,14 @@ export declare const dbConfigSchema: z.ZodObject<{
511
530
  default?: unknown;
512
531
  }>;
513
532
  writable: true;
514
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
533
+ table?: any;
534
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
515
535
  }> | undefined;
516
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
536
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
517
537
  }>;
518
- export type DBUserConfig = z.input<typeof dbConfigSchema>;
538
+ export type DBUserConfig = Omit<z.input<typeof dbConfigSchema>, 'data'> & {
539
+ data(params: DBDataContext): MaybePromise<void>;
540
+ };
519
541
  export declare const astroConfigWithDbSchema: z.ZodObject<{
520
542
  db: z.ZodOptional<z.ZodObject<{
521
543
  studio: z.ZodOptional<z.ZodBoolean>;
@@ -620,8 +642,9 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
620
642
  unique?: boolean | undefined;
621
643
  default?: unknown;
622
644
  }>]>>;
623
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
624
645
  writable: z.ZodLiteral<false>;
646
+ table: z.ZodAny;
647
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
625
648
  }, "strip", z.ZodTypeAny, {
626
649
  fields: Record<string, {
627
650
  type: "boolean";
@@ -658,7 +681,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
658
681
  default?: unknown;
659
682
  }>;
660
683
  writable: false;
661
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
684
+ table?: any;
685
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
662
686
  }, {
663
687
  fields: Record<string, {
664
688
  type: "boolean";
@@ -695,7 +719,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
695
719
  default?: unknown;
696
720
  }>;
697
721
  writable: false;
698
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
722
+ table?: any;
723
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
699
724
  }>, z.ZodObject<{
700
725
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
701
726
  label: z.ZodOptional<z.ZodString>;
@@ -797,8 +822,9 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
797
822
  unique?: boolean | undefined;
798
823
  default?: unknown;
799
824
  }>]>>;
800
- seed: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
801
825
  writable: z.ZodLiteral<true>;
826
+ table: z.ZodAny;
827
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
802
828
  }, "strip", z.ZodTypeAny, {
803
829
  fields: Record<string, {
804
830
  type: "boolean";
@@ -835,7 +861,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
835
861
  default?: unknown;
836
862
  }>;
837
863
  writable: true;
838
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
864
+ table?: any;
865
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
839
866
  }, {
840
867
  fields: Record<string, {
841
868
  type: "boolean";
@@ -872,9 +899,10 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
872
899
  default?: unknown;
873
900
  }>;
874
901
  writable: true;
875
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
902
+ table?: any;
903
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
876
904
  }>]>>>;
877
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodUnknown>>;
905
+ data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodVoid, z.ZodPromise<z.ZodVoid>]>>>;
878
906
  }, "strip", z.ZodTypeAny, {
879
907
  studio?: boolean | undefined;
880
908
  collections?: Record<string, {
@@ -913,7 +941,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
913
941
  default?: unknown;
914
942
  }>;
915
943
  writable: false;
916
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
944
+ table?: any;
945
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
917
946
  } | {
918
947
  fields: Record<string, {
919
948
  type: "boolean";
@@ -950,9 +979,10 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
950
979
  default?: unknown;
951
980
  }>;
952
981
  writable: true;
953
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
982
+ table?: any;
983
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
954
984
  }> | undefined;
955
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
985
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
956
986
  }, {
957
987
  studio?: boolean | undefined;
958
988
  collections?: Record<string, {
@@ -991,7 +1021,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
991
1021
  default?: unknown;
992
1022
  }>;
993
1023
  writable: false;
994
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1024
+ table?: any;
1025
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
995
1026
  } | {
996
1027
  fields: Record<string, {
997
1028
  type: "boolean";
@@ -1028,9 +1059,10 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
1028
1059
  default?: unknown;
1029
1060
  }>;
1030
1061
  writable: true;
1031
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1062
+ table?: any;
1063
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1032
1064
  }> | undefined;
1033
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
1065
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
1034
1066
  }>>;
1035
1067
  }, "strip", z.ZodTypeAny, {
1036
1068
  db?: {
@@ -1071,7 +1103,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
1071
1103
  default?: unknown;
1072
1104
  }>;
1073
1105
  writable: false;
1074
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1106
+ table?: any;
1107
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1075
1108
  } | {
1076
1109
  fields: Record<string, {
1077
1110
  type: "boolean";
@@ -1108,9 +1141,10 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
1108
1141
  default?: unknown;
1109
1142
  }>;
1110
1143
  writable: true;
1111
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1144
+ table?: any;
1145
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1112
1146
  }> | undefined;
1113
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
1147
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
1114
1148
  } | undefined;
1115
1149
  }, {
1116
1150
  db?: {
@@ -1151,7 +1185,8 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
1151
1185
  default?: unknown;
1152
1186
  }>;
1153
1187
  writable: false;
1154
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1188
+ table?: any;
1189
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1155
1190
  } | {
1156
1191
  fields: Record<string, {
1157
1192
  type: "boolean";
@@ -1188,27 +1223,21 @@ export declare const astroConfigWithDbSchema: z.ZodObject<{
1188
1223
  default?: unknown;
1189
1224
  }>;
1190
1225
  writable: true;
1191
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1226
+ table?: any;
1227
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1192
1228
  }> | undefined;
1193
- data?: ((args_0: any, ...args_1: unknown[]) => unknown) | undefined;
1229
+ data?: ((...args: unknown[]) => void | Promise<void>) | undefined;
1194
1230
  } | undefined;
1195
1231
  }>;
1196
- type CollectionConfig<TFields extends z.input<typeof collectionSchema>['fields'], Writable extends boolean> = Writable extends true ? {
1232
+ type CollectionConfig<TFields extends DBFieldsConfig> = {
1197
1233
  fields: TFields;
1198
- seed?: Writable extends false ? never : () => MaybePromise<Array<Record<keyof TFields, any> & {
1199
- id?: string;
1200
- }>>;
1201
- } : {
1202
- fields: TFields;
1203
- data?: Writable extends true ? never : () => MaybePromise<Array<Record<keyof TFields, any> & {
1204
- id?: string;
1205
- }>>;
1206
1234
  };
1207
- type ResolvedCollectionConfig<TFields extends z.input<typeof collectionSchema>['fields'], Writable extends boolean> = CollectionConfig<TFields, Writable> & {
1235
+ export type ResolvedCollectionConfig<TFields extends DBFieldsConfig = DBFieldsConfig, Writable extends boolean = boolean> = CollectionConfig<TFields> & {
1208
1236
  writable: Writable;
1237
+ table: Table<string, TFields>;
1209
1238
  };
1210
- export declare function defineCollection<TFields extends z.input<typeof collectionSchema>['fields']>(userConfig: CollectionConfig<TFields, false>): ResolvedCollectionConfig<TFields, false>;
1211
- export declare function defineWritableCollection<TFields extends z.input<typeof collectionSchema>['fields']>(userConfig: CollectionConfig<TFields, true>): ResolvedCollectionConfig<TFields, true>;
1239
+ export declare function defineCollection<TFields extends DBFieldsConfig>(userConfig: CollectionConfig<TFields>): ResolvedCollectionConfig<TFields, false>;
1240
+ export declare function defineWritableCollection<TFields extends DBFieldsConfig>(userConfig: CollectionConfig<TFields>): ResolvedCollectionConfig<TFields, true>;
1212
1241
  export type AstroConfigWithDB = z.infer<typeof astroConfigWithDbSchema>;
1213
1242
  type FieldOpts<T extends DBFieldInput> = Omit<T, 'type'>;
1214
1243
  export declare const field: {
package/dist/config.js CHANGED
@@ -5,22 +5,39 @@ import { z } from "zod";
5
5
  const dbConfigSchema = z.object({
6
6
  studio: z.boolean().optional(),
7
7
  collections: collectionsSchema.optional(),
8
- // TODO: strict types
9
- data: z.function().args(z.any()).optional()
8
+ data: z.function().returns(z.union([z.void(), z.promise(z.void())])).optional()
10
9
  });
11
10
  const astroConfigWithDbSchema = z.object({
12
11
  db: dbConfigSchema.optional()
13
12
  });
14
13
  function defineCollection(userConfig) {
14
+ const meta = { table: null };
15
+ function _setMeta(values) {
16
+ Object.assign(meta, values);
17
+ }
15
18
  return {
16
19
  ...userConfig,
17
- writable: false
20
+ writable: false,
21
+ get table() {
22
+ return meta.table;
23
+ },
24
+ // @ts-expect-error private field
25
+ _setMeta
18
26
  };
19
27
  }
20
28
  function defineWritableCollection(userConfig) {
29
+ const meta = { table: null };
30
+ function _setMeta(values) {
31
+ Object.assign(meta, values);
32
+ }
21
33
  return {
22
34
  ...userConfig,
23
- writable: true
35
+ writable: true,
36
+ get table() {
37
+ return meta.table;
38
+ },
39
+ // @ts-expect-error private field
40
+ _setMeta
24
41
  };
25
42
  }
26
43
  const baseDefaults = {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export { defineCollection, defineWritableCollection, field } from './config.js';
2
+ export type { ResolvedCollectionConfig, DBDataContext } from './config.js';
3
+ export type { DBCollection, DBCollections, DBSnapshot, DBField, BooleanField, NumberField, TextField, DateField, DateFieldInput, JsonField, FieldType, } from './types.js';
2
4
  export { cli } from './cli/index.js';
3
5
  export { integration as default } from './integration.js';
@@ -3,9 +3,10 @@ import { type BooleanField, type DBCollection, type DBCollections, type DBField,
3
3
  import { type LibSQLDatabase } from 'drizzle-orm/libsql';
4
4
  import { type ColumnDataType } from 'drizzle-orm';
5
5
  import type { AstroIntegrationLogger } from 'astro';
6
- export { createRemoteDatabaseClient, findLocalDatabase } from './utils-runtime.js';
6
+ import type { DBUserConfig } from './config.js';
7
7
  export type SqliteDB = SqliteRemoteDatabase;
8
8
  export type { Table } from './types.js';
9
+ export { createRemoteDatabaseClient, findLocalDatabase } from './utils-runtime.js';
9
10
  export declare function hasPrimaryKey(field: DBField): boolean;
10
11
  export declare function createLocalDatabaseClient({ collections, dbUrl, seeding, }: {
11
12
  dbUrl: string;
@@ -13,10 +14,10 @@ export declare function createLocalDatabaseClient({ collections, dbUrl, seeding,
13
14
  seeding: boolean;
14
15
  }): Promise<LibSQLDatabase<Record<string, never>>>;
15
16
  export declare function setupDbTables({ db, data, collections, logger, mode, }: {
16
- db: LibSQLDatabase;
17
- data?: (...params: any) => any;
17
+ db: SqliteRemoteDatabase;
18
+ data?: DBUserConfig['data'];
18
19
  collections: DBCollections;
19
- logger: AstroIntegrationLogger;
20
+ logger?: AstroIntegrationLogger;
20
21
  mode: 'dev' | 'build';
21
22
  }): Promise<void>;
22
23
  export declare function getCreateTableQuery(collectionName: string, collection: DBCollection): string;
package/dist/internal.js CHANGED
@@ -20,9 +20,6 @@ const sqlite = new SQLiteAsyncDialect();
20
20
  function hasPrimaryKey(field) {
21
21
  return "primaryKey" in field && !!field.primaryKey;
22
22
  }
23
- function isReadableCollection(collection) {
24
- return !collection.writable;
25
- }
26
23
  function checkIfModificationIsAllowed(collections, Table) {
27
24
  const tableName = getTableName(Table);
28
25
  const collection = collections[tableName];
@@ -72,25 +69,25 @@ async function setupDbTables({
72
69
  await db.run(q);
73
70
  }
74
71
  if (data) {
75
- const ormObjects = Object.fromEntries(
76
- Object.entries(collections).map(([name, collection]) => {
77
- const table = collectionToTable(name, collection, false);
78
- return [name, table];
79
- })
80
- );
81
- await data({ db, ...ormObjects, mode });
82
- }
83
- for (const [name, collection] of Object.entries(collections)) {
84
- if (!isReadableCollection(collection) || !collection.data)
85
- continue;
86
- const table = collectionToTable(name, collection);
72
+ for (const [name, collection] of Object.entries(collections)) {
73
+ const table = collectionToTable(name, collection);
74
+ collection._setMeta?.({ table });
75
+ }
87
76
  try {
88
- await db.insert(table).values(await collection.data());
77
+ await data({
78
+ async seed({ table }, values) {
79
+ const result = Array.isArray(values) ? (
80
+ // TODO: fix values typing once we can infer fields type correctly
81
+ await db.insert(table).values(values).returning()
82
+ ) : await db.insert(table).values(values).returning().get();
83
+ return result;
84
+ },
85
+ db,
86
+ mode
87
+ });
89
88
  } catch (e) {
90
- logger.error(
91
- `Failed to seed ${bold(
92
- name
93
- )} data. Did you update to match recent schema changes? Full error:
89
+ (logger ?? console).error(
90
+ `Failed to seed data. Did you update to match recent schema changes? Full error:
94
91
 
95
92
  ${e}`
96
93
  );
package/dist/types.d.ts CHANGED
@@ -406,8 +406,9 @@ export declare const readableCollectionSchema: z.ZodObject<{
406
406
  unique?: boolean | undefined;
407
407
  default?: unknown;
408
408
  }>]>>;
409
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
410
409
  writable: z.ZodLiteral<false>;
410
+ table: z.ZodAny;
411
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
411
412
  }, "strip", z.ZodTypeAny, {
412
413
  fields: Record<string, {
413
414
  type: "boolean";
@@ -444,7 +445,8 @@ export declare const readableCollectionSchema: z.ZodObject<{
444
445
  default?: unknown;
445
446
  }>;
446
447
  writable: false;
447
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
448
+ table?: any;
449
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
448
450
  }, {
449
451
  fields: Record<string, {
450
452
  type: "boolean";
@@ -481,7 +483,8 @@ export declare const readableCollectionSchema: z.ZodObject<{
481
483
  default?: unknown;
482
484
  }>;
483
485
  writable: false;
484
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
486
+ table?: any;
487
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
485
488
  }>;
486
489
  export declare const writableCollectionSchema: z.ZodObject<{
487
490
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
@@ -584,8 +587,9 @@ export declare const writableCollectionSchema: z.ZodObject<{
584
587
  unique?: boolean | undefined;
585
588
  default?: unknown;
586
589
  }>]>>;
587
- seed: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
588
590
  writable: z.ZodLiteral<true>;
591
+ table: z.ZodAny;
592
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
589
593
  }, "strip", z.ZodTypeAny, {
590
594
  fields: Record<string, {
591
595
  type: "boolean";
@@ -622,7 +626,8 @@ export declare const writableCollectionSchema: z.ZodObject<{
622
626
  default?: unknown;
623
627
  }>;
624
628
  writable: true;
625
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
629
+ table?: any;
630
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
626
631
  }, {
627
632
  fields: Record<string, {
628
633
  type: "boolean";
@@ -659,7 +664,8 @@ export declare const writableCollectionSchema: z.ZodObject<{
659
664
  default?: unknown;
660
665
  }>;
661
666
  writable: true;
662
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
667
+ table?: any;
668
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
663
669
  }>;
664
670
  export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
665
671
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
@@ -762,8 +768,9 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
762
768
  unique?: boolean | undefined;
763
769
  default?: unknown;
764
770
  }>]>>;
765
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
766
771
  writable: z.ZodLiteral<false>;
772
+ table: z.ZodAny;
773
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
767
774
  }, "strip", z.ZodTypeAny, {
768
775
  fields: Record<string, {
769
776
  type: "boolean";
@@ -800,7 +807,8 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
800
807
  default?: unknown;
801
808
  }>;
802
809
  writable: false;
803
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
810
+ table?: any;
811
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
804
812
  }, {
805
813
  fields: Record<string, {
806
814
  type: "boolean";
@@ -837,7 +845,8 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
837
845
  default?: unknown;
838
846
  }>;
839
847
  writable: false;
840
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
848
+ table?: any;
849
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
841
850
  }>, z.ZodObject<{
842
851
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
843
852
  label: z.ZodOptional<z.ZodString>;
@@ -939,8 +948,9 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
939
948
  unique?: boolean | undefined;
940
949
  default?: unknown;
941
950
  }>]>>;
942
- seed: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
943
951
  writable: z.ZodLiteral<true>;
952
+ table: z.ZodAny;
953
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
944
954
  }, "strip", z.ZodTypeAny, {
945
955
  fields: Record<string, {
946
956
  type: "boolean";
@@ -977,7 +987,8 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
977
987
  default?: unknown;
978
988
  }>;
979
989
  writable: true;
980
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
990
+ table?: any;
991
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
981
992
  }, {
982
993
  fields: Record<string, {
983
994
  type: "boolean";
@@ -1014,7 +1025,8 @@ export declare const collectionSchema: z.ZodUnion<[z.ZodObject<{
1014
1025
  default?: unknown;
1015
1026
  }>;
1016
1027
  writable: true;
1017
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1028
+ table?: any;
1029
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1018
1030
  }>]>;
1019
1031
  export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
1020
1032
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
@@ -1117,8 +1129,9 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1117
1129
  unique?: boolean | undefined;
1118
1130
  default?: unknown;
1119
1131
  }>]>>;
1120
- data: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
1121
1132
  writable: z.ZodLiteral<false>;
1133
+ table: z.ZodAny;
1134
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
1122
1135
  }, "strip", z.ZodTypeAny, {
1123
1136
  fields: Record<string, {
1124
1137
  type: "boolean";
@@ -1155,7 +1168,8 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1155
1168
  default?: unknown;
1156
1169
  }>;
1157
1170
  writable: false;
1158
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1171
+ table?: any;
1172
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1159
1173
  }, {
1160
1174
  fields: Record<string, {
1161
1175
  type: "boolean";
@@ -1192,7 +1206,8 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1192
1206
  default?: unknown;
1193
1207
  }>;
1194
1208
  writable: false;
1195
- data?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1209
+ table?: any;
1210
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1196
1211
  }>, z.ZodObject<{
1197
1212
  fields: z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodObject<{
1198
1213
  label: z.ZodOptional<z.ZodString>;
@@ -1294,8 +1309,9 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1294
1309
  unique?: boolean | undefined;
1295
1310
  default?: unknown;
1296
1311
  }>]>>;
1297
- seed: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnion<[z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">, z.ZodPromise<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>]>>>;
1298
1312
  writable: z.ZodLiteral<true>;
1313
+ table: z.ZodAny;
1314
+ _setMeta: z.ZodOptional<z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodUnknown>>;
1299
1315
  }, "strip", z.ZodTypeAny, {
1300
1316
  fields: Record<string, {
1301
1317
  type: "boolean";
@@ -1332,7 +1348,8 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1332
1348
  default?: unknown;
1333
1349
  }>;
1334
1350
  writable: true;
1335
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1351
+ table?: any;
1352
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1336
1353
  }, {
1337
1354
  fields: Record<string, {
1338
1355
  type: "boolean";
@@ -1369,7 +1386,8 @@ export declare const collectionsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<[z.Z
1369
1386
  default?: unknown;
1370
1387
  }>;
1371
1388
  writable: true;
1372
- seed?: ((...args: unknown[]) => Record<string, unknown>[] | Promise<Record<string, unknown>[]>) | undefined;
1389
+ table?: any;
1390
+ _setMeta?: ((...args: unknown[]) => unknown) | undefined;
1373
1391
  }>]>>;
1374
1392
  export type BooleanField = z.infer<typeof booleanFieldSchema>;
1375
1393
  export type NumberField = z.infer<typeof numberFieldSchema>;
@@ -1446,6 +1464,7 @@ export type AstroId<T extends Pick<GeneratedConfig<'string'>, 'tableName'>> = SQ
1446
1464
  baseColumn: never;
1447
1465
  }>;
1448
1466
  export type MaybePromise<T> = T | Promise<T>;
1467
+ export type MaybeArray<T> = T | T[];
1449
1468
  export type Column<T extends DBField['type'], S extends GeneratedConfig> = T extends 'boolean' ? AstroBoolean<S> : T extends 'number' ? AstroNumber<S> : T extends 'text' ? AstroText<S> : T extends 'date' ? AstroDate<S> : T extends 'json' ? AstroJson<S> : never;
1450
1469
  export type Table<TTableName extends string, TFields extends Record<string, Pick<DBField, 'type' | 'default' | 'optional'>>> = SQLiteTableWithColumns<{
1451
1470
  name: TTableName;
package/dist/types.js CHANGED
@@ -40,16 +40,17 @@ const fieldSchema = z.union([
40
40
  jsonFieldSchema
41
41
  ]);
42
42
  const fieldsSchema = z.record(fieldSchema);
43
- const dataResponse = z.array(z.record(z.unknown()));
44
43
  const readableCollectionSchema = z.object({
45
44
  fields: fieldsSchema,
46
- data: z.function().returns(z.union([dataResponse, z.promise(dataResponse)])).optional(),
47
- writable: z.literal(false)
45
+ writable: z.literal(false),
46
+ table: z.any(),
47
+ _setMeta: z.function().optional()
48
48
  });
49
49
  const writableCollectionSchema = z.object({
50
50
  fields: fieldsSchema,
51
- seed: z.function().returns(z.union([dataResponse, z.promise(dataResponse)])).optional(),
52
- writable: z.literal(true)
51
+ writable: z.literal(true),
52
+ table: z.any(),
53
+ _setMeta: z.function().optional()
53
54
  });
54
55
  const collectionSchema = z.union([readableCollectionSchema, writableCollectionSchema]);
55
56
  const collectionsSchema = z.record(collectionSchema);
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { DB_PATH } from "./consts.js";
4
4
  function findLocalDatabase(localDbURL) {
5
5
  let dbURL = void 0;
6
- if (import.meta.env.VERCEL) {
6
+ if (process.env.VERCEL) {
7
7
  dbURL = new URL(DB_PATH, "file://" + process.cwd() + "/vercel/path0/");
8
8
  } else {
9
9
  dbURL = new URL(localDbURL);
@@ -59,7 +59,9 @@ function getStudioVirtualModContents({
59
59
  return `
60
60
  import {collectionToTable, createRemoteDatabaseClient} from ${INTERNAL_MOD_IMPORT};
61
61
 
62
- export const db = await createRemoteDatabaseClient(${JSON.stringify(appToken)}, import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL);
62
+ export const db = await createRemoteDatabaseClient(${JSON.stringify(
63
+ appToken
64
+ )}, import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL);
63
65
  export * from ${DRIZZLE_MOD_IMPORT};
64
66
 
65
67
  ${getStringifiedCollectionExports(collections)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrojs/db",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -40,7 +40,7 @@
40
40
  "components"
41
41
  ],
42
42
  "dependencies": {
43
- "@libsql/client": "0.4.0-pre.5",
43
+ "@libsql/client": "0.4.0-pre.10",
44
44
  "deep-diff": "^1.0.2",
45
45
  "drizzle-orm": "^0.28.6",
46
46
  "kleur": "^4.1.5",