Skip to content

Add sql.describe() #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,20 @@ sql.file(path.join(__dirname, 'query.sql'), [], {

```

## Describe `sql.describe(stmt) -> Promise`

Describe the parameters and output columns of the given SQL statement.

```js

const { params, columns } = await sql.describe('select * from users where id = $1 and name like $2')

```

The resulting `params` is an array of Postgres data type ids (OIDs) for parameters in order `$1`, `$2`,
etc. `columns` is an array of objects `{ name, type, parser }`, where `name` is the column name, `type`
is the type OID, and `parser` is a function used to parse the value to JavaScript.

## Transactions


Expand Down
18 changes: 15 additions & 3 deletions lib/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,10 @@ function Backend({
: console.log(parseError(x)) // eslint-disable-line
}

function NoData() { /* No handling needed */ }
function NoData() {
if (backend.query.describe)
backend.query.result.columns = []
}

function Authentication(x) {
const type = x.readInt32BE(5)
Expand All @@ -174,8 +177,17 @@ function Backend({
}

/* c8 ignore next 3 */
function ParameterDescription() {
backend.error = errors.notSupported('ParameterDescription')
function ParameterDescription(x) {
const length = x.readInt16BE(5)
let index = 7

backend.query.statement.params = Array(length)

for (let i = 0; i < length; ++i) {
backend.query.statement.params[i] = x.readInt32BE(index)
index += 4
}
backend.query.result.params = backend.query.statement.params
}

function RowDescription(x) {
Expand Down
5 changes: 4 additions & 1 deletion lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ function Connection(options = {}) {
query.args = args
query.result = []
query.result.count = null
if (!query.describe) query.result.count = null
idle_timeout && clearTimeout(timer)

typeof options.debug === 'function' && options.debug(id, str, args)
Expand Down Expand Up @@ -168,7 +169,9 @@ function Connection(options = {}) {
query.statement = { name: sig ? 'p' + uid + statement_id++ : '', sig }
return Buffer.concat([
frontend.Parse(query.statement.name, str, args),
bind(query, args)
query.describe
? frontend.Describe(query.statement.name)
: bind(query, args)
])
}

Expand Down
15 changes: 13 additions & 2 deletions lib/frontend.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ const { errors } = require('./errors.js')

const N = String.fromCharCode(0)
const empty = Buffer.alloc(0)
const flushSync = Buffer.concat([
bytes.H().end(),
bytes.S().end()
])
const execute = Buffer.concat([
bytes.D().str('P').str(N).end(),
bytes.E().str(N).i32(0).end(),
bytes.H().end(),
bytes.S().end()
flushSync,
])

const authNames = {
Expand Down Expand Up @@ -39,6 +42,7 @@ module.exports = {
auth,
Bind,
Parse,
Describe,
Query,
Close,
Execute
Expand Down Expand Up @@ -190,6 +194,13 @@ function Parse(name, str, args) {
return bytes.end()
}

function Describe(name) {
return Buffer.concat([
bytes.D().str('S').str(name).str(N).end(),
flushSync,
])
}

function Execute(rows) {
return Buffer.concat([
bytes.E().str(N).i32(rows).end(),
Expand Down
7 changes: 6 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,8 @@ function Postgres(a, b) {
unsafe,
array,
file,
json
json,
describe,
})

function notify(channel, payload) {
Expand Down Expand Up @@ -316,6 +317,10 @@ function Postgres(a, b) {
return promise
}

function describe(stmt) {
return query({ raw: true, describe: true }, connection || getConnection(), stmt)
}

options.types && entries(options.types).forEach(([name, type]) => {
sql.types[name] = (x) => ({ type: type.to, value: x })
})
Expand Down
30 changes: 30 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1101,3 +1101,33 @@ t('Catches query format errors', async() => [
'wat',
await sql.unsafe({ toString: () => { throw new Error('wat') } }).catch((e) => e.message)
])

t('Describe a statement', async() => {
await sql`create table tester (name text, age int)`
const r = await sql.describe('select name, age from tester where name like $1 and age > $2')
return [
'25,23/name:25,age:23',
`${r.params.join(',')}/${r.columns.map(c => `${c.name}:${c.type}`).join(',')}`,
await sql`drop table tester`
]
})

t('Describe a statement without parameters', async() => {
await sql`create table tester (name text, age int)`
const r = await sql.describe('select name, age from tester')
return [
'0,2',
`${r.params.length},${r.columns.length}`,
await sql`drop table tester`
]
})

t('Describe a statement without columns', async () => {
await sql`create table tester (name text, age int)`
const r = await sql.describe('insert into tester (name, age) values ($1, $2)')
return [
'2,0',
`${r.params.length},${r.columns.length}`,
await sql`drop table tester`
]
})
6 changes: 6 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,11 @@ declare namespace postgres {
columns: ColumnList<U>;
}

interface DescribeResult {
params: number[]
columns: ColumnList<string>
}

type ExecutionResult<T> = [] & ResultQueryMeta<number, T>;
type RowList<T extends readonly Row[]> = T & ResultQueryMeta<T['length'], keyof T[number]>;

Expand Down Expand Up @@ -318,6 +323,7 @@ declare namespace postgres {
PostgresError: typeof PostgresError;

array<T extends SerializableParameter[] = SerializableParameter[]>(value: T): ArrayParameter<T>;
describe(stmt: string): Promise<DescribeResult>
begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
end(options?: { timeout?: number }): Promise<void>;
Expand Down