Skip to content

Commit 84871b1

Browse files
committed
+
1 parent c747029 commit 84871b1

File tree

10 files changed

+43
-90
lines changed

10 files changed

+43
-90
lines changed

drizzle-kit/src/cli/commands/generate-mysql.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { prepareFilenames, prepareOutFolder } from 'src/utils/utils-node';
44
import { type Column, createDDL, interimToDDL, type Table, type View } from '../../dialects/mysql/ddl';
55
import { ddlDiff, ddlDiffDry } from '../../dialects/mysql/diff';
66
import { resolver } from '../prompts';
7-
import { withStyle } from '../validations/outputs';
8-
import { mysqlExplain } from '../views';
7+
import { explain } from '../views';
98
import { writeResult } from './generate-common';
109
import type { ExportConfig, GenerateConfig } from './utils';
1110

@@ -41,13 +40,8 @@ export const handle = async (config: GenerateConfig) => {
4140
'default',
4241
);
4342

44-
const messages: string[] = [`\n\nThe following migration was generated:\n`];
45-
for (const { jsonStatement, sqlStatements: sql } of groupedStatements) {
46-
const msg = mysqlExplain(jsonStatement, sql);
47-
if (msg) messages.push(msg);
48-
else messages.push(...sql);
49-
}
50-
console.log(withStyle.info(messages.join('\n')));
43+
const explainMessage = explain('mysql', groupedStatements, false, []);
44+
if (explainMessage) console.log(explainMessage);
5145

