Skip to content

Commit

Permalink
build
Browse files Browse the repository at this point in the history
  • Loading branch information
porsager committed Sep 12, 2023
1 parent 8b8a133 commit 519575a
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 13 deletions.
2 changes: 1 addition & 1 deletion cf/src/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
try {
x = options.socket
? (await Promise.resolve(options.socket(options)))
: net.Socket()
: new net.Socket()
} catch (e) {
error(e)
return
Expand Down
2 changes: 1 addition & 1 deletion cjs/src/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
try {
x = options.socket
? (await Promise.resolve(options.socket(options)))
: net.Socket()
: new net.Socket()
} catch (e) {
error(e)
return
Expand Down
2 changes: 1 addition & 1 deletion cjs/tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2352,7 +2352,7 @@ t('Custom socket', {}, async() => {
let result
const sql = postgres({
socket: () => new Promise((resolve, reject) => {
const socket = net.Socket()
const socket = new net.Socket()
socket.connect(5432)
socket.once('data', x => result = x[0])
socket.on('error', reject)
Expand Down
54 changes: 46 additions & 8 deletions deno/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ async function insertUser({ name, age }) {
* [Teardown / Cleanup](#teardown--cleanup)
* [Error handling](#error-handling)
* [TypeScript support](#typescript-support)
* [Reserving connections](#reserving-connections)
* [Changelog](./CHANGELOG.md)


Expand Down Expand Up @@ -171,14 +172,23 @@ const user = {
age: 68
}

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

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

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

await sql`
insert into users ${
sql(user, columns)
}
`
```

**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.
Expand Down Expand Up @@ -218,7 +228,7 @@ const user = {
age: 68
}

sql`
await sql`
update users set ${
sql(user, 'name', 'age')
}
Expand All @@ -227,10 +237,20 @@ sql`

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

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

await sql`
update users set ${
sql(user, columns)
}
where user_id = ${ user.id }
`
```

### Multiple updates in one query
It's possible to create multiple udpates in a single query. It's necessary to use arrays intead of objects to ensure the order of the items so that these correspond with the column names.
To create multiple updates in a single query, it is necessary to use arrays instead of objects to ensure that the order of the items correspond with the column names.
```js
const users = [
[1, 'John', 34],
Expand Down Expand Up @@ -575,6 +595,7 @@ const [user, account] = await sql.begin(async sql => {
) values (
'Murray'
)
returning *
`

const [account] = await sql`
Expand All @@ -583,12 +604,15 @@ const [user, account] = await sql.begin(async sql => {
) values (
${ user.user_id }
)
returning *
`

return [user, account]
})
```

Do note that you can often achieve the same result using [`WITH` queries (Common Table Expressions)](https://www.postgresql.org/docs/current/queries-with.html) instead of using transactions.

It's also possible to pipeline the requests in a transaction if needed by returning an array with queries from the callback function like this:

```js
Expand Down Expand Up @@ -634,9 +658,9 @@ sql.begin('read write', async sql => {
```


#### PREPARE `await sql.prepare([name]) -> fn()`
#### PREPARE TRANSACTION `await sql.prepare([name]) -> fn()`

Indicates that the transactions should be prepared using the `PREPARED TRANASCTION [NAME]` statement
Indicates that the transactions should be prepared using the [`PREPARE TRANSACTION [NAME]`](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) statement
instead of being committed.

```js
Expand All @@ -653,8 +677,6 @@ sql.begin('read write', async sql => {
})
```

Do note that you can often achieve the same result using [`WITH` queries (Common Table Expressions)](https://www.postgresql.org/docs/current/queries-with.html) instead of using transactions.

## Data Transformation

Postgres.js allows for transformation of the data passed to or returned from a query by using the `transform` option.
Expand Down Expand Up @@ -937,7 +959,7 @@ const sql = postgres('postgres://username:password@host:port/database', {
connect_timeout : 30, // Connect timeout in seconds
prepare : true, // Automatic creation of prepared statements
types : [], // Array of custom types, see more below
onnotice : fn, // Defaults to console.log
onnotice : fn, // Default console.log, set false to silence NOTICE
onparameter : fn, // (key, value) when server param change
debug : fn, // Is called with (connection, query, params, types)
socket : fn, // fn returning custom socket to use
Expand Down Expand Up @@ -1147,6 +1169,22 @@ prexit(async () => {
})
```

## Reserving connections

### `await sql.reserve()`

The `reserve` method pulls out a connection from the pool, and returns a client that wraps the single connection. This can be used for running queries on an isolated connection.

```ts
const reserved = await sql.reserve()
await reserved`select * from users`
await reserved.release()
```

### `reserved.release()`

Once you have finished with the reserved connection, call `release` to add it back to the pool.

## Error handling

Errors are all thrown to related queries and never globally. Errors coming from database itself are always in the [native Postgres format](https://www.postgresql.org/docs/current/errcodes-appendix.html), and the same goes for any [Node.js errors](https://nodejs.org/api/errors.html#errors_common_system_errors) eg. coming from the underlying connection.
Expand Down
2 changes: 1 addition & 1 deletion deno/src/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
try {
x = options.socket
? (await Promise.resolve(options.socket(options)))
: net.Socket()
: new net.Socket()
} catch (e) {
error(e)
return
Expand Down
2 changes: 1 addition & 1 deletion deno/tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2354,7 +2354,7 @@ t('Custom socket', {}, async() => {
let result
const sql = postgres({
socket: () => new Promise((resolve, reject) => {
const socket = net.Socket()
const socket = new net.Socket()
socket.connect(5432)
socket.once('data', x => result = x[0])
socket.on('error', reject)
Expand Down
6 changes: 6 additions & 0 deletions deno/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,8 @@ declare namespace postgres {
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
file<T extends readonly any[] = Row[]>(path: string | Buffer | URL | number, args: (ParameterOrJSON<TTypes[keyof TTypes]>)[], options?: { cache?: boolean | undefined } | undefined): PendingQuery<T>;
json(value: JSONValue): Parameter;

reserve(): Promise<ReservedSql<TTypes>>
}

interface UnsafeQueryOptions {
Expand All @@ -701,6 +703,10 @@ declare namespace postgres {

prepare<T>(name: string): Promise<UnwrapPromiseArray<T>>;
}

interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
release(): void;
}
}

export = postgres;

0 comments on commit 519575a

Please sign in to comment.