Skip to main content
Module

x/postgres/mod.ts>Transaction#queryObject

PostgreSQL driver for Deno
Extremely Popular
Go to Latest
method Transaction.prototype.queryObject
import { Transaction } from "https://deno.land/x/postgres@v0.17.0/mod.ts";

This method allows executed queries to be retrieved as object entries. It supports a generic interface in order to type the entries retrieved by the query

import { Client } from "../client.ts";

const client = new Client();
const transaction = client.createTransaction("transaction");

{
  const { rows } = await transaction.queryObject(
    "SELECT ID, NAME FROM CLIENTS"
  ); // Record<string, unknown>
}

{
  const { rows } = await transaction.queryObject<{id: number, name: string}>(
    "SELECT ID, NAME FROM CLIENTS"
  ); // Array<{id: number, name: string}>
}

You can also map the expected results to object fields using the configuration interface. This will be assigned in the order they were provided

import { Client } from "../client.ts";

const client = new Client();
const transaction = client.createTransaction("transaction");

{
  const { rows } = await transaction.queryObject(
    "SELECT ID, NAME FROM CLIENTS"
  );

  console.log(rows); // [{id: 78, name: "Frank"}, {id: 15, name: "Sarah"}]
}

{
  const { rows } = await transaction.queryObject({
    text: "SELECT ID, NAME FROM CLIENTS",
    fields: ["personal_id", "complete_name"],
  });

  console.log(rows); // [{personal_id: 78, complete_name: "Frank"}, {personal_id: 15, complete_name: "Sarah"}]
}

It also allows you to execute prepared stamements with template strings

import { Client } from "../client.ts";

const client = new Client();
const transaction = client.createTransaction("transaction");

const id = 12;
// Array<{id: number, name: string}>
const {rows} = await transaction.queryObject<{id: number, name: string}>`SELECT ID, NAME FROM CLIENTS WHERE ID = ${id}`;

Parameters

query: string
optional
args: QueryArguments

Returns

Promise<QueryObjectResult<T>>

Returns

Promise<QueryObjectResult<T>>

Parameters

query: TemplateStringsArray
...args: unknown[]

Returns

Promise<QueryObjectResult<T>>