FxSQL icon indicating copy to clipboard operation
FxSQL copied to clipboard

Ability to insert dynamic sql statements

Open dylanplural opened this issue 5 years ago • 1 comments

  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.

dylanplural avatar Jan 28 '21 15:01 dylanplural

You can just use reduce function to merge some SQL statements:

  await QUERY/* sql */`
    SELECT *
    FROM table_1
    ${dynamicStatements.reduce((acc, sql) => SQL`${acc} ${sql}`)}
  `

and there is also a SQLS tag function that does the same thing.

Sorry for the late reply.

shine1594 avatar Mar 03 '21 04:03 shine1594