Skip to content

Commit 7ffdc7e

Browse files
committed
+
1 parent 28c1bfc commit 7ffdc7e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+5965
-9338
lines changed

Diff for: drizzle-kit/build.ext.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,18 @@ const main = async () => {
1212
// format: ['esm'],
1313
// });
1414

15+
// await tsup.build({
16+
// entryPoints: ['./src/utils/studio-sqlite.ts'],
17+
// outDir: './dist',
18+
// external: [],
19+
// splitting: false,
20+
// dts: true,
21+
// platform: 'browser',
22+
// format: ['esm'],
23+
// });
24+
1525
await tsup.build({
16-
entryPoints: ['./src/utils/studio-sqlite.ts'],
26+
entryPoints: ['./src/dialects/postgres/introspect.ts'],
1727
outDir: './dist',
1828
external: [],
1929
splitting: false,

Diff for: drizzle-kit/src/api-v2.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { randomUUID } from 'crypto';
22
import type { CasingType } from './cli/validations/common';
33
import { originUUID } from './global';
4-
import { prepareFromExports } from './serializer/pgImports';
4+
import { prepareFromExports } from './dialects/postgres/pgImports';
55
import type { PgSchema as PgSchemaKit } from './dialects/postgres/ddl';
66
import { generatePgSnapshot } from './dialects/postgres/drizzle';
77
import type { SchemaError, SchemaWarning } from './utils';

Diff for: drizzle-kit/src/api.ts

+9-9
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ import {
1717
tablesResolver,
1818
uniqueResolver,
1919
viewsResolver,
20-
} from './cli/commands/migrate';
21-
import { pgPushIntrospect } from './cli/commands/pgIntrospect';
20+
} from './cli/commands/generate-common';
21+
import { pgPushIntrospect } from './cli/commands/pull-postgres';
2222
import { pgSuggestions } from './cli/commands/pgPushUtils';
23-
import { updateUpToV6 as upPgV6, updateUpToV7 as upPgV7 } from './cli/commands/pgUp';
24-
import { sqlitePushIntrospect } from './cli/commands/sqliteIntrospect';
23+
import { updateUpToV6 as upPgV6, updateUpToV7 as upPgV7 } from './cli/commands/up-postgres';
24+
import { sqlitePushIntrospect } from './cli/commands/pull-sqlite';
2525
import { logSuggestionsAndReturn } from './cli/commands/sqlitePushUtils';
2626
import type { CasingType } from './cli/validations/common';
2727
import { schemaError, schemaWarning } from './cli/views';
@@ -31,7 +31,7 @@ import type { Config } from './index';
3131
import { fillPgSnapshot } from './migrationPreparator';
3232
import { MySqlSchema as MySQLSchemaKit, mysqlSchema, squashMysqlScheme } from './serializer/mysqlSchema';
3333
import { generateMySqlSnapshot } from './serializer/mysqlSerializer';
34-
import { prepareFromExports } from './serializer/pgImports';
34+
import { prepareFromExports } from './dialects/postgres/pgImports';
3535
import {
3636
PgSchema as PgSchemaKit,
3737
pgSchema,
@@ -101,7 +101,7 @@ export const generateMigration = async (
101101
prev: DrizzleSnapshotJSON,
102102
cur: DrizzleSnapshotJSON,
103103
) => {
104-
const { applyPgSnapshotsDiff } = await import('./dialects/postgres/diff');
104+
const { ddlDif: applyPgSnapshotsDiff } = await import('./dialects/postgres/diff');
105105

106106
const validatedPrev = pgSchema.parse(prev);
107107
const validatedCur = pgSchema.parse(cur);
@@ -140,7 +140,7 @@ export const pushSchema = async (
140140
tablesFilter?: string[],
141141
extensionsFilters?: Config['extensionsFilters'],
142142
) => {
143-
const { applyPgSnapshotsDiff } = await import('./dialects/postgres/diff');
143+
const { ddlDif: applyPgSnapshotsDiff } = await import('./dialects/postgres/diff');
144144
const { sql } = await import('drizzle-orm');
145145
const filters = (tablesFilter ?? []).concat(
146146
getTablesFilterByExtensions({ extensionsFilters, dialect: 'postgresql' }),
@@ -366,7 +366,7 @@ export const pushMySQLSchema = async (
366366
'./cli/commands/mysqlPushUtils'
367367
);
368368
const { mysqlPushIntrospect } = await import(
369-
'./cli/commands/mysqlIntrospect'
369+
'./cli/commands/pull-mysql'
370370
);
371371
const { sql } = await import('drizzle-orm');
372372

@@ -473,7 +473,7 @@ export const pushSingleStoreSchema = async (
473473
'./cli/commands/singlestorePushUtils'
474474
);
475475
const { singlestorePushIntrospect } = await import(
476-
'./cli/commands/singlestoreIntrospect'
476+
'./cli/commands/pull-singlestore'
477477
);
478478
const { sql } = await import('drizzle-orm');
479479

Diff for: drizzle-kit/src/cli/commands/drop.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { render } from 'hanji';
55
import { join } from 'path';
66
import { Journal } from '../../utils';
77
import { DropMigrationView } from '../views';
8-
import { embeddedMigrations } from './migrate';
8+
import { embeddedMigrations } from './generate-common';
99

1010
export const dropMigration = async ({
1111
out,

Diff for: drizzle-kit/src/cli/commands/generate-common.ts

+164
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import chalk from 'chalk';
2+
import fs from 'fs';
3+
import { render } from 'hanji';
4+
import path, { join } from 'path';
5+
import { PostgresSnapshot } from 'src/dialects/postgres/snapshot';
6+
import type { SqliteSnapshot } from '../../dialects/sqlite/snapshot';
7+
import { BREAKPOINT } from '../../global';
8+
import { Journal } from '../../utils';
9+
import { prepareMigrationMetadata } from '../../utils/words';
10+
import { Driver, Prefix } from '../validations/common';
11+
12+
export const writeResult = ({
13+
cur,
14+
sqlStatements,
15+
journal,
16+
_meta = {
17+
columns: {},
18+
schemas: {},
19+
tables: {},
20+
},
21+
outFolder,
22+
breakpoints,
23+
name,
24+
bundle = false,
25+
type = 'none',
26+
prefixMode,
27+
driver,
28+
}: {
29+
cur: SqliteSnapshot | PostgresSnapshot;
30+
sqlStatements: string[];
31+
journal: Journal;
32+
_meta: {
33+
columns: {};
34+
schemas: {};
35+
tables: {};
36+
} | {
37+
columns: {};
38+
tables: {};
39+
} | null;
40+
outFolder: string;
41+
breakpoints: boolean;
42+
prefixMode: Prefix;
43+
name?: string;
44+
bundle?: boolean;
45+
type?: 'introspect' | 'custom' | 'none';
46+
driver?: Driver;
47+
}) => {
48+
if (type === 'none') {
49+
// TODO: handle
50+
// console.log(schema(cur));
51+
52+
if (sqlStatements.length === 0) {
53+
console.log('No schema changes, nothing to migrate 😴');
54+
return;
55+
}
56+
}
57+
58+
// append entry to _migrations.json
59+
// append entry to _journal.json->entries
60+
// dialect in _journal.json
61+
// append sql file to out folder
62+
// append snapshot file to meta folder
63+
const lastEntryInJournal = journal.entries[journal.entries.length - 1];
64+
const idx = typeof lastEntryInJournal === 'undefined' ? 0 : lastEntryInJournal.idx + 1;
65+
66+
const { prefix, tag } = prepareMigrationMetadata(idx, prefixMode, name);
67+
68+
const snToSave = { ...cur, meta: _meta };
69+
const toSave = JSON.parse(JSON.stringify(snToSave));
70+
71+
// todo: save results to a new migration folder
72+
const metaFolderPath = join(outFolder, 'meta');
73+
const metaJournal = join(metaFolderPath, '_journal.json');
74+
75+
fs.writeFileSync(
76+
join(metaFolderPath, `${prefix}_snapshot.json`),
77+
JSON.stringify(toSave, null, 2),
78+
);
79+
80+
const sqlDelimiter = breakpoints ? BREAKPOINT : '\n';
81+
let sql = sqlStatements.join(sqlDelimiter);
82+
83+
if (type === 'introspect') {
84+
sql =
85+
`-- Current sql file was generated after introspecting the database\n-- If you want to run this migration please uncomment this code before executing migrations\n/*\n${sql}\n*/`;
86+
}
87+
88+
if (type === 'custom') {
89+
console.log('Prepared empty file for your custom SQL migration!');
90+
sql = '-- Custom SQL migration file, put your code below! --';
91+
}
92+
93+
journal.entries.push({
94+
idx,
95+
version: cur.version,
96+
when: +new Date(),
97+
tag,
98+
breakpoints: breakpoints,
99+
});
100+
101+
fs.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
102+
103+
fs.writeFileSync(`${outFolder}/${tag}.sql`, sql);
104+
105+
// js file with .sql imports for React Native / Expo and Durable Sqlite Objects
106+
if (bundle) {
107+
const js = embeddedMigrations(journal, driver);
108+
fs.writeFileSync(`${outFolder}/migrations.js`, js);
109+
}
110+
111+
render(
112+
`[${
113+
chalk.green(
114+
'✓',
115+
)
116+
}] Your SQL migration file ➜ ${
117+
chalk.bold.underline.blue(
118+
path.join(`${outFolder}/${tag}.sql`),
119+
)
120+
} 🚀`,
121+
);
122+
};
123+
124+
export const embeddedMigrations = (journal: Journal, driver?: Driver) => {
125+
let content = driver === 'expo'
126+
? '// This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo\n\n'
127+
: '';
128+
129+
content += "import journal from './meta/_journal.json';\n";
130+
journal.entries.forEach((entry) => {
131+
content += `import m${entry.idx.toString().padStart(4, '0')} from './${entry.tag}.sql';\n`;
132+
});
133+
134+
content += `
135+
export default {
136+
journal,
137+
migrations: {
138+
${
139+
journal.entries
140+
.map((it) => `m${it.idx.toString().padStart(4, '0')}`)
141+
.join(',\n')
142+
}
143+
}
144+
}
145+
`;
146+
return content;
147+
};
148+
149+
export const prepareSnapshotFolderName = () => {
150+
const now = new Date();
151+
return `${now.getFullYear()}${two(now.getUTCMonth() + 1)}${
152+
two(
153+
now.getUTCDate(),
154+
)
155+
}${two(now.getUTCHours())}${two(now.getUTCMinutes())}${
156+
two(
157+
now.getUTCSeconds(),
158+
)
159+
}`;
160+
};
161+
162+
const two = (input: number): string => {
163+
return input.toString().padStart(2, '0');
164+
};

Diff for: drizzle-kit/src/cli/commands/generate-libsql.ts

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { prepareSqliteMigrationSnapshot } from '../../dialects/sqlite/serializer';
2+
import { applyLibSQLSnapshotsDiff } from '../../snapshot-differ/libsql';
3+
import { assertV1OutFolder, prepareMigrationFolder } from '../../utils-node';
4+
import type { GenerateConfig } from './utils';
5+
6+
export const handle = async (config: GenerateConfig) => {
7+
const outFolder = config.out;
8+
const schemaPath = config.schema;
9+
const casing = config.casing;
10+
11+
try {
12+
assertV1OutFolder(outFolder);
13+
14+
const { snapshots, journal } = prepareMigrationFolder(outFolder, 'sqlite');
15+
const { prev, cur, custom } = await prepareSqliteMigrationSnapshot(
16+
snapshots,
17+
schemaPath,
18+
casing,
19+
);
20+
21+
const validatedPrev = sqliteSchema.parse(prev);
22+
const validatedCur = sqliteSchema.parse(cur);
23+
24+
if (config.custom) {
25+
writeResult({
26+
cur: custom,
27+
sqlStatements: [],
28+
journal,
29+
outFolder,
30+
name: config.name,
31+
breakpoints: config.breakpoints,
32+
bundle: config.bundle,
33+
type: 'custom',
34+
prefixMode: config.prefix,
35+
});
36+
return;
37+
}
38+
39+
const squashedPrev = squashSqliteScheme(validatedPrev, SQLiteGenerateSquasher);
40+
const squashedCur = squashSqliteScheme(validatedCur, SQLiteGenerateSquasher);
41+
42+
const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
43+
squashedPrev,
44+
squashedCur,
45+
tablesResolver,
46+
columnsResolver,
47+
sqliteViewsResolver,
48+
validatedPrev,
49+
validatedCur,
50+
);
51+
52+
writeResult({
53+
cur,
54+
sqlStatements,
55+
journal,
56+
_meta,
57+
outFolder,
58+
name: config.name,
59+
breakpoints: config.breakpoints,
60+
bundle: config.bundle,
61+
prefixMode: config.prefix,
62+
});
63+
} catch (e) {
64+
console.error(e);
65+
}
66+
};

0 commit comments

Comments
 (0)