Skip to content

Commit

Permalink
Merge origin/master
Browse files Browse the repository at this point in the history
  • Loading branch information
brianc committed Dec 27, 2019
2 parents 766e48f + 47af4e8 commit 68e063e
Show file tree
Hide file tree
Showing 31 changed files with 2,440 additions and 17 deletions.
12 changes: 12 additions & 0 deletions .devcontainer/Dockerfile
Expand Up @@ -32,7 +32,11 @@ RUN apt-get update \
&& curl -sS https://dl.yarnpkg.com/$(lsb_release -is | tr '[:upper:]' '[:lower:]')/pubkey.gpg | apt-key add - 2>/dev/null \
&& echo "deb https://dl.yarnpkg.com/$(lsb_release -is | tr '[:upper:]' '[:lower:]')/ stable main" | tee /etc/apt/sources.list.d/yarn.list \
&& apt-get update \
<<<<<<< HEAD
&& apt-get -y install --no-install-recommends yarn tmux locales postgresql \
=======
&& apt-get -y install --no-install-recommends yarn tmux locales \
>>>>>>> origin/master
#
# Install eslint globally
&& npm install -g eslint \
Expand All @@ -58,6 +62,14 @@ RUN curl https://raw.githubusercontent.com/brianc/dotfiles/master/.tmux.conf > ~
# install nvm
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

<<<<<<< HEAD
=======
# set up a nicer prompt
RUN git clone https://github.com/magicmonty/bash-git-prompt.git ~/.bash-git-prompt --depth=1

RUN echo "source $HOME/.bash-git-prompt/gitprompt.sh" >> ~/.bashrc

>>>>>>> origin/master
# Set the locale
RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
Expand Down
3 changes: 3 additions & 0 deletions .github/FUNDING.yml
@@ -0,0 +1,3 @@
# These are supported funding model platforms

github: [brianc]
29 changes: 18 additions & 11 deletions README.md
Expand Up @@ -7,15 +7,22 @@

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

## Install
## Monorepo

