Chapter 3 · Performance and Production
Security: Roles, SQL Injection, Sensitive Data and Backups
- Page 11 of 22
- 19 min read
A database holds the most valuable data a company has: customers, payments, and — for AI teams — the training data, prompts and logs that models are built on. Most data breaches are not clever attacks. They are an application user that could do anything, a query glued together from user input, a password in a Git repository, a CSV of customer emails copied to a laptop for "a quick analysis", or a backup nobody ever tried to restore.
This page covers the habits that prevent those failures, each shown working: roles and least privilege on PostgreSQL and MySQL, SQL injection demonstrated and fixed, protecting personal data before it reaches analytics or ML, and backups you have actually restored.
What you will learn
- Users, roles,
GRANTandREVOKE, and least privilege: a read-only analytics role and an application role - How SQL injection works, and why parameters (prepared statements) stop it
- Where credentials belong: environment variables and secret managers
- Protecting personal data: masking and pseudonymisation with a keyed hash
- Backups and restore (SQLite backup API,
mysqldump,pg_dump), audit logs and a production checklist
Users, roles and least privilege
SQLite has no users: whoever can read the file can read everything, so you protect it with file permissions. Server databases authenticate every connection as a user, and permissions are usually granted to roles (named bundles of privileges) that users are members of. The rule is least privilege: every user and program gets exactly the access its job needs. A dashboard reads; it never deletes. A web app inserts orders; it never drops tables. A text-to-SQL feature that runs LLM-written queries gets a read-only role and nothing more.
PostgreSQL: a read-only analytics role
In PostgreSQL users and roles are the same thing: a "user" is a role with LOGIN, and CREATE USER is just CREATE ROLE … LOGIN. Roles exist for the whole server, not for one database, so the script starts by removing any old copies:
-- PostgreSQL
DROP ROLE IF EXISTS bi_reader;
DROP ROLE IF EXISTS analytics_ro;
CREATE ROLE analytics_ro NOLOGIN; -- a group: nobody logs in as it
GRANT USAGE ON SCHEMA public TO analytics_ro;
GRANT SELECT ON orders, order_items, products, categories TO analytics_ro;
CREATE ROLE bi_reader LOGIN PASSWORD 'change-me-123' IN ROLE analytics_ro;
SET ROLE bi_reader; -- act as that user to test
SELECT current_user, COUNT(*) AS orders FROM orders;
DELETE FROM orders WHERE order_id = 13;+--------------+--------+
| current_user | orders |
+--------------+--------+
| bi_reader | 14 |
+--------------+--------+
Error: permission denied for table ordersThe dashboard user can count orders but not delete them. Notice customers and payments were not granted at all: analysts get personal data only through a view that leaves out what they do not need.
-- PostgreSQL
SELECT name, email FROM customers LIMIT 1;Error: permission denied for table customers-- PostgreSQL
RESET ROLE; -- back to the administrator
CREATE VIEW customers_analytics AS
SELECT customer_id, city, joined_on FROM customers; -- no name, no email
GRANT SELECT ON customers_analytics TO analytics_ro;
SET ROLE bi_reader;
SELECT city, COUNT(*) AS customers
FROM customers_analytics
GROUP BY city
ORDER BY customers DESC, city
LIMIT 3;+------------+-----------+
| city | customers |
+------------+-----------+
| Dhaka | 3 |
| Chattogram | 1 |
| Khulna | 1 |
+------------+-----------+An application role, and REVOKE
The web shop's backend needs to read products and create orders, nothing else. REVOKE takes a privilege back:
-- PostgreSQL
RESET ROLE;
DROP ROLE IF EXISTS orders_app;
CREATE ROLE orders_app LOGIN PASSWORD 'change-me-456';
GRANT USAGE ON SCHEMA public TO orders_app;
GRANT SELECT ON products, customers TO orders_app;
GRANT SELECT, INSERT, UPDATE ON orders, order_items TO orders_app;
REVOKE UPDATE ON order_items FROM orders_app; -- items are never edited after checkout
SELECT grantee, table_name, string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants
WHERE grantee IN ('analytics_ro', 'orders_app')
GROUP BY grantee, table_name
ORDER BY grantee, table_name;+--------------+---------------------+------------------------+
| grantee | table_name | privileges |
+--------------+---------------------+------------------------+
| analytics_ro | categories | SELECT |
| analytics_ro | customers_analytics | SELECT |
| analytics_ro | order_items | SELECT |
| analytics_ro | orders | SELECT |
| analytics_ro | products | SELECT |
| orders_app | customers | SELECT |
| orders_app | order_items | INSERT, SELECT |
| orders_app | orders | INSERT, SELECT, UPDATE |
| orders_app | products | SELECT |
+--------------+---------------------+------------------------+Three more PostgreSQL details. GRANT SELECT ON ALL TABLES IN SCHEMA public covers only tables that exist now; ALTER DEFAULT PRIVILEGES … GRANT SELECT ON TABLES TO analytics_ro covers future ones. A table's owner can do anything with it, so the application should never connect as the role that owns the tables (migrations run as the owner; the app runs as orders_app). And since PostgreSQL 15, ordinary roles can no longer create tables in the public schema; on older servers, run REVOKE CREATE ON SCHEMA public FROM PUBLIC yourself, or any login could add tables there. (USAGE on public is still granted to everyone, so the GRANT USAGE lines above matter only for other schemas, but they make the intent explicit.)
Because roles belong to the server, they outlive any one database, and removing them is part of the job. DROP ROLE refuses while the role still holds privileges:
-- PostgreSQL
DROP ROLE orders_app;Error: role "orders_app" cannot be dropped because some objects depend on it-- PostgreSQL
DROP OWNED BY orders_app, analytics_ro; -- revoke their grants in this database (and drop anything they own)
DROP ROLE orders_app;
DROP ROLE bi_reader;
DROP ROLE analytics_ro;DROP OWNED BY works one database at a time, and it also drops objects the role owns; if those must survive, move them first with REASSIGN OWNED BY old_role TO new_role.
MySQL: users, roles and grants
MySQL 8 separates users from roles. A user is 'name'@'host' — the host part limits where they may connect from ('%' means anywhere; prefer a specific network). Granting a role is not enough: its privileges apply only while the role is active in the session. SET ROLE activates it for one session; SET DEFAULT ROLE activates it at every login (the alternative is the server setting activate_all_roles_on_login, off by default). In a script for your own server you would write GRANT SELECT ON shop.* TO analytics_ro; here the database name comes from the environment, as it does in real deployment scripts:
import os
import pymysql
settings = dict(host=os.environ["MYSQL_HOST"], port=int(os.environ["MYSQL_PORT"]),
database=os.environ["MYSQL_DATABASE"], autocommit=True)
db = os.environ["MYSQL_DATABASE"]
admin = pymysql.connect(user=os.environ["MYSQL_USER"], password=os.environ["MYSQL_PASSWORD"], **settings)
with admin.cursor() as cur:
cur.execute("DROP USER IF EXISTS 'bi_reader'@'%'")
cur.execute("DROP ROLE IF EXISTS 'analytics_ro'")
cur.execute("CREATE ROLE 'analytics_ro'")
cur.execute(f"GRANT SELECT ON `{db}`.* TO 'analytics_ro'")
cur.execute("CREATE USER 'bi_reader'@'%' IDENTIFIED BY 'change-me-789'")
cur.execute("GRANT 'analytics_ro' TO 'bi_reader'@'%'")
cur.execute("SET DEFAULT ROLE 'analytics_ro' TO 'bi_reader'@'%'")
cur.execute("""SELECT GRANTEE, PRIVILEGE_TYPE FROM information_schema.SCHEMA_PRIVILEGES
WHERE GRANTEE = "'analytics_ro'@'%'" """)
print(cur.fetchall())
reader = pymysql.connect(user="bi_reader", password="change-me-789", **settings)
with reader.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM orders")
print("orders visible to bi_reader:", cur.fetchone()[0])
try:
cur.execute("DELETE FROM orders WHERE order_id = 13")
except pymysql.err.OperationalError as error:
print("DELETE refused, MySQL error", error.args[0])
reader.close()
with admin.cursor() as cur: # users and roles are server-wide: clean up
cur.execute("DROP USER 'bi_reader'@'%'")
cur.execute("DROP ROLE 'analytics_ro'")
admin.close()(("'analytics_ro'@'%'", 'SELECT'),)
orders visible to bi_reader: 14
DELETE refused, MySQL error 1142Error 1142 is MySQL's "command denied to user". Without the SET DEFAULT ROLE line, bi_reader would log in with no active role and be refused access to the database altogether. To take access away: REVOKE SELECT ON shop.* FROM 'analytics_ro'; for one privilege, or DROP USER and DROP ROLE as at the end of the script. SHOW GRANTS FOR 'bi_reader'@'%' USING 'analytics_ro'; lists what a user can do through a role.
SQL injection
SQL injection happens when a program builds SQL by pasting user input into the query text. The input stops being data and becomes part of the code. It has been in every edition of the OWASP Top 10 list of web risks since the first one in 2003, and it is just as real in AI apps: a chatbot tool that looks up "the user's orders", or a search box feeding a RAG pipeline, is exactly the kind of code that gets written in a hurry.
from sqlhelp import con, show
def find_customer_unsafe(email):
sql = f"SELECT customer_id, name, city FROM customers WHERE email = '{email}'" # DON'T
return con.execute(sql).fetchall()
print(find_customer_unsafe("[email protected]"))
print(find_customer_unsafe("nobody' OR '1'='1"))[(1, 'Nadia Rahman', 'Dhaka')]
[(1, 'Nadia Rahman', 'Dhaka'), (2, 'Tanvir Ahmed', 'Chattogram'), (3, 'Farhana Akter', 'Dhaka'), (4, 'Rafiq Islam', 'Sylhet'), (5, 'Sadia Chowdhury', None), (6, 'Imran Hossain', 'Khulna'), (7, 'Mitu Das', 'Dhaka'), (8, 'Karim Uddin', 'Rajshahi')]The second "email" closed the quote and added OR '1'='1', which is true for every row — so the lookup returned all eight customers. The query the database actually ran was:
SELECT customer_id, name, city FROM customers WHERE email = 'nobody' OR '1'='1'An attacker can go further and read tables the query never mentioned, with UNION (the -- comments out the rest of the original query):
attack = "nobody' UNION SELECT employee_id, name, salary FROM employees --"
for row in find_customer_unsafe(attack)[:3]:
print(row)(1, 'Ayesha Siddiqua', 250000)
(2, 'Hasan Mahmud', 180000)
(3, 'Nusrat Jahan', 120000)Salaries, through a customer lookup. The classic "'; DROP TABLE customers; --" depends on the driver: Python's sqlite3 refuses to run two statements in one execute(), but other drivers and settings (MySQL with multi-statements enabled, or executescript()) will:
try:
find_customer_unsafe("x'; DROP TABLE customers; --")
except Exception as error:
print(type(error).__name__, "-", error)ProgrammingError - You can only execute one statement at a time.The fix: parameters
Never put values into SQL text. Put a placeholder in the query and pass the values separately, so no quote or keyword in them can change the query. With sqlite3 and psycopg 3 this is a real prepared statement (also called parameter binding): the query is parsed with holes in it, and the values arrive separately, as data. PyMySQL and psycopg2 instead quote and escape each value correctly on the client before sending the query; that is just as safe, because the driver, not your code, does the quoting.
def find_customer(email):
sql = "SELECT customer_id, name, city FROM customers WHERE email = ?"
return con.execute(sql, (email,)).fetchall()
print(find_customer("[email protected]"))
print(find_customer("nobody' OR '1'='1"))
print(find_customer("nobody' UNION SELECT employee_id, name, salary FROM employees --"))[(1, 'Nadia Rahman', 'Dhaka')]
[]
[]The attacks now look for a customer whose email literally is nobody' OR '1'='1 — there is none. The placeholder style depends on the driver: ? (or :name) for sqlite3, %s (or %(name)s) for PyMySQL, psycopg2 and psycopg 3. The %s looks like Python string formatting but is not: always pass the values as the second argument to execute(), never with % or an f-string.
Identifiers cannot be parameters
Placeholders work only for values. A column or table name chosen by the user — "sort by" in a dashboard — cannot be a parameter. Check it against an allow-list instead:
SORTABLE = {"name": "name", "city": "city", "joined": "joined_on"}
def list_customers(sort_by):
column = SORTABLE.get(sort_by)
if column is None:
raise ValueError(f"cannot sort by {sort_by!r}")
return con.execute(f"SELECT name FROM customers ORDER BY {column}, customer_id LIMIT 3").fetchall()
print(list_customers("joined"))
try:
list_customers("name; DROP TABLE customers")
except ValueError as error:
print(error)[('Nadia Rahman',), ('Tanvir Ahmed',), ('Farhana Akter',)]
cannot sort by 'name; DROP TABLE customers'The f-string is safe here only because column can only be one of three strings you wrote. Escaping functions and "cleaning" input with replace("'", "") are not a defence; parameters and allow-lists are. Least privilege is the second layer: an injected query can do no more than the connected role may.
Credentials: never in code
A password in source code ends up in Git history, in screenshots, in an LLM prompt pasted for help, and in every copy of the repository. Read connection settings from the environment instead, and fail loudly if they are missing:
import os
def database_url():
password = os.environ.get("SHOP_DB_PASSWORD")
if not password:
raise RuntimeError("SHOP_DB_PASSWORD is not set; refusing to start")
user = os.environ.get("SHOP_DB_USER", "orders_app")
host = os.environ.get("SHOP_DB_HOST", "localhost")
return f"postgresql://{user}:{password}@{host}/shop"
try:
database_url()
except RuntimeError as error:
print(error)SHOP_DB_PASSWORD is not set; refusing to startLocally, keep these in a .env file that is listed in .gitignore (the python-dotenv package loads it). In production, use the platform's secret manager — AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault, or your deployment platform's secrets — which also lets you rotate a password without changing code. Give every application and person its own login, so you can revoke one without breaking the others and the logs show who did what. If a secret ever leaks, rotate it; deleting the commit is not enough.
Personal data in analytics and ML
Training data and analytics rarely need to know who a person is — only that two rows belong to the same person. Laws such as the GDPR (and Bangladesh's own data protection rules) also expect you to keep personal data to the minimum. Three techniques, from weakest to strongest:
- Masking hides part of a value for display:
n***@example.com,+880 17** *** 123. - Pseudonymisation replaces an identifier with a stable token, so joins and per-customer features still work but the token does not reveal the person.
- Generalisation and aggregation: a birth date becomes an age band, an address becomes a city, a row becomes a count.
A plain hash is not pseudonymisation: anyone can hash a list of known emails and match them. You will often read "hash it with a salt", which means two different things. A random salt per value, the way passwords are stored (with a slow hash such as bcrypt or Argon2), gives the same email a different token every time, so joins and per-customer features break. What pseudonymisation needs is one secret shared by all values, and the standard, safe way to build that is a keyed hash (HMAC), with the key kept in your secret manager, never stored next to the data:
import hashlib
import hmac
SECRET_KEY = b"demo-key-load-me-from-a-secret-manager" # in real code: os.environ[...]
def pseudonym(value):
return hmac.new(SECRET_KEY, value.lower().encode(), hashlib.sha256).hexdigest()[:16]
def mask_email(email):
user, domain = email.split("@")
return user[0] + "***@" + domain
rows = con.execute("SELECT email, city, joined_on FROM customers ORDER BY customer_id LIMIT 3").fetchall()
for email, city, joined_on in rows:
print(pseudonym(email), mask_email(email), city, joined_on[:7])
plain = hashlib.sha256(b"[email protected]").hexdigest()[:16]
guess = hashlib.sha256(b"[email protected]").hexdigest()[:16] # an attacker's guess
print("plain hash matched by a guess:", plain == guess)8c5c6ae09e320ce8 n***@example.com Dhaka 2025-11
e34e782d6c23800d t***@example.com Chattogram 2025-12
17b63faab2172a2a f***@example.com Dhaka 2026-01
plain hash matched by a guess: TrueThe analytics copy keeps a stable customer token, the city and the join month; the email itself never leaves the production database. Keep the key as protected as the data: whoever holds it can test guesses again. Pseudonymised data is still personal data in law, because it can be re-linked with the key. Also strip personal data from things that are easy to forget: LLM prompts and responses you log, error messages, and evaluation datasets built from real support tickets.
Backups and restore
A backup you have never restored is a hope, not a backup. SQLite's backup API copies a live database safely (a plain file copy during a write can be corrupt):
import sqlite3
backup = sqlite3.connect("shop_backup.db")
con.backup(backup) # consistent copy of the whole database
print("payments in backup:", backup.execute("SELECT COUNT(*) FROM payments").fetchone()[0])
con.execute("DELETE FROM payments") # disaster: someone forgot the WHERE
con.commit()
print("payments after the mistake:", con.execute("SELECT COUNT(*) FROM payments").fetchone()[0])
backup.backup(con) # restore: copy the backup back
print("payments after restore:", con.execute("SELECT COUNT(*) FROM payments").fetchone()[0])
backup.close()payments in backup: 13
payments after the mistake: 0
payments after restore: 13From the sqlite3 shell the same is .backup shop_backup.db and .restore shop_backup.db. The server databases ship dump tools:
# MySQL: a consistent logical dump of one database, then a restore into a new one
mysqldump --single-transaction --routines --triggers --events shop > shop_2026-06-30.sql
mysql -e "CREATE DATABASE shop_restore_test"
mysql shop_restore_test < shop_2026-06-30.sql
# PostgreSQL: custom format (compressed, restorable table by table)
pg_dump --format=custom --file=shop_2026-06-30.dump shop
createdb shop_restore_test
pg_restore --dbname=shop_restore_test shop_2026-06-30.dump- Automate and schedule backups, and keep copies off the server (another region or account), encrypted.
- Test restores regularly, into a scratch database, and check row counts — that is the step everyone skips.
--single-transactiongives a consistent snapshot for InnoDB tables without locking them;pg_dumpalways works from a consistent snapshot.- A database dump does not contain server-wide objects: users, roles and their passwords. Save them separately (
pg_dumpall --globals-onlyfor PostgreSQL; for MySQL, the output ofSHOW CREATE USERandSHOW GRANTS, or the setup scripts that created them). - Logical dumps are simple but slow for big databases. Large systems add physical backups plus the transaction log for point-in-time recovery ("restore to 14:31, just before the bad
DELETE"); managed cloud databases do this for you. - Know your targets: how much data may you lose (RPO), and how long may a restore take (RTO)?
Audit logs and safe changes
When something goes wrong you need to know who did what. Server logs record connections and, if enabled, statements (PostgreSQL's log_connections and log_statement = 'ddl'; the pgaudit extension; MySQL Enterprise Audit or Percona's audit plugin). For changes to important rows, the trigger-based audit trail from Views, Stored Procedures, Functions and Triggers records old and new values. Schema changes themselves should go through reviewed, versioned migrations (see Designing a Real Schema, and Changing It Safely), run by a deployment role — not typed by hand into production.
A production checklist
| Area | Check |
|---|---|
| Access | Every app and person has its own login; roles grant only what each job needs; the app is not the table owner; no shared admin password |
| Queries | All values passed as parameters; identifiers from allow-lists; LLM-generated SQL runs read-only, with row limits and timeouts |
| Secrets | No credentials in code or notebooks; secrets in environment or a secret manager; rotation possible |
| Network | Database not reachable from the internet; TLS for connections; host limits on MySQL users |
| Personal data | Analysts and ML pipelines see views or pseudonymised copies; logs and prompts scrubbed; retention limits |
| Backups | Automatic, off-site, encrypted; restores tested on a schedule; RPO/RTO known |
| Changes | Migrations reviewed and versioned; destructive statements run in a transaction after a SELECT check |
| Monitoring | Audit logs on; alerts for failed logins, privilege changes, unusual exports |
Common mistakes
- The app connects as a superuser or as
root. One injection or bug can then drop everything. Create an application role with only the grants it needs (asorders_appabove). - Building SQL with f-strings "because the input is trusted". Input from another table, a file or an LLM is not trusted either. Use parameters every time:
con.execute("… WHERE email = ?", (email,)). - Using
%with PyMySQL or psycopg.cur.execute("… WHERE id = %s" % user_id)is string formatting, not a parameter. Writecur.execute("… WHERE id = %s", (user_id,)). - Hashing emails without a key and calling it anonymous. A plain SHA-256 of an email is reversible by guessing. Use HMAC with a secret key, and remember the result is still personal data.
- Backups that were never restored. Schedule a restore test and check row counts against production.
Try it yourself
- Easy: This function is injectable:
con.execute(f"SELECT name FROM products WHERE name LIKE '%{term}%'"). Rewrite it with a parameter (hint: build the pattern in Python) and show it finds"Mouse"but nothing for"x' OR '1'='1". - Medium: In PostgreSQL, create a role
support_agentthat can readordersand update only thestatuscolumn (column-level grant), and show an update oforder_dateis refused. - Hard: Build a pseudonymised training table in SQLite:
customer_features(customer_token, city, orders, spent), wherecustomer_tokenis your HMAC pseudonym of the email. Registerpseudonymas an SQL function withcon.create_functionso the whole table is built in oneCREATE TABLE … AS SELECT.
Answers
# 1. Easy
def search_products(term):
return con.execute("SELECT name FROM products WHERE name LIKE ? ORDER BY name",
(f"%{term}%",)).fetchall()
print(search_products("Mouse"))
print(search_products("x' OR '1'='1"))-- PostgreSQL
-- 2. Medium
RESET ROLE;
DROP ROLE IF EXISTS support_agent;
CREATE ROLE support_agent LOGIN PASSWORD 'change-me-000';
GRANT SELECT ON orders TO support_agent;
GRANT UPDATE (status) ON orders TO support_agent; -- column-level: only status may change
SET ROLE support_agent;
UPDATE orders SET status = 'delivered' WHERE order_id = 12;
UPDATE orders SET order_date = '2026-01-01' WHERE order_id = 12;Error: permission denied for table orders-- PostgreSQL
RESET ROLE; -- tidy up: roles are server-wide
DROP OWNED BY support_agent;
DROP ROLE support_agent;# 3. Hard
con.create_function("pseudonym", 1, pseudonym, deterministic=True)
con.execute("DROP TABLE IF EXISTS customer_features")
con.execute("""
CREATE TABLE customer_features AS
SELECT pseudonym(c.email) AS customer_token,
c.city,
COUNT(DISTINCT o.order_id) AS orders, -- DISTINCT: items would fan out
COALESCE(SUM(oi.quantity * oi.unit_price), 0) AS spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id AND o.status <> 'cancelled'
LEFT JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id""")
con.commit()
show("SELECT * FROM customer_features ORDER BY spent DESC, customer_token LIMIT 3")Summary
- Grant privileges to roles, give each app and person its own login, and grant only what the job needs; use views to hide sensitive columns.
REVOKEtakes access back. - SQL injection turns input into code. Parameters (
?,%s) keep values as data; identifiers come from allow-lists. - Credentials live in the environment or a secret manager, never in code or notebooks.
- Analytics and ML usually need a stable token, not an identity: mask for display, pseudonymise with HMAC and a secret key, generalise and aggregate.
- Back up automatically, store copies elsewhere, and prove you can restore.
Next: Data Handling Fundamentals: Formats, Quality and Lineage steps back from the database to the data itself: where it comes from, the formats it arrives in, how to judge its quality, and how to process it so that every result can be traced and reproduced.

