cadena
cadena helps you to write safer SQL
- supports parameterized query
run()
returns promise- supports mysql, sqlite3 and rqlite
usage
npm install --save cadena
const { select, connect, query, sql } = require('cadena')
const db = connect('mysql', 'mysql://guest:guest@127.0.0.1/test')
select('name', 'id')
.from('players')
.where({score: { '>=': 90 }})
.limit(0, 10)
.orderBy('score').desc().run(db)
select().from('players').toString()
let id = '33b27b80-bee3-4d1b-aa9a-231bf250f344'
sql`select * from tbl where id=${id}`.run(db)
sql`select * from tbl where id=${id}`.toString()
select
select(['name', 'id'])
select()
where
where({key: 'value'})
where({
score: {between: [80, 90]},
name: {contains: 'alberto'}
group: ['A', 'B']
})
where({key: {'<': min}}).or({key: {'>': max}})
undefined values are ignored
where({key: undefined})
where({key: undefined, key2: 'value'})
where({key: undefined}).or({key2: 'value'})
nested and/or
where(and(
or({ n: 1 }, { n: 2 }),
{ k: 1 }))
a more verbose form
where({
$and: [
{ $or: [{n: 1}, {n: 2}] },
{ k: 1 }
]
})
orderBy
orderBy('field1', 'field2')
orderBy(['field1', 'field2'])
orderBy(['-field1', 'field2'])
orderBy('field1', 'ASC', 'field2', 'DESC')
orderBy('field1').desc().orderBy('field2').asc()
join
select('name', 'id').from('tbl').leftJoin('tbl2').on({tbl.id: "tbl2.tblId"})
subquery
let tbl = select('name', 'id').from('tbl')
select().from(tbl)
count
let query = select().from('tbl').where({key: value}).orderBy('created_at').desc()
query.count().sql
insert
insert({name: 'foo', score: 1}).into('players')
insert(['name', 'score'], [['foo', 1], ['bar', 2]]).into('players')
upsert
upsert({name: 'foo', score: 1}).into('players')
update
update('players').set({name: 'foo', score: 1}).where({id: 1})
update('players').set('name', 'foo').set('score', 1).limit(1)
delete
del('players').where({id: 1})
del('players').where({name: {contains: 'alberto'}}).limit(1)
parameterized query
const { sql } = require('cadena')
let name = 'first'
let id = 1
sql`insert into tbl set name=${name} where id=${id}`.run(db)
database intergration
mysql
const db = cadena.connect('mysql', 'mysql://root:@127.0.0.1/test')
sqlite3
const db = cadena.connect('sqlite3', ':memory:')
rqlite
const db = cadena.connect('rqlite', 'http://127.0.0.1:4001')