drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.49k stars 643 forks source link

[BUG]: sql placeholder with an array throws an error #2872

Open Wisieneu opened 2 months ago

Wisieneu commented 2 months ago

What version of drizzle-orm are you using?

0.33.0

What version of drizzle-kit are you using?

No response

Describe the Bug

when executing this code:

const prepQuery = db
  .select()
  .from(table)
  .where(inArray(table.postId, sql.placeholder("postIds")))
  .prepare("prepquery");

const result = await prepQuery.execute({
  postIds: ["esaeasdas", "esaeasdas", "esaeasdas"]
})

Drizzle throws an error: syntax error at or near \"$1\. The code works when I execute the prepared query without the sql.placeholder, hardcoding an argument inside prepQuery - the error is not reproduced anyway else. Do I need to pass the array of strings there differently? I tried converting it into a string, but that does not work neither. It would also be awesome if this case was handled by the ORM, so that no workarounds are needed.

Expected behavior

 sql.placeholder<string[]>("postIds")

Environment & setup

No response

jonathanpalma commented 1 month ago

Is there any current solution to pass arrays as placeholders in prepared statements?

hyunbinseo commented 2 weeks ago

In SQLite, you cannot pass an array into a placeholder.

In-fact, you need as many ? as the array item count, which can't be done in prepared queries.

A viable workaround is to use json_each — you do have to write a little bit of raw SQL, but it works.

WHERE id IN (SELECT value FROM json_each(?))

Referenced https://ricardoanderegg.com/posts/sqlite-list-array-parameter-query/