Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to insert dynamic sql statements #5

Open
dylanplural opened this issue Jan 28, 2021 · 1 comment
Open

Ability to insert dynamic sql statements #5

dylanplural opened this issue Jan 28, 2021 · 1 comment

Comments

@dylanplural
Copy link

dylanplural commented Jan 28, 2021

  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.

@shine1594
Copy link
Contributor

shine1594 commented Mar 3, 2021

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.

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

No branches or pull requests

2 participants