SQL Tagged Templates
Table Of Contents
- What is it?
- Why make this library?
- What database libraries are supported?
- Why is this library helpful?
- What all changed from sql-template-strings?
- More Usage Info
- API Reference
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?
- This is a pure ESM package
- Only supports LTS versions of node
- Drop support for the older mysql package
- Add support for the mariadb package
- Only support the latest major versions of the other libraries listed above.
- The older versions may work fine, I just don't want to write tests for them nor support compatibility
- Dialects are now explicit
- The exported dialects are pure and immutable.
- This means a lot of the API has been removed e.g. no append, useBind, setName and no exported class SQLStatement.
- Migrating from that API? See our migration guide
- Queries can be nested
- Raw sql is now explicit
More Usage Info
Additional usage documentation can be found here