USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksPostgreSQL Book
HomePostgreSQL BookFoundations
PreviousBuild Your First SignalDesk AI SchemaNextPostgreSQL Data Types, Defaults, and Constraints
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

18 sections

Progress0%
1 / 18

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Master psql and a Safe Data Workflow

psql is PostgreSQL’s universal command-line client and a precise tool for learning, administration, scripts, and incident response. A safe workflow proves the target, inspects before changing, wraps experiments in transactions, stops scripts on errors, records evidence, and separates psql meta-commands from SQL understood by the server.

What will you be able to do?

  • Navigate and inspect with essential psql commands.
  • Run versioned SQL files and stop on the first error.
  • Use variables without unsafe string construction.
  • Test writes inside transactions and savepoints.
  • Capture query results and timings as reproducible evidence.

Prerequisites

The SignalDesk foundation schema and seed row must exist in signaldesk_learning.

What is the mental model?

psql has two languages:

  • SQL ends with ; and is sent to PostgreSQL.
  • Meta-commands begin with \ and are handled by psql.

The prompt communicates transaction state. A prompt ending in =* indicates an open transaction; =! indicates an aborted one. Read it before typing the next command.

Which commands should you know first?

text
\? help for psql commands \h SELECT SQL syntax help \conninfo connection identity \dn schemas \dt signaldesk.* tables \d+ signaldesk.tickets detailed object definition \x auto expanded output when useful \timing on client-observed statement time \pset pager off disable pager for automation \q quit

Use \d+ to discover what PostgreSQL actually created instead of relying on memory.

How do you make an experiment safe?

Inspect, change in a transaction, verify, then choose rollback or commit:

sql
SELECT id, status, updated_at FROM signaldesk.tickets ORDER BY id; BEGIN; UPDATE signaldesk.tickets SET status = 'pending', updated_at = now() WHERE id = 1 RETURNING id, status, updated_at; SELECT id, status, updated_at FROM signaldesk.tickets WHERE id = 1; ROLLBACK;

The transaction reduces risk but is not magic: some commands have external effects, long transactions retain old row versions, and an accidental COMMIT is final. Always inspect the target predicate first.

Use savepoints to recover within a larger transaction:

sql
BEGIN; SAVEPOINT before_experiment; UPDATE signaldesk.tickets SET priority = 'impossible' WHERE id = 1; ROLLBACK TO SAVEPOINT before_experiment; SELECT id, priority FROM signaldesk.tickets WHERE id = 1; COMMIT;

How do you run scripts reproducibly?

Create migration or lab files in version control and execute them with error stopping:

bash
psql -X \ --set=ON_ERROR_STOP=on \ --dbname=YOUR_DATABASE_URL \ --file=path/to/lab.sql

-X avoids user startup-file surprises. ON_ERROR_STOP prevents later statements from running after a failure. In CI, also record the client and server versions.

For identifiers or values supplied externally, prefer application parameters or carefully reviewed psql variable quoting:

text
\set ticket_id 1
sql
SELECT id, subject FROM signaldesk.tickets WHERE id = :'ticket_id'::bigint;

psql substitution is not the same as server-side bind parameters and must not become an internet-facing query API.

How do you capture evidence?

text
\o signaldesk-evidence.txt \timing on
sql
SELECT current_database(), current_user, now(); SELECT count(*) AS ticket_count FROM signaldesk.tickets;
text
\o

Inspect the file for secrets before sharing or committing it. Query output can contain personal or tenant data even when SQL text does not.

Prove it worked

Start a transaction, change one known ticket with RETURNING, verify the new value, roll back, and prove the original value returned. Save the before/change/after evidence with connection identity.

Then run a script containing one valid statement, one invalid statement, and another valid statement using ON_ERROR_STOP. Prove the third statement did not execute. Use only disposable objects in the learning schema.

Why does this matter in AI-native systems?

An AI assistant can help draft a diagnostic query, but the human workflow must supply target identity, least privilege, timeouts, result limits, transaction boundaries, and independent verification. Captured evidence also becomes a better incident and evaluation artifact than a chat transcript that claims a command succeeded.

Production judgment

  • Use a read-only or narrowly privileged role for investigation.
  • Configure statement_timeout and lock_timeout for risky interactive work.
  • Never paste unreviewed model output into a privileged psql session.
  • Do not export sensitive rows casually with \copy or \o.
  • \timing includes client-observed time but is not a substitute for plans, server metrics, or repeated workload tests.

Useful session guards for reviewed maintenance:

sql
SET statement_timeout = '30s'; SET lock_timeout = '3s'; SET idle_in_transaction_session_timeout = '60s';

Confirm these values fit the task; indiscriminate timeouts can interrupt necessary operations.

Common mistakes

SymptomCauseFix
Later script steps ran after an errorON_ERROR_STOP was absentEnable it and make transactions explicit
Session holds locks unexpectedlyTransaction was left openRead the prompt; inspect activity; commit or roll back
Output differs between machinesStartup files changed settingsUse psql -X for reproducible automation
Shared evidence leaks dataOutput file was treated as harmlessMinimize, redact, protect, and apply retention rules
AI-generated query changes too muchScope and proof were missingInspect with SELECT, add exact predicates, use rollback, verify

AI Pair-Programmer Prompt

text
Turn my database task into a safe psql runbook. Require connection identity, least- privileged role, exact target query, row-count expectation, lock and statement timeouts, transaction plan, RETURNING evidence, rollback/commit decision, and post-check. Do not execute commands. Flag commands that are non-transactional, destructive, broad, or may expose sensitive output. Provide a dry-run inspection before any write.

Hands-on exercise

Write a psql runbook that changes the priority of exactly one ticket and aborts if the intended ticket does not exist. It must show target identity, before state, changed state, and after state, then roll back.

Acceptance criterion: the runbook exits on errors, affects one row during the transaction, leaves zero durable changes, and produces non-sensitive evidence.

Knowledge check

  1. What is the difference between \d and SQL?
  2. Why use -X in automation?
  3. What does an aborted transaction require before normal work continues?
  4. Why is a transaction not complete protection for an experiment?

Answers

  1. \d is a psql meta-command; SQL is sent to PostgreSQL.
  2. It prevents local startup configuration from silently changing script behavior.
  3. ROLLBACK or rollback to a valid savepoint.
  4. Long/open transactions, external effects, broad predicates, privileges, and an accidental commit still create risk.

Completion checklist

  • I can inspect connection and schema objects in psql.
  • I performed and proved a rollbackable update.
  • My scripts stop on the first error.
  • I can identify an open or aborted transaction from the prompt.
  • I protect output as data, not merely text.

Primary references

  • psql
  • Transactions
  • Runtime client connection defaults
  • SET