npm.io
0.1.0 • Published 21h ago

sql-tagged-templates

Licence
SEE LICENSE IN license.txt
Version
0.1.0
Deps
0
Size
11 kB
Vulns
0
Weekly
0

SQL Tagged Templates

Table Of Contents


What is it?

A library to simplify writing dynamic sql.

For example, you can write a parameterized query to MariaDB like this:

import stt from 'sql-tagged-templates/mariadb`

const author = 'Kurt Vonnegut'
const booksQuery = stt`select * from books where author = ${author}`
// booksQuery.sql is 'select * from books author = ?'
// booksQuery.values is ['Kurt Vonnegut']

const rows = await mariadbPool.query(query)

Why make this library?

This is a fork/rewrite of Felix Becker's node-sql-template-strings

I forked it because I wanted a few features for cleaner and more re-usable queries

  • immutability
  • nested queries

Please note this isn't a drop-in replacement. If you're porting from sql-template-strings then view our migration guide.


What database libraries are supported?

Quick examples for each can be viewed here.


Why is this library helpful?

It makes your larger dynamic queries more readable.

For example, inserting many values:

db.query(
  `
  insert into books (title, author, isbn, category, recommended_age, pages, price)
  values (?, ?, ?, ?, ?, ?, ?)`,
  [title, author, isbn, category, recommendedAge, pages, price]
)

// is more readable as
db.query(stt`
  insert into books (title, author, isbn, category, recommended_age, pages, price)
  values (${title}, ${author}, ${isbn}, ${category}, ${recommendedAge}, ${pages}, ${price})
`)

As your queries grow more complex, sql-tagged-templates allows you to easily reuse portions and compose them into full queries via nesting. Acheiving the same with sql-template-strings becomes unweildy using .append().


What all changed from sql-template-strings?


More Usage Info

Additional usage documentation can be found here

API Reference

View the API reference here

Keywords