Lego is a lightweight SQL (string) builder for Node.js that uses ES6 template strings to parameterize queries. Instead of abstracting SQL, it embraces raw SQL while safely handling parameterization. Current stable version is 5.0.1, with active maintenance. Key differentiators: no ORM-like abstraction, uses tagged template literals for safe parameterized queries, supports nested queries with arrays of Lego instances, built-in row-to-object parsing, and transaction support via export. Unlike knex.js, Lego does not provide a full query building API but rather wraps SQL strings with parameter injection.
npm install lego-sqlNo compatibility data collected yet for this library.
Verified import paths — ran on the pinned version, not inferred.
Shows basic usage: parameterized queries, INSERT with RETURNING, arrays of Lego instances, first(), and row-to-object parsing.
Use await only on the final .then() or use .then() to get the result. Example: await Lego.sql`...`.then(res => res.rows);
Use import { Lego } from 'lego-sql' or const { Lego } = require('lego-sql').Set DATABASE_URL env variable or create a pg Pool and pass it to Lego.createPool(pool).
Only use Lego.raw with hardcoded values or trusted column names. For user input, always use the template literal parameter insertion.
Access result.rows instead of expecting result as array. For DELETE/UPDATE without RETURNING, use result.rowCount.
Correct: Lego.sql`INSERT INTO t (v) VALUES ${arr.map(x => Lego.sql`(${x})`)}`. Incorrect: Lego.sql`...`, arr.Always pass an array (even empty) to Lego.parse. Example: Lego.parse(rows || [], definition).
Use import { Lego } from 'lego-sql' instead of import Lego from 'lego-sql' (if using ESM) or const { Lego } = require('lego-sql').Call Lego.createPool(new pg.Pool({ connectionString: process.env.DATABASE_URL })) before any query. Or set DATABASE_URL env variable.Use const result = await Lego.sql`...`.then(r => r.rows); or await Lego.sql`...` and then access .rows property.
Install pg: npm install pg.
Use backticks: Lego.sql`SELECT * FROM users WHERE id = ${id}`