drizzle-team / drizzle-team/drizzle-orm
[FEATURE]: Ability to attach a pre-existing table to a schema table factory
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Describe what you want
Currently, in order to get a schema'd table, you need to create a function that returns a `Schema` object.
> from https://github.com/drizzle-team/drizzle-orm/issues/423#issuecomment-1501232679
> ```typescript
> function getUsersTable(schemaName: TSchema) {
> return mysqlSchema(schemaName).table('users', {
> id: int('id').primaryKey(),
> name: text('name').notNull(),
> });
>}
> ```
However, this makes it difficult/impossible to use references to other tables because the table object doesn't actually exist outside the schema factory.
In order to bypass this restriction, you need to define the table twice. Once for `mysqlTable`, a second time for `mysqlSchema.table()`
```typescript
const roleColumns = {
id: int('id').primaryKey(),
roleName: varchar('role_name', {length:20}),
};
const roleTable = mysqlTable('roles', roleColumns);
const getRoleTable = (schemaName: TSchema) => {
return mysqlSchema(schemaName).table('roles', roleColumns);
}
const userColumns = {
id: int('id').primaryKey(),
name: text('name').notNull(),
role: int('role_key').references(() => roleTable.id),
}
const userTable = mysqlTable('user', userColumns);
const getUsersTable = (schemaName: TSchema) => {
return mysqlSchema(schemaName).table('user', userColumns);
}
```
My feature request would be to just be able to pass the already defined 'schemaless' table into `mysqlSchema.table()`.
Example
```typescript
export const roleTable = mysqlTable('roles', {
id: int('id').primaryKey(),
roleName: varchar('role_name', {length:20}),
});
export const getRoleTable = (schemaName: TSchema) => {
return mysqlSchema(schemaName).table(roleTable);
}
export const userTable = mysqlTable('user', {
id: int('id').primaryKey(),
name: text('name').notNull(),
role: int('role_key').references(() => roleTable.id),
});
export const getUsersTable = (schemaName: TSchema) => {
return mysqlSchema(schemaName).table(userTable);
}
```
This has a few benefits in my opinion.
- The table is just defined a single time
- It brings the code back to more of a similar style from Drizzle's docs (inline colum definitions instead of a separate variable)
- ~~The schema table factories could be put into a separate file, or just organized differently in the current file (all the factories at the bottom of the file, etc...).~~ I guess you can probably do this without this request
Thank you for consideration!
Refs #423
Contributor guide
Assessment
This issue has not been assessed yet.