drizzle-team / drizzle-team/drizzle-orm
[BUG]: `drizzle-kit generate` creates invalid migration for primary key addition in SQLite
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Report hasn't been filed before.
- [x] I have verified that the bug I'm about to report hasn't been filed before.
### What version of `drizzle-orm` are you using?
0.38.3
### What version of `drizzle-kit` are you using?
0.30.1
### Other packages
_No response_
### Describe the Bug
> What is the undesired behavior?
`drizzle-kit generate` creates an invalid SQL script that leads to an error during `drizzle-kit migrate`:
```
code: 'SQL_INPUT_ERROR',
rawCode: undefined,
[cause]: [ResponseError: SQL input error: no such column: id (at offset 128)] {
code: 'SQL_INPUT_ERROR',
proto: {
message: 'SQL input error: no such column: id (at offset 128)',
code: 'SQL_INPUT_ERROR'
}
}
```
> What are the steps to reproduce it?
First, you need to create a simple table, generate migration script, and migrate it:
1. In `testTable.ts`:
```
import { sqliteTable } from "drizzle-orm/sqlite-core";
export const testTable = sqliteTable("test_table", (t) => ({
name: t.text(),
}));
```
2. In `0001_test_table-creation.sql`:
```
CREATE TABLE `test_table` (
`name` text
);
```
3. Migrate this changes.
Then, you have to modify your table - add a primary key:
1. In `testTable.ts`:
```
import { sqliteTable } from "drizzle-orm/sqlite-core";
export const testTable = sqliteTable("test_table", (t) => ({
id: t.integer().primaryKey(),
name: t.text(),
}));
```
2. In `0002_test_table-add-primary-key.sql`:
```
PRAGMA foreign_keys=OFF;--> statement-breakpoint
CREATE TABLE `__new_test_table` (
`id` integer PRIMARY KEY NOT NULL,
`name` text
);
--> statement-breakpoint
INSERT INTO `__new_test_table`("id", "name") SELECT "id", "name" FROM `test_table`;--> statement-breakpoint
DROP TABLE `test_table`;--> statement-breakpoint
ALTER TABLE `__new_test_table` RENAME TO `test_table`;--> statement-breakpoint
PRAGMA foreign_keys=ON;
```
**NOTE: At the line "INSERT INTO `__new_test_table`("id", "name") SELECT "id", "name" FROM `test_table`;" we're trying to access the `id` column, but it doesn't exist yet.**
3. Migrate this changes (getting an error on this step).
> What is the desired result?
Don't use the `id` column during insertion from old table.
> What database engine are you using? Are you using a specific cloud provider? Which one?
I'm using the `turso` as a cloud provider. And there was another very weird bug, I suppose which is not related to this issue: I've successfully migrated (invalid!) script to the remote `libsql` database. However, applying this changes to the local turso server (launched with `turso dev` cmd) threw described above error.
Contributor guide
Assessment
This issue has not been assessed yet.