SQL from application code

Topic 4 of 4 in Beyond the basics12 min readBeginnerFree course

Overview

Most SQL isn’t typed into psql — it’s sent by programs: a web server placing orders, a script loading data, a dashboard asking for numbers. Everything you’ve learned applies unchanged; what’s new is how the program sends the SQL and gets the rows back. Getting one detail wrong — how user input reaches the query — causes one of the most common and damaging security holes on the web. This lesson shows the right way, in Python and in Node.js.

Drivers and connections

A program connects through a driver, a library that speaks PostgreSQL’s network protocol:

Language Popular drivers
Python psycopg (version 3), asyncpg
Node.js / TypeScript pg (node-postgres), postgres (postgres.js)
Java / Kotlin the PostgreSQL JDBC driver
Go pgx
C# / .NET Npgsql

The program needs the same connection details as psql, usually as one URL. Keep it out of the source code — in an environment variable or a secrets manager — so passwords don’t end up in Git:

Terminal
export DATABASE_URL="postgresql://shop_app:secret@localhost:5432/shop"

A query from Python

With psycopg 3:

Python
import os
import psycopg

DATABASE_URL = os.environ["DATABASE_URL"]

def find_customer(email):
    with psycopg.connect(DATABASE_URL) as conn:
        return conn.execute(
            "SELECT id, first_name, city FROM customers WHERE email = %s",
            (email,),
        ).fetchone()

print(find_customer("asha.rao@example.com"))   # (1, 'Asha', 'Pune')
print(find_customer("' OR '1'='1"))            # None

The SQL contains a placeholder, %s, and the value is passed separately as a tuple. psycopg sends the SQL text and the value to the server as two different things. The second call — with an attack string as the “email” — simply finds no customer.

A query from Node.js

With pg (node-postgres), placeholders are numbered: $1, $2, …

JavaScript
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export async function findCustomer(email) {
  const { rows } = await pool.query(
    "SELECT id, first_name, city FROM customers WHERE email = $1",
    [email],
  );
  return rows[0] ?? null;
}

console.log(await findCustomer("ben.carter@example.com"));
// { id: 2, first_name: 'Ben', city: 'Leeds' }

Rows come back as JavaScript objects keyed by column name. (postgres.js uses tagged templates instead — sql`SELECT … WHERE email = ${email}` — which look like string building but are parameterized under the hood.)

SQL injection: what goes wrong

Now the mistake. Suppose the code built the query by gluing strings together:

Python
# DON'T DO THIS
query = "SELECT id, first_name, city FROM customers WHERE email = '" + email + "'"

With a normal email, it works. But the person typing into the login form controls part of the SQL. If they type ' OR '1'='1 as their email, the program builds and runs this:

SQL
SELECT id, first_name, city FROM customers WHERE email = '' OR '1'='1';
Text
 id | first_name |   city    
----+------------+-----------
  1 | Asha       | Pune
  2 | Ben        | Leeds
  3 | Chen       | Singapore
  4 | Dee        | Lagos
  5 | Elena      | Madrid
  6 | Farhan     | Pune
  7 | Grace      | Seattle
  8 | Hugo       | Lyon
  9 | Isha       | Mumbai
 10 | Jack       | Austin
(10 rows)

Every customer, because '1'='1' is always true. With other inputs, an attacker could read any table, bypass logins, or — with '; DROP TABLE customers; -- — destroy data. This is SQL injection, and it has caused some of the largest data breaches in history.

Parameterized queries stop SQL injection. Unsafe: building SQL by gluing strings, as in sql = “SELECT * FROM customers WHERE email = ‘” + user_input + “’”. With user_input set to ’ OR ‘1’=’1, the database runs SELECT * FROM customers WHERE email = ‘’ OR ‘1’=‘1’, which returns every customer. Safe: send the SQL and the values separately, as in cur.execute(“SELECT * FROM customers WHERE email = %s”, (user_input,)) in Python with psycopg, or await sqlSELECT * FROM customers WHERE email = ${userInput} in Node with postgres.js. The SQL text with $1 and the value ’ OR ‘1’=’1 travel separately to PostgreSQL, where the value is only data: no customer has that email, so 0 rows come back.

Why parameters fix it

With a parameterized query, the SQL text (… WHERE email = $1) is parsed before the value is considered. The value then fills the slot as a plain piece of data — it can never become part of the SQL. You can see the same mechanism in plain SQL with PREPARE and EXECUTE, which is exactly what drivers do behind the scenes:

SQL
PREPARE find_customer(text) AS
SELECT id, first_name, city FROM customers WHERE email = $1;

