drizzle-team / drizzle-team/drizzle-orm

[BUG]: SQL Generation - Views with Dependencies Created in Alphabetical Order Instead of Schema Definition Order

Open
#4,076 7 comments 9 reactions 0 assignees View on GitHub
bug drizzle/kit priority
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.39.1

### What version of `drizzle-kit` are you using?

0.30.4

### Other packages

_No response_

### Describe the Bug

## Issue Description
When generating SQL migrations, Drizzle Kit creates tables and views in alphabetical order rather than following the schema definition order. This causes issues particularly with views that depend on other views.

## Example Case
In our schema, we have two views where one depends on another:

```typescript
// Schema definition order
export const userTokenUsageView = mysqlView('user_token_usage').as((qb) => {
// Base view that aggregates user token usage from chat_messages
});

export const teamTokenUsageView = mysqlView('team_token_usage').as((qb) => {
// Depends on user_token_usage view
// Aggregates team level statistics from user_token_usage
});
```

However, the generated SQL creates them in alphabetical order:

```sql
VIEW `team_token_usage` AS (
// References user_token_usage which doesn't exist yet
);

VIEW `user_token_usage` AS (
// Base view definition
);
```

### Current Behavior:

- Tables and views are created in alphabetical order
- Dependencies are not considered in creation order
- Results in SQL errors when views reference not-yet-created views or tables

### Expected Behavior:

- Tables and views should be created following the schema definition order
- Or consider dependencies when determining creation order
- Views with dependencies should be created after their dependencies

### Workaround
Currently, we need to either:

- Rename views with prefixes to force correct alphabetical order
- Split migrations into multiple files
- Use numerical prefixes in view names

### Impact
This issue affects any schema where:

- Views depend on other views
- Tables have complex foreign key relationships
- The alphabetical order doesn't match the required creation order

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.