Database View is not created with usual drizzle-kit push command for migrations
I am trying to define a database view like this:
export const userSubscriptionView = pgView("user_subscription_view").as(
(qb) => {
return qb
.select({
userId: user.id,
email: user.email,
name: user.name,
subscriptionId: userSubscription.id,
status: userSubscription.status,
})
.from(user)
.leftJoin(
userSubscription,
sql`${user.id} = ${userSubscription.userId} AND (${userSubscription.status} = 'active' OR ${userSubscription.status} = 'trialing')`
)
}
);
Then I created a custom migration with SQL code to create the view like this:
-- Custom SQL migration file
DROP VIEW IF EXISTS user_subscription_view;
CREATE VIEW user_subscription_view AS
SELECT
u.id AS "userId",
u.email AS "email",
u.name AS "name",
us.id AS "subscriptionId",
us.status AS "status",
FROM
"user" u
LEFT JOIN
user_subscription us ON u.id = us.user_id AND (us.status = 'active' OR us.status = 'trialing')
But when running drizzle-kit push the view is not created in the database even though logs say that changes were applied.
However, if I create a script like the following and run it manually, the view is then created. This is not ideal for production development to have to run manual scripts for each view created. So what is the correct way to create views with migrations?
// lib/db/migrate.ts
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { db } from '@/lib/db';
import { sql } from 'drizzle-orm';
export async function runMigrations() {
// First run schema migrations
await migrate(db, { migrationsFolder: './drizzle' });
// Then create views
try {
console.log('Creating views...');
await db.execute(sql`
DROP VIEW IF EXISTS user_subscription_view;
CREATE VIEW user_subscription_view AS
SELECT
u.id AS "userId",
u.email AS "email",
u.name AS "name",
us.id AS "subscriptionId",
us.status AS "status",
FROM
"user" u
LEFT JOIN
user_subscription us ON u.id = us.user_id AND (us.status = 'active' OR us.status = 'trialing')
console.log('Views created successfully');
} catch (error) {
console.error('Error creating views:', error);
}
}
As a separate question, is the view created when you use automatically generated migrations?
Sadly not! The only way to create the view is to run the TS script manually
Hi guys, same issue here but with mysql driver.
Hi, the same story with op-sqlite driver (react-native application). The SQL gets generated correctly and contains commands to create the view, but view does not get created. In my case migrations are being run from code (migrate)
To give you some more information:
- File 0000_snapshot.json does contain information about the view
- Output from the drizzle-kit command looks like following:
PS D:\Dokumenty\Dev\VS\ExpenseManager\ExpenseManagerLite> npx drizzle-kit generate --name Initial
No config path provided, using default 'drizzle.config.ts'
Reading config file 'D:\Dokumenty\Dev\VS\ExpenseManager\ExpenseManagerLite\drizzle.config.ts'
9 tables
Cars 4 columns 1 indexes 1 fks
(...)
Users 3 columns 1 indexes 0 fks
[β] Your SQL migration file β drizzle\0000_Initial.sql π
Note no views mentioned.
Contents of __drizzle_migrations:
id | hash | created_at
-----------------------
NULL | | 1750248907487
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!
Hi @everspader.
Could you provide step-by-step reproduction instructions alongside your Drizzle schema (schema.ts), drizzle.config.ts, and the exact versions of drizzle-orm and drizzle-kit? That would help me reproduce the issue.
If you want to use migration files to manage your database, you should use drizzle-kit generate and drizzle-kit migrate, not drizzle-kit push.
drizzle-kit push reads from your schema file (specified in drizzle.config.ts) and directly applies schema changes to the database, skipping SQL file generation.
Hereβs an example of a schema file that should work with drizzle-kit push:
import { sql } from "drizzle-orm"
import { integer, pgTable, pgView, serial, text } from "drizzle-orm/pg-core"
export const user = pgTable('user', {
id: serial().primaryKey(),
email: text(),
name: text(),
})
export const userSubscription = pgTable('user_subscription', {
id: serial().primaryKey(),
userId: integer().references(() => user.id),
status: text(),
})
export const userSubscriptionView = pgView("user_subscription_view", {
userId: integer(),
email: text(),
name: text(),
subscriptionId: integer(),
status: text(),
}).as(sql`SELECT u.id AS "userId", u.email, u.name, us.id AS "subscriptionId", us.status
FROM "user" u
LEFT JOIN
user_subscription us ON u.id = us."userId" AND (us.status = 'active' OR us.status = 'trialing')`
);
Also, on the alternation-engine branch, you can define a view like this:
const userSubscriptionView1 = pgView('user_subscription_view1').as(
(qb) => {
return qb
.select({
userId: user.id.as('userId'),
email: user.email,
name: user.name,
subscriptionId: userSubscription.id.as('subscriptionId'),
status: userSubscription.status,
})
.from(user)
.leftJoin(
userSubscription,
and(
eq(user.id, userSubscription.userId),
or(eq(userSubscription.status, 'active'), eq(userSubscription.status, 'trialing')),
),
);
},
);
The alternation-engine branch will be merged into main in the near future.