Readme

sqliteBuilder: Opinionated safe(r) query builder using tagged templates

import { Statement } from "https://esm.town/v/postpostscript/sqliteBuilder"; const unsafeId = "1234 or TRUE" console.log(Statement` SELECT * FROM table WHERE id = ${unsafeId} ${Statement`AND otherCondition`} `) // StatementInstance { // sql: "\nSELECT *\nFROM table\nWHERE id = ?\nAND otherCondition\n", // args: [ "1234 or TRUE" ], // log: false // } const results = await Statement`SELECT ...`.execute() // [ { key: "value", anotherKey: "anotherValue" }, ... ]

Or you can pass it directly to @std/sqlite.execute:

import { sqlite } from "https://esm.town/v/std/sqlite" await sqlite.execute(Statement`Select ...`)

You can combine multiple statements using Statement.prototype.combineWith:

Statement`...`.combineWith(Statement`...`, " AND ") [ Statement`fieldA`, Statement`fieldB`, Statement`fieldC`, ].reduce((a, b) => a.combineWith(b, ", "))
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
5
stevekrouse avatar

This is AWESOME! I hate having to do it with with the ?s

nbbaier avatar

@postpostscript, would there be a way to make Statement type safe in a way where we could do something like this:

interface User {
  name: string;
  age: number;
}

Statement<User>`insert into user values(${name}, ${age})`

Where it would type check if the write types were provided in replacements?

postpostscript avatar
nbbaier avatar

@postpostscript Awesome! Really cool, thanks for implementing this

postpostscript avatar

@nbbaier thanks, and no problem!

March 17, 2024