@astrojs/db 0.15.0 → 0.16.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.
Files changed (39) hide show
  1. package/dist/_internal/core/schemas.d.ts +57 -57
  2. package/dist/_internal/core/types.d.ts +1 -1
  3. package/dist/_internal/core/utils.d.ts +1 -10
  4. package/dist/_internal/runtime/utils.d.ts +0 -15
  5. package/dist/_internal/runtime/virtual.d.ts +2 -2
  6. package/dist/core/cli/commands/execute/index.js +5 -5
  7. package/dist/core/cli/commands/push/index.js +6 -40
  8. package/dist/core/cli/commands/shell/index.js +3 -9
  9. package/dist/core/cli/commands/verify/index.js +2 -7
  10. package/dist/core/cli/index.js +4 -16
  11. package/dist/core/cli/migration-queries.d.ts +1 -4
  12. package/dist/core/cli/migration-queries.js +9 -32
  13. package/dist/core/cli/print-help.js +1 -1
  14. package/dist/core/integration/index.js +5 -8
  15. package/dist/core/integration/vite-plugin-db.d.ts +4 -4
  16. package/dist/core/integration/vite-plugin-db.js +13 -22
  17. package/dist/core/load-file.d.ts +5 -5
  18. package/dist/core/load-file.js +0 -2
  19. package/dist/core/queries.d.ts +3 -3
  20. package/dist/core/schemas.d.ts +257 -257
  21. package/dist/core/schemas.js +1 -1
  22. package/dist/core/types.d.ts +1 -1
  23. package/dist/core/utils.d.ts +1 -10
  24. package/dist/core/utils.js +2 -27
  25. package/dist/index.d.ts +1 -1
  26. package/dist/runtime/db-client.d.ts +5 -6
  27. package/dist/runtime/db-client.js +10 -167
  28. package/dist/runtime/index.d.ts +1 -1
  29. package/dist/runtime/index.js +1 -1
  30. package/dist/runtime/utils.d.ts +0 -15
  31. package/dist/runtime/utils.js +1 -26
  32. package/dist/runtime/virtual.js +21 -21
  33. package/package.json +4 -9
  34. package/dist/core/cli/commands/link/index.d.ts +0 -1
  35. package/dist/core/cli/commands/link/index.js +0 -266
  36. package/dist/core/cli/commands/login/index.d.ts +0 -8
  37. package/dist/core/cli/commands/login/index.js +0 -76
  38. package/dist/core/cli/commands/logout/index.d.ts +0 -1
  39. package/dist/core/cli/commands/logout/index.js +0 -9
