Nano Queries, a state of the art Query Builder

https://vitonsky.net/blog/2026/01/24/nano-queries/

18 points · 7 comments · view on lemmy.world

7 Comments

JakenVeina@midwest.social · 2 pts · 218d

Dear lord, why are they running a database in a browser?

verstra@programming.dev · 1 pts · 220d

I wouldn't call it state-of-the-art, but rather maybe most-straightforward or database-agnostic or as-simple-as-they-get

inzen@lemmy.world · 0 pts · 219d (4 replies)

I don't understand the usecase for this. Why would I want to create sql queries dynamically? Seems like a testing and index optimaziation nightmare. Maybe I'm just lacking.

Kache@lemmy.zip · 1 pts · 219d (3 replies)

What do you mean? SQL query builders exist in pretty much every lang

inzen@lemmy.world · 1 pts · 219d (2 replies)

I have never used one and I don't quite understand the benefits. I have used some orm's but I prefer to raw dog SQL.

Kache@lemmy.zip · 2 pts · 219d

Then you've used one without knowing, because somewhere between the ORM you used and the database was SQL, and that SQL was put together by the ORM's query builder

If by "raw dog SQL" you mean dynamically concatenating strings (conditionally, interpolating runtime values), that's literally a query builder, albeit a janky SQL-injectable one.

vitonsky@programming.dev · 2 pts · 219d

When you use query builder, you write a raw SQL code.

The benifit is you can insert user input right in string, and your query remain secure against injections. Additionally, a Nano Queries let you compose queries, and extend it, so you may build complex queries simply.

Let's say you develop a site to search something by its features, for example a movies. Your SQL query may easy takes 100-500 lines. Some part of this query will be a basic, some will be optional depends on provided filters.

With a query builder you may conditionally extend your query like that

if (userInput.rating > 0) {
  filter.and(sql`rating >= ${userInput.rating}`);
}

That's all Query Builder does. It let you avoid to write code like that

const values = [];
const getPlaceholder = (value) => {
  values.push(value);
  return `$${values.length}`;
};

const where = [];
if (year) {
  where.push(`release_year = ${getPlaceholder(year)}`);
}
if (rating) {
  where.push(`rating >= ${getPlaceholder(rating)}`);
}

db.query(
  `SELECT title FROM movies ${where.length ? 'WHERE ' + where.join(' AND ') : ''} LIMIT 100`,
  values,
);