### Example: Using onConnect for setup commands Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx A JavaScript example illustrating the use of the `onConnect` configuration option to execute setup SQL commands on each newly created client within the pool. ```javascript import { Pool } from 'pg' const pool = new Pool({ onConnect: async (client) => { await client.query('SET search_path TO my_schema') }, }) ``` -------------------------------- ### Client Initialization Example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx An example demonstrating how to create a new Client instance with specific connection configuration details. ```javascript import { Client } from 'pg' const client = new Client({ user: 'database-user', password: 'secretpassword!!', host: 'my.database-server.com', port: 5334, database: 'database-name', }) ``` -------------------------------- ### Install pg and pg-native Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/native.mdx Command to install the necessary packages. ```sh $ npm install pg pg-native ``` -------------------------------- ### Client Connection Example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Example of connecting a Client instance to the database. ```javascript import { Client } from 'pg' const client = new Client() await client.connect() ``` -------------------------------- ### Route Example Using DB Adapter Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/project-structure.md An example of a route file (`routes/user.js`) that requires the custom database adapter instead of `pg` directly. ```javascript // notice here I'm requiring my database adapter file // and not requiring node-postgres directly import * as db from '../db/index.js' app.get('/:id', async (req, res, next) => { const result = await db.query('SELECT * FROM users WHERE id = $1', [req.params.id]) res.send(result.rows[0]) }) // ... many other routes in this file ``` -------------------------------- ### Install pg-cursor Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/cursor.mdx Install the pg-cursor package using npm. ```bash $ npm install pg pg-cursor ``` -------------------------------- ### Install node-postgres Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/index.mdx Install the node-postgres package using npm. ```bash $ npm install pg ``` -------------------------------- ### Install pg-pool Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Install the pg-pool package and the pg driver. ```sh npm i pg-pool pg ``` -------------------------------- ### Example: Creating a new pool with configuration Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx A JavaScript example demonstrating how to instantiate a new Pool with various configuration options like host, user, max connections, and timeouts. ```javascript import { Pool } from 'pg' const pool = new Pool({ host: 'localhost', user: 'database-user', max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000, maxLifetimeSeconds: 60, }) ``` -------------------------------- ### installation Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-query-stream/README.md Install the pg and pg-query-stream packages. ```bash $ npm install pg --save $ npm install pg-query-stream --save ``` -------------------------------- ### Installation Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Install the pg-cloudflare package. ```bash npm i --save-dev pg-cloudflare ``` -------------------------------- ### Install pg-cursor Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cursor/README.md Install the pg-cursor package using npm. ```sh $ npm install pg-cursor ``` -------------------------------- ### Install pg-native Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Install the pg-native package using npm. ```sh $ npm i pg-native ``` -------------------------------- ### Connect Event Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example demonstrating the 'connect' event, fired when a new pg.Client instance is created and connected. ```javascript const Pool = require('pg-pool') const pool = new Pool() const count = 0 pool.on('connect', (client) => { client.count = count++ }) pool .connect() .then((client) => { return client .query('SELECT $1::int AS "clientCount"', [client.count]) .then((res) => console.log(res.rows[0].clientCount)) // outputs 0 .then(() => client) }) .then((client) => client.release()) ``` -------------------------------- ### Install dependencies Source: https://github.com/brianc/node-postgres/blob/master/docs/README.md Clone the repository and install the dependencies using yarn. ```bash cd docs yarn ``` -------------------------------- ### Query Execution Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Shows how to execute a simple query to get the current timestamp and a parameterized query with a single string value. ```javascript const client = new Client() client.connect(function(err) { if (err) throw err client.query('SELECT NOW()', function(err, rows) { if (err) throw err console.log(rows) // [{ "now": "Tue Sep 16 2014 23:42:39 GMT-0400 (EDT)" }] client.query('SELECT $1::text as name', ['Brian'], function(err, rows) { if (err) throw err console.log(rows) // [{ "name": "Brian" }] client.end() }) }) }) ``` -------------------------------- ### Install postgres Source: https://github.com/brianc/node-postgres/blob/master/LOCAL_DEV.md Installs postgresql using homebrew. ```sh brew install postgresql ``` -------------------------------- ### Run development server Source: https://github.com/brianc/node-postgres/blob/master/docs/README.md Start the development server to view the documentation locally. ```bash yarn dev ``` -------------------------------- ### Install node-postgres Source: https://github.com/brianc/node-postgres/blob/master/packages/pg/README.md Install the node-postgres package using npm. This is the first step to using the library in your Node.js project. ```sh npm install pg ``` -------------------------------- ### Programmatic connection configuration Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/connecting.mdx This example demonstrates configuring a pool or client programmatically with connection information. ```javascript import pg from 'pg' const { Pool, Client } = pg const pool = new Pool({ user: 'dbuser', password: 'secretpassword', host: 'database.server.com', port: 3211, database: 'mydb', }) console.log(await pool.query('SELECT NOW()')) const client = new Client({ user: 'dbuser', password: 'secretpassword', host: 'database.server.com', port: 3211, database: 'mydb', }) await client.connect() console.log(await client.query('SELECT NOW()')) await client.end() ``` -------------------------------- ### Synchronous Connect Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Shows how to synchronously connect to a PostgreSQL backend server. ```javascript const client = new Client() client.connectSync() ``` -------------------------------- ### Prepare Statement Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates how to prepare a named statement for later execution. ```javascript const client = new Client() client.connect(function(err) { if(err) throw err client.prepare('prepared_statement', 'SELECT $1::text as name', 1, function(err) { if(err) throw err console.log('statement prepared') client.end() }) }) ``` -------------------------------- ### Connecting using environment variables Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/connecting.mdx This example shows how to connect to a PostgreSQL server using environment variables for connection information. ```javascript import pg from 'pg' const { Pool, Client } = pg // pools will use environment variables // for connection information const pool = new Pool() // you can also use async/await const res = await pool.query('SELECT NOW()') await pool.end() // clients will also use environment variables // for connection information const client = new Client() await client.connect() const res = await client.query('SELECT NOW()') await client.end() ``` ```sh $ PGUSER=dbuser \ PGPASSWORD=secretpassword \ PGHOST=database.server.com \ PGPORT=3211 \ PGDATABASE=mydb \ node script.js ``` -------------------------------- ### Using native bindings Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/native.mdx Example of how to import and use native Client and Pool constructors. ```js import pg from 'pg' const { native } = pg const { Client, Pool } = native ``` -------------------------------- ### Connect, Query, and Disconnect with Async/Await Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/index.mdx A simple example demonstrating how to connect to a PostgreSQL database, execute a query, and disconnect using async/await. ```js import { Client } from 'pg' const client = await new Client().connect() const res = await client.query('SELECT $1::text as message', ['Hello world!']) console.log(res.rows[0].message) // Hello world! await client.end() ``` -------------------------------- ### Async/await example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example of using pg-pool with async/await for cleaner asynchronous code. ```js // with async/await ;(async () => { const pool = new Pool() const client = await pool.connect() try { const result = await client.query('select $1::text as name', ['brianc']) console.log('hello from', result.rows[0]) } finally { client.release() } })().catch((e) => console.error(e.message, e.stack)) ``` -------------------------------- ### ESM Import Example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/esm.mdx Example of how to import the 'pg' module using ESM. ```javascript import { Client } from 'pg' // etc... ``` -------------------------------- ### Client Connection Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates how to connect to a PostgreSQL database using the Client class, both with default and connection string parameters. ```javascript const client = new Client() client.connect(function(err) { if(err) throw err console.log('connected!') }) const client2 = new Client() client2.connect('postgresql://user:password@host:5432/database?param=value', function(err) { if(err) throw err console.log('connected with connection string!') }) ``` -------------------------------- ### Start Postgres server Source: https://github.com/brianc/node-postgres/blob/master/LOCAL_DEV.md Starts the Postgres server with the specified data directory. ```sh /opt/homebrew/opt/postgresql@14/bin/postgres -D /opt/homebrew/var/postgresql@14 ``` -------------------------------- ### Synchronous Prepare Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Illustrates synchronous preparation of a named statement. ```javascript const client = new Client() client.prepareSync('prepared_statement', 'SELECT $1::text as name', 1) ``` -------------------------------- ### Execute Prepared Statement Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Shows how to execute a previously prepared statement with provided values. ```javascript const client = new Client() client.connect(function(err) { if(err) throw err client.prepare('i_like_beans', 'SELECT $1::text as beans', 1, function(err) { if(err) throw err client.execute('i_like_beans', ['Brak'], function(err, rows) { if(err) throw err console.log(rows) // [{ "i_like_beans": "Brak" }] client.end() }) }) }) ``` -------------------------------- ### Example calculation of maxUses Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md An example calculation demonstrating how to determine maxUses with specific values for rebalancing window, total requests per second, number of app instances, and pool size. ```text maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize 7200 = 1800 * 1000 / 10 / 25 ``` -------------------------------- ### Callback query example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example of using the pool.query method with a callback function. ```js const pool = new Pool() pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { console.log(res.rows[0].name) // brianc }) ``` -------------------------------- ### Client End Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates how to properly end the database connection. ```javascript const client = new Client() client.connect(function(err) { if(err) throw err client.end(function() { console.log('client ended') // client ended }) }) ``` -------------------------------- ### Connection URI initialization Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/connecting.mdx This example shows how to initialize a pool or client with a connection string URI, common in environments like Heroku. ```javascript import pg from 'pg' const { Pool, Client } = pg const connectionString = 'postgresql://dbuser:secretpassword@database.server.com:3211/mydb' const pool = new Pool({ connectionString, }) await pool.query('SELECT NOW()') await pool.end() const client = new Client({ connectionString, }) await client.connect() await client.query('SELECT NOW()') await client.end() ``` -------------------------------- ### co example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example of using pg-pool with the 'co' library for generator-based asynchronous operations. ```js // with co co(function* () { const client = yield pool.connect() try { const result = yield client.query('select $1::text as name', ['brianc']) console.log('hello from', result.rows[0]) } finally { client.release() } }).catch((e) => console.error(e.message, e.stack)) ``` -------------------------------- ### Acquire Event Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example demonstrating the 'acquire' event, fired whenever a client is acquired from the pool, used here to count acquired clients. ```javascript const Pool = require('pg-pool') const pool = new Pool() const acquireCount = 0 pool.on('acquire', function (client) { acquireCount++ }) const connectCount = 0 pool.on('connect', function () { connectCount++ }) for (let i = 0; i < 200; i++) { pool.query('SELECT NOW()') } setTimeout(function () { console.log('connect count:', connectCount) // output: connect count: 10 console.log('acquire count:', acquireCount) // output: acquire count: 200 }, 100) ``` -------------------------------- ### CommonJS Import Example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/esm.mdx Example of how to import the 'pg' module using CommonJS. ```javascript const pg = require('pg') const { Client } = pg // etc... ``` -------------------------------- ### Releasing a client Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx Example showing how to acquire a client and then release it back to the pool. ```javascript import { Pool } from 'pg' const pool = new Pool() // check out a single client const client = await pool.connect() // release the client client.release() ``` -------------------------------- ### Synchronous Query Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates synchronous query execution. ```javascript const client = new Client() const results = client.querySync('SELECT NOW()') ``` -------------------------------- ### Using a Connection Pool Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/index.mdx An example of how to use a connection pool to manage database connections efficiently. This is recommended for most applications. ```js import { Pool } from 'pg' const pool = new Pool() const res = await pool.query('SELECT $1::text as message', ['Hello world!']) console.log(res.rows[0].message) // Hello world! ``` -------------------------------- ### Using pool.connect Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx An example demonstrating how to acquire a client from the pool using pool.connect, execute a query, and then release the client. ```javascript import { Pool } from 'pg' const pool = new Pool() const client = await pool.connect() await client.query('SELECT NOW()') client.release() ``` -------------------------------- ### Synchronous Execute Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Shows how to synchronously execute a previously prepared statement. ```javascript const client = new Client() const results = client.executeSync('prepared_statement', ['Brian']) ``` -------------------------------- ### Sync Usage Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates synchronous connection, text queries, parameterized queries, and prepared statements. ```javascript const Client = require('pg-native') const client = new Client() client.connectSync() // text queries const rows = client.querySync('SELECT NOW() AS the_date') console.log(rows[0].the_date) // Tue Sep 16 2014 23:42:39 GMT-0400 (EDT) // parameterized queries const rows = client.querySync('SELECT $1::text as twitter_handle', ['@briancarlson']) console.log(rows[0].twitter_handle) // @briancarlson // prepared statements client.prepareSync('get_twitter', 'SELECT $1::text as twitter_handle', 1) const rows = client.executeSync('get_twitter', ['@briancarlson']) console.log(rows[0].twitter_handle) // @briancarlson const rows = client.executeSync('get_twitter', ['@realcarrotfacts']) console.log(rows[0].twitter_handle) // @realcarrotfacts ``` -------------------------------- ### Async Usage Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Demonstrates asynchronous connection, text queries, parameterized statements, and prepared statements. ```javascript const Client = require('pg-native') const client = new Client(); client.connect(function(err) { if(err) throw err // text queries client.query('SELECT NOW() AS the_date', function(err, rows) { if(err) throw err console.log(rows[0].the_date) // Tue Sep 16 2014 23:42:39 GMT-0400 (EDT) // parameterized statements client.query('SELECT $1::text as twitter_handle', ['@briancarlson'], function(err, rows) { if(err) throw err console.log(rows[0].twitter_handle) //@briancarlson }) // prepared statements client.prepare('get_twitter', 'SELECT $1::text as twitter_handle', 1, function(err) { if(err) throw err // execute the prepared, named statement client.execute('get_twitter', ['@briancarlson'], function(err, rows) { if(err) throw err console.log(rows[0].twitter_handle) //@briancarlson // execute the prepared, named statement again client.execute('get_twitter', ['@realcarrotfacts'], function(err, rows) { if(err) throw err console.log(rows[0].twitter_handle) // @realcarrotfacts client.end(function() { console.log('ended') }) }) }) }) }) }) ``` -------------------------------- ### client.end example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Shows how to disconnect the client from the PostgreSQL server. ```javascript await client.end() console.log('client has disconnected') ``` -------------------------------- ### Instantiate a new Cursor Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/cursor.mdx Example of instantiating a new Cursor and using it to query data. ```javascript import { Pool } from 'pg' import Cursor from 'pg-cursor' const pool = new Pool() const client = await pool.connect() const text = 'SELECT * FROM my_large_table WHERE something > $1' const values = [10] const cursor = client.query(new Cursor(text, values)) const { rows } = await cursor.read(100) console.log(rows.length) // 100 (unless the table has fewer than 100 rows) client.release() ``` -------------------------------- ### Parameterized query example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Shows how to execute a SQL query with parameters using the client.query method. ```javascript import { Client } from 'pg' const client = new Client() await client.connect() const result = await client.query('SELECT $1::text as name', ['brianc']) console.log(result) await client.end() ``` -------------------------------- ### client.query with a QueryConfig example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Illustrates using a QueryConfig object with the client.query method, including prepared statements. ```javascript const query = { name: 'get-name', text: 'SELECT $1::text', values: ['brianc'], rowMode: 'array', } const result = await client.query(query) console.log(result.rows) // ['brianc'] await client.end() ``` -------------------------------- ### Transaction Example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/transactions.mdx Demonstrates how to perform a transaction using BEGIN, COMMIT, and ROLLBACK queries with a single client instance. ```javascript import { Pool } from 'pg' const pool = new Pool() const client = await pool.connect() try { await client.query('BEGIN') const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id' const res = await client.query(queryText, ['brianc']) const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)' const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo'] await client.query(insertPhotoText, insertPhotoValues) await client.query('COMMIT') } catch (e) { await client.query('ROLLBACK') throw e } finally { client.release() } ``` -------------------------------- ### Mounting Individual Routers Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/async-express.md Example of a main routes index file that mounts individual routers into the application. ```javascript // ./routes/index.js import users from './user.js' import photos from './photos.js' const mountRoutes = (app) => { app.use('/users', users) app.use('/photos', photos) // etc.. } export default mountRoutes ``` -------------------------------- ### Run Tests with Specific Host Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Example of supplying a specific host for the tests using environment variables. ```sh $ PGHOST=blabla.mydatabasehost.com npm test ``` -------------------------------- ### Checking transaction state example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Demonstrates using getTransactionStatus to monitor the client's transaction state. ```javascript import { Client } from 'pg' const client = new Client() await client.connect() await client.query('BEGIN') console.log(client.getTransactionStatus()) // 'T' - in transaction await client.query('SELECT * FROM users') console.log(client.getTransactionStatus()) // 'T' - still in transaction await client.query('COMMIT') console.log(client.getTransactionStatus()) // 'I' - idle await client.end() ``` -------------------------------- ### Plain text query example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Demonstrates executing a simple SQL query using the client.query method with a plain text string. ```javascript import { Client } from 'pg' const client = new Client() await client.connect() const result = await client.query('SELECT NOW()') console.log(result) await client.end() ``` -------------------------------- ### Destroying a client Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx Example demonstrating how to acquire a client and then explicitly destroy it using client.release(true), which removes it from the pool. ```javascript import { Pool } from 'pg' const pool = new Pool() assert(pool.totalCount === 0) assert(pool.idleCount === 0) const client = await pool.connect() await client.query('SELECT NOW()') assert(pool.totalCount === 1) assert(pool.idleCount === 0) // tell the pool to destroy this client await client.release(true) assert(pool.idleCount === 0) assert(pool.totalCount === 0) ``` -------------------------------- ### client.query with a Submittable example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Demonstrates using a Submittable object (like pg-cursor or pg-query-stream) with client.query for advanced query dispatching. ```javascript import { Query } from 'pg' const query = new Query('select $1::text as name', ['brianc']) const result = client.query(query) assert(query === result) // true query.on('row', (row) => { console.log('row!', row) // { name: 'brianc' } }) query.on('end', () => { console.log('query done') }) query.on('error', (err) => { console.error(err.stack) }) ``` -------------------------------- ### Tearing down a client pool Source: https://github.com/brianc/node-postgres/wiki/Testing Example of how to tear down a client pool by connecting and then ending the client. ```javascript tearDown: function() { var connectionString = /*whatever connection you use for testing*/ pg.connect(connectionString, function(err, client) { client.end() }); } ``` -------------------------------- ### Connecting via Unix Domain Sockets Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/connecting.mdx This example demonstrates connecting to unix sockets, which can be useful on distros like Ubuntu where authentication is managed via the socket connection. ```javascript import pg from 'pg' const { Client } = pg client = new Client({ user: 'username', password: 'password', host: '/cloudsql/myproject:zone:mydb', database: 'database_name', }) ``` -------------------------------- ### SSL Options Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/announcements.mdx Example demonstrating how to pass SSL options to the client constructor. It highlights the change in default behavior regarding `rejectUnauthorized` and provides a workaround for the old behavior. ```javascript const client = new Client({ ssl: true }) ``` ```javascript const client = new Client({ ssl: { rejectUnauthorized: false } }) ``` -------------------------------- ### Basic DB Index File Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/project-structure.md Initial setup for the `db/index.js` file to export a query function using a connection pool. ```javascript import { Pool } from 'pg' const pool = new Pool() export const query = (text, params) => { return pool.query(text, params) } ``` -------------------------------- ### Parameterized query example against SQL injection Source: https://github.com/brianc/node-postgres/wiki/FAQ An example demonstrating how parameterized queries prevent SQL injection. ```javascript client.query("INSERT INTO user(name) VALUES($1)", ["'; DROP TABLE user;"]) ``` -------------------------------- ### Getting the count of columns Source: https://github.com/brianc/node-postgres/wiki/FAQ Demonstrates how to get the total number of columns in the result set using result.fields.length. ```javascript const result = await client.query(...); const columnCount = result.fields.length; ``` -------------------------------- ### PowerShell fix for pg-native installation on Windows Source: https://github.com/brianc/node-postgres/wiki/FAQ A quick fix for PowerShell to add the PostgreSQL bin directory to the PATH environment variable, resolving 'pg_config --libdir' errors during pg-native installation. ```powershell $env:PATH+=";C:\Program Files\PostgreSQL\9.2\bin" npm install pg ``` -------------------------------- ### esbuild Configuration Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Example esbuild.config.js to resolve the 'workerd' condition. ```javascript await esbuild.build({ ..., conditions: [..., 'workerd'], }) ``` -------------------------------- ### Reading to the end of a cursor Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/cursor.mdx Example of reading to the end of a cursor. ```javascript import { Pool } from 'pg' import Cursor from 'pg-cursor' const pool = new Pool() const client = await pool.connect() const cursor = client.query(new Cursor('select * from generate_series(0, 5)')) let rows = await cursor.read(100) assert(rows.length == 6) rows = await cursor.read(100) assert(rows.length == 0) ``` -------------------------------- ### Client Cancel Query Example Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-native/README.md Illustrates how to cancel an active query on the client. ```javascript const client = new Client() client.connectSync() // sleep for 100 seconds client.query('select pg_sleep(100)', function(err) { console.log(err) // [Error: ERROR: canceling statement due to user request] }) client.cancel(function(err) { console.log('cancel dispatched') }) ``` -------------------------------- ### DB Index File with getClient Method Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/project-structure.md Adds a `getClient` method to `db/index.js` to allow checking out clients from the pool for transactions. ```javascript import { Pool } from 'pg' const pool = new Pool() export const query = async (text, params) => { const start = Date.now() const res = await pool.query(text, params) const duration = Date.now() - start console.log('executed query', { text, duration, rows: res.rowCount }) return res } export const getClient = () => { return pool.connect() } ``` -------------------------------- ### Text-only query Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/queries.mdx Example of executing a SQL query that does not require any parameters. ```javascript await client.query('SELECT NOW() as now') ``` -------------------------------- ### Callback Usage with Pool and Client Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/callbacks.mdx Demonstrates how to use callbacks with both Pool and Client instances for executing queries and managing connections. ```javascript const { Pool, Client } = require('pg') // pool const pool = new Pool() // run a query on an available client pool.query('SELECT NOW()', (err, res) => { console.log(err, res) }) // check out a client to do something more complex like a transaction pool.connect((err, client, release) => { client.query('SELECT NOW()', (err, res) => { release() console.log(err, res) pool.end() }) }) // single client const client = new Client() client.connect((err) => { if (err) throw err client.query('SELECT NOW()', (err, res) => { console.log(err, res) client.end() }) }) ``` -------------------------------- ### Shutting down the pool Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example of how to explicitly end the pool when you don't want to wait for the idle timeout. ```javascript const pool = new Pool() const client = await pool.connect() console.log(await client.query('select now()')) client.release() await pool.end() ``` -------------------------------- ### Handling transaction errors example Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/client.mdx Illustrates how to handle transaction errors using getTransactionStatus and ROLLBACK. ```javascript import { Client } from 'pg' const client = new Client() await client.connect() await client.query('BEGIN') try { await client.query('INVALID SQL') } catch (err) { console.log(client.getTransactionStatus()) // 'E' - error state // Must rollback to recover await client.query('ROLLBACK') console.log(client.getTransactionStatus()) // 'I' - idle again } await client.end() ``` -------------------------------- ### Using pool.end Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/apis/pool.mdx An example of how to gracefully shut down the pool by calling pool.end(), which disconnects all active clients. ```javascript // again both promises and callbacks are supported: import { Pool } from 'pg' const pool = new Pool() await pool.end() ``` -------------------------------- ### Rollup Configuration Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Example rollup.config.js to resolve the 'workerd' condition and exclude 'cloudflare:sockets' from bundling. ```javascript export default defineConfig({ ..., plugins: [..., nodeResolve({ exportConditions: [..., 'workerd'] })], // don't try to bundle cloudflare:sockets external: [..., 'cloudflare:sockets'], }) ``` -------------------------------- ### Vite Configuration Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Example vite.config.js to resolve the 'workerd' condition and exclude 'cloudflare:sockets' from bundling. ```javascript export default defineConfig({ ..., resolve: { conditions: [..., "workerd"], }, build: { ..., // don't try to bundle cloudflare:sockets rollupOptions: { external: [..., 'cloudflare:sockets'], }, }, }) ``` -------------------------------- ### Webpack Configuration Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Example webpack.config.js to resolve the 'workerd' condition and ignore 'cloudflare:sockets' imports. ```javascript export default { ..., resolve: { conditionNames: [..., "workerd"] }, plugins: [ // ignore cloudflare:sockets imports new webpack.IgnorePlugin({ resourceRegExp: /^cloudflare:sockets$/, }), ] } ``` -------------------------------- ### Checkout, use, and return Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/pooling.mdx Demonstrates how to check out a client from the pool, execute a query, and then release the client back to the pool. ```javascript import pg from 'pg' const { Pool } = pg const pool = new Pool() // the pool will emit an error on behalf of any idle clients // it contains if a backend error or network partition happens pool.on('error', (err, client) => { console.error('Unexpected error on idle client', err) process.exit(-1) }) const client = await pool.connect() const res = await client.query('SELECT * FROM users WHERE id = $1', [1]) console.log(res.rows[0]) client.release() ``` -------------------------------- ### Error Event Handling Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-pool/README.md Example of attaching an error handler to the pool for when an idle client encounters an error. ```javascript const Pool = require('pg-pool') const pool = new Pool() // attach an error handler to the pool for when a connected, idle client // receives an error by being disconnected, etc pool.on('error', function (error, client) { // handle this in the same way you would treat process.on('uncaughtException') // it is supplied the error as well as the idle client which received the error }) ``` -------------------------------- ### Express Application Bootstrap Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/async-express.md The main application file that bootstraps Express and mounts all defined routes. ```javascript // ./app.js import express from 'express' import mountRoutes from './routes.js' const app = express() mountRoutes(app) // ... more express setup stuff can follow ``` -------------------------------- ### Migrating from pg singleton to Pool Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/guides/upgrading.md Illustrates the old, deprecated method of using the global pg singleton for connections and the new, recommended approach using a user-managed Pool. ```javascript // old way, deprecated in 6.3.0: // connection using global singleton pg.connect(function (err, client, done) { client.query(/* etc, etc */) done() }) // singleton pool shutdown pg.end() // ------------------ // new way, available since 6.0.0: // create a pool const pool = new pg.Pool() // connection using created pool pool.connect(function (err, client, done) { client.query(/* etc, etc */) done() }) // pool shutdown pool.end() ``` -------------------------------- ### Dynamic passwords with callback function Source: https://github.com/brianc/node-postgres/blob/master/docs/pages/features/connecting.mdx This example shows how node-postgres supports dynamic passwords via a callback function, useful for cloud providers using short-lived authentication tokens. ```javascript import pg from 'pg' const { Pool } = pg import { RDS } from 'aws-sdk' const signerOptions = { credentials: { accessKeyId: 'YOUR-ACCESS-KEY', secretAccessKey: 'YOUR-SECRET-ACCESS-KEY', }, region: 'us-east-1', hostname: 'example.aslfdewrlk.us-east-1.rds.amazonaws.com', port: 5432, username: 'api-user', } const signer = new RDS.Signer(signerOptions) const getPassword = () => signer.getAuthToken() const pool = new Pool({ user: signerOptions.username, password: getPassword, host: signerOptions.hostname, port: signerOptions.port, database: 'my-db', }) ``` -------------------------------- ### Conditional Usage in Non-Node.js Environments Source: https://github.com/brianc/node-postgres/blob/master/packages/pg-cloudflare/README.md Example of how to conditionally use 'net' in Node.js and 'pg-cloudflare' in non-Node.js environments. ```javascript module.exports.getStream = function getStream(ssl = false) { const net = require('net') if (typeof net.Socket === 'function') { return net.Socket() } const { CloudflareSocket } = require('pg-cloudflare') return new CloudflareSocket(ssl) } ```