Skip to content

Commit 8b2aefe

Browse files
authored
Merge pull request #1552 from cipherstash/claude/project-thread-1t65aj
fix(cli): follow drizzle-kit's reported path for drop migrations
2 parents 9de3535 + 398af26 commit 8b2aefe

10 files changed

Lines changed: 375 additions & 97 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'stash': patch
3+
---
4+
5+
`stash encrypt drop` and `stash decrypt drop` now write the Drizzle migration to the directory drizzle-kit reports (the `out` in `drizzle.config.ts`) instead of scanning `--migrations-dir`. Previously, when the two differed, the SQL could be written over an older migration with the same name while drizzle-kit journaled an empty stub in the real `out`, so the DROP never shipped. When a scan fallback is needed it matches the exact `_<name>.sql` suffix and refuses to overwrite any file that is not a drizzle-kit scaffold (blank or comment-only), and `--migrations-dir` now warns when drizzle-kit wrote elsewhere.

‎languages/typescript/packages/cli/src/cli/registry.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,8 @@ export const registry: CommandGroup[] = [
634634
{
635635
name: '--migrations-dir',
636636
value: '<path>',
637-
description: 'Directory to write the drop migration into.',
637+
description:
638+
'Directory to write the drop migration into (Drizzle projects: drizzle.config.ts `out` wins; this is the fallback).',
638639
},
639640
],
640641
},
@@ -773,7 +774,8 @@ export const registry: CommandGroup[] = [
773774
{
774775
name: '--migrations-dir',
775776
value: '<path>',
776-
description: 'Directory to write the drop migration into.',
777+
description:
778+
'Directory to write the drop migration into (Drizzle projects: drizzle.config.ts `out` wins; this is the fallback).',
777779
},
778780
{
779781
name: '--uninstall-eql',

‎languages/typescript/packages/cli/src/commands/db/__tests__/find-generated-migration.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
22
import { tmpdir } from 'node:os'
33
import { join } from 'node:path'
44
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5-
import { findGeneratedMigration } from '../../eql/migration.js'
5+
import { findGeneratedMigration } from '../drizzle-migration.js'
66

77
/**
88
* `findGeneratedMigration` locates the custom migration scaffolded by
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { existsSync } from 'node:fs'
2+
import { readdir } from 'node:fs/promises'
3+
import { isAbsolute, join, resolve } from 'node:path'
4+
5+
/**
6+
* Helpers for locating the file `drizzle-kit generate --custom` just wrote.
7+
* Shared by `eql migration --drizzle` and the `encrypt drop` / `decrypt`
8+
* scaffolds, so both agree on where drizzle-kit's `drizzle.config.ts` sent it.
9+
*/
10+
11+
/**
12+
* Find the most recently generated Drizzle migration matching the name.
13+
*
14+
* Matches the exact `_<name>.sql` suffix, so a longer name that merely contains
15+
* the stem (`drop_users_email_backup`) is never mistaken for it.
16+
*/
17+
export async function findGeneratedMigration(
18+
outDir: string,
19+
migrationName: string,
20+
): Promise<string> {
21+
if (!existsSync(outDir)) {
22+
throw new Error(
23+
`Drizzle output directory not found: ${outDir}\nMake sure drizzle-kit is configured correctly.`,
24+
)
25+
}
26+
const migrationSuffix = `_${migrationName}.sql`
27+
const matchingFiles = (await readdir(outDir))
28+
.filter((entry) => entry.endsWith(migrationSuffix))
29+
.sort()
30+
if (matchingFiles.length === 0) {
31+
throw new Error(
32+
`Could not find a migration matching "${migrationName}" in ${outDir}`,
33+
)
34+
}
35+
return join(outDir, matchingFiles[matchingFiles.length - 1])
36+
}
37+
38+
// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ESC is the point
39+
const ANSI_ESCAPE = /\u001b\[[0-9;]*[A-Za-z]/g
40+
41+
function stripAnsi(text: string): string {
42+
return text.replace(ANSI_ESCAPE, '')
43+
}
44+
45+
/**
46+
* Pull the migration path out of drizzle-kit's own success line:
47+
*
48+
* [✓] Your SQL migration file ➜ drizzle/0000_install-eql.sql 🚀
49+
*
50+
* Since we no longer pass `--out` (drizzle-kit rejects the run when we do —
51+
* see `generateDrizzleEqlMigration`), `drizzle.config.ts` owns the output
52+
* directory and this line is how we learn it. The path is printed relative to
53+
* the cwd drizzle-kit ran in, which is ours.
54+
*
55+
* Returns `undefined` unless the file is actually there, so an unrecognised
56+
* banner or a moved file falls through to the directory scan rather than
57+
* pointing the SQL write at a path that does not exist.
58+
*/
59+
export function parseReportedMigrationPath(
60+
stdout: string | undefined,
61+
): string | undefined {
62+
if (!stdout) return undefined
63+
// Scanned per line, taking everything between the arrow and the LAST `.sql`
64+
// on it, because an output directory may contain spaces — a `\S+` pattern
65+
// truncates such a path, fails the existence check, and drops us into the
66+
// fallback scan of an unrelated directory.
67+
//
68+
// Last line wins: one invocation writes one file, but a wrapper that echoes
69+
// its own banner first should not shadow drizzle-kit's.
70+
let found: string | undefined
71+
for (const line of stdout.split(/\r?\n/)) {
72+
const arrow = line.indexOf('➜')
73+
if (arrow === -1) continue
74+
// drizzle-kit colours its banner on a TTY-like stdout; escape codes inside
75+
// the path would fail the existence check and drop us into the fallback.
76+
const rest = stripAnsi(line.slice(arrow + 1))
77+
const end = rest.lastIndexOf('.sql')
78+
if (end === -1) continue
79+
const candidate = rest.slice(0, end + '.sql'.length).trim()
80+
if (!candidate) continue
81+
const abs = isAbsolute(candidate) ? candidate : resolve(candidate)
82+
if (existsSync(abs)) found = abs
83+
}
84+
return found
85+
}
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import {
2+
existsSync,
3+
mkdirSync,
4+
mkdtempSync,
5+
readFileSync,
6+
realpathSync,
7+
rmSync,
8+
writeFileSync,
9+
} from 'node:fs'
10+
import { tmpdir } from 'node:os'
11+
import { join } from 'node:path'
12+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
13+
14+
const spawnSyncMock = vi.hoisted(() => vi.fn())
15+
vi.mock('node:child_process', () => ({ spawnSync: spawnSyncMock }))
16+
vi.mock('@/commands/init/utils.js', () => ({
17+
detectPackageManager: () => 'npm',
18+
runnerArgv: () => ({ command: 'npx', prefixArgs: [] }),
19+
}))
20+
21+
import { scaffoldDrizzleMigration } from '../drizzle-helper.js'
22+
23+
/**
24+
* drizzle.config.ts's `out` owns where drizzle-kit writes. The scaffold must
25+
* follow the path drizzle-kit reports, never the --migrations-dir it scans as
26+
* a fallback (CIP-5162).
27+
*/
28+
// What drizzle-kit's `generate --custom` actually writes.
29+
const PLACEHOLDER = '-- Custom SQL migration file, put your code below! --\n'
30+
31+
describe('scaffoldDrizzleMigration', () => {
32+
let root: string
33+
let cwd: string
34+
beforeEach(() => {
35+
// realpath: process.cwd() reports the physical path after chdir, so a
36+
// symlinked TMPDIR would otherwise break the expected-path assertions.
37+
root = realpathSync(mkdtempSync(join(tmpdir(), 'stash-scaffold-')))
38+
cwd = process.cwd()
39+
process.chdir(root)
40+
spawnSyncMock.mockReset()
41+
})
42+
afterEach(() => {
43+
process.chdir(cwd)
44+
rmSync(root, { recursive: true, force: true })
45+
})
46+
47+
function drizzleKitWrites(relPath: string) {
48+
spawnSyncMock.mockImplementation(() => {
49+
mkdirSync(join(relPath, '..'), { recursive: true })
50+
writeFileSync(relPath, PLACEHOLDER)
51+
return {
52+
status: 0,
53+
stdout: `[✓] Your SQL migration file ➜ ${relPath} 🚀\n`,
54+
stderr: '',
55+
}
56+
})
57+
}
58+
59+
it('writes to the directory drizzle-kit reports, not the scanned one', async () => {
60+
mkdirSync('drizzle')
61+
writeFileSync(
62+
'drizzle/0000_drop_users_email.sql',
63+
'ALTER TABLE t DROP COLUMN c;',
64+
)
65+
drizzleKitWrites('src/db/migrations/0003_drop_users_email.sql')
66+
67+
const result = await scaffoldDrizzleMigration({
68+
name: 'drop_users_email',
69+
outDir: 'drizzle',
70+
sql: 'ALTER TABLE users DROP COLUMN email;',
71+
})
72+
73+
expect(result.path).toBe(
74+
join(root, 'src/db/migrations/0003_drop_users_email.sql'),
75+
)
76+
expect(readFileSync(result.path, 'utf-8')).toContain('DROP COLUMN email')
77+
expect(readFileSync('drizzle/0000_drop_users_email.sql', 'utf-8')).toBe(
78+
'ALTER TABLE t DROP COLUMN c;',
79+
)
80+
expect(result.dir).not.toBe(result.requestedDir)
81+
})
82+
83+
it('does not require the fallback directory to exist when the path is reported', async () => {
84+
drizzleKitWrites('db/0000_drop_a.sql')
85+
const result = await scaffoldDrizzleMigration({
86+
name: 'drop_a',
87+
outDir: 'drizzle',
88+
sql: 'SELECT 1;',
89+
})
90+
expect(existsSync(result.path)).toBe(true)
91+
})
92+
93+
it('falls back to the scan when the banner is unrecognised, taking only a new exact-suffix file', async () => {
94+
mkdirSync('drizzle')
95+
writeFileSync('drizzle/0000_drop_a.sql', 'ALTER TABLE t DROP COLUMN c;')
96+
spawnSyncMock.mockImplementation(() => {
97+
writeFileSync('drizzle/0001_drop_a.sql', PLACEHOLDER)
98+
writeFileSync('drizzle/0002_drop_a_backup.sql', '')
99+
return { status: 0, stdout: 'done', stderr: '' }
100+
})
101+
const result = await scaffoldDrizzleMigration({
102+
name: 'drop_a',
103+
outDir: 'drizzle',
104+
sql: 'SELECT 1;',
105+
})
106+
expect(result.path).toBe(join(root, 'drizzle/0001_drop_a.sql'))
107+
expect(readFileSync('drizzle/0000_drop_a.sql', 'utf-8')).toBe(
108+
'ALTER TABLE t DROP COLUMN c;',
109+
)
110+
})
111+
112+
it('refuses to overwrite a pre-existing same-stem file when nothing new appeared', async () => {
113+
mkdirSync('drizzle')
114+
writeFileSync('drizzle/0000_drop_a.sql', 'ALTER TABLE t DROP COLUMN c;')
115+
spawnSyncMock.mockReturnValue({ status: 0, stdout: 'done', stderr: '' })
116+
await expect(
117+
scaffoldDrizzleMigration({
118+
name: 'drop_a',
119+
outDir: 'drizzle',
120+
sql: 'SELECT 1;',
121+
}),
122+
).rejects.toThrow(/Refusing to overwrite/)
123+
expect(readFileSync('drizzle/0000_drop_a.sql', 'utf-8')).toBe(
124+
'ALTER TABLE t DROP COLUMN c;',
125+
)
126+
})
127+
128+
it('follows a reported path even when the banner is colourised', async () => {
129+
mkdirSync('db')
130+
spawnSyncMock.mockImplementation(() => {
131+
writeFileSync('db/0000_drop_a.sql', PLACEHOLDER)
132+
return {
133+
status: 0,
134+
stdout:
135+
'[✓] Your SQL migration file \u001b[2m➜\u001b[0m \u001b[1mdb/0000_drop_a.sql\u001b[0m 🚀',
136+
stderr: '',
137+
}
138+
})
139+
const result = await scaffoldDrizzleMigration({
140+
name: 'drop_a',
141+
outDir: 'drizzle',
142+
sql: 'SELECT 1;',
143+
})
144+
expect(result.path).toBe(join(root, 'db/0000_drop_a.sql'))
145+
})
146+
147+
it('refuses to overwrite a reported file that already has content', async () => {
148+
mkdirSync('db')
149+
writeFileSync('db/0000_old.sql', 'ALTER TABLE t DROP COLUMN c;')
150+
spawnSyncMock.mockReturnValue({
151+
status: 0,
152+
stdout: '➜ db/0000_old.sql',
153+
stderr: '',
154+
})
155+
await expect(
156+
scaffoldDrizzleMigration({
157+
name: 'x',
158+
outDir: 'drizzle',
159+
sql: 'SELECT 1;',
160+
}),
161+
).rejects.toThrow(/not a drizzle-kit scaffold/)
162+
expect(readFileSync('db/0000_old.sql', 'utf-8')).toBe(
163+
'ALTER TABLE t DROP COLUMN c;',
164+
)
165+
})
166+
167+
it('surfaces drizzle-kit stdout and stderr on failure', async () => {
168+
spawnSyncMock.mockReturnValue({
169+
status: 1,
170+
stdout: 'config error',
171+
stderr: 'boom',
172+
})
173+
await expect(
174+
scaffoldDrizzleMigration({ name: 'x', outDir: 'drizzle', sql: '' }),
175+
).rejects.toThrow(/config error\nboom/)
176+
})
177+
})

0 commit comments

Comments
 (0)