
Read named SQL statements from .sql files and/or use named parameters in prepared statements.
Read named SQL statements from .sql files
Put your statements in a .sql file and name them with a comment above.
e.g. /myproject/sql/pokemon.sql
SELECT * from pokemon
WHERE id = ?;
INSERT INTO pokemon(name, price)
VALUES ($name, $price);
UPDATE pokemon
SET price = :price;
Raw / SQLite
Use them in code by giving the directory where .sql files(s) are
const sql = require('yesql')('/myproject/sql/')
const db = new sqlite3.Database('/myproject/sql/db.sqlite3')
db.all(sql.getPokemon, 1337, (err, rows) => {...})
db
.prepare(sql.addPokemon)
.run({name: 'pikachu', price: 99}, err => {...}
MySQL / MariaDB
Prepared statements for MySQL / MariaDB are supported
const sql = require('yesql')('/myproject/sql/', {type: 'mysql'})
const named = require('yesql').mysql
const mysql = require('mysql').createConnection...
mysql.query(sql.updatePokemon({price: 5}), (err, result) => {...})
mysql.query(named('UPDATE ::ptable SET price = :price;')({price: 5, ptable: 'pokemon'}), (err, result) => {...})
PostgreSQL
Prepared statements for node-postgres (pg) are supported
const sql = require('yesql')('/myproject/sql/', {type: 'pg'})
const named = require('yesql').pg
const pg = require('pg').connect...
pg.query(sql.updatePokemon({price: 5}), (err, result) => {...})
pg.query(named('UPDATE pokemon SET price = :price;')({price: 5}), (err, result) => {...})
Handling missing parameters
By default MySQL and PG versions throw an error if a parameter is not given.
Passing a flag "useNullForMissing" a null value is used instead.
Example only for PG, but works for MySQL also.
const sql = require('yesql')('/myproject/sql/', {type: 'pg', useNullForMissing: true})
const named = require('yesql').pg
const pg = require('pg').connect...
pg.query(sql.updatePokemon(), (err, result) => {...})
pg.query(named('UPDATE pokemon SET price = :price;', {useNullForMissing: true})({}), (err, result) => {...})
Changelog
7.0.0
- MySQL supports quoted strings
6.1.0
- PG statement returning string with escaped backslash
6.0.0
- PG statement returning string with escaped backslash
5.0.0
4.1.3
4.1.2
4.1.1
4.1.0
4.0.0
3.2.2
3.2.1
- Add security build and badge
- Update deps
3.2.0
- Support Windows new lines
3.1.6
- Add CI build and Greenkeeper check
- Update dev dependencies
3.1.5
- Add MySQL table name as parameter to example
3.1.4
- Fix pg type cast and docs
3.1.1
- Support mysql prepared statements
2.6.0
- Support pg prepared statements