Skip to content

[BUG]: alias doesn't work with views (Postgres) #4875

@anthonyma94

Description

@anthonyma94

Report hasn't been filed before.

  • 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.44.4

What version of drizzle-kit are you using?

0.31.4

Other packages

No response

Describe the Bug

When using alias() with a view, the query fails with this error: Your "id" field references a column "view"."id", but the table "view" is not part of the query! Did you forget to join it?. I double checked that I'm importing the correct alias from drizzle-orm/pg-core.

export const productionJobTable = pgTable("production_job", {
    id: text("id").primaryKey(),
    name: text("name"),
});

export const rfidTagTable = pgTable(
    "rfid_tag",
    {
        createdAt: pgTimestamp("created_at") // custom type
            .notNull()
            .default(sql`now()`),
        epc: text("epc").notNull(),
        locationId: text("location_id")
            .notNull(),
        id: text("id").notNull().unique().$default(nanoid),
    });

export const productionJobWithLocationView = pgView(
    "production_job_with_location"
).as((qb) => {
    const productionColumns = getTableColumns(productionJobTable);
    const sub = qb
        .selectDistinctOn([rfidTagTable.epc])
        .from(rfidTagTable)
        .orderBy(rfidTagTable.epc, desc(rfidTagTable.createdAt))
        .as("r");
    return qb
        .select({
            ...productionColumns,
            locationId: sub.locationId,
            tagId: sql`${sub.id}`.mapWith(sub.id).as("tag_id"),
            tagCreatedAt: sql`${sub.createdAt}`
                .mapWith(sub.createdAt)
                .as("tag_created_at"),
        })
        .from(productionJobTable)
        .leftJoin(
            sub,
            and(
                eq(productionJobTable.id, sql`LTRIM(${sub.epc}, '0')`),
                sql`${sub.epc} ~ '^0?[0-9]+'`
            )
        );
});

const sub = alias(productionJobWithLocationView, "p");
db.select().from(sub); // Errors here

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions