@astrojs/db 0.5.0 → 0.6.1

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.
@@ -14,6 +14,7 @@ const baseColumnSchema = z.object({
14
14
  label: z.string().optional(),
15
15
  optional: z.boolean().optional().default(false),
16
16
  unique: z.boolean().optional().default(false),
17
+ deprecated: z.boolean().optional().default(false),
17
18
  // Defined when `defineReadableTable()` is called
18
19
  name: z.string().optional(),
19
20
  // TODO: rename to `tableName`. Breaking schema change
@@ -115,7 +116,8 @@ const foreignKeysSchema = z.object({
115
116
  const tableSchema = z.object({
116
117
  columns: columnsSchema,
117
118
  indexes: z.record(indexSchema).optional(),
118
- foreignKeys: z.array(foreignKeysSchema).optional()
119
+ foreignKeys: z.array(foreignKeysSchema).optional(),
120
+ deprecated: z.boolean().optional().default(false)
119
121
  });
120
122
  const tablesSchema = z.preprocess((rawTables) => {
121
123
  const tables = z.record(z.any()).parse(rawTables, { errorMap });
@@ -4,4 +4,3 @@ export declare function getAstroStudioEnv(envMode?: string): Record<`ASTRO_STUDI
4
4
  export declare function getRemoteDatabaseUrl(): string;
5
5
  export declare function getAstroStudioUrl(): string;
6
6
  export declare function getDbDirectoryUrl(root: URL | string): URL;
7
- export declare function getMigrationsDirectoryUrl(root: URL | string): URL;
@@ -14,13 +14,9 @@ function getAstroStudioUrl() {
14
14
  function getDbDirectoryUrl(root) {
15
15
  return new URL("db/", root);
16
16
  }
17
- function getMigrationsDirectoryUrl(root) {
18
- return new URL("migrations/", getDbDirectoryUrl(root));
19
- }
20
17
  export {
21
18
  getAstroStudioEnv,
22
19
  getAstroStudioUrl,
23
20
  getDbDirectoryUrl,
24
- getMigrationsDirectoryUrl,
25
21
  getRemoteDatabaseUrl
26
22
  };
@@ -4,6 +4,7 @@ export declare const column: {
4
4
  name?: string | undefined;
5
5
  label?: string | undefined;
6
6
  unique?: boolean | undefined;
7
+ deprecated?: boolean | undefined;
7
8
  collection?: string | undefined;
8
9
  } & ({
9
10
  primaryKey?: false | undefined;
@@ -20,6 +21,7 @@ export declare const column: {
20
21
  name?: string | undefined;
21
22
  label?: string | undefined;
22
23
  unique?: boolean | undefined;
24
+ deprecated?: boolean | undefined;
23
25
  collection?: string | undefined;
24
26
  } & {
25
27
  primaryKey?: false | undefined;
@@ -29,6 +31,7 @@ export declare const column: {
29
31
  name?: string | undefined;
30
32
  label?: string | undefined;
31
33
  unique?: boolean | undefined;
34
+ deprecated?: boolean | undefined;
32
35
  collection?: string | undefined;
33
36
  } & {
34
37
  primaryKey: true;
@@ -48,6 +51,7 @@ export declare const column: {
48
51
  label?: string | undefined;
49
52
  optional?: boolean | undefined;
50
53
  unique?: boolean | undefined;
54
+ deprecated?: boolean | undefined;
51
55
  collection?: string | undefined;
52
56
  default?: boolean | import("drizzle-orm").SQL<any> | undefined;
53
57
  }>(opts?: T_1) => {
@@ -61,6 +65,7 @@ export declare const column: {
61
65
  name?: string | undefined;
62
66
  label?: string | undefined;
63
67
  unique?: boolean | undefined;
68
+ deprecated?: boolean | undefined;
64
69
  collection?: string | undefined;
65
70
  default?: string | import("drizzle-orm").SQL<any> | undefined;
66
71
  multiline?: boolean | undefined;
@@ -77,6 +82,7 @@ export declare const column: {
77
82
  name?: string | undefined;
78
83
  label?: string | undefined;
79
84
  unique?: boolean | undefined;
85
+ deprecated?: boolean | undefined;
80
86
  collection?: string | undefined;
81
87
  default?: string | import("drizzle-orm").SQL<any> | undefined;
82
88
  multiline?: boolean | undefined;
@@ -87,6 +93,7 @@ export declare const column: {
87
93
  name?: string | undefined;
88
94
  label?: string | undefined;
89
95
  unique?: boolean | undefined;
96
+ deprecated?: boolean | undefined;
90
97
  collection?: string | undefined;
91
98
  default?: string | import("drizzle-orm").SQL<any> | undefined;
92
99
  multiline?: boolean | undefined;
@@ -107,6 +114,7 @@ export declare const column: {
107
114
  label?: string | undefined;
108
115
  optional?: boolean | undefined;
109
116
  unique?: boolean | undefined;
117
+ deprecated?: boolean | undefined;
110
118
  collection?: string | undefined;
111
119
  default?: Date | import("drizzle-orm").SQL<any> | undefined;
112
120
  }>(opts?: T_3): {
@@ -121,6 +129,7 @@ export declare const column: {
121
129
  label?: string | undefined;
122
130
  optional?: boolean | undefined;
123
131
  unique?: boolean | undefined;
132
+ deprecated?: boolean | undefined;
124
133
  collection?: string | undefined;
125
134
  default?: unknown;
126
135
  }>(opts?: T_4): {
@@ -5,7 +5,6 @@ import { z } from "zod";
5
5
  const isWebContainer = !!process.versions?.webcontainer;
6
6
  function createLocalDatabaseClient({ dbUrl }) {
7
7
  const url = isWebContainer ? "file:content.db" : dbUrl;
8
- console.log("memory", process.env.TEST_IN_MEMORY_DB);
9
8
  const client = createClient({ url: process.env.TEST_IN_MEMORY_DB ? ":memory:" : url });
10
9
  const db = drizzleLibsql(client);
11
10
  return db;
@@ -10,6 +10,7 @@ export declare function recreateTables({ db, tables }: {
10
10
  db: SqliteDB;
11
11
  tables: DBTables;
12
12
  }): Promise<void>;
13
+ export declare function getDropTableIfExistsQuery(tableName: string): string;
13
14
  export declare function getCreateTableQuery(tableName: string, table: DBTable): string;
14
15
  export declare function getCreateIndexQueries(tableName: string, table: Pick<DBTable, 'indexes'>): string[];
15
16
  export declare function getCreateForeignKeyQueries(tableName: string, table: DBTable): string[];
@@ -19,6 +20,7 @@ export declare function getReferencesConfig(column: DBColumn): {
19
20
  type: "number";
20
21
  schema: ({
21
22
  unique: boolean;
23
+ deprecated: boolean;
22
24
  name?: string | undefined;
23
25
  label?: string | undefined;
24
26
  collection?: string | undefined;
@@ -30,6 +32,7 @@ export declare function getReferencesConfig(column: DBColumn): {
30
32
  references?: any | undefined;
31
33
  }) | ({
32
34
  unique: boolean;
35
+ deprecated: boolean;
33
36
  name?: string | undefined;
34
37
  label?: string | undefined;
35
38
  collection?: string | undefined;
@@ -44,6 +47,7 @@ export declare function getReferencesConfig(column: DBColumn): {
44
47
  type: "text";
45
48
  schema: ({
46
49
  unique: boolean;
50
+ deprecated: boolean;
47
51
  name?: string | undefined;
48
52
  label?: string | undefined;
49
53
  collection?: string | undefined;
@@ -56,6 +60,7 @@ export declare function getReferencesConfig(column: DBColumn): {
56
60
  references?: any | undefined;
57
61
  }) | ({
58
62
  unique: boolean;
63
+ deprecated: boolean;
59
64
  name?: string | undefined;
60
65
  label?: string | undefined;
61
66
  collection?: string | undefined;
@@ -46,6 +46,9 @@ async function recreateTables({ db, tables }) {
46
46
  ...setupQueries.map((q) => db.run(q))
47
47
  ]);
48
48
  }
49
+ function getDropTableIfExistsQuery(tableName) {
50
+ return `DROP TABLE IF EXISTS ${sqlite.escapeName(tableName)}`;
51
+ }
49
52
  function getCreateTableQuery(tableName, table) {
50
53
  let query = `CREATE TABLE ${sqlite.escapeName(tableName)} (`;
51
54
  const colQueries = [];
@@ -193,6 +196,7 @@ export {
193
196
  getCreateForeignKeyQueries,
194
197
  getCreateIndexQueries,
195
198
  getCreateTableQuery,
199
+ getDropTableIfExistsQuery,
196
200
  getModifiers,
197
201
  getReferencesConfig,
198
202
  hasDefault,
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@astrojs/db",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "types": "./index.d.ts",
8
7
  "author": "withastro",
8
+ "types": "./index.d.ts",
9
9
  "main": "./dist/index.js",
10
10
  "exports": {
11
11
  ".": {
@@ -51,7 +51,6 @@
51
51
  },
52
52
  "files": [
53
53
  "index.d.ts",
54
- "config-augment.d.ts",
55
54
  "dist"
56
55
  ],
57
56
  "keywords": [
@@ -83,7 +82,7 @@
83
82
  "mocha": "^10.2.0",
84
83
  "typescript": "^5.2.2",
85
84
  "vite": "^5.1.4",
86
- "astro": "4.4.9",
85
+ "astro": "4.4.11",
87
86
  "astro-scripts": "0.0.14"
88
87
  },
89
88
  "scripts": {
@@ -1,8 +0,0 @@
1
- import type { AstroConfig } from 'astro';
2
- import type { Arguments } from 'yargs-parser';
3
- import type { DBConfig } from '../../../types.js';
4
- export declare function cmd({ astroConfig, dbConfig, }: {
5
- astroConfig: AstroConfig;
6
- dbConfig: DBConfig;
7
- flags: Arguments;
8
- }): Promise<void>;
@@ -1,47 +0,0 @@
1
- import { writeFile } from "node:fs/promises";
2
- import { relative } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { bgRed, bold, red, reset } from "kleur/colors";
5
- import { getMigrationsDirectoryUrl } from "../../../utils.js";
6
- import { getMigrationQueries } from "../../migration-queries.js";
7
- import {
8
- MIGRATIONS_CREATED,
9
- MIGRATIONS_UP_TO_DATE,
10
- getMigrationStatus,
11
- initializeMigrationsDirectory
12
- } from "../../migrations.js";
13
- async function cmd({
14
- astroConfig,
15
- dbConfig
16
- }) {
17
- const migration = await getMigrationStatus({ dbConfig, root: astroConfig.root });
18
- const migrationsDir = getMigrationsDirectoryUrl(astroConfig.root);
19
- if (migration.state === "no-migrations-found") {
20
- await initializeMigrationsDirectory(migration.currentSnapshot, migrationsDir);
21
- console.log(MIGRATIONS_CREATED);
22
- return;
23
- } else if (migration.state === "up-to-date") {
24
- console.log(MIGRATIONS_UP_TO_DATE);
25
- return;
26
- }
27
- const { oldSnapshot, newSnapshot, newFilename, diff } = migration;
28
- const { queries: migrationQueries, confirmations } = await getMigrationQueries({
29
- oldSnapshot,
30
- newSnapshot
31
- });
32
- confirmations.map((message) => console.log(bgRed(" !!! ") + " " + red(message)));
33
- const content = {
34
- diff,
35
- db: migrationQueries,
36
- // TODO(fks): Encode the relevant data, instead of the raw message.
37
- // This will give `db push` more control over the formatting of the message.
38
- confirm: confirmations.map((c) => reset(c))
39
- };
40
- const fileUrl = new URL(newFilename, migrationsDir);
41
- const relativePath = relative(fileURLToPath(astroConfig.root), fileURLToPath(fileUrl));
42
- await writeFile(fileUrl, JSON.stringify(content, void 0, 2));
43
- console.log(bold(relativePath) + " created!");
44
- }
45
- export {
46
- cmd
47
- };
@@ -1,37 +0,0 @@
1
- import deepDiff from 'deep-diff';
2
- import { type DBConfig, type DBSnapshot } from '../types.js';
3
- export type MigrationStatus = {
4
- state: 'no-migrations-found';
5
- currentSnapshot: DBSnapshot;
6
- } | {
7
- state: 'ahead';
8
- oldSnapshot: DBSnapshot;
9
- newSnapshot: DBSnapshot;
10
- diff: deepDiff.Diff<DBSnapshot, DBSnapshot>[];
11
- newFilename: string;
12
- summary: string;
13
- newFileContent?: string;
14
- } | {
15
- state: 'up-to-date';
16
- currentSnapshot: DBSnapshot;
17
- };
18
- export declare const INITIAL_SNAPSHOT = "0000_snapshot.json";
19
- export declare function getMigrationStatus({ dbConfig, root, }: {
20
- dbConfig: DBConfig;
21
- root: URL;
22
- }): Promise<MigrationStatus>;
23
- export declare const MIGRATIONS_CREATED: string;
24
- export declare const MIGRATIONS_UP_TO_DATE: string;
25
- export declare const MIGRATIONS_NOT_INITIALIZED: string;
26
- export declare const MIGRATION_NEEDED: string;
27
- export declare function getMigrations(dir: URL): Promise<string[]>;
28
- export declare function loadMigration(migration: string, dir: URL): Promise<{
29
- diff: any[];
30
- db: string[];
31
- confirm?: string[];
32
- }>;
33
- export declare function loadInitialSnapshot(dir: URL): Promise<DBSnapshot>;
34
- export declare function initializeMigrationsDirectory(currentSnapshot: DBSnapshot, dir: URL): Promise<void>;
35
- export declare function initializeFromMigrations(allMigrationFiles: string[], dir: URL): Promise<DBSnapshot>;
36
- export declare function createCurrentSnapshot({ tables }: DBConfig): DBSnapshot;
37
- export declare function createEmptySnapshot(): DBSnapshot;
@@ -1,135 +0,0 @@
1
- import deepDiff from "deep-diff";
2
- import { mkdir, readFile, readdir, writeFile } from "fs/promises";
3
- import { cyan, green, yellow } from "kleur/colors";
4
- import {} from "../types.js";
5
- import { getMigrationsDirectoryUrl } from "../utils.js";
6
- const { applyChange, diff: generateDiff } = deepDiff;
7
- const INITIAL_SNAPSHOT = "0000_snapshot.json";
8
- async function getMigrationStatus({
9
- dbConfig,
10
- root
11
- }) {
12
- const currentSnapshot = createCurrentSnapshot(dbConfig);
13
- const dir = getMigrationsDirectoryUrl(root);
14
- const allMigrationFiles = await getMigrations(dir);
15
- if (allMigrationFiles.length === 0) {
16
- return {
17
- state: "no-migrations-found",
18
- currentSnapshot
19
- };
20
- }
21
- const previousSnapshot = await initializeFromMigrations(allMigrationFiles, dir);
22
- const diff = generateDiff(previousSnapshot, currentSnapshot);
23
- if (diff) {
24
- const n = getNewMigrationNumber(allMigrationFiles);
25
- const newFilename = `${String(n + 1).padStart(4, "0")}_migration.json`;
26
- return {
27
- state: "ahead",
28
- oldSnapshot: previousSnapshot,
29
- newSnapshot: currentSnapshot,
30
- diff,
31
- newFilename,
32
- summary: generateDiffSummary(diff)
33
- };
34
- }
35
- return {
36
- state: "up-to-date",
37
- currentSnapshot
38
- };
39
- }
40
- const MIGRATIONS_CREATED = `${green(
41
- "\u25A0 Migrations initialized!"
42
- )}
43
-
44
- To execute your migrations, run
45
- ${cyan("astro db push")}`;
46
- const MIGRATIONS_UP_TO_DATE = `${green(
47
- "\u25A0 No migrations needed!"
48
- )}
49
-
50
- Your database is up to date.
51
- `;
52
- const MIGRATIONS_NOT_INITIALIZED = `${yellow(
53
- "\u25B6 No migrations found!"
54
- )}
55
-
56
- To scaffold your migrations folder, run
57
- ${cyan("astro db sync")}
58
- `;
59
- const MIGRATION_NEEDED = `${yellow(
60
- "\u25B6 Changes detected!"
61
- )}
62
-
63
- To create the necessary migration file, run
64
- ${cyan("astro db sync")}
65
- `;
66
- function generateDiffSummary(diff) {
67
- return JSON.stringify(diff, null, 2);
68
- }
69
- function getNewMigrationNumber(allMigrationFiles) {
70
- const len = allMigrationFiles.length - 1;
71
- return allMigrationFiles.reduce((acc, curr) => {
72
- const num = Number.parseInt(curr.split("_")[0] ?? len, 10);
73
- return num > acc ? num : acc;
74
- }, 0);
75
- }
76
- async function getMigrations(dir) {
77
- const migrationFiles = await readdir(dir).catch((err) => {
78
- if (err.code === "ENOENT") {
79
- return [];
80
- }
81
- throw err;
82
- });
83
- return migrationFiles;
84
- }
85
- async function loadMigration(migration, dir) {
86
- return JSON.parse(await readFile(new URL(migration, dir), "utf-8"));
87
- }
88
- async function loadInitialSnapshot(dir) {
89
- const snapshot = JSON.parse(await readFile(new URL(INITIAL_SNAPSHOT, dir), "utf-8"));
90
- if (snapshot.experimentalVersion === 1) {
91
- return snapshot;
92
- }
93
- if (!snapshot.schema) {
94
- return { experimentalVersion: 1, schema: snapshot };
95
- }
96
- throw new Error("Invalid snapshot format");
97
- }
98
- async function initializeMigrationsDirectory(currentSnapshot, dir) {
99
- await mkdir(dir, { recursive: true });
100
- await writeFile(new URL(INITIAL_SNAPSHOT, dir), JSON.stringify(currentSnapshot, void 0, 2));
101
- }
102
- async function initializeFromMigrations(allMigrationFiles, dir) {
103
- const prevSnapshot = await loadInitialSnapshot(dir);
104
- for (const migration of allMigrationFiles) {
105
- if (migration === INITIAL_SNAPSHOT)
106
- continue;
107
- const migrationContent = await loadMigration(migration, dir);
108
- migrationContent.diff.forEach((change) => {
109
- applyChange(prevSnapshot, {}, change);
110
- });
111
- }
112
- return prevSnapshot;
113
- }
114
- function createCurrentSnapshot({ tables = {} }) {
115
- const schema = JSON.parse(JSON.stringify(tables));
116
- return { experimentalVersion: 1, schema };
117
- }
118
- function createEmptySnapshot() {
119
- return { experimentalVersion: 1, schema: {} };
120
- }
121
- export {
122
- INITIAL_SNAPSHOT,
123
- MIGRATIONS_CREATED,
124
- MIGRATIONS_NOT_INITIALIZED,
125
- MIGRATIONS_UP_TO_DATE,
126
- MIGRATION_NEEDED,
127
- createCurrentSnapshot,
128
- createEmptySnapshot,
129
- getMigrationStatus,
130
- getMigrations,
131
- initializeFromMigrations,
132
- initializeMigrationsDirectory,
133
- loadInitialSnapshot,
134
- loadMigration
135
- };