EXECUTE find_customer('chen.wei@example.com');
EXECUTE find_customer(''' OR ''1''=''1');
Text
PREPARE
 id | first_name |   city    
----+------------+-----------
  3 | Chen       | Singapore
(1 row)

 id | first_name | city 
----+------------+------
(0 rows)

The second call searched for a customer whose email is literally ' OR '1'='1. There isn’t one.

The rules:

  • Always use parameters for values — every piece of data that comes from outside the program: forms, URLs, files, APIs, even your own database.
  • Never escape by hand. Home-made quoting misses cases. Parameters are simpler and correct.
  • Parameters can’t stand in for names. Table and column names (say, a sort column chosen by the user) can’t be parameters; check them against a fixed list of allowed names in code.
  • Least privilege limits the damage if something slips through — a role that can’t DROP can’t be made to drop (see Users and permissions).

Transactions in code

Drivers have built-in transaction support. Placing an order — create the order, reduce stock, add items — must be all-or-nothing:

Python
def place_order(customer_id, items):
    """items is a list of (product_id, quantity) pairs."""
    with psycopg.connect(DATABASE_URL) as conn:
        with conn.transaction():
            order_id = conn.execute(
                "INSERT INTO orders (customer_id, ordered_at, status) "
                "VALUES (%s, now(), 'pending') RETURNING id",
                (customer_id,),
            ).fetchone()[0]
            for product_id, quantity in items:
                row = conn.execute(
                    "UPDATE products SET stock = stock - %s "
                    "WHERE id = %s AND stock >= %s RETURNING price",
                    (quantity, product_id, quantity),
                ).fetchone()
                if row is None:
                    raise ValueError(f"not enough stock for product {product_id}")
                conn.execute(
                    "INSERT INTO order_items (order_id, product_id, quantity, unit_price) "
                    "VALUES (%s, %s, %s, %s)",
                    (order_id, product_id, quantity, row[0]),
                )
    return order_id

If anything inside conn.transaction() raises an error — including the “not enough stock” check — psycopg rolls the whole transaction back, so no half-placed order is ever saved. The stock check uses the safe pattern from Transactions: the database does the arithmetic and the WHERE stock >= %s guard, so two simultaneous orders can’t oversell.

In node-postgres, a transaction must run on one connection from the pool:

JavaScript
export async function cancelOrder(orderId) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const { rows } = await client.query(
      "UPDATE orders SET status = 'cancelled' WHERE id = $1 AND status = 'pending' RETURNING id",
      [orderId],
    );
    if (rows.length === 0) throw new Error(`order ${orderId} can't be cancelled`);
    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

Both examples in this lesson were run against the Bean & Leaf database with psycopg 3.3 and node-postgres 8.

Connection pools

Opening a database connection takes time and server memory, so a busy application doesn’t open one per request. A connection pool keeps a few connections open and lends them out — pg.Pool in Node, psycopg_pool in Python, and frameworks configure one for you. For many application servers sharing one database, a separate pooler such as PgBouncer is common. Always return connections to the pool (client.release(), or a with block).

The N+1 problem

A classic performance mistake in application code looks innocent:

Python
orders = conn.execute("SELECT id, customer_id FROM orders").fetchall()
for order_id, customer_id in orders:            # 1 query…
    name = conn.execute("SELECT first_name FROM customers WHERE id = %s",
                        (customer_id,)).fetchone()   # …plus N more

One query for the list, then one more for every row — 1 + N round trips to the database. With 24 orders it’s unnoticeable; with 10,000 it takes seconds. The fix is to let the database do the combining, in one query:

SQL
SELECT o.id, c.first_name
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.id <= 3
ORDER BY o.id;
Text
 id | first_name 
----+------------
  1 | Asha
  2 | Ben
  3 | Asha
(3 rows)

…or, when you already have a list of ids, WHERE id = ANY($1) with the list as one parameter. ORMs (SQLAlchemy, Django ORM, Prisma, Hibernate…) can generate N+1 patterns silently; learn your ORM’s way of loading related data eagerly, and check the SQL it produces.

ORMs and query builders

ORMs map tables to classes and write SQL for you. They’re productive for everyday create/read/update/delete code, and they parameterize queries automatically. But everything in this course still matters: ORMs generate joins, transactions and indexes-dependent queries, and when something is slow or wrong, you’ll debug it by reading the SQL they produce — and sometimes by writing it yourself. Most ORMs let you drop down to raw, parameterized SQL for complex reports.

Tip: log the SQL your application sends while developing (most drivers and ORMs have a setting for it). Reading it is the fastest way to spot N+1 queries, missing filters and string-built SQL.

Exercise

Prepared statements in SQL

Drivers send parameters separately from the SQL text. You can see the same mechanism in plain SQL with PREPARE and EXECUTE. Prepare a statement named orders_for that takes one text parameter — a customer's email — and returns that customer's order id and status, sorted by order id, by joining orders to customers. Execute it for 'grace.kim@example.com' (two orders), then execute it with the classic injection attempt ' OR '1'='1 as the parameter (no rows — it's treated as an email that doesn't exist).

SQL
PREPARE orders_for(text) AS
SELECT o.id, o.status
FROM orders AS o
-- join customers and filter by the parameter $1
;

EXECUTE orders_for('grace.kim@example.com');

Summary

  • Applications talk to PostgreSQL through a driver — psycopg for Python, pg or postgres.js for Node.js, JDBC for Java — using a connection string kept out of the code.
  • Never build SQL by concatenating user input: that allows SQL injection, where input is executed as SQL.
  • Parameterized queries ($1, %s, ?) send values separately from the SQL, so input is always treated as data.
  • Use the driver's transaction support so multi-step changes commit or roll back together, and a connection pool to reuse connections.
  • Avoid the N+1 problem: fetch related data with one join or IN query, not one query per row.