```sh
$ npm install pg
```
This repo is a monorepo which contains the core [pg](https://github.com/brianc/node-postgres/tree/master/packages/pg) module as well as a handful of related modules.

---
## :star: [Documentation](https://node-postgres.com) :star:
- [pg](https://github.com/brianc/node-postgres/tree/master/packages/pg)
- [pg-cursor](https://github.com/brianc/node-postgres/tree/master/packages/pg-cursor)
- [pg-query-stream](https://github.com/brianc/node-postgres/tree/master/packages/pg-query-stream)

_(more to come, I'm in the process of migrating repos over here)_


## Documenation

Each package in this repo should have it's 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](https://node-postgres.com) :star:

### Features

Expand Down Expand Up @@ -44,13 +51,11 @@ When you open an issue please provide:

You can also follow me [@briancarlson](https://twitter.com/briancarlson) if that's your thing. I try to always announce noteworthy changes & developments with node-postgres on Twitter.

### Professional Support

I offer professional support for node-postgres. I provide implementation, training, and many years of expertise on how to build applications with Node, Express, PostgreSQL, and React/Redux. Please contact me at [brian.m.carlson@gmail.com](mailto:brian.m.carlson@gmail.com) to discuss how I can help your company be more successful!

### Sponsorship :star:

If you are benefiting from node-postgres and would like to help keep the project financially sustainable please visit Brian Carlson's [Patreon page](https://www.patreon.com/node_postgres).
[If you or your company are benefiting from node-postgres and would like to help keep the project financially sustainable please consider supporting](https://github.com/sponsors/brianc) its development.

Also, you can view a historical list of all [previous and existing sponsors](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md).

## Contributing

Expand All @@ -61,6 +66,8 @@ I will __happily__ accept your pull request if it:
- 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 communicate it will require.

## Troubleshooting and FAQ

The causes and solutions to common errors can be found among the [Frequently Asked Questions (FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ)
Expand Down
5 changes: 4 additions & 1 deletion lerna.json
Expand Up @@ -4,5 +4,8 @@
],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent"
"version": "independent",
"ignoreChanges": [
"**/*.md"
]
}
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -10,7 +10,7 @@
"packages/*"
],
"scripts": {
"test": "yarn lerna exec --parallel yarn test",
"test": "yarn lerna exec yarn test",
"lint": "yarn lerna exec --parallel yarn lint"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions packages/pg-cursor/package.json
@@ -1,6 +1,6 @@
{
"name": "pg-cursor",
"version": "2.0.2",
"version": "2.0.3",
"description": "Query cursor extension for node-postgres",
"main": "index.js",
"directories": {
Expand All @@ -21,7 +21,7 @@
"eslint-config-prettier": "^6.4.0",
"eslint-plugin-prettier": "^3.1.1",
"mocha": "^6.2.2",
"pg": "^7.15.1",
"pg": "^7.15.2",
"prettier": "^1.18.2"
},
"prettier": {
Expand Down
1 change: 1 addition & 0 deletions packages/pg-query-stream/.gitignore
@@ -0,0 +1 @@
node_modules
9 changes: 9 additions & 0 deletions packages/pg-query-stream/LICENSE
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2013 Brian M. Carlson

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.
68 changes: 68 additions & 0 deletions packages/pg-query-stream/README.md
@@ -0,0 +1,68 @@
# pg-query-stream

[![Build Status](https://travis-ci.org/brianc/node-pg-query-stream.svg)](https://travis-ci.org/brianc/node-pg-query-stream)

Receive result rows from [pg](https://github.com/brianc/node-postgres) as a readable (object) stream.


## installation

```bash
$ npm install pg --save
$ npm install pg-query-stream --save
```

_requires pg>=2.8.1_


## use

```js
const pg = require('pg')
const QueryStream = require('pg-query-stream')
const JSONStream = require('JSONStream')

//pipe 1,000,000 rows to stdout without blowing up your memory usage
pg.connect((err, client, done) => {
if (err) throw err;
const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [1000000])
const stream = client.query(query)
//release the client when the stream is finished
stream.on('end', done)
stream.pipe(JSONStream.stringify()).pipe(process.stdout)
})
```

The stream uses a cursor on the server so it efficiently keeps only a low number of rows in memory.

This is especially useful when doing [ETL](http://en.wikipedia.org/wiki/Extract,_transform,_load) on a huge table. Using manual `limit` and `offset` queries to fake out async itteration through your data is cumbersome, and _way way way_ slower than using a cursor.

_note: this module only works with the JavaScript client, and does not work with the native bindings. libpq doesn't expose the protocol at a level where a cursor can be manipulated directly_

## contribution

I'm very open to contribution! Open a pull request with your code or idea and we'll talk about it. If it's not way insane we'll merge it in too: isn't open source awesome?

## license

The MIT License (MIT)

Copyright (c) 2013 Brian M. Carlson

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.
61 changes: 61 additions & 0 deletions packages/pg-query-stream/index.js
@@ -0,0 +1,61 @@
'use strict'
var Cursor = require('pg-cursor')
var Readable = require('stream').Readable

class PgQueryStream extends Readable {
constructor (text, values, options) {
super(Object.assign({ objectMode: true }, options))
this.cursor = new Cursor(text, values, options)
this._reading = false
this._closed = false
this.batchSize = (options || {}).batchSize || 100

// delegate Submittable callbacks to cursor
this.handleRowDescription = this.cursor.handleRowDescription.bind(this.cursor)
this.handleDataRow = this.cursor.handleDataRow.bind(this.cursor)
this.handlePortalSuspended = this.cursor.handlePortalSuspended.bind(this.cursor)
this.handleCommandComplete = this.cursor.handleCommandComplete.bind(this.cursor)
this.handleReadyForQuery = this.cursor.handleReadyForQuery.bind(this.cursor)
this.handleError = this.cursor.handleError.bind(this.cursor)
}

submit (connection) {
this.cursor.submit(connection)
}

close (callback) {
this._closed = true
const cb = callback || (() => this.emit('close'))
this.cursor.close(cb)
}

_read (size) {
if (this._reading || this._closed) {
return false
}
this._reading = true
const readAmount = Math.max(size, this.batchSize)
this.cursor.read(readAmount, (err, rows) => {
if (this._closed) {
return
}
if (err) {
return this.emit('error', err)
}
// if we get a 0 length array we've read to the end of the cursor
if (!rows.length) {
this._closed = true
setImmediate(() => this.emit('close'))
return this.push(null)
}

// push each row into the stream
this._reading = false
for (var i = 0; i < rows.length; i++) {
this.push(rows[i])
}
})
}
}

module.exports = PgQueryStream
38 changes: 38 additions & 0 deletions packages/pg-query-stream/package.json
@@ -0,0 +1,38 @@
{
"name": "pg-query-stream",
"version": "2.0.2",
"description": "Postgres query result returned as readable stream",
"main": "index.js",
"scripts": {
"test": "mocha",
"lint": "eslint ."
},
"repository": {
"type": "git",
"url": "git://github.com/brianc/node-postgres.git"
},
"keywords": [
"postgres",
"pg",
"query",
"stream"
],
"author": "Brian M. Carlson",
"license": "MIT",
"bugs": {
"url": "https://github.com/brianc/node-postgres/issues"
},
"devDependencies": {
"JSONStream": "~0.7.1",
"concat-stream": "~1.0.1",
"eslint-plugin-promise": "^3.5.0",
"mocha": "^6.2.2",
"pg": "^7.15.2",
"stream-spec": "~0.3.5",
"stream-tester": "0.0.5",
"through": "~2.3.4"
},
"dependencies": {
"pg-cursor": "^2.0.3"
}
}
57 changes: 57 additions & 0 deletions packages/pg-query-stream/test/async-iterator.es6
@@ -0,0 +1,57 @@
const QueryStream = require('../')
const pg = require('pg')
const assert = require('assert')

const queryText = 'SELECT * FROM generate_series(0, 200) num'
describe('Async iterator', () => {
it('works', async () => {
const stream = new QueryStream(queryText, [])
const client = new pg.Client()
await client.connect()
const query = client.query(stream)
const rows = []
for await (const row of query) {
rows.push(row)
}
assert.equal(rows.length, 201)
await client.end()
})

it('can async iterate and then do a query afterwards', async () => {
const stream = new QueryStream(queryText, [])
const client = new pg.Client()
await client.connect()
const query = client.query(stream)
const iteratorRows = []
for await (const row of query) {
iteratorRows.push(row)
}
assert.equal(iteratorRows.length, 201)
const { rows } = await client.query('SELECT NOW()')
assert.equal(rows.length, 1)
await client.end()
})

it('can async iterate multiple times with a pool', async () => {
const pool = new pg.Pool({ max: 1 })

const allRows = []
const run = async () => {
// get the client
const client = await pool.connect()
// stream some rows
const stream = new QueryStream(queryText, [])
const iteratorRows = []
client.query(stream)
for await (const row of stream) {
iteratorRows.push(row)
allRows.push(row)
}
assert.equal(iteratorRows.length, 201)
client.release()
}
await Promise.all([run(), run(), run()])
assert.equal(allRows.length, 603)
await pool.end()
})
})
4 changes: 4 additions & 0 deletions packages/pg-query-stream/test/async-iterator.js
@@ -0,0 +1,4 @@
// only newer versions of node support async iterator
if (!process.version.startsWith('v8')) {
require('./async-iterator.es6')
}

0 comments on commit 68e063e

Please sign in to comment.