@@ -32,18 +32,6 @@ async function cli({
32
32
  const { cmd } = await import("./commands/execute/index.js");
33
33
  return await cmd({ astroConfig, dbConfig, flags });
34
34
  }
35
- case "login": {
36
- const { cmd } = await import("./commands/login/index.js");
37
- return await cmd({ astroConfig, dbConfig, flags });
38
- }
39
- case "logout": {
40
- const { cmd } = await import("./commands/logout/index.js");
41
- return await cmd();
42
- }
43
- case "link": {
44
- const { cmd } = await import("./commands/link/index.js");
45
- return await cmd();
46
- }
47
35
  default: {
48
36
  if (command != null) {
49
37
  console.error(`Unknown command: ${command}`);
@@ -54,15 +42,15 @@ async function cli({
54
42
  headline: " ",
55
43
  tables: {
56
44
  Commands: [
57
- ["push", "Push table schema updates to Astro Studio."],
58
- ["verify", "Test schema updates /w Astro Studio (good for CI)."],
45
+ ["push", "Push table schema updates to libSQL."],
46
+ ["verify", "Test schema updates with libSQL (good for CI)."],
59
47
  [
60
48
  "astro db execute <file-path>",
61
- "Execute a ts/js file using astro:db. Use --remote to connect to Studio."
49
+ "Execute a ts/js file using astro:db. Use --remote to connect to libSQL."
62
50
  ],
63
51
  [
64
52
  "astro db shell --query <sql-string>",
65
- "Execute a SQL string. Use --remote to connect to Studio."
53
+ "Execute a SQL string. Use --remote to connect to libSQL."
66
54
  ]
67
55
  ]
68
56
  }
@@ -16,10 +16,7 @@ export declare function getTableChangeQueries({ tableName, oldTable, newTable, }
16
16
  queries: string[];
17
17
  confirmations: string[];
18
18
  }>;
19
- export declare function getProductionCurrentSnapshot(options: {
20
- dbInfo: RemoteDatabaseInfo;
21
- appToken: string;
22
- }): Promise<DBSnapshot | undefined>;
19
+ export declare function getProductionCurrentSnapshot({ url, token, }: RemoteDatabaseInfo): Promise<DBSnapshot | undefined>;
23
20
  export declare function createCurrentSnapshot({ tables }: DBConfig): DBSnapshot;
24
21
  export declare function createEmptySnapshot(): DBSnapshot;
25
22
  export declare function formatDataLossMessage(confirmations: string[], isColor?: boolean): string;
@@ -4,10 +4,9 @@ import { sql } from "drizzle-orm";
4
4
  import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
5
5
  import * as color from "kleur/colors";
6
6
  import { customAlphabet } from "nanoid";
7
- import { hasPrimaryKey } from "../../runtime/index.js";
8
- import { createRemoteDatabaseClient } from "../../runtime/index.js";
7
+ import { createRemoteDatabaseClient, hasPrimaryKey } from "../../runtime/index.js";
9
8
  import { isSerializedSQL } from "../../runtime/types.js";
10
- import { isDbError, safeFetch } from "../../runtime/utils.js";
9
+ import { isDbError } from "../../runtime/utils.js";
11
10
  import { MIGRATION_VERSION } from "../consts.js";
12
11
  import { RENAME_COLUMN_ERROR, RENAME_TABLE_ERROR } from "../errors.js";
13
12
  import {
@@ -303,14 +302,16 @@ function canChangeTypeWithoutQuery(oldColumn, newColumn) {
303
302
  function hasRuntimeDefault(column) {
304
303
  return !!(column.schema.default && isSerializedSQL(column.schema.default));
305
304
  }
306
- function getProductionCurrentSnapshot(options) {
307
- return options.dbInfo.type === "studio" ? getStudioCurrentSnapshot(options.appToken, options.dbInfo.url) : getDbCurrentSnapshot(options.appToken, options.dbInfo.url);
305
+ function getProductionCurrentSnapshot({
306
+ url,
307
+ token
308
+ }) {
309
+ return getDbCurrentSnapshot(token, url);
308
310
  }
309
311
  async function getDbCurrentSnapshot(appToken, remoteUrl) {
310
312
  const client = createRemoteDatabaseClient({
311
- dbType: "libsql",
312
- appToken,
313
- remoteUrl
313
+ token: appToken,
314
+ url: remoteUrl
314
315
  });
315
316
  try {
316
317
  const res = await client.get(
@@ -331,30 +332,6 @@ async function getDbCurrentSnapshot(appToken, remoteUrl) {
331
332
  throw error;
332
333
  }
333
334
  }
334
- async function getStudioCurrentSnapshot(appToken, remoteUrl) {
335
- const url = new URL("/db/schema", remoteUrl);
336
- const response = await safeFetch(
337
- url,
338
- {
339
- method: "POST",
340
- headers: new Headers({
341
- Authorization: `Bearer ${appToken}`
342
- })
343
- },
344
- async (res) => {
345
- console.error(`${url.toString()} failed: ${res.status} ${res.statusText}`);
346
- console.error(await res.text());
347
- throw new Error(`/db/schema fetch failed: ${res.status} ${res.statusText}`);
348
- }
349
- );
350
- const result = await response.json();
351
- if (!result.success) {
352
- console.error(`${url.toString()} unsuccessful`);
353
- console.error(await response.text());
354
- throw new Error(`/db/schema fetch unsuccessful`);
355
- }
356
- return result.data;
357
- }
358
335
  function getDropTableQueriesForSnapshot(snapshot) {
359
336
  const queries = [];
360
337
  for (const tableName of Object.keys(snapshot.schema)) {
@@ -27,7 +27,7 @@ function printHelp({
27
27
  message.push(
28
28
  linebreak(),
29
29
  ` ${bgGreen(black(` ${commandName} `))} ${green(
30
- `v${"0.15.0"}`
30
+ `v${"0.16.0"}`
31
31
  )} ${headline}`
32
32
  );
33
33
  }
@@ -14,7 +14,7 @@ import { CONFIG_FILE_NAMES, DB_PATH, VIRTUAL_MODULE_ID } from "../consts.js";
14
14
  import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR } from "../errors.js";
15
15
  import { resolveDbConfig } from "../load-file.js";
16
16
  import { SEED_DEV_FILE_NAME } from "../queries.js";
17
- import { getDbDirectoryUrl, getManagedRemoteToken } from "../utils.js";
17
+ import { getDbDirectoryUrl, getRemoteDatabaseInfo } from "../utils.js";
18
18
  import { fileURLIntegration } from "./file-url.js";
19
19
  import { getDtsContent } from "./typegen.js";
20
20
  import {
@@ -24,7 +24,6 @@ function astroDBIntegration() {
24
24
  let connectToRemote = false;
25
25
  let configFileDependencies = [];
26
26
  let root;
27
- let appToken;
28
27
  let tempViteServer;
29
28
  let tables = {
30
29
  get() {
@@ -55,10 +54,9 @@ function astroDBIntegration() {
55
54
  const args = parseArgs(process.argv.slice(3));
56
55
  connectToRemote = process.env.ASTRO_INTERNAL_TEST_REMOTE || args["remote"];
57
56
  if (connectToRemote) {
58
- appToken = await getManagedRemoteToken();
59
57
  dbPlugin = vitePluginDb({
60
- connectToStudio: connectToRemote,
61
- appToken: appToken.token,
58
+ connectToRemote,
59
+ appToken: getRemoteDatabaseInfo().token,
62
60
  tables,
63
61
  root: config.root,
64
62
  srcDir: config.srcDir,
@@ -67,7 +65,7 @@ function astroDBIntegration() {
67
65
  });
68
66
  } else {
69
67
  dbPlugin = vitePluginDb({
70
- connectToStudio: false,
68
+ connectToRemote,
71
69
  tables,
72
70
  seedFiles,
73
71
  root: config.root,
@@ -133,7 +131,7 @@ function astroDBIntegration() {
133
131
  "astro:build:start": async ({ logger }) => {
134
132
  if (!connectToRemote && !databaseFileEnvDefined() && finalBuildOutput === "server") {
135
133
  const message = `Attempting to build without the --remote flag or the ASTRO_DATABASE_FILE environment variable defined. You probably want to pass --remote to astro build.`;
136
- const hint = "Learn more connecting to Studio: https://docs.astro.build/en/guides/astro-db/#connect-to-astro-studio";
134
+ const hint = "Learn more connecting to libSQL: https://docs.astro.build/en/guides/astro-db/#connect-a-libsql-database-for-production";
137
135
  throw new AstroDbError(message, hint);
138
136
  }
139
137
  logger.info("database: " + (connectToRemote ? yellow("remote") : blue("local database.")));
@@ -145,7 +143,6 @@ function astroDBIntegration() {
145
143
  };
146
144
  },
147
145
  "astro:build:done": async ({}) => {
148
- await appToken?.destroy();
149
146
  await tempViteServer?.close();
150
147
  }
151
148
  }
@@ -12,7 +12,7 @@ export type SeedHandler = {
12
12
  execute: (fileUrl: URL) => Promise<void>;
13
13
  };
14
14
  type VitePluginDBParams = {
15
- connectToStudio: false;
15
+ connectToRemote: false;
16
16
  tables: LateTables;
17
17
  seedFiles: LateSeedFiles;
18
18
  srcDir: URL;
@@ -21,7 +21,7 @@ type VitePluginDBParams = {
21
21
  output: AstroConfig['output'];
22
22
  seedHandler: SeedHandler;
23
23
  } | {
24
- connectToStudio: true;
24
+ connectToRemote: true;
25
25
  tables: LateTables;
26
26
  appToken: string;
27
27
  srcDir: URL;
@@ -31,11 +31,11 @@ type VitePluginDBParams = {
31
31
  };
32
32
  export declare function vitePluginDb(params: VitePluginDBParams): VitePlugin;
33
33
  export declare function getConfigVirtualModContents(): string;
34
- export declare function getLocalVirtualModContents({ tables, root, }: {
34
+ export declare function getLocalVirtualModContents({ tables, root }: {
35
35
  tables: DBTables;
36
36
  root: URL;
37
37
  }): string;
38
- export declare function getStudioVirtualModContents({ tables, appToken, isBuild, output, }: {
38
+ export declare function getRemoteVirtualModContents({ tables, appToken, isBuild, output, }: {
39
39
  tables: DBTables;
40
40
  appToken: string;
41
41
  isBuild: boolean;
@@ -6,7 +6,7 @@ import { createLocalDatabaseClient } from "../../runtime/db-client.js";
6
6
  import { normalizeDatabaseUrl } from "../../runtime/index.js";
7
7
  import { DB_PATH, RUNTIME_IMPORT, RUNTIME_VIRTUAL_IMPORT, VIRTUAL_MODULE_ID } from "../consts.js";
8
8
  import { getResolvedFileUrl } from "../load-file.js";
9
- import { SEED_DEV_FILE_NAME, getCreateIndexQueries, getCreateTableQuery } from "../queries.js";
9
+ import { getCreateIndexQueries, getCreateTableQuery, SEED_DEV_FILE_NAME } from "../queries.js";
10
10
  import {
11
11
  getAstroEnv,
12
12
  getDbDirectoryUrl,
@@ -33,8 +33,8 @@ function vitePluginDb(params) {
33
33
  },
34
34
  async load(id) {
35
35
  if (id !== resolved.module && id !== resolved.importedFromSeedFile) return;
36
- if (params.connectToStudio) {
37
- return getStudioVirtualModContents({
36
+ if (params.connectToRemote) {
37
+ return getRemoteVirtualModContents({
38
38
  appToken: params.appToken,
39
39
  tables: params.tables.get(),
40
40
  isBuild: command === "build",
@@ -70,10 +70,7 @@ function vitePluginDb(params) {
70
70
  function getConfigVirtualModContents() {
71
71
  return `export * from ${RUNTIME_VIRTUAL_IMPORT}`;
72
72
  }
73
- function getLocalVirtualModContents({
74
- tables,
75
- root
76
- }) {
73
+ function getLocalVirtualModContents({ tables, root }) {
77
74
  const { ASTRO_DATABASE_FILE } = getAstroEnv();
78
75
  const dbInfo = getRemoteDatabaseInfo();
79
76
  const dbUrl = new URL(DB_PATH, root);
@@ -87,7 +84,7 @@ export * from ${RUNTIME_VIRTUAL_IMPORT};
87
84
 
88
85
  ${getStringifiedTableExports(tables)}`;
89
86
  }
90
- function getStudioVirtualModContents({
87
+ function getRemoteVirtualModContents({
91
88
  tables,
92
89
  appToken,
93
90
  isBuild,
@@ -96,11 +93,10 @@ function getStudioVirtualModContents({
96
93
  const dbInfo = getRemoteDatabaseInfo();
97
94
  function appTokenArg() {
98
95
  if (isBuild) {
99
- const envPrefix = dbInfo.type === "studio" ? "ASTRO_STUDIO" : "ASTRO_DB";
100
96
  if (output === "server") {
101
- return `process.env.${envPrefix}_APP_TOKEN`;
97
+ return `process.env.ASTRO_DB_APP_TOKEN`;
102
98
  } else {
103
- return `process.env.${envPrefix}_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
99
+ return `process.env.ASTRO_DB_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
104
100
  }
105
101
  } else {
106
102
  return JSON.stringify(appToken);
@@ -109,7 +105,7 @@ function getStudioVirtualModContents({
109
105
  function dbUrlArg() {
110
106
  const dbStr = JSON.stringify(dbInfo.url);
111
107
  if (isBuild) {
112
- return dbInfo.type === "studio" ? `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}` : `import.meta.env.ASTRO_DB_REMOTE_URL ?? ${dbStr}`;
108
+ return `import.meta.env.ASTRO_DB_REMOTE_URL ?? ${dbStr}`;
113
109
  } else {
114
110
  return dbStr;
115
111
  }
@@ -118,9 +114,8 @@ function getStudioVirtualModContents({
118
114
  import {asDrizzleTable, createRemoteDatabaseClient} from ${RUNTIME_IMPORT};
119
115
 
120
116
  export const db = await createRemoteDatabaseClient({
121
- dbType: ${JSON.stringify(dbInfo.type)},
122
- remoteUrl: ${dbUrlArg()},
123
- appToken: ${appTokenArg()},
117
+ url: ${dbUrlArg()},
118
+ token: ${appTokenArg()},
124
119
  });
125
120
 
126
121
  export * from ${RUNTIME_VIRTUAL_IMPORT};
@@ -137,10 +132,9 @@ function getStringifiedTableExports(tables) {
137
132
  }
138
133
  const sqlite = new SQLiteAsyncDialect();
139
134
  async function recreateTables({ tables, root }) {
140
- const dbInfo = getRemoteDatabaseInfo();
141
135
  const { ASTRO_DATABASE_FILE } = getAstroEnv();
142
136
  const dbUrl = normalizeDatabaseUrl(ASTRO_DATABASE_FILE, new URL(DB_PATH, root).href);
143
- const db = createLocalDatabaseClient({ dbUrl, enableTransactions: dbInfo.type === "libsql" });
137
+ const db = createLocalDatabaseClient({ dbUrl });
144
138
  const setupQueries = [];
145
139
  for (const [name, table] of Object.entries(tables.get() ?? {})) {
146
140
  const dropQuery = sql.raw(`DROP TABLE IF EXISTS ${sqlite.escapeName(name)}`);
@@ -153,10 +147,7 @@ async function recreateTables({ tables, root }) {
153
147
  ...setupQueries.map((q) => db.run(q))
154
148
  ]);
155
149
  }
156
- function getResolvedSeedFiles({
157
- root,
158
- seedFiles
159
- }) {
150
+ function getResolvedSeedFiles({ root, seedFiles }) {
160
151
  const localSeedFiles = SEED_DEV_FILE_NAME.map((name) => new URL(name, getDbDirectoryUrl(root)));
161
152
  const integrationSeedFiles = seedFiles.get().map((s) => getResolvedFileUrl(root, s));
162
153
  return [...integrationSeedFiles, ...localSeedFiles];
@@ -164,6 +155,6 @@ function getResolvedSeedFiles({
164
155
  export {
165
156
  getConfigVirtualModContents,
166
157
  getLocalVirtualModContents,
167
- getStudioVirtualModContents,
158
+ getRemoteVirtualModContents,
168
159
  vitePluginDb
169
160
  };
@@ -18,10 +18,10 @@ export declare function resolveDbConfig({ root, integrations, }: Pick<AstroConfi
18
18
  optional: boolean;
19
19
  unique: boolean;
20
20
  deprecated: boolean;
21
+ default?: boolean | import("../runtime/types.js").SerializedSQL | undefined;
21
22
  name?: string | undefined;
22
23
  label?: string | undefined;
23
24
  collection?: string | undefined;
24
- default?: boolean | import("../runtime/types.js").SerializedSQL | undefined;
25
25
  };
26
26
  } | {
27
27
  type: "number";
@@ -37,8 +37,8 @@ export declare function resolveDbConfig({ root, integrations, }: Pick<AstroConfi
37
37
  default?: number | import("../runtime/types.js").SerializedSQL | undefined;
38
38
  } | {
39
39
  primaryKey: true;
40
- optional?: false | undefined;
41
40
  default?: undefined;
41
+ optional?: false | undefined;
42
42
  })) & {
43
43
  references?: import("./types.js").NumberColumn;
44
44
  };
@@ -47,10 +47,10 @@ export declare function resolveDbConfig({ root, integrations, }: Pick<AstroConfi
47
47
  schema: ({
48
48
  unique: boolean;
49
49
  deprecated: boolean;
50
+ default?: string | import("../runtime/types.js").SerializedSQL | undefined;
50
51
  name?: string | undefined;
51
52
  label?: string | undefined;
52
53
  collection?: string | undefined;
53
- default?: string | import("../runtime/types.js").SerializedSQL | undefined;
54
54
  multiline?: boolean | undefined;
55
55
  } & ({
56
56
  optional: boolean;
@@ -67,10 +67,10 @@ export declare function resolveDbConfig({ root, integrations, }: Pick<AstroConfi
67
67
  optional: boolean;
68
68
  unique: boolean;
69
69
  deprecated: boolean;
70
+ default?: string | import("../runtime/types.js").SerializedSQL | undefined;
70
71
  name?: string | undefined;
71
72
  label?: string | undefined;
72
73
  collection?: string | undefined;
73
- default?: string | import("../runtime/types.js").SerializedSQL | undefined;
74
74
  };
75
75
  } | {
76
76
  type: "json";
@@ -78,10 +78,10 @@ export declare function resolveDbConfig({ root, integrations, }: Pick<AstroConfi
78
78
  optional: boolean;
79
79
  unique: boolean;
80
80
  deprecated: boolean;
81
+ default?: unknown;
81
82
  name?: string | undefined;
82
83
  label?: string | undefined;
83
84
  collection?: string | undefined;
84
- default?: unknown;
85
85
  };
86
86
  }>;
87
87
  foreignKeys?: (Omit<{
@@ -115,8 +115,6 @@ async function bundleFile({
115
115
  sourcemap: "inline",
116
116
  metafile: true,
117
117
  define: {
118
- "import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL": "undefined",
119
- "import.meta.env.ASTRO_DB_REMOTE_DB_URL": "undefined",
120
118
  "import.meta.env.ASTRO_DATABASE_FILE": JSON.stringify(ASTRO_DATABASE_FILE ?? "")
121
119
  },
122
120
  plugins: [
@@ -1,4 +1,4 @@
1
- import type { BooleanColumn, ColumnType, DBColumn, DBTable, DateColumn, JsonColumn, NumberColumn, TextColumn } from './types.js';
1
+ import type { BooleanColumn, ColumnType, DateColumn, DBColumn, DBTable, JsonColumn, NumberColumn, TextColumn } from './types.js';
2
2
  export declare const SEED_DEV_FILE_NAME: string[];
3
3
  export declare function getDropTableIfExistsQuery(tableName: string): string;
4
4
  export declare function getCreateTableQuery(tableName: string, table: DBTable): string;
@@ -19,8 +19,8 @@ export declare function getReferencesConfig(column: DBColumn): {
19
19
  default?: number | import("../runtime/types.js").SerializedSQL | undefined;
20
20
  } | {
21
21
  primaryKey: true;
22
- optional?: false | undefined;
23
22
  default?: undefined;
23
+ optional?: false | undefined;
24
24
  })) & {
25
25
  references?: NumberColumn;
26
26
  };
@@ -29,10 +29,10 @@ export declare function getReferencesConfig(column: DBColumn): {
29
29
  schema: ({
30
30
  unique: boolean;
31
31
  deprecated: boolean;
32
+ default?: string | import("../runtime/types.js").SerializedSQL | undefined;
32
33
  name?: string | undefined;
33
34
  label?: string | undefined;
34
35
  collection?: string | undefined;
35
- default?: string | import("../runtime/types.js").SerializedSQL | undefined;
36
36
  multiline?: boolean | undefined;
37
37
  } & ({
38
38
  optional: boolean;