Skip to content

Export Expression, isExpression as public API#697

Merged
romeerez merged 1 commit into
romeerez:mainfrom
IlyaSemenov:export-expression
May 23, 2026
Merged

Export Expression, isExpression as public API#697
romeerez merged 1 commit into
romeerez:mainfrom
IlyaSemenov:export-expression

Conversation

@IlyaSemenov
Copy link
Copy Markdown
Contributor

I need Expression as a reusable type for my decomposed raw SQL builders.

Real-life example:

export function buildEffectiveAccessRoleSql<Role extends string>({
  userId,
  roleWeight,
  weightedRoles,
}: {
  userId: string
  roleWeight: Expression // <------- Here
  weightedRoles: WeightedRoles<Role>
}) {
  const { schema } = getActiveTenant()
  const roleWhens = makeRoleWeightEntries(weightedRoles)
    .map(({ role, weight }) => `WHEN ${weight} THEN '${role}'`)
    .join(" ")
  const roleCaseWhens = sql({ raw: roleWhens })

  return sql<Role | null>`
    CASE
      WHEN EXISTS (
        SELECT 1
        FROM ${sql.ref(`${schema}.user`)} active_user
        WHERE active_user.id = ${userId}
          AND active_user.deleted_at IS NULL
      )
      THEN CASE ${roleWeight} ${roleCaseWhens} ELSE NULL END
      ELSE NULL
    END
  `
}

and usage:

buildEffectiveAccessRoleSql<SectionAccessRole>({
    userId,
    roleWeight: sql<number>`
      GREATEST(
        ${buildGlobalCompanyRoleWeightSql({
          userId,
          weightedRoles: SECTION_WEIGHTED_ROLES,
        })},
        ${allowEveryoneWeight},
        ${ownAccessWeight}
      )
    `,
    weightedRoles: SECTION_WEIGHTED_ROLES,
  })

currently, I have to infer the type with weird hacks:

import { sql } from "../base"

const _makeRawSql = () => sql``
const _makeSqlRefExpression = () => sql.ref("")

// Quick replacement for import type { Expression } from "pqb/internal"
export type Expression = ReturnType<typeof _makeRawSql> | ReturnType<typeof _makeSqlRefExpression>

@netlify
Copy link
Copy Markdown

netlify Bot commented May 21, 2026

Deploy Preview for orchid-orm canceled.

Name Link
🔨 Latest commit ecb8952
🔍 Latest deploy log https://app.netlify.com/projects/orchid-orm/deploys/6a0f28e1e0feca00086caac8

@romeerez romeerez merged commit b72b95a into romeerez:main May 23, 2026
6 checks passed
@romeerez
Copy link
Copy Markdown
Owner

Thanks for formulating and doing the PR - merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants