Skip to content

Ability to insert dynamic sql statements #5

@dylanplural

Description

@dylanplural
  const dynamicStatements = []
  dynamicStatements.push(SQL` WHERE table_1.column_1 = ${x}`)
  dynamicStatements.push(SQL` AND table_1.column_2 = ${y}`)

  await QUERY/* sql */`
    SELECT *
    FROM table_1
    ${dynamicStatements}
  `

Currently this throws an error as it tries to parse the dynamicsStatements array as just a single statement.

My current workaround is as follows:

export function joinStatements(statements: any[], { join = ' ', prefix = ' ' }: { join: string, prefix: string } = { join: ' ', prefix: ' ' }) {
  const tagSymbol = Object.getOwnPropertySymbols(statements[0])[0]

  const values: any[] = []
  const textParts: string[] = []
  for (const statement of statements) {
    const res = statement()
    textParts.push(res.text)
    values.push(...res.values)
  }

  const res = Object.assign(
    () => ({
      text: prefix + textParts.join(join),
      values,
    }),
    {
      [tagSymbol]: true,
    },
  )

  return res
}

It's especially hacky as the tag Symbol isn't exported, so I have to fetch it like so.

If there is functionality to support this and I missed it, please let me know.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions