L-Mario564 / drizzle-dbml-generator

Generate DBML markup from your schema defined with Drizzle ORM.
MIT License
161 stars 8 forks source link

Composite Keys don't generate ref statements #11

Open RiyeUK opened 6 months ago

RiyeUK commented 6 months ago

With a table defined in the schema as so:

export const warehouseOffices = pgTable(
    'warehouse_offices',
    {
        officeId: integer('office_id')
            .notNull()
            .references(() => offices.id),
        warehouseId: integer('warehouse_id')
            .notNull()
            .references(() => warehouses.id),
    },
    (table) => {
        return {
            pk: primaryKey({ columns: [table.officeId, table.warehouseId] }),
        };
    }
);

The generated .dbml doesn't include any refs for this table:

table warehouse_offices {
  office_id integer [not null]
  warehouse_id integer [not null]

  indexes {
    (office_id, warehouse_id) [pk]
  }
}

I need to add these lines to the resulting .dbml:

ref: warehouse_offices.warehouse_id - warehouses.id
ref: warehouse_offices.office_id - offices.id
L-Mario564 commented 6 months ago

What version of the ORM are you using? Do you know if this worked in a previous version?

stdrnddev commented 4 months ago

Hey @L-Mario564 i had this issue too Wanted it fast so i changed your index.cjs to use this

var Columns = Symbol.for("drizzle:Columns");
const pkColumns = wrapColumns(Object.values(index.table[Columns]), this.buildQueryConfig.escapeName);

Also the references are missing the schema's name which you can do it like this

sourceTable: `${relation.sourceTable[Schema]}.${relation.sourceTable[TableName]}`,
foreignTable: `${relation.sourceTable[Schema]}.${relation.referencedTableName}`,

your escapeSpaces function will introduce quotes to {schema}.{tableName} after adding the schema so i changed the regex to /\s/

didn't open a PR because i just tested for my own situation but it may help you to handle this

currently using "drizzle-orm": "^0.30.4" this version for drizzle-orm