Registry / database / lego-sql

lego-sql

JSON →
library5.0.1jsnpmunverified

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-sql
INSTALL
IMPORT
SIG · LEGO-SQL
L
lego-sql
databasejavascriptv5.0.1
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Lego
import { Lego } from 'lego-sql'
const Lego = require('lego-sql')
ESM syntax requires named import since v3; CommonJS require may work but is not recommended.
lego
import lego from 'lego-sql'
const lego = require('lego-sql').default
Default export provides the same Lego object but not recommended; use named import for clarity.
Lego.sql
import { Lego } from 'lego-sql'; await Lego.sql `SELECT 1`
Lego`SELECT 1`
Lego.sql is the tagged template function; directly calling Lego as a function does not work.
Lego.raw
import { Lego } from 'lego-sql'; const column = 'name'; const lego = Lego.sql `UPDATE users SET ${Lego.raw(column)} = ${value}`
Lego.raw(column) inside regular string interpolation without template literal
Lego.raw escapes the raw value; only use with trusted input to avoid SQL injection.
Lego.parse
import { Lego } from 'lego-sql'; const rows = []; const result = Lego.parse(rows, definition)
Lego.parse(rows, {})
Pass rows (array) and a definition object that maps column names to properties (string or array of subdefinitions).

Shows basic usage: parameterized queries, INSERT with RETURNING, arrays of Lego instances, first(), and row-to-object parsing.

import { Lego } from 'lego-sql'; import pg from 'pg'; // Set DATABASE_URL environment variable or manually configure pg pool // Lego uses pg internally; it expects a default pool or explicit config. // Insert a user const name = 'John'; const result = await Lego.sql `INSERT INTO users (name) VALUES (${name}) RETURNING *`; console.log(result.rows); // rows from INSERT // Query with parameter const users = await Lego.sql `SELECT * FROM users WHERE name = ${name}`; console.log(users.rows); // Use first() to get single result const user = await Lego.sql `SELECT * FROM users LIMIT 1`.first(); console.log(user); // first row or null // Nest arrays of Lego instances for multiple values const projects = ['Alpha', 'Beta']; await Lego.sql `INSERT INTO projects (name) VALUES ${projects.map(p => Lego.sql`(${p})`)}`; // Parse flat rows to nested objects const rows = [ { id: 1, test_id: 1, test_name: 'Test 1' }, { id: 1, test_id: 2, test_name: 'Test 2' } ]; const objects = Lego.parse(rows, [ { id: 'id', tests: [{ id: 'test_id', name: 'test_name' }] } ]); console.log(objects); // [{ id: 1, tests: [...] }]
Debug
Known issues
gotchaLego.sql returns a promise-like object, not a Promise. Calling .then() executes the query. Do not await the query before .then().
fix
Use await only on the final .then() or use .then() to get the result. Example: await Lego.sql`...`.then(res => res.rows);
affects: >=0.0.0
breakingIn v3, import changed from default to named export. const lego = require('lego-sql') stopped working.
fix
Use import { Lego } from 'lego-sql' or const { Lego } = require('lego-sql').
affects: >=3.0.0
deprecatedLego.sql no longer automatically connects to DATABASE_URL; you must configure pg pool manually or provide an environment variable.
fix
Set DATABASE_URL env variable or create a pg Pool and pass it to Lego.createPool(pool).
affects: >=5.0.0
gotchaLego.raw is for trusted input only. Using it with user-provided values can lead to SQL injection.
fix
Only use Lego.raw with hardcoded values or trusted column names. For user input, always use the template literal parameter insertion.
affects: >=0.0.0
breakingIn v4, the result of a query is no longer the raw array of rows but an object with rows and command. Use .rows property.
fix
Access result.rows instead of expecting result as array. For DELETE/UPDATE without RETURNING, use result.rowCount.
affects: >=4.0.0
gotchaNested arrays of Lego instances (e.g., for multiple values) must be inside the template literal, not as separate arguments.
fix
Correct: Lego.sql`INSERT INTO t (v) VALUES ${arr.map(x => Lego.sql`(${x})`)}`. Incorrect: Lego.sql`...`, arr.
affects: >=0.0.0
gotchaLego.parse expects rows as array of objects; if rows is undefined or not an array, it throws silently.
fix
Always pass an array (even empty) to Lego.parse. Example: Lego.parse(rows || [], definition).
affects: >=0.0.0
Errors
Common errors & fixes
TypeError: Lego.sql is not a function
Using default import from CommonJS or wrong import syntax.
fix
Use import { Lego } from 'lego-sql' instead of import Lego from 'lego-sql' (if using ESM) or const { Lego } = require('lego-sql').
Error: No pool defined. Please call Lego.createPool(pool) or set DATABASE_URL.
No pg pool configured before calling Lego.sql that executes a query.
fix
Call Lego.createPool(new pg.Pool({ connectionString: process.env.DATABASE_URL })) before any query. Or set DATABASE_URL env variable.
Query result is undefined
Using the result of Lego.sql directly without .then() or awaiting the wrong value.
fix
Use const result = await Lego.sql`...`.then(r => r.rows); or await Lego.sql`...` and then access .rows property.
Cannot find module 'pg'
pg is a peer dependency but not installed.
fix
Install pg: npm install pg.
SyntaxError: Unexpected template string
Missing backticks or using regular strings instead of template literals.
fix
Use backticks: Lego.sql`SELECT * FROM users WHERE id = ${id}`
Upgrade
Version history
5.0.1latest on npm
Audit
Dependencies
pgrequiredPostgreSQL driver required for executing queries; used internally for pool and query execution.
Agent activity
6 hits · last 30 days
node
6
Resources