5246
writeResult({
5347
snapshot,

drizzle-kit/src/cli/commands/generate-postgres.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@ import { createDDL, interimToDDL } from '../../dialects/postgres/ddl';
2020
import { ddlDiff, ddlDiffDry } from '../../dialects/postgres/diff';
2121
import { prepareSnapshot } from '../../dialects/postgres/serializer';
2222
import { resolver } from '../prompts';
23-
import { withStyle } from '../validations/outputs';
24-
import { psqlExplain } from '../views';
23+
import { explain } from '../views';
2524
import { writeResult } from './generate-common';
2625
import type { ExportConfig, GenerateConfig } from './utils';
2726

@@ -66,13 +65,8 @@ export const handle = async (config: GenerateConfig) => {
6665
'default',
6766
);
6867

69-
const messages: string[] = [`\n\nThe following migration was generated:\n`];
70-
for (const { jsonStatement, sqlStatements: sql } of groupedStatements) {
71-
const msg = psqlExplain(jsonStatement, sql);
72-
if (msg) messages.push(msg);
73-
else messages.push(...sql);
74-
}
75-
console.log(withStyle.info(messages.join('\n')));
68+
const explainMessage = explain('mysql', groupedStatements, false, []);
69+
if (explainMessage) console.log(explainMessage);
7670

7771
writeResult({
7872
snapshot: snapshot,

drizzle-kit/src/cli/commands/push-mysql.ts

Lines changed: 14 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ import type { JsonStatement } from '../../dialects/mysql/statements';
99
import type { DB } from '../../utils';
1010
import { prepareFilenames } from '../../utils/utils-node';
1111
import { connectToMySQL } from '../connections';
12+
import { highlightSQL } from '../highlighter';
1213
import { resolver } from '../prompts';
1314
import { Select } from '../selector-ui';
1415
import type { EntitiesFilterConfig } from '../validations/cli';
1516
import type { CasingType } from '../validations/common';
1617
import type { MysqlCredentials } from '../validations/mysql';
17-
import { withStyle } from '../validations/outputs';
18-
import { mysqlExplain, ProgressView } from '../views';
18+
import { explain, ProgressView } from '../views';
1919
import { introspect } from './pull-mysql';
2020

2121
export const handle = async (
@@ -25,7 +25,7 @@ export const handle = async (
2525
force: boolean,
2626
casing: CasingType | undefined,
2727
filters: EntitiesFilterConfig,
28-
explain: boolean,
28+
explainFlag: boolean,
2929
) => {
3030
const { prepareFromSchemaFiles, fromDrizzleSchema } = await import('../../dialects/mysql/drizzle');
3131

@@ -64,62 +64,27 @@ export const handle = async (
6464
render(`[${chalk.blue('i')}] No changes detected`);
6565
}
6666

67-
if (explain) {
68-
const messages: string[] = [`\n\nThe following migration was generated:\n`];
69-
for (const { jsonStatement, sqlStatements: sql } of groupedStatements) {
70-
const msg = mysqlExplain(jsonStatement, sql);
71-
if (msg) messages.push(msg);
72-
// Logic below should show all statements depending on flags like 'verbose' etc.
73-
// else messages.push(...sql);
74-
}
75-
console.log(withStyle.info(messages.join('\n')));
76-
process.exit(0);
77-
}
67+
const hints = await suggestions(db, filteredStatements);
68+
const explainMessage = explain('mysql', groupedStatements, explainFlag, hints);
7869

79-
const { hints, truncates } = await suggestions(db, filteredStatements);
80-
81-
const combinedStatements = [...truncates, ...sqlStatements];
82-
if (verbose) {
83-
console.log();
84-
console.log(
85-
withStyle.warning('You are about to execute current statements:'),
86-
);
87-
console.log();
88-
console.log(combinedStatements.map((s) => chalk.blue(s)).join('\n'));
89-
console.log();
90-
}
70+
if (explainMessage) console.log(explainMessage);
71+
if (explainFlag) return;
9172

9273
if (!force && hints.length > 0) {
93-
const { data } = await render(
94-
new Select(['No, abort', `Yes, I want to execute all statements`]),
95-
);
74+
const { data } = await render(new Select(['No, abort', 'Yes, I want to execute all statements']));
75+
9676
if (data?.index === 0) {
9777
render(`[${chalk.red('x')}] All changes were aborted`);
9878
process.exit(0);
9979
}
10080
}
10181

102-
if (!force && hints.length > 0) {
103-
console.log(withStyle.warning('Found data-loss statements:'));
104-
console.log(truncates.join('\n'));
105-
console.log();
106-
console.log(
107-
chalk.red.bold(
108-
'THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n',
109-
),
110-
);
82+
const lossStatements = hints.map((x) => x.statement).filter((x) => typeof x !== 'undefined');
11183

112-
console.log(chalk.white('Do you still want to push changes?'));
84+
for (const statement of [...lossStatements, ...sqlStatements]) {
85+
if (verbose) console.log(highlightSQL(statement));
11386

114-
const { data } = await render(new Select(['No, abort', `Yes, execute`]));
115-
if (data?.index === 0) {
116-
render(`[${chalk.red('x')}] All changes were aborted`);
117-
process.exit(0);
118-
}
119-
}
120-
121-
for (const st of combinedStatements) {
122-
await db.query(st);
87+
await db.query(statement);
12388
}
12489

12590
if (filteredStatements.length > 0) {
@@ -228,10 +193,7 @@ export const handle = async (
228193
// };
229194

230195
export const suggestions = async (_db: DB, _statements: JsonStatement[]) => {
231-
const hints: string[] = [];
232-
const truncates: string[] = [];
233-
234-
return { hints, truncates };
196+
return [] as { hint: string; statement?: string | undefined }[];
235197

236198
// TODO: update and implement
237199

drizzle-kit/src/cli/views.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ function formatOptionChanges(
100100

101101
export const explain = (
102102
dialect: 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'mssql' | 'common' | 'gel' | 'cockroach',
103-
grouped: { jsonStatement: StatementPostgres | StatementSqlite; sqlStatements: string[] }[],
103+
grouped: { jsonStatement: StatementPostgres | StatementSqlite | StatementMysql; sqlStatements: string[] }[],
104104
explain: boolean,
105105
hints: { hint: string; statement?: string }[],
106106
) => {
@@ -111,6 +111,8 @@ export const explain = (
111111
? psqlExplain(jsonStatement as StatementPostgres)
112112
: dialect === 'sqlite'
113113
? sqliteExplain(jsonStatement as StatementSqlite)
114+
: dialect === 'mysql'
115+
? mysqlExplain(jsonStatement as StatementMysql)
114116
: null;
115117

116118
if (res) {

drizzle-kit/tests/mysql/mocks.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ export const push = async (config: {
191191
'push',
192192
);
193193

194-
const { hints, truncates } = await suggestions(db, statements);
194+
const res = await suggestions(db, statements);
195195

196196
for (const sql of sqlStatements) {
197197
if (log === 'statements') console.log(sql);
@@ -223,7 +223,7 @@ export const push = async (config: {
223223
}
224224
}
225225

226-
return { sqlStatements, statements, hints, truncates };
226+
return { sqlStatements, statements, hints: res };
227227
};
228228

229229
export const diffDefault = async <T extends MySqlColumnBuilder>(

drizzle-kit/tests/postgres/mocks.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
5050
import pg from 'pg';
5151
import { introspect } from 'src/cli/commands/pull-postgres';
5252
import { suggestions } from 'src/cli/commands/push-postgres';
53-
import { EmptyProgressView, psqlExplain } from 'src/cli/views';
53+
import { EmptyProgressView, explain, psqlExplain } from 'src/cli/views';
5454
import { hash } from 'src/dialects/common';
5555
import { defaultToSQL, isSystemNamespace, isSystemRole } from 'src/dialects/postgres/grammar';
5656
import { fromDatabaseForDrizzle } from 'src/dialects/postgres/introspect';
@@ -257,8 +257,8 @@ export const push = async (config: {
257257
const hints = await suggestions(db, statements);
258258

259259
if (config.explain) {
260-
const text = groupedStatements.map((x) => psqlExplain(x.jsonStatement, x.sqlStatements)).filter(Boolean).join('\n');
261-
console.log(text);
260+
const explainMessage = explain('postgres', groupedStatements, false, []);
261+
if (explainMessage) console.log(explainMessage);
262262
return { sqlStatements, statements, hints };
263263
}
264264

drizzle-kit/tests/singlestore/mocks.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import getPort from 'get-port';
66
import { Connection, createConnection } from 'mysql2/promise';
77
import { suggestions } from 'src/cli/commands/push-mysql';
88
import { CasingType } from 'src/cli/validations/common';
9+
import { explain } from 'src/cli/views';
910
import { createDDL, interimToDDL } from 'src/dialects/mysql/ddl';
1011
import { ddlDiff, ddlDiffDry } from 'src/dialects/mysql/diff';
1112
import { fromDatabaseForDrizzle } from 'src/dialects/mysql/introspect';
@@ -130,7 +131,7 @@ export const diffPush = async (config: {
130131
// TODO: handle errors
131132

132133
const renames = new Set(rens);
133-
const { sqlStatements, statements } = await ddlDiff(
134+
const { sqlStatements, statements, groupedStatements } = await ddlDiff(
134135
ddl1,
135136
ddl2,
136137
mockResolver(renames),
@@ -139,8 +140,10 @@ export const diffPush = async (config: {
139140
'push',
140141
);
141142

142-
const { hints, truncates } = await suggestions(db, statements);
143-
return { sqlStatements, statements, hints, truncates };
143+
const explainMessage = explain('singlestore', groupedStatements, false, []);
144+
if (explainMessage) console.log(explainMessage);
145+
146+
return { sqlStatements, statements, hints: [] };
144147
};
145148

146149
async function createDockerDB(): Promise<{ url: string; container: Container }> {

drizzle-kit/tests/sqlite/mocks.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,11 +153,12 @@ export const push = async (config: {
153153
'push',
154154
);
155155

156-
const { hints, statements: losses } = await suggestions(db, statements);
156+
const hints = await suggestions(db, statements);
157157

158158
if (force) {
159-
for (const st of losses) {
160-
await db.run(st);
159+
for (const st of hints) {
160+
if (!st.statement) continue;
161+
await db.run(st.statement);
161162
}
162163
}
163164

@@ -191,7 +192,7 @@ export const push = async (config: {
191192
}
192193
}
193194

194-
return { sqlStatements, statements, hints, losses, error, next: ddl2 };
195+
return { sqlStatements, statements, hints, error, next: ddl2 };
195196
};
196197

197198
export const diffDefault = async <T extends SQLiteColumnBuilder>(

drizzle-kit/tests/sqlite/sqlite-columns.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ test('added column not null and without default to table with data', async (t) =
235235
await db.run(`INSERT INTO \`companies\` ("name") VALUES ('turso');`);
236236

237237
// TODO: reivise
238-
const { sqlStatements: pst, hints: phints, error, losses } = await push({
238+
const { sqlStatements: pst, hints: phints, error } = await push({
239239
db,
240240
to: schema2,
241241
expectError: true,
@@ -250,7 +250,7 @@ test('added column not null and without default to table with data', async (t) =
250250
"· You're about to add not-null 'age' column without default value to non-empty 'companies' table",
251251
]);
252252
expect(error).toBeNull();
253-
expect(losses).toStrictEqual(['DELETE FROM "companies" where true;']);
253+
expect(phints[0].statement).toStrictEqual('DELETE FROM "companies" where true;');
254254

255255
// TODO: check truncations
256256
});

drizzle-kit/tests/sqlite/sqlite-tables.test.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,7 @@ test('recreate table with added column not null and without default with data',
902902
await db.run(`INSERT INTO \`users\` ("name", "age") VALUES ('drizzle', 12)`);
903903
await db.run(`INSERT INTO \`users\` ("name", "age") VALUES ('turso', 12)`);
904904

905-
const { sqlStatements: pst, hints: phints, losses, error } = await push({
905+
const { sqlStatements: pst, hints: phints, error } = await push({
906906
db,
907907
to: schema2,
908908
expectError: true,
@@ -926,10 +926,7 @@ test('recreate table with added column not null and without default with data',
926926
expect(st).toStrictEqual(st0);
927927
expect(pst).toStrictEqual(st0);
928928

929-
expect(phints).toStrictEqual([
930-
`· You're about to add not-null 'new_column' column without default value to non-empty 'users' table`,
931-
]);
932-
expect(losses).toStrictEqual(['DELETE FROM "users" where true;']);
929+
expect(phints[0].statement).toStrictEqual('DELETE FROM "users" where true;');
933930
expect(error).toBeNull();
934931
});
935932

0 commit comments

Comments
 (0)