Convert Figma logo to code with AI

brianc logonode-postgres

PostgreSQL client for node.js.

12,180
1,213
12,180
488

Top Related Projects

:zap: fast mysqljs/mysql compatible mysql driver for node.js

18,264

A pure node.js JavaScript Client implementing the MySQL protocol.

1,570

Node TDS module for connecting to SQL Server databases.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Quick Overview

node-postgres (pg) is a popular PostgreSQL client for Node.js. It provides a pure JavaScript and native libpq binding interface to interact with PostgreSQL databases, offering both a callback-based API and support for promises.

Pros

  • High performance and efficient connection pooling
  • Supports both JavaScript and TypeScript
  • Extensive documentation and active community support
  • Flexible query interface with parameterized queries for security

Cons

  • Learning curve for beginners, especially with complex queries
  • Some advanced PostgreSQL features require additional setup or plugins
  • Connection management can be tricky in certain scenarios
  • Occasional breaking changes between major versions

Code Examples

  1. Basic query execution:
const { Pool } = require('pg');
const pool = new Pool();

async function getUserById(id) {
  const { rows } = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
  return rows[0];
}
  1. Using a connection pool with async/await:
const { Pool } = require('pg');
const pool = new Pool();

async function createUser(name, email) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const result = await client.query(
      'INSERT INTO users(name, email) VALUES($1, $2) RETURNING id',
      [name, email]
    );
    await client.query('COMMIT');
    return result.rows[0].id;
  } catch (e) {
    await client.query('ROLLBACK');
    throw e;
  } finally {
    client.release();
  }
}
  1. Using parameterized queries for security:
const { Pool } = require('pg');
const pool = new Pool();

async function searchUsers(searchTerm) {
  const query = {
    text: 'SELECT * FROM users WHERE name ILIKE $1',
    values: [`%${searchTerm}%`],
  };
  const { rows } = await pool.query(query);
  return rows;
}

Getting Started

  1. Install the package:

    npm install pg
    
  2. Set up a connection:

    const { Pool } = require('pg');
    const pool = new Pool({
      user: 'dbuser',
      host: 'database.server.com',
      database: 'mydb',
      password: 'secretpassword',
      port: 5432,
    });
    
  3. Execute a query:

    async function runQuery() {
      const { rows } = await pool.query('SELECT NOW()');
      console.log(rows[0]);
    }
    
    runQuery();
    

Competitor Comparisons

:zap: fast mysqljs/mysql compatible mysql driver for node.js

Pros of node-mysql2

  • Supports prepared statements, which can improve performance and security
  • Offers both Promise-based and callback APIs, providing flexibility
  • Generally faster performance, especially for large result sets

Cons of node-mysql2

  • Less mature and potentially less stable than node-postgres
  • Smaller community and fewer third-party extensions
  • Documentation may not be as comprehensive

Code Comparison

node-mysql2:

const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
  host: 'localhost',
  user: 'user',
  database: 'test'
});
const [rows, fields] = await connection.execute('SELECT * FROM users WHERE id = ?', [userId]);

node-postgres:

const { Pool } = require('pg');
const pool = new Pool({
  host: 'localhost',
  user: 'user',
  database: 'test'
});
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
const rows = result.rows;

Both libraries offer similar functionality for basic database operations. node-mysql2 uses execute for prepared statements, while node-postgres uses query with parameterized queries. node-postgres returns results in a single object, whereas node-mysql2 separates rows and fields.

18,264

A pure node.js JavaScript Client implementing the MySQL protocol.

Pros of mysql

  • Simpler API with fewer abstractions, making it easier for beginners to get started
  • Supports both callbacks and promises, offering flexibility in coding style
  • Larger community and more extensive documentation due to its longer history

Cons of mysql

  • Less performant compared to node-postgres, especially for large datasets
  • Lacks built-in connection pooling, requiring additional setup for optimal performance
  • Not as actively maintained, with slower updates and bug fixes

Code Comparison

mysql:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'mydb'
});
connection.query('SELECT * FROM users', (error, results) => {
  if (error) throw error;
  console.log(results);
});

node-postgres:

const { Pool } = require('pg');
const pool = new Pool({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'mydb'
});
pool.query('SELECT * FROM users', (error, results) => {
  if (error) throw error;
  console.log(results.rows);
});

Both libraries offer similar basic functionality for connecting to and querying databases. However, node-postgres provides built-in connection pooling and better performance, while mysql offers a simpler API and more flexible coding options. The choice between them depends on specific project requirements and developer preferences.

1,570

Node TDS module for connecting to SQL Server databases.

Pros of Tedious

  • Native implementation of the TDS protocol, providing better performance for SQL Server connections
  • Supports more advanced SQL Server-specific features like TVPs and bulk insert operations
  • More granular control over connection settings and query execution

Cons of Tedious

  • Steeper learning curve due to lower-level API and more complex configuration options
  • Limited to SQL Server databases, whereas node-postgres supports multiple PostgreSQL-compatible databases
  • Requires more boilerplate code for basic operations compared to node-postgres

Code Comparison

Tedious:

const connection = new Connection(config);
connection.on('connect', (err) => {
  if (err) console.error(err);
  const request = new Request("SELECT * FROM users", (err, rowCount) => {
    if (err) console.error(err);
    connection.close();
  });
  connection.execSql(request);
});

node-postgres:

const client = new Client(config);
client.connect();
client.query('SELECT * FROM users', (err, res) => {
  if (err) console.error(err);
  console.log(res.rows);
  client.end();
});

