[BUG]:push creates duplicate statements for unique column index
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.36.3
What version of drizzle-kit are you using?
0.28.1
Other packages
No response
Describe the Bug
When using drizzle-kit push to update existing table, statements for creating unique index appear twice, leading to SqliteError: index user_email_unique already exists.
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
CREATE UNIQUE INDEX `user_username_unique` ON `user` (`username`);
PRAGMA foreign_keys=ON;
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
CREATE UNIQUE INDEX `user_username_unique` ON `user` (`username`);
Table schema
export const user = sqliteTable('user', {
id: text('id').primaryKey().notNull(),
googleId: text('google_id'),
email: text('email').notNull().unique(),
username: text('username').unique(),
...
});
SQL statement
PRAGMA foreign_keys=OFF;
CREATE TABLE `__new_user` (
`id` text PRIMARY KEY NOT NULL,
`google_id` text,
`email` text NOT NULL,
`username` text,
...
);
INSERT INTO `__new_user`("id", "google_id", "email", "username", ...) SELECT "id", "google_id", "email", "username", ... FROM `user`;
DROP TABLE `user`;
ALTER TABLE `__new_user` RENAME TO `user`;
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
CREATE UNIQUE INDEX `user_username_unique` ON `user` (`username`);
PRAGMA foreign_keys=ON;
CREATE UNIQUE INDEX `user_email_unique` ON `user` (`email`);
CREATE UNIQUE INDEX `user_username_unique` ON `user` (`username`);
i have a very similar problem.
- drizzle orm: 0.36.3
- drizzle kit: 0.28.0
i did the following:
- deleted all the indizes in the db
- deleted .drizzle folder
- ran db:generate
it tries to add another index that doesn't exist in the current database, not in the schema or anywhere else as far as i know.
this is the generated sql file:
CREATE TABLE `setting` (
`id` integer PRIMARY KEY NOT NULL,
`key` text NOT NULL,
`value` text NOT NULL,
`user_id` text NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE UNIQUE INDEX `setting_key_unique` ON `setting` (`key`);--> statement-breakpoint
CREATE UNIQUE INDEX `user_setting_idx` ON `setting` (`user_id`,`key`);--> statement-breakpoint`
this is the schema for setting:
export const setting = sqliteTable(
'setting',
{
id: integer().primaryKey().notNull(),
key: text().notNull().unique(),
value: text().notNull(),
userId: text('user_id')
.notNull()
.references(() => user.id)
},
(table) => ({
userSettingsIndex: uniqueIndex('user_setting_idx').on(table.userId, table.key)
})
);```
setting_key_unique index is created because you set setting.key to be unique.
UNIQUE constraints are implemented by creating a unique index in the database
Thank you so much. But should drizzle-kit recognize that?
jmyt8 @.***> schrieb am Mo. 18. Nov. 2024 um 02:20:
setting_key_unique index is created because you set setting.key to be unique.
UNIQUE constraints are implemented by creating a unique index in the database
— Reply to this email directly, view it on GitHub https://github.com/drizzle-team/drizzle-orm/issues/3574#issuecomment-2481740884, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJGM6JJWVTOASYUE4CAJIFL2BE6ELAVCNFSM6AAAAABR546QOCVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDIOBRG42DAOBYGQ . You are receiving this because you commented.Message ID: @.***>
I am using @libsql/client and I am seeing similar behavior with verbose on:
CREATE UNIQUE INDEX data_sources_uri_unique ON data_sources (uri);
CREATE UNIQUE INDEX data_sources_uri_unique ON data_sources (uri);
On an update scenario (using drizzle-kit push), we've run into the same type of breaking issue. The table in question has no unique indexes (other than primary). The upgrade code effectively doubles the index creation step, which is after a creating a new table, moving data into it, then renaming it.
ALTER TABLE `__new_events` RENAME TO `events`;
CREATE INDEX `events_investment_index` ON `events` (`investmentId`);
CREATE INDEX `events_account_index` ON `events` (`accountId`,`transactionDate`);
CREATE INDEX `events_investment_index` ON `events` (`investmentId`);
CREATE INDEX `events_account_index` ON `events` (`accountId`,`transactionDate`);
PRAGMA foreign_keys=OFF;
This breaks even the simplest upgrade.
Table schema:
export const events = s.sqliteTable("events",
{
id: s.integer().primaryKey(),
investmentId: s.integer().references(() => investments.id),
accountId: s.integer().references(() => accounts.id, {onDelete: 'cascade'}),
transactionDate: s.integer({ mode: 'timestamp' }).notNull(),
planning: s.integer({ mode: 'boolean' }).notNull().default(false),
amount: s.real().notNull(),
type: s.text({enum: ["Issue", "Maturity", "Call"]}).notNull()
},
(t) => [
s.index("events_investment_index").on(t.investmentId),
s.index("events_account_index").on(t.accountId, t.transactionDate)
]
);
Experimenting with the schema, I see if my array of indexes has more than 1 value, then I will see the doubling behavior. Here's another example with 3 indexes. None of the tables that have a single index experience the doubling issue.
DROP TABLE `investments`;
ALTER TABLE `__new_investments` RENAME TO `investments`;
CREATE INDEX `investments_account_index` ON `investments` (`accountId`);
CREATE INDEX `test` ON `investments` (`securityId`);
CREATE INDEX `another_test` ON `investments` (`accountId`,`securityId`);
PRAGMA foreign_keys=ON;
CREATE INDEX `investments_account_index` ON `investments` (`accountId`);
CREATE INDEX `test` ON `investments` (`securityId`);
CREATE INDEX `another_test` ON `investments` (`accountId`,`securityId`);
The difference between the first and second set is the location of the pragma step.
Version info: drizzle-kit: v0.30.5 drizzle-orm: v0.40.0
Running into this too
PRAGMA foreign_keys=OFF;
CREATE TABLE `__new_users` (
`id` text PRIMARY KEY NOT NULL,
`email` text NOT NULL,
`userName` text,
`hashedPassword` text,
`emailVerified` integer DEFAULT FALSE NOT NULL,
`picture` text,
`createdAt` text,
`updatedAt` text,
`deletedAt` text
);
INSERT INTO `__new_users`("id", "email", "userName", "hashedPassword", "emailVerified", "picture", "createdAt", "updatedAt", "deletedAt") SELECT "id", "email", "userName", "hashedPassword", "emailVerified", "picture", "createdAt", "updatedAt", "deletedAt" FROM `users`;
DROP TABLE `users`;
ALTER TABLE `__new_users` RENAME TO `users`;
CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);
PRAGMA foreign_keys=ON;
CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);
ALTER TABLE `email_verification_tokens` ADD `type` text;
Duplicate CREATE UNIQUE INDEX when pushing to db
Also running into the initial issue, is there any suggested fix?
Also running into the initial issue, is there any suggested fix?
Not that I am aware of, I switched to prisma to work with d1
Hey everyone!
I've created this message to send in a batch to all opened issues we have, just because there are a lot of them and I want to update all of you with our current work, why issues are not responded to, and the amount of work that has been done by our team over ~8 months.
I saw a lot of issues with suggestions on how to fix something while we were not responding – so thanks everyone. Also, thanks to everyone patiently waiting for a response from us and continuing to use Drizzle!
We currently have 4 major branches with a lot of work done. Each branch was handled by different devs and teams to make sure we could make all the changes in parallel.
First branch is drizzle-kit rewrite
All of the work can be found on the alternation-engine branch. Here is a PR with the work done: https://github.com/drizzle-team/drizzle-orm/pull/4439
As you can see, it has 167k added lines of code and 67k removed, which means we've completely rewritten the drizzle-kit alternation engine, the way we handle diffs for each dialect, together with expanding our test suite from 600 tests to ~9k test units for all different types of actions you can do with kit. More importantly, we changed the migration folder structure and made commutative migrations, so you won't face complex conflicts on migrations when working in a team.
What's left here:
- We are finishing handling defaults for Postgres, the last being geometry (yes, we fixed the
sridissue here as well). - We are finishing commutative migrations for all dialects.
- We are finishing up the command, so the migration flow will be as simple as
drizzle-kit upfor you.
Where it brings us:
- We are getting drizzle-kit into a new good shape where we can call it
[email protected]!
Timeline:
- We need ~2 weeks to finish all of the above and send this branch to beta for testing.
Second big branch is a complex one with several HUGE updates
- Bringing Relational Queries v2 finally live. We've done a lot of work here to actually make it faster than RQBv1 and much better from a DX point of view. But in implementing it, we had to make another big rewrite, so we completely rewrote the drizzle-orm type system, which made it much simpler and improved type performance by ~21.4x:
(types instantiations for 3300 lines production drizzle schema + 990 lines relations)
TS v5.8.3: 728.8k -> 34.1k
TS v5.9.2: 553.7k -> 25.4k
You can read more about it here.
What's left here:
- We have 1 issue with TS that is already in progress of being fixed. The issue and Post about fixing.
Where it brings us:
- We are getting drizzle-orm into a new good shape where we can call it
[email protected]!
Breaking changes:
- We will have them, but we will have open channels for everyone building on top of drizzle types, so we can guide you through all the changes.
Third branch is adding support for CockroachDB and MSSQL dialects
Support for them is already in the alternation-engine branch and will be available together with the drizzle-kit rewrite.
Summary
All of the work we are doing is crucial and should be done sooner rather than later. We've received a lot of feedback and worked really hard to find the best strategies and decisions for API, DX, architecture, etc., so we can confidently mark it as v1 and be sure we can improve it and remain flexible for all the features you are asking for, while becoming even better for everyone building on top of the drizzle API as well.
We didn't want to stay with some legacy decisions and solutions we had, and instead wanted to shape Drizzle in a way that will be best looking ahead to 2025–2026 trends (v1 will get proper effect support, etc.).
We believe that all of the effort we've put in will boost Drizzle and benefit everyone using it.
Thanks everyone, as we said, we are here to stay for a long time to build a great tool together!
Timelines
We are hoping to get v1 for drizzle in beta this fall and same timeline for latest. Right after that we can go through all of the issues and PRs and resond everyone. v1 for drizzle should close ~70% of all the bug tickets we have, so on beta release we will start marking them as closed!
still valid