Postgres.js

The fastest full featured PostgreSQL client for Node.js, Deno, Bun and Clou...

README

Fastest full PostgreSQL nodejs client

- 🏷 ES6 Tagged Template Strings at the core
- 🏄‍♀️ Simple surface API
- 🖊️ Dynamic query support
- 💬 Chat and help on Gitter
- 🐦 Follow on Twitter



Getting started



Good UX with Postgres.js

Installation

  1. ```bash
  2. $ npm install postgres
  3. ```

Usage

Create your sql database instance
  1. ```js
  2. // db.js
  3. import postgres from 'postgres'

  4. const sql = postgres({ /* options */ }) // will use psql environment variables

  5. export default sql
  6. ```

Simply import for use elsewhere
  1. ```js
  2. // users.js
  3. import sql from './db.js'

  4. async function getUsersOver(age) {
  5.   const users = await sql`
  6.     select
  7.       name,
  8.       age
  9.     from users
  10.     where age > ${ age }
  11.   `
  12.   // users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]
  13.   return users
  14. }


  15. async function insertUser({ name, age }) {
  16.   const users = await sql`
  17.     insert into users
  18.       (name, age)
  19.     values
  20.       (${ name }, ${ age })
  21.     returning name, age
  22.   `
  23.   // users = Result [{ name: "Murray", age: 68 }]
  24.   return users
  25. }
  26. ```

ESM dynamic imports


The library can be used with ESM dynamic imports as well as shown here.

  1. ```js
  2. const { default: postgres } = await import('postgres')
  3. ```

Table of Contents




Connection


postgres([url], [options])


You can use either a postgres:// url connection string or the options to define your database connection properties. Options in the object will override any present in the url. Options will fall back to the same environment variables as psql.

  1. ```js
  2. const sql = postgres('postgres://username:password@host:port/database', {
  3.   host                 : '',            // Postgres ip address[s] or domain name[s]
  4.   port                 : 5432,          // Postgres server port[s]
  5.   database             : '',            // Name of database to connect to
  6.   username             : '',            // Username of database user
  7.   password             : '',            // Password of database user
  8.   ...and more
  9. })
  10. ```

More options can be found in the Connection details section.

Queries


await sql... -> Result[]


Postgres.js utilizes Tagged template functions to process query parametersbefore interpolation. Using tagged template literals benefits developers by:

1. Enforcing safe query generation
2. Giving the sql function powerful utility and query building features.

Any generic value will be serialized according to an inferred type, and replaced by a PostgreSQL protocol placeholder $1, $2, .... The parameters are then sent separately to the database which handles escaping & casting.

All queries will return a Result array, with objects mapping column names to each row.

  1. ```js
  2. const xs = await sql`
  3.   insert into users (
  4.     name, age
  5.   ) values (
  6.     'Murray', 68
  7.   )

  8.   returning *
  9. `

  10. // xs = [{ user_id: 1, name: 'Murray', age: 68 }]
  11. ```

Please note that queries are first executed when awaited – or instantly by using [.execute()](#execute).


Query parameters


Parameters are automatically extracted and handled by the database so that SQL injection isn't possible. No special handling is necessary, simply use tagged template literals as usual.

  1. ```js
  2. const name = 'Mur'
  3.     , age = 60

  4. const users = await sql`
  5.   select
  6.     name,
  7.     age
  8.   from users
  9.   where
  10.     name like ${ name + '%' }
  11.     and age > ${ age }
  12. `
  13. // users = [{ name: 'Murray', age: 68 }]
  14. ```

Be careful with quotation marks here. Because Postgres infers column types, you do not need to wrap your interpolated parameters in quotes like '${name}'. This will cause an error because the tagged template replaces ${name} with $1 in the query string, leaving Postgres to do the interpolation. If you wrap that in a string, Postgres will see '$1' and interpret it as a string as opposed to a parameter.


Dynamic column selection


  1. ```js
  2. const columns = ['name', 'age']

  3. await sql`
  4.   select
  5.     ${ sql(columns) }
  6.   from users
  7. `

  8. // Which results in:
  9. select "name", "age" from users
  10. ```

Dynamic inserts


  1. ```js
  2. const user = {
  3.   name: 'Murray',
  4.   age: 68
  5. }

  6. await sql`
  7.   insert into users ${
  8.     sql(user, 'name', 'age')
  9.   }
  10. `

  11. // Which results in:
  12. insert into users ("name", "age") values ($1, $2)

  13. // The columns can also be given with an array
  14. const columns = ['name', 'age']

  15. await sql`
  16.   insert into users ${
  17.     sql(user, columns)
  18.   }
  19. `
  20. ```

You can omit column names and simply execute sql(user) to get all the fields from the object as columns. Be careful not to allow users to supply columns that you do not want to be inserted.

Multiple inserts in one query

If you need to insert multiple rows at the same time it's also much faster to do it with a single insert. Simply pass an array of objects to sql().

  1. ```js
  2. const users = [{
  3.   name: 'Murray',
  4.   age: 68,
  5.   garbage: 'ignore'
  6. },
  7. {
  8.   name: 'Walter',
  9.   age: 80
  10. }]

  11. await sql`insert into users ${ sql(users, 'name', 'age') }`

  12. // Is translated to:
  13. insert into users ("name", "age") values ($1, $2), ($3, $4)

  14. // Here you can also omit column names which will use object keys as columns
  15. await sql`insert into users ${ sql(users) }`

  16. // Which results in:
  17. insert into users ("name", "age") values ($1, $2), ($3, $4)
  18. ```

Dynamic columns in updates

This is also useful for update queries
  1. ```js
  2. const user = {
  3.   id: 1,
  4.   name: 'Murray',
  5.   age: 68
  6. }

  7. await sql`
  8.   update users set ${
  9.     sql(user, 'name', 'age')
  10.   }
  11.   where user_id = ${ user.id }
  12. `

  13. // Which results in:
  14. update users set "name" = $1, "age" = $2 where user_id = $3

  15. // The columns can also be given with an array
  16. const columns = ['name', 'age']

  17. await sql`
  18.   update users set ${
  19.     sql(user, columns)
  20.   }
  21.   where user_id = ${ user.id }
  22. `
  23. ```