The code examples demonstrate that Tedious requires more setup and event handling, while node-postgres offers a simpler, more straightforward API for basic database operations. Tedious provides finer control but at the cost of increased complexity, whereas node-postgres prioritizes ease of use for common tasks.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Provides a query builder with a more intuitive and chainable API
  • Supports multiple database systems (PostgreSQL, MySQL, SQLite, etc.)
  • Offers built-in migration and seeding tools for database schema management

Cons of Knex

  • Adds an extra layer of abstraction, potentially impacting performance
  • Steeper learning curve for developers already familiar with raw SQL
  • May not support all advanced database-specific features

Code Comparison

node-postgres:

const { Client } = require('pg');
const client = new Client();
await client.connect();
const res = await client.query('SELECT * FROM users WHERE id = $1', [userId]);
console.log(res.rows[0]);

Knex:

const knex = require('knex')(config);
const user = await knex('users').where('id', userId).first();
console.log(user);

Summary

node-postgres is a low-level driver for PostgreSQL, offering direct access to the database with minimal abstraction. It's lightweight and provides excellent performance for PostgreSQL-specific applications.

Knex is a query builder and migration tool that supports multiple database systems. It offers a more user-friendly API and additional features like migrations, but at the cost of some performance and added complexity.

Choose node-postgres for PostgreSQL-specific projects requiring maximum performance, and Knex for multi-database support or when a higher-level abstraction is preferred.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • Provides an ORM (Object-Relational Mapping) layer, simplifying database interactions
  • Supports multiple database systems beyond PostgreSQL
  • Offers built-in data validation and migration tools

Cons of Sequelize

  • Steeper learning curve due to its abstraction layer
  • Can be slower for complex queries compared to raw SQL
  • May introduce unnecessary complexity for simple database operations

Code Comparison

Sequelize:

const User = sequelize.define('User', {
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
});

const users = await User.findAll();

node-postgres:

const { Pool } = require('pg');
const pool = new Pool();

const { rows } = await pool.query('SELECT * FROM users');

Summary

Sequelize is an ORM that provides a higher level of abstraction for database operations, supporting multiple databases and offering features like migrations and validations. It's beneficial for complex applications but may introduce overhead for simpler projects.

node-postgres is a lightweight PostgreSQL client for Node.js, offering direct database access with raw SQL queries. It's faster for simple operations and provides more control, but requires manual handling of database schema changes and lacks built-in ORM features.

The choice between the two depends on project requirements, team expertise, and performance considerations.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • Supports multiple databases (PostgreSQL, MySQL, SQLite, etc.)
  • Provides ORM features like entity relationships and migrations
  • Offers both Active Record and Data Mapper patterns

Cons of TypeORM

  • Steeper learning curve due to more complex features
  • Potentially slower performance for simple queries
  • Larger bundle size and more dependencies

Code Comparison

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

const user = await repository.findOne({ where: { name: "John" } });

node-postgres:

const { Pool } = require('pg');
const pool = new Pool();

const result = await pool.query('SELECT * FROM users WHERE name = $1', ['John']);
const user = result.rows[0];

TypeORM provides a more abstracted, object-oriented approach with decorators and built-in query methods. node-postgres offers a lower-level interface, requiring manual SQL query writing but providing more direct control over database interactions.

TypeORM is better suited for complex applications with multiple entities and relationships, while node-postgres is ideal for simpler projects or when fine-grained control over queries is needed. The choice between them depends on project requirements, team expertise, and performance considerations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

node-postgres

Build Status NPM version NPM downloads

Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings.

Monorepo

This repo is a monorepo which contains the core pg module as well as a handful of related modules.

Documentation

Each package in this repo should have its own readme more focused on how to develop/contribute. For overall documentation on the project and the related modules managed by this repo please see:

:star: Documentation :star:

The source repo for the documentation is available for contribution here.

Features

  • Pure JavaScript client and native libpq bindings share the same API
  • Connection pooling
  • Extensible JS ↔ PostgreSQL data-type coercion
  • Supported PostgreSQL features
    • Parameterized queries
    • Named statements with query plan caching
    • Async notifications with LISTEN/NOTIFY
    • Bulk import & export with COPY TO/COPY FROM

Extras

node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture. The entire list can be found on our wiki.

Support

node-postgres is free software. If you encounter a bug with the library please open an issue on the GitHub repo. If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better!

When you open an issue please provide:

  • version of Node
  • version of Postgres
  • smallest possible snippet of code to reproduce the problem

You can also follow me @briancarlson if that's your thing. I try to always announce noteworthy changes & developments with node-postgres on Twitter.

Sponsorship :two_hearts:

node-postgres's continued development has been made possible in part by generous financial support from the community.

If you or your company are benefiting from node-postgres and would like to help keep the project financially sustainable please consider supporting its development.

Contributing

:heart: contributions!

I will happily accept your pull request if it:

  • has tests
  • looks reasonable
  • does not break backwards compatibility

If your change involves breaking backwards compatibility please please point that out in the pull request & we can discuss & plan when and how to release it and what type of documentation or communication it will require.

Setting up for local development

  1. Clone the repo
  2. From your workspace root run yarn and then yarn lerna bootstrap
  3. Ensure you have a PostgreSQL instance running with SSL enabled and an empty database for tests
  4. Ensure you have the proper environment variables configured for connecting to the instance
  5. Run yarn test to run all the tests

Troubleshooting and FAQ

The causes and solutions to common errors can be found among the Frequently Asked Questions (FAQ)

License

Copyright (c) 2010-2020 Brian Carlson (brian.m.carlson@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days