Part of AI in CanadaAI · Workflow

An assistant that answers questions from your own database.

Ask “what did we sell last month in the Outaouais?” and get an answer built from real rows. The model writes SQL through a tool call, your app runs it as a read-only Postgres role that can see only the views you chose, and the model writes the answer from the result. Here is the whole app, run end to end against Canner’s AI endpoints, with the guardrails that belong in the database rather than in the prompt.

Facts checked

How the assistant works

The app gives the model one tool, run_sql, and the list of columns it may query. The model answers a question by calling the tool, one or more times; your code runs each query and sends the rows back; when the model has what it needs, it writes the answer. In our tests most questions took one or two queries, and the model fixed its own query when Postgres returned an error.

Three things make this safe enough to put in front of staff. The database login can only read a few views, so a bad query can’t change anything or read data the views don’t show (it can still see the names of other tables). Every query runs with a timeout and a row cap. And every query is logged with the question that produced it, so you can check any answer.

It is not an instant chat. On Canner’s AI endpoints the models run on processors, and each step of the loop is a model call: a question took from a quarter of a minute to about a minute in our tests. Run the question as a job and let the page poll for it, as below.

A read-only role and an allowlist of views

Don’t rely on the prompt to keep the model away from tables. Create views that expose only what the assistant should answer from, then a login that can read those views and nothing else. A view reads its tables with its owner’s rights, so the role needs SELECT on the views and no grant at all on the tables underneath. Leave names, email addresses and phone numbers out of the views unless a question you actually want answered needs them.

local_date is the fix for the time-zone trap described in the next section: the conversion to Montréal time is done once, in the view, instead of by the model in every query.

-- Run as the database owner (dedicated Postgres instance).
CREATE SCHEMA assistant;

-- Only what the assistant may see. No names, emails or phone numbers.
CREATE VIEW assistant.orders AS
SELECT o.id          AS order_id,
       o.placed_at,                                                   -- timestamptz
       (o.placed_at AT TIME ZONE 'America/Toronto')::date AS local_date, -- the day in Montréal
       o.status,
       o.total_cents / 100.0 AS total,
       c.region
FROM public.orders o
JOIN public.customers c ON c.id = o.customer_id;

CREATE VIEW assistant.order_lines AS
SELECT i.order_id, p.sku, p.name AS product, p.category,
       i.quantity, i.quantity * i.unit_cents / 100.0 AS line_total
FROM public.order_items i
JOIN public.products p ON p.id = i.product_id;

-- A login that can read those two views and nothing else.
CREATE ROLE assistant_ro LOGIN PASSWORD 'replace-with-a-generated-password' CONNECTION LIMIT 3;
DO $$ BEGIN
  EXECUTE format('GRANT CONNECT ON DATABASE %I TO assistant_ro', current_database());
END $$;
GRANT USAGE ON SCHEMA assistant TO assistant_ro;
GRANT SELECT ON assistant.orders, assistant.order_lines TO assistant_ro;
ALTER ROLE assistant_ro SET search_path = assistant;
ALTER ROLE assistant_ro SET default_transaction_read_only = on;
ALTER ROLE assistant_ro SET statement_timeout = '5s';

-- Every query the model writes, kept by the app (written with the owner's connection).
CREATE TABLE assistant_log (
  id         bigserial PRIMARY KEY,
  at         timestamptz NOT NULL DEFAULT now(),
  question   text NOT NULL,
  sql        text NOT NULL,
  row_count  int,
  ms         int,
  error      text
);
GuardrailWhat it stopsWhere it lives
Views over the tables, SELECT on the views only †Reading tables and columns you left out, such as customers’ contact detailsThe view runs with its owner’s rights
default_transaction_read_only and BEGIN READ ONLY †INSERT, UPDATE, DELETE, DDL, even if a grant slips in laterThe role and each transaction
statement_timeout (role and SET LOCAL) †A query that scans for minutesThe role and each transaction
SELECT * FROM (…) LIMIT 201 around the model’s SQLTwo statements in one call, and huge result sets in the promptYour code
CONNECTION LIMIT 3 and a pool of 2The assistant using up the database’s connectionsThe role and your code
assistant_logAnswers nobody can checkYour code, with the owner’s connection

† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. Views over the tables, `SELECT` on the views only (2026-11-23) · `default_transaction_read_only` and `BEGIN READ ONLY` (2026-11-23) · `statement_timeout` (role and `SET LOCAL`) (2026-11-23)

The time-zone trap: “last month” in Montréal

Store times as timestamptz and Postgres keeps the instant; which day it falls on depends on the time zone you ask in. Application databases usually run in UTC. An order placed at 9:30 p.m. on October 31 in Montréal is 01:30 UTC on November 1, so a query that cuts months in UTC moves it into November.

We seeded a shop database with two such orders and asked Gemma for last month’s revenue. With only placed_at in the view and a UTC session, it compared placed_at with date_trunc('month', current_date …) and reported $2,426 instead of $3,016. Adding “in Montréal time” to the question changed nothing: the model wrote the same query. The other common mistake is converting twice, (placed_at AT TIME ZONE 'UTC') AT TIME ZONE 'America/Toronto', which shifts every order by four or five hours.

The fix is to take the decision away from the model. The view exposes local_date, the order’s day in Montréal, and the system prompt tells the model to filter on it. Each transaction also sets TIME ZONE 'America/Toronto', so now(), current_date and date_trunc() agree with it. With both, the same question came back with the right figures.

-- What the model wrote (session time zone UTC): October in UTC, not in Montréal
SELECT region, SUM(total) FROM orders
WHERE status = 'paid'
  AND placed_at >= date_trunc('month', current_date - interval '1 month')
  AND placed_at <  date_trunc('month', current_date)
GROUP BY region;

-- Also wrong, and common: converting twice shifts every order by 4 or 5 hours
--   (placed_at AT TIME ZONE 'UTC') AT TIME ZONE 'America/Toronto'

-- Right: one conversion, done once in the view, and the model filters on a date
SELECT region, SUM(total) FROM orders
WHERE status = 'paid'
  AND local_date >= date_trunc('month', current_date - interval '1 month')
  AND local_date <  date_trunc('month', current_date)
GROUP BY ROLLUP (region);
Postgres behaviourConsequence
timestamptz AT TIME ZONE zone returns a timestamp as the time would appear in that zone †One conversion gives the local wall-clock time; cast it to date for the local day
timestamp AT TIME ZONE zone returns a timestamptz, assuming the value is in that zone †Applying it to an already converted value is the double conversion
date_trunc on a timestamptz truncates in the session’s TimeZone setting † †Set the session time zone per transaction, or month boundaries are UTC midnights
America/Toronto is the IANA zone for Montréal; America/Montreal is kept as a link to it †Either name works in Postgres; the view uses the canonical one

† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. `timestamptz AT TIME ZONE zone` returns a `timestamp` as the time would appear in that zone (2026-11-23) · `timestamp AT TIME ZONE zone` returns a `timestamptz`, assuming the value is in that zone (2026-11-23) · `date_trunc` on a `timestamptz` truncates in the session’s `TimeZone` setting (2026-11-23) · `date_trunc` on a `timestamptz` truncates in the session’s `TimeZone` setting (2026-11-23) · `America/Toronto` is the IANA zone for Montréal; `America/Montreal` is kept as a link to it (2026-11-23)

The tool loop

The model sees the columns of the views, read from information_schema as the read-only role, so it never learns about tables it can’t query. Errors go back to the model as tool results: in our tests that was enough for it to repair a query. The loop stops after six queries, so a confused model can’t spin forever. temperature: 0 keeps the SQL repeatable from one run to the next.

// assistant.js
import OpenAI from "openai";
import pg from "pg";

const ai = new OpenAI({ maxRetries: 4 });          // OPENAI_BASE_URL + OPENAI_API_KEY; retries 429 after Retry-After
const readonly = new pg.Pool({ connectionString: process.env.ASSISTANT_DATABASE_URL, max: 2 });
const owner = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
const MODEL = "gemma-4-26b-a4b";
const TZ = "America/Toronto";                      // Montréal
const MAX_ROWS = 200;

const TOOLS = [{
  type: "function",
  function: {
    name: "run_sql",
    description: "Run one read-only PostgreSQL SELECT on the views in the system prompt. Returns at most 200 rows.",
    parameters: {
      type: "object",
      properties: { sql: { type: "string", description: "A single SELECT statement" } },
      required: ["sql"],
    },
  },
}];

// The schema the model sees: only the columns this role can read.
async function describeViews() {
  const { rows } = await readonly.query(
    `SELECT table_name, column_name, data_type FROM information_schema.columns
      WHERE table_schema = 'assistant' ORDER BY table_name, ordinal_position`);
  const views = {};
  for (const r of rows) (views[r.table_name] ??= []).push(`${r.column_name} ${r.data_type}`);
  return Object.entries(views).map(([v, cols]) => `${v}(${cols.join(", ")})`).join("\n");
}

export async function runSql(sql, question) {
  const q = sql.trim().replace(/;\s*$/, "");
  const started = Date.now();
  let result;
  if (q.includes(";")) {
    result = { error: "Send one SELECT statement, without semicolons." };
  } else {
    const client = await readonly.connect();
    try {
      await client.query("BEGIN READ ONLY");
      await client.query("SET LOCAL statement_timeout = '5s'");
      await client.query(`SET LOCAL TIME ZONE '${TZ}'`);
      // Wrapping forces a single SELECT and caps the rows.
      const r = await client.query(`SELECT * FROM (${q}) AS answer LIMIT ${MAX_ROWS + 1}`);
      result = { rows: r.rows.slice(0, MAX_ROWS), truncated: r.rows.length > MAX_ROWS };
    } catch (e) {
      result = { error: e.message };                // the model reads it and fixes its query
    } finally {
      await client.query("ROLLBACK").catch(() => {});
      client.release();
    }
  }
  await owner.query(
    "INSERT INTO assistant_log (question, sql, row_count, ms, error) VALUES ($1, $2, $3, $4, $5)",
    [question, q, result.rows?.length ?? null, Date.now() - started, result.error ?? null]);
  return result;
}

export async function ask(question) {
  const today = new Intl.DateTimeFormat("en-CA", { timeZone: TZ, dateStyle: "full" }).format(new Date());
  const messages = [
    { role: "system", content:
`You answer questions about the shop's orders by querying PostgreSQL with the run_sql tool.
Today is ${today} in Montréal.
Views you can query (nothing else exists for you):
${await describeViews()}
Rules:
- Calendar questions (days, weeks, months) use local_date, which is already the Montréal day. Don't convert placed_at yourself.
- The session time zone is ${TZ}: now(), current_date and date_trunc() are already in Montréal time.
- Amounts are in dollars. Only status = 'paid' counts as revenue.
- Do all arithmetic in SQL. Every number in your answer must appear in a query result: for a breakdown with its grand total, use GROUP BY ROLLUP (the grand-total row has NULL in the grouped column).
- If a query fails, read the error and fix the query.
- If the views can't answer the question, say so. Never guess numbers.
- Answer in the user's language, in a few sentences.` },
    { role: "user", content: question },
  ];
  const queries = [];
  for (let step = 0; step < 6; step++) {
    const r = await ai.chat.completions.create({ model: MODEL, messages, tools: TOOLS, temperature: 0 });
    const msg = r.choices[0].message;
    messages.push(msg);
    if (!msg.tool_calls?.length) return { answer: msg.content, queries };
    for (const call of msg.tool_calls) {
      let sql = "";
      try { sql = JSON.parse(call.function.arguments).sql ?? ""; } catch {}
      queries.push(sql);
      const result = await runSql(sql, question);
      messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
    }
  }
  return { answer: "I couldn't answer that in six queries.", queries };
}

Let SQL do the arithmetic

In one run the model queried revenue by region correctly, then reported the Montréal row, $1,168, as the total. In another it wrote a query that put a per-region sum in a column named total_revenue. Both are the same failure: the model added up, or labelled, numbers in prose instead of asking the database.

The rule that fixed it in our tests: every number in the answer must appear in a query result, and a breakdown with its total uses GROUP BY ROLLUP, which adds one row aggregated over everything. The next run made one query and returned $3,016 with Montréal at $1,168. Show the SQL next to the answer in your interface: people trust a figure they can check, and they report the wrong ones.

A web endpoint that doesn’t hold the request open

The browser posts the question, gets a job id back at once, and polls until the answer is ready. Questions are answered one after another: the AI endpoint answers one request at a time anyway, and a queue in your app keeps your organization’s waiting requests under the limit. If several people will use it at once, move the jobs to Postgres with a library such as pg-boss (background jobs).

// server.js: the browser posts a question and polls for the answer.
import express from "express";
import { randomUUID } from "node:crypto";
import { ask } from "./assistant.js";

const app = express();
app.use(express.json());
const jobs = new Map();           // id -> { state, answer, queries, error }
let queue = Promise.resolve();    // one question at a time: the AI endpoint answers one request at a time anyway

app.post("/ask", (req, res) => {
  // Put your own login check here: only staff who may see these figures.
  const question = String(req.body?.question ?? "").slice(0, 500);
  if (!question) return res.status(400).json({ error: "question required" });
  const id = randomUUID();
  jobs.set(id, { state: "queued" });
  queue = queue.then(async () => {
    jobs.set(id, { state: "running" });
    try {
      jobs.set(id, { state: "done", ...(await ask(question)) });
    } catch (e) {
      jobs.set(id, { state: "failed", error: e.message });
    }
    setTimeout(() => jobs.delete(id), 15 * 60_000);
  });
  res.status(202).json({ id });
});

app.get("/ask/:id", (req, res) => {
  const job = jobs.get(req.params.id);
  return job ? res.json(job) : res.status(404).json({ error: "unknown or expired" });
});

app.listen(process.env.PORT || 3000);

What we tested

The code above, run against Canner’s AI endpoint with gemma-4-26b-a4b, on a seeded shop database (customers, products, orders, order lines) in PGlite with the same SQL. PGlite has no statement timeouts, so statement_timeout is the one guardrail we couldn’t exercise there; it is standard Postgres behaviour.

Question or inputWhat happened
Revenue last month and the top region, view without local_date, session in UTC2 queries. $2,426 instead of $3,016: the two orders from the evening of October 31 counted in November
The same, with “in Montréal time” in the questionSame wrong query, same wrong total
The same, with local_date and the session time zoneRight figures per region, but the Montréal row given as the total
The same, with the ROLLUP rule1 query, $3,016 in total and Montréal first at $1,168: right
In French: the best-selling product in the Outaouais in October, and refunds that month2 queries across both views, right on both counts, answered in French
The email address of last month’s best customerNo query; the model said the views hold no customer contact details
DELETE in a CTE, SELECT from public.customers, two statementsRejected: Postgres refuses a data-modifying WITH inside the wrapper, permission denied, refused by the app

Law 25: the model reading a row is still a use of it

If the views expose personal information, the assistant uses it every time it answers, even though no person looks at the rows. Quebec’s private-sector act limits use to the purposes the information was collected for (section 12) and asks for a privacy impact assessment for a new information system that involves personal information (section 3.3). Our Law 25 overview and Law 25 for developers cover both.

The views are where you apply that. Aggregates by region need no names; a question that does (“which customers haven’t ordered since June?”) is a decision to make deliberately, for a stated purpose, with access limited to the staff who need it. The query log also holds what people asked, so treat it like any other log with personal information: limited access and a retention period.

Running it on Canner

A login of your own needs the dedicated Postgres instance: on the shared tier the owner’s credential is the only one, and it can write everything. On the instance, your database owner can create roles in SQL.

  • Keep usage down. Usage is measured in model time with a monthly allowance per plan (AI endpoints has current allowances). Cache answers to repeated questions for a few minutes, keep the system prompt short (it is sent with every step), and set a requests-per-minute limit on the endpoint so a stuck loop can’t burn through the month.
  • Busy service. The OpenAI SDK retries 429 server_busy after Retry-After; maxRetries: 4 gives a busy morning some slack.
  • When to use something else. For dashboards people look at every day, write the queries once and chart them: a fixed query is faster, cheaper and always right. An assistant earns its place on the long tail of questions nobody built a report for.
# 1. With the dedicated Postgres instance on the project, run the setup as the owner
#    (generate a password and put it in setup.sql first)
psql "$DATABASE_URL" -f setup.sql

# 2. The role's connection string: DATABASE_URL with assistant_ro and its password
canner env set ASSISTANT_DATABASE_URL='postgres://assistant_ro:PASSWORD@HOST:PORT/DBNAME' --sensitive

# 3. An AI endpoint with Gemma, attached to the project
canner ai create db-assistant --models gemma-4-26b-a4b
canner ai attach db-assistant
canner redeploy

Questions

Is it safe to let an AI run SQL on my database?

Only with limits the database enforces. Give it its own login that can read a few views and nothing else, in read-only transactions with a statement timeout and a row cap, and log every query. A prompt that says “only SELECT” is not a limit.

Why does my AI SQL assistant get “last month” wrong?

Usually time zones. With timestamptz columns and a UTC session, month boundaries fall at UTC midnight, so late-evening orders move into the next month. Expose a local date column in the view and set the session time zone per transaction.

Which model should I use for natural language to SQL on Canner?

gemma-4-26b-a4b. It handled multi-step tool calls and repaired its own queries in our tests. granite-4.2-3b is made for fast chat and classification; we didn’t build this assistant on it.

Does the model see my data?

It sees the rows its queries return, and only from the views you grant. On Canner the AI endpoint processes them in memory in Montréal and doesn’t store them.

Can I do this on the shared database tier?

Not safely. A separate read-only login needs the dedicated Postgres instance; on the shared tier the only credential is the owner’s, which can write everything.

Your data and the model, both in Montréal.

Add the dedicated Postgres instance and an AI endpoint to a project. See pricing.