I have an AWS Lamda function that gets some computed data and then is supposed to insert it into a table in Cockroach. I can create the table, but I cannot add rows into it.
Here is the pg part of my code: (I'll end up using pooling, but the connection is for testing and should do the trick):
It's also worth noting that my query looks exactly like the ones in node-postgres' examples, as well as cockroach's documentation.
const dbClient = new Client("omitted but it works")
try {
await dbClient.connect()
await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`)
await dbClient.query(`INSERT INTO outputs(
user_id,
content,
image_url)
VALUES(
$1,
$2,
$3
)`,
[
userID,
response.results.choices[0].text,
response.imageResponse[0].url,
])
} catch (e) {
} finally {
dbClient.end()
}
}
Apparently I just didn't understand how pg/node-postgres handles dynamic values. I had to install and use pg-format to allow me to safely use dynamic values. Here is an example:
const date = new Date()
await dbClient.query(`CREATE TABLE IF NOT EXISTS outputs(_id STRING PRIMARY KEY, user_id STRING NOT NULL, date_created TIMESTAMPTZ, date_modified TIMESTAMPTZ, content STRING NOT NULL, image_url STRING NOT NULL)`)
const query = format(`INSERT INTO tablename (
_id,
user_id,
date_created,
content,
image_url)
VALUES(
%L,
%L,
%L,
%L,
%L
)`,
response.id,
userID,
date.toISOString(),
response.choices[0].text,
response.url