Kloosk
Kloosk

Reputation: 1

Is there a way to create dynamic table names in slonik?

I'm trying to create queries dynamically like this:

function getInsertColumns(tableName) {
  const keys = [];
  if (tableName === 'users_files') {
    return ['user_id', 'file_id'];
  }
  return keys.map((key) => sql.identifier([key]));
}

function getRecordsetColumns(tableName) {
  if (tableName === 'users_files') {
    return sql.fragment`user_id text, file_id text`;
  }
}

const insertValues = batch.map((item) => ({
   ...item,
}));

transactionConnection.query(sql.unsafe`
INSERT INTO ${sql.identifier([tableName])} (${sql.join(
getInsertColumns(tableName),
sql.fragment`, `,
)})
SELECT * FROM jsonb_to_recordset(${sql.jsonb(insertValues)})
AS t ${getRecordsetColumns(tableName)}
`);

but I keep getting errors like: syntax error at or near "$1" at character 41

I tried using sql.identifier and sql.literalValue but it still doesn't work.

Upvotes: 0

Views: 71

Answers (0)

Related Questions