Add template tags to node:sqlite for convenient and safe SQL querying with built-in LRU caching for prepared statements.
npm install sqlite-tags
const { open } = require('sqlite-tags')
// Open a database with query tag support
const db = open('mydb.sqlite')
// Create table and insert data
db.exec(`
CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL);
INSERT INTO products VALUES (1, 'Product A', 10.99);
INSERT INTO products VALUES (2, 'Product B', 24.99);
`)
// Query using tagged template literals
const id = 1
const products = db.query`SELECT * FROM products WHERE id = ${id}`
console.log(products) // [{ id: 1, name: 'Product A', price: 10.99 }]
// Multiple parameters
const minPrice = 15
const category = 'electronics'
const results = db.query`
SELECT * FROM products
WHERE price > ${minPrice}
AND category = ${category}
`
// Check cache status
console.log(`Cache size: ${db.query.cacheSize()}`)
console.log(`Cache capacity: ${db.query.cacheCapacity()}`)
// Clear the cache if needed
db.query.clearCache()
// Close the database when done
db.close()
The module uses an LRU (Least Recently Used) cache to store prepared statements, which improves performance by reusing statements instead of re-preparing them for each query execution. This is especially useful for frequently executed queries.
By default, the cache can store up to 100 prepared statements. You can customize this with the cacheSize
option.
Opens a SQLite database and adds the query tag functionality.
filename
: String, URL, or Buffer - Path to the database fileoptions
: Object - Options for opening the database and query tagcacheSize
: Number - Maximum number of prepared statements to cache (default: 100)- ... (and all other standard options from node:sqlite)
- Returns: DatabaseSync - Enhanced database with query tag method
Adds the query tag functionality to an existing database instance.
db
: DatabaseSync - An existing SQLite database instanceoptions
: Object - Configuration optionscacheSize
: Number - Maximum number of prepared statements to cache (default: 100)
- Returns: DatabaseSync - The same database object with added query tag functionality
Tagged template function for SQL queries with automatic parameter binding.
- Parameters are automatically extracted from the template and bound safely
- Returns: Array - Query results as objects
Clears the prepared statement cache.
Returns the current number of statements in the cache.
Returns the maximum capacity of the statement cache.
Run the tests with:
npm test
Using the LRU cache for prepared statements can significantly improve performance in applications that:
- Execute the same queries repeatedly
- Have complex queries that are expensive to parse and prepare
- Execute queries in tight loops or high-frequency operations
The cache helps avoid the overhead of re-parsing and preparing SQL statements, which can be substantial for complex queries.
MIT