Text Input and dynamic SQL Queries

Hello,
Always starting with a big thanks! I have some code here

```js
const db = DuckDBClient.of({foo: FileAttachment("./data/poem_data.parquet")});
const text = view(Inputs.textarea({placeholder:'Write your SQL query here', submit: true, rows: 6}));

and then use this string to run an SQL query using DuckDB

```js
const ans = db.sql`${text}`

but I get the error

Thanks much
Saptarshi

DuckDBClient.sql replaces interpolated values with placeholders before passing them on as parameters. Your call is equivalent to

const ans = db.query("?", [text])

If you want to pass the raw string as query you’ll have to call .query instead:

const ans = db.query(text)

You can find more information about the available methods in the Framework docs: DuckDB | Observable Framework

Yes, that’s expected. The sql template literal will create queries with placeholders for values (which will then be properly escaped), but it does not build arbitrary queries. Instead you might want to do something like:

const ans = db.sql([text]);

Thank you both of you. I am in the enjoyable spot of learning JavaScript and observable framework at the same time :). Yesterday I was reading for the first time template literals …

Interestingly chatgpt (and its ilk) has helped out but doesnt compete at all with experts here.

Thanks again
Saptarshi

1 Like