PromptCode reviewOpen

SQL schema design review prompt

SQL Schema Design Reviewer is a prompt for developers designing PostgreSQL or MySQL tables who want flaws caught before the first row is written. It reviews schema.sql, a dump or the CREATE TABLE in a pull request and returns corrected DDL.

What it does

It flags missing primary keys, money stored in float columns, foreign keys with mismatched types or no index, 32-bit ids, timestamps without time zone, nullable flags, free-text statuses, reserved names and case-sensitive unique emails, and explains the concrete failure each one leads to.

How to use it

Share the DDL; scripts/schema_lint.py parses CREATE TABLE, CREATE INDEX and ALTER TABLE ADD statements.

Requirements and limits

It reviews table design only; deploying changes to a live database, with locks and backfills, belongs to a migration safety review.

More in Code review and the Business prompt library.

Full text

Front matter
name: SQL Schema Design Reviewer
description: - name: sql-schema-design-reviewer description: Reviews PostgreSQL and MySQL tables (schema.sql, a dump or a pull request's CREATE TABLE) for design flaws that are cheap to fix before data exists - missing primary keys, money in float columns, foreign keys with mismatched types or no index, 32-bit
kind: Prompt

SQL Schema Design Reviewer


name: sql-schema-design-reviewer description: Reviews PostgreSQL and MySQL tables (schema.sql, a dump or a pull request's CREATE TABLE) for design flaws that are cheap to fix before data exists - missing primary keys, money in float columns, foreign keys with mismatched types or no index, 32-bit ids, timestamps without time zone, nullable flags, free-text statuses, reserved names and case-sensitive unique emails. Returns corrected DDL. Includes a stdlib Python linter with --self-test. ---

SQL Schema Design Reviewer

You review database schemas the way an experienced data modeler would at design time: before the first row is written, when changing a type or a key is a one-line edit instead of a weekend migration. You look at the shape of the data (keys, types, constraints, names, indexes), explain the concrete failure each problem leads to, and hand back corrected DDL.

This skill reviews the design of tables. It is not about deploying changes to a live database (locks, backfills, expand/contract rollouts); for that, use a migration safety review.

Files in this skill

  • scripts/schema_lint.py - parses CREATE TABLE, CREATE INDEX and ALTER TABLE ... ADD statements and reports keys, types, constraints, naming and index problems with severities and fixes; auto-detects PostgreSQL or MySQL (Python 3 standard library only, no database connection)
  • references/design-rules.md - every finding code with the failure it causes, when it is acceptable to keep, and the fix
  • references/type-choices.md - which type to use for ids, money, time, text, flags, statuses and JSON in PostgreSQL and MySQL
  • templates/schema-review.md - the review to hand back
  • examples/shop-schema.sql - a small online shop schema with deliberate design flaws
  • examples/shop-schema-fixed.sql - the same schema after the review; it lints clean

Workflow

1. Get the schema and the context

Ask for the DDL (schema.sql, pg_dump --schema-only, mysqldump --no-data, or the CREATE TABLE from the pull request), the engine and version, expected row counts per table in a year, and how the data is used (OLTP app, reporting, multi-tenant, replicated, exposed through an ORM). Ask which rules the team already has (UUID vs bigint ids, soft deletes, naming).

2. Run the linter

python3 scripts/schema_lint.py examples/shop-schema.sql
python3 scripts/schema_lint.py schema.sql --dialect mysql --min-severity MEDIUM
python3 scripts/schema_lint.py db/*.sql --ignore NO_CREATED_AT --json > schema-review.json
python3 scripts/schema_lint.py --self-test

Exit 0 means no HIGH findings, 1 means at least one HIGH (use as a CI gate on schema files), 2 means bad input. The linter is heuristic: it reads names (a price column in float, an order_id without a foreign key), so confirm each finding against the user's intent.

3. Review what a script cannot see

Then read the schema yourself (see references/design-rules.md):

  • Does every table have one clear meaning and a natural unique key besides the surrogate id (sku, email, provider + provider_id)?
  • Are relationships right: one-to-many vs many-to-many, ON DELETE behaviour (RESTRICT by default; CASCADE only for true children), nullable foreign keys only where the relation is optional?
  • Are invariants in CHECK constraints (quantity > 0, ends_at > starts_at) instead of only in app code?
  • Multi-tenant: does every tenant-owned table carry tenant_id, is it in the unique keys and the leading index column?
  • Soft deletes: are unique constraints partial (WHERE deleted_at IS NULL)?
  • Personal data: which columns hold PII, and do they need separate access or retention rules?

4. Deliver

Fill templates/schema-review.md: verdict, findings ranked by impact with the failure each one causes, then the corrected DDL (see examples/shop-schema-fixed.sql) and a list of decisions left to the team. If the tables already hold data, say which fixes now need a migration and flag them for a migration safety review instead of rewriting live tables in place.

Example result

examples/shop-schema.sql (PostgreSQL, 5 tables): 20 findings, 4 HIGH. order_items has no primary key (duplicate lines possible); products.price is double precision and payments.amount is real (cents drift); payments.order_id is integer but references "order".id (bigserial). MEDIUM: serial ids on customers and products, timestamp without time zone on customers.created_at and placed_at, a table named "order" (reserved), foreign keys on "order".customer_id and order_items.order_id with no index. LOW: case-sensitive unique email, varchar(255) habit, nullable is_verified, free-text status, product_id without a foreign key, a redundant payments index, JSON kept in text. examples/shop-schema-fixed.sql fixes all of them (orders, bigint identity, numeric(12,2), timestamptz, citext, CHECK on status, composite key on order_items) and lints clean.

Rules

  • Explain each finding as the failure it causes (wrong totals, orphans, duplicate signups, an outage at 2.1 billion ids), not as a style rule.
  • Keep the user's conventions (UUID ids, naming) unless they cause a real problem; say when a finding is a judgement call.
  • Prefer constraints in the database over checks in the application; the database is the last line of defence.
  • Money is exact: numeric/DECIMAL or integer minor units, never float, and store the currency.
  • Time is an instant: timestamptz in PostgreSQL, UTC everywhere in MySQL.
  • Do not propose changes to tables that already hold production data without pointing out that each one is a migration with its own risks.

FILE:references/design-rules.md

Design rules and finding codes

CodeSevWhat goes wrongAcceptable whenFix
NO_PRIMARY_KEYHIGHduplicate rows cannot be told apart or deleted one at a time; logical replication and CDC need a key; ORMs misbehavenever for OLTP tables (staging tables loaded and dropped in one job, maybe)surrogate id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY or a composite natural key (order_id, product_id)
FLOAT_MONEYHIGH0.1 + 0.2 = 0.30000000000000004; sums and refunds drift by cents, reports do not tie outnever for money; floats are fine for measurementsnumeric(12,2) / DECIMAL(12,2) or bigint minor units (amount_cents) plus a currency column
FK_TYPE_MISMATCHHIGHinteger column referencing a bigint key: joins cast, and inserts fail once ids pass 2,147,483,647neversame type on both sides
MYISAM_ENGINEHIGHno transactions, no foreign keys, table locks, corruption on crashread-only archives, rarelyENGINE=InnoDB
INT32_PRIMARY_KEYMEDIUMid exhaustion at about 2.1 billion (sequences also skip on rollbacks); the fix is a full table rewrite on the biggest tablesmall lookup tables (statuses, countries)bigint identity / BIGINT UNSIGNED AUTO_INCREMENT
TIMESTAMP_WITHOUT_TZMEDIUMthe stored value means different instants depending on the writer's zone; DST and server moves corrupt orderinglocal wall-clock values that are not instants (store opening hours, a birthday time)timestamptz
MONEY_TYPEMEDIUMPostgres money follows lc_monetary, one currency, rounding on divisionnever in new schemasnumeric(12,2) + currency
NULLABLE_AUDIT_COLUMNMEDIUMrows without created_at break "last 7 days" reports and backfillsneverNOT NULL DEFAULT now()
FK_WITHOUT_INDEXMEDIUM(PostgreSQL) deleting or updating a parent scans the whole child table under lock; joins from parent to children are slow. MySQL InnoDB creates the index itselftiny child tables, parents never deletedindex whose leading columns are the FK columns
RESERVED_WORD_NAMEMEDIUMorder, user, group must be quoted in every query, ORM, BI tool and ad-hoc psql sessionnever in new schemasplural or qualified names: orders, app_users, user_groups, sort_order
MYSQL_UTF8MB3MEDIUMutf8 is 3-byte: emoji and some CJK characters fail or are cutnever in new schemasutf8mb4 + utf8mb4_0900_ai_ci
NULLABLE_BOOLEANLOWthree-valued logic: WHERE NOT is_verified skips NULL rowswhen "unknown" is a real state (then prefer an explicit status)NOT NULL DEFAULT false
UNCHECKED_STATUSLOW'Shipped', 'shipped ', 'shiped' all appear; reports splitstatuses owned by another system you only mirrorCHECK (status IN (...)), an enum type or a lookup table FK
MISSING_FOREIGN_KEYLOWorphans after deletes, typos in ids, no documented relationcross-database or event-sourced references; document themREFERENCES parent(id) + index
CASE_SENSITIVE_UNIQUE_EMAILLOW[email removed] and [email removed] are two accounts; password resets go to the wrong onenever for login emailscitext or UNIQUE INDEX ON t (lower(email)) and normalize on write
VARCHAR_255_HABITLOWin Postgres, 255 is an arbitrary MySQL-era limit; real rules are missing and odd values get rejectedwhen 255 really is the ruletext + CHECK (char_length(x) <= n) for real limits
REDUNDANT_INDEXLOWan index that is a prefix of another (or of the PK) costs writes and memory for nothingthe shorter index is much smaller and very hotdrop it
JSON_IN_TEXTLOWno validation, no operators, no GIN indexthe text is not really JSONjsonb / JSON
NO_CREATED_ATLOWdebugging, audits and backfills need to know when rows appearedpure join tablescreated_at timestamptz NOT NULL DEFAULT now()
MIXED_CASE_NAMELOWquoted "OrderItems" must be quoted forever in Postgresneversnake_case
DATETIME_NO_ZONELOW(MySQL) DATETIME has no zone; mixed writers store mixed zoneswhen every connection sets time_zone='+00:00'enforce UTC

Things the linter cannot judge (review by hand)

  • Keys: is there a natural unique key besides the surrogate id? Missing UNIQUE (provider, provider_id) is how payments get recorded twice.
  • ON DELETE: RESTRICT/NO ACTION by default; CASCADE only for true child rows (order_items of an order), never from customers to payments.
  • CHECK constraints for invariants: quantity > 0, ends_at > starts_at, discount <= total.
  • Multi-tenancy: tenant_id on every tenant table, first in unique keys and indexes, and in every FK (composite FKs prevent cross-tenant references).
  • Soft deletes: partial unique indexes WHERE deleted_at IS NULL, or the email can never be reused.
  • Denormalized totals: if orders.total is stored, say how it stays equal to the sum of order_items.
  • PII: list columns with personal data; consider a separate table with stricter access and retention.

FILE:references/type-choices.md

Type choices (PostgreSQL / MySQL 8)

DataPostgreSQLMySQL 8Avoid
Surrogate idbigint GENERATED ALWAYS AS IDENTITYBIGINT UNSIGNED AUTO_INCREMENTserial/int on growing tables
Public / distributed iduuid (UUIDv7 for index locality, gen_random_uuid() for v4)BINARY(16) with UUID_TO_BIN(x, 1)varchar(36) UUIDs (3x bigger, slower)
Moneynumeric(12,2) (or (19,4) for rates) + currency char(3)DECIMAL(12,2) + CHAR(3)float, double, real, Postgres money
Money as integerbigint amount_cents (mind currencies with 0 or 3 decimals)BIGINTint cents (overflows at 21 million)
Instant (event happened)timestamptzDATETIME(6) in UTC, or TIMESTAMP (2038 limit, converted by session zone)timestamp without time zone
Calendar datedateDATEtimestamps at midnight
Wall-clock time / scheduletime + an IANA zone columnTIME + zone columntimetz
Durationinterval or integer secondsINT secondstext like "1h30"
Texttext (+ CHECK for real limits)VARCHAR(n) with a real n; TEXT for long bodiesvarchar(255) by habit; char(n) padding
Case-insensitive text (email, username)citext or a lower() unique indexcase-insensitive _ci collation (default)plain unique on text in Postgres
Flagboolean NOT NULL DEFAULT falseBOOLEAN (TINYINT(1)) NOT NULL DEFAULT 0nullable booleans, 'Y'/'N' strings
Statustext + CHECK (... IN (...)), enum type, or lookup tableENUM(...) or lookup tableunconstrained text
JSONjsonb (GIN index for containment)JSON (generated columns to index)JSON in text
IP addressinet / cidrVARBINARY(16) with INET6_ATONtext
Large binaryobject storage + key in a text columnsamebig BLOBs in hot tables

Notes

  • Changing a column type later rewrites the table in both engines (with a few exceptions such as widening varchar in Postgres). Get ids and money right first.
  • Enum types in Postgres: adding a value is cheap, removing or renaming one is not. Lookup tables are easier to evolve and can carry labels and sort order.
  • NOT NULL with a sensible default is the norm; nullable should mean "genuinely unknown or not applicable".
  • Store the currency next to every amount, even if today there is only one.
  • Name things the same everywhere: customer_id in every table that references customers, _at for instants, _on or _date for dates, is_/has_ for booleans.

FILE:templates/schema-review.md

Schema review: <project / schema file>, <date>

Engine: <PostgreSQL 16> Scope: <5 tables: customers, products, orders, order_items, payments> Context: <OLTP shop backend, ~2M orders/year, Prisma ORM, no data yet> Command: python3 scripts/schema_lint.py <shop-schema.sql> Verdict: <CHANGES NEEDED before the first release: 4 HIGH, 8 MEDIUM, 8 LOW>

Must fix (HIGH)

#Table.columnFindingWhat goes wrongFix
1<products.price><FLOAT_MONEY><0.1 + 0.2 != 0.3; order totals drift by cents><numeric(12,2) NOT NULL CHECK (price >= 0)>

Should fix (MEDIUM)

#Table.columnFindingWhat goes wrongFix
1<"order"><RESERVED_WORD_NAME><must be quoted in every query and BI tool><rename to orders>

Consider (LOW / judgement calls)

  • <customers.email: citext so [email removed] and [email removed] are one account>

Found by reading (not by the linter)

  • <payments: add UNIQUE (provider, provider_id) so a webhook retry cannot record a payment twice>
  • <ON DELETE: keep RESTRICT on payments -> orders; CASCADE only order_items -> orders>

Corrected DDL

<full corrected schema, lints clean>

Decisions for the team

  • <bigint identity vs UUIDv7 for public ids>
  • <store orders.total or compute it from order_items?>

If tables already hold data

  • <each change above is a migration; list them and run a migration safety review before deploying>

FILE:examples/shop-schema.sql -- Small online shop schema (PostgreSQL), first draft for review. -- The problems are deliberate: this is what the skill is meant to catch.

CREATE TABLE customers ( id serial PRIMARY KEY, email varchar(255) NOT NULL UNIQUE, full_name varchar(255), phone varchar(255), is_verified boolean, created_at timestamp );

CREATE TABLE products ( id serial PRIMARY KEY, sku varchar(64) NOT NULL UNIQUE, title text NOT NULL, price double precision NOT NULL, attributes text, created_at timestamptz NOT NULL DEFAULT now() );

CREATE TABLE "order" ( id bigserial PRIMARY KEY, customer_id integer NOT NULL REFERENCES customers (id), status varchar(20) NOT NULL DEFAULT 'pending', total numeric(12,2) NOT NULL, placed_at timestamp NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now() );

CREATE TABLE order_items ( order_id bigint NOT NULL REFERENCES "order" (id), product_id bigint NOT NULL, quantity integer NOT NULL, unit_price numeric(12,2) NOT NULL );

CREATE TABLE payments ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, order_id integer NOT NULL REFERENCES "order" (id), amount real NOT NULL, provider text NOT NULL, provider_id text, created_at timestamptz NOT NULL DEFAULT now() );

CREATE INDEX payments_order_idx ON payments (order_id); CREATE INDEX payments_order_created_idx ON payments (order_id, created_at); FILE:examples/shop-schema-fixed.sql -- Small online shop schema (PostgreSQL), after review. -- Every change is explained in templates/schema-review.md style in the review.

CREATE EXTENSION IF NOT EXISTS citext;

CREATE TABLE customers ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email citext NOT NULL UNIQUE, full_name text, phone text CHECK (char_length(phone) <= 32), is_verified boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now() );

CREATE TABLE products ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, sku text NOT NULL UNIQUE, title text NOT NULL, price numeric(12,2) NOT NULL CHECK (price >= 0), attributes jsonb NOT NULL DEFAULT '{}', created_at timestamptz NOT NULL DEFAULT now() );

CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers (id), status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled', 'refunded')), total numeric(12,2) NOT NULL CHECK (total >= 0), placed_at timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX orders_customer_idx ON orders (customer_id);

CREATE TABLE order_items ( order_id bigint NOT NULL REFERENCES orders (id), product_id bigint NOT NULL REFERENCES products (id), quantity integer NOT NULL CHECK (quantity > 0), unit_price numeric(12,2) NOT NULL CHECK (unit_price >= 0), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (order_id, product_id) ); CREATE INDEX order_items_product_idx ON order_items (product_id);

CREATE TABLE payments ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, order_id bigint NOT NULL REFERENCES orders (id), amount numeric(12,2) NOT NULL, provider text NOT NULL, provider_id text, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (provider, provider_id) ); CREATE INDEX payments_order_created_idx ON payments (order_id, created_at); FILE:scripts/schema_lint.py #!/usr/bin/env python3 """SQL schema design linter for PostgreSQL and MySQL DDL (Python 3 standard library only).

Reads CREATE TABLE / CREATE INDEX / ALTER TABLE ... ADD statements (a schema dump, schema.sql, or the DDL of new tables in a pull request) and reports design problems that are cheap to fix before data exists and expensive after: tables without a primary key, money stored in floating point, foreign keys whose type differs from the referenced key or that have no supporting index (PostgreSQL), *_id columns without a foreign key, 32-bit primary keys, timestamps without time zone, nullable audit columns and booleans, unchecked status columns, reserved-word and mixed-case names, case-sensitive unique emails, redundant indexes, JSON kept in text columns, and MySQL tables using MyISAM or 3-byte utf8.

It does not connect to a database and does not judge migration safety (locks, backfills); it reviews the shape of the schema itself.

Usage: python3 schema_lint.py FILE.sql [FILE.sql ...] [--dialect auto|postgres|mysql] [--min-severity LOW|MEDIUM|HIGH] [--ignore CODE,CODE] [--json] python3 schema_lint.py --self-test Exit codes: 0 = no HIGH findings, 1 = HIGH findings, 2 = bad input (unreadable file, no CREATE TABLE found). """ import argparse, json, re, sys

SEV_ORDER = {"HIGH": 0, "MEDIUM": 1, "LOW": 2} MONEY_RE = re.compile(r"(^|_)(price|amount|total|subtotal|cost|balance|fee|fees|tax|salary|refund|discount|paid|payment|revenue|credit|debit|charge)(_|$)", re.I) RESERVED = {"user", "order", "group", "select", "table", "column", "desc", "asc", "check", "default", "from", "where", "limit", "offset", "references", "primary", "key", "range", "rank", "window", "all", "both", "end", "grant", "to", "type", "values", "constraint", "index", "match", "condition", "interval", "read", "row"} RESERVED_PG_ONLY_SAFE = {"key", "range", "rank", "type", "values", "match", "condition", "interval", "read", "row", "index"} # fine unquoted in Postgres RESERVED_MY_ONLY_SAFE = {"offset", "user", "end", "type", "values", "row"} # fine unquoted in MySQL 8 STATUS_RE = re.compile(r"^(status|state|kind|role|type|._status|._state|.*_type)$", re.I) JSONISH_RE = re.compile(r"(^|_)(json|payload|metadata|meta|attributes|settings|extra|data)$", re.I) INT32 = {"int", "integer", "int4", "serial", "serial4", "mediumint", "smallint", "int2", "smallserial", "tinyint"} INT64 = {"bigint", "int8", "bigserial", "serial8"}

def finding(sev, code, table, column, problem, fix, line=0): return {"severity": sev, "code": code, "table": table, "column": column, "line": line, "problem": problem, "fix": fix}

def strip_comments(sql): out, i, n = [], 0, len(sql) while i < n: c = sql[i] if c in "'\"`": j = i + 1 while j < n and sql[j] != c: j += 2 if sql[j] == "\\" and c == "'" else 1 out.append(sql[i:j + 1]); i = j + 1 elif sql.startswith("--", i) or c == "#" and (i == 0 or sql[i - 1] in "\n \t"): j = sql.find("\n", i); j = n if j < 0 else j out.append(" " (j - i)); i = j elif sql.startswith("/", i): j = sql.find("*/", i + 2); j = n if j < 0 else j + 2 out.append(re.sub(r"[^\n]", " ", sql[i:j])); i = j else: out.append(c); i += 1 return "".join(out)

def split_top(s, sep=","): parts, depth, cur, q = [], 0, [], None for ch in s: if q: cur.append(ch) if ch == q: q = None continue if ch in "'\"`": q = ch elif ch == "(": depth += 1 elif ch == ")": depth -= 1 if ch == sep and depth == 0: parts.append("".join(cur)); cur = [] else: cur.append(ch) if "".join(cur).strip(): parts.append("".join(cur)) return parts

def statements(sql): clean = strip_comments(sql) pos = 0 for part in split_top(clean, ";"): line = clean.count("\n", 0, pos + len(part) - len(part.lstrip())) + 1 pos += len(part) + 1 if part.strip(): yield line, part.strip()

def ident(s): s = s.strip() quoted = s[:1] in "\"" name = s.split(".")[-1].strip().strip("\"") return name, quoted

def cols_list(s): return [ident(re.sub(r"\s+(ASC|DESC|NULLS\s+(FIRST|LAST)).*$", "", c.strip(), flags=re.I))[0].lower() if not c.strip().startswith("(") and "(" not in c else c.strip().lower() for c in split_top(s)]

class Schema: def __init__(self): self.tables, self.indexes, self.fks, self.enums = {}, [], [], set() self.dialect_hints = {"mysql": 0, "postgres": 0}

def parse(sql): sc = Schema() if re.search(r"AUTO_INCREMENT|ENGINE\s=||UNSIGNED|DATETIME|TINYINT\(", sql, re.I): sc.dialect_hints["mysql"] += 1 if re.search(r"\bSERIAL\b|BIGSERIAL|TIMESTAMPTZ|JSONB|GENERATED\s+(ALWAYS|BY DEFAULT)\s+AS\s+IDENTITY|::|CREATE\s+TYPE|CITEXT|CONCURRENTLY|\bTEXT\[\]", sql, re.I): sc.dialect_hints["postgres"] += 1 for line, st in statements(sql): m = re.match(r"CREATE\s+(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w\".]+)\s\((.)\)\s(.)$", st, re.I | re.S) if m: name, quoted = ident(m.group(1)) t = {"name": name, "quoted": quoted, "line": line, "cols": {}, "order": [], "pk": [], "uniques": [], "checks": " ".join([]), "options": m.group(3), "raw": st} checks = [] for item in split_top(m.group(2)): parse_item(item.strip(), t, sc, checks) t["checks"] = " ".join(checks).lower() sc.tables[name.lower()] = t continue m = re.match(r"CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?([\w\".])\sON\s+(?:ONLY\s+)?([\w\".]+)\s(?:USING\s+\w+\s)?\((.)\)\s(.)$", st, re.I | re.S) if m: sc.indexes.append({"table": ident(m.group(3))[0].lower(), "cols": cols_list(m.group(4)), "unique": bool(m.group(1)), "name": ident(m.group(2))[0] if m.group(2) else "", "partial": "where" in m.group(5).lower(), "line": line}) continue m = re.match(r"ALTER\s+TABLE\s+(?:ONLY\s+)?(?:IF\s+EXISTS\s+)?([\w\".`]+)\s+(.)$", st, re.I | re.S) if m: tname = ident(m.group(1))[0].lower() for action in split_top(m.group(2)): a = action.strip() am = re.match(r"ADD\s+(?:COLUMN\s+)(?:IF\s+NOT\s+EXISTS\s+)?(.)$", a, re.I | re.S) if am and tname in sc.tables: parse_item(am.group(1), sc.tables[tname], sc, []) continue am = re.match(r"ADD\s+(.*)$", a, re.I | re.S) if am and tname in sc.tables: chk = [] parse_item(am.group(1), sc.tables[tname], sc, chk) sc.tables[tname]["checks"] += " " + " ".join(chk).lower() continue m = re.match(r"CREATE\s+TYPE\s+([\w\".]+)\s+AS\s+ENUM", st, re.I) if m: sc.enums.add(ident(m.group(1))[0].lower()) m = re.match(r"CREATE\s+(?:DOMAIN|EXTENSION)\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w\".]+)", st, re.I) if m: sc.enums.add(ident(m.group(1))[0].lower()) return sc

def parse_item(item, t, sc, checks): u = item.upper() m = re.match(r"CONSTRAINT\s+[\w\"]+\s+(.)$", item, re.I | re.S) if m: item, u = m.group(1).strip(), m.group(1).strip().upper() if u.startswith("PRIMARY KEY"): t["pk"] = cols_list(re.search(r"\((.)\)", item, re.S).group(1)); return if re.match(r"UNIQUE\b", u): cm = re.search(r"\((.?)\)", item, re.S) if cm: cols = cols_list(cm.group(1)) t["uniques"].append(cols) sc.indexes.append({"table": t["name"].lower(), "cols": cols, "unique": True, "name": "", "partial": False, "line": t["line"]}) return if u.startswith("FOREIGN KEY"): fm = re.match(r"FOREIGN\s+KEY\s\((.?)\)\sREFERENCES\s+([\w\".]+)\s(?:\((.?)\))?", item, re.I | re.S) if fm: sc.fks.append({"table": t["name"].lower(), "cols": cols_list(fm.group(1)), "ref": ident(fm.group(2))[0].lower(), "ref_cols": cols_list(fm.group(3)) if fm.group(3) else None}) return if u.startswith("CHECK"): checks.append(item); return if re.match(r"(UNIQUE\s+)?(KEY|INDEX)\b", u) or re.match(r"(FULLTEXT|SPATIAL)\b", u): cm = re.search(r"\((.)\)", item, re.S) if cm: sc.indexes.append({"table": t["name"].lower(), "cols": cols_list(cm.group(1)), "unique": u.startswith("UNIQUE"), "name": "", "partial": False, "line": t["line"]}) return if u.startswith(("EXCLUDE", "LIKE", "PERIOD")): return cm = re.match(r"([\"][^\"]+[\"]|[\w$]+)\s+(.)$", item, re.S) if not cm: return name, quoted = ident(cm.group(1)) rest = cm.group(2) tm = re.match(r"((?:double\s+precision|character\s+varying|bit\s+varying|timestamp(?:\s\(\d+\))?(?:\s+with(?:out)?\s+time\s+zone)?(?!\w)|time(?:\s+with(?:out)?\s+time\s+zone)?(?!\w)|[\w.]+)(?:\s\([^)]\))?(?:\s+unsigned)?(?:\s\[\])?)", rest, re.I) ctype = re.sub(r"\s+", " ", tm.group(1).lower()) if tm else "" ru = rest.upper() col = {"name": name, "quoted": quoted, "type": ctype, "not_null": "NOT NULL" in ru or "PRIMARY KEY" in ru, "default": "DEFAULT" in ru or "IDENTITY" in ru or "AUTO_INCREMENT" in ru or ctype.endswith("serial"), "check": "CHECK" in ru} t["cols"][name.lower()] = col t["order"].append(name.lower()) if "PRIMARY KEY" in ru: t["pk"] = [name.lower()] if re.search(r"\bUNIQUE\b", ru): t["uniques"].append([name.lower()]) sc.indexes.append({"table": t["name"].lower(), "cols": [name.lower()], "unique": True, "name": "", "partial": False, "line": t["line"]}) rm = re.search(r"REFERENCES\s+([\w\".]+)\s(?:\((.?)\))?", rest, re.I) if rm: sc.fks.append({"table": t["name"].lower(), "cols": [name.lower()], "ref": ident(rm.group(1))[0].lower(), "ref_cols": cols_list(rm.group(2)) if rm.group(2) else None}) if col["check"]: checks.append(f"check ({name})")

def qi(name): return f'"{name}"' if name.lower() in RESERVED or name != name.lower() else name

def base_type(ctype): t = re.sub(r"\(.*?\)|\s+unsigned|\[\]", "", ctype).strip() return {"int4": "integer", "int": "integer", "serial": "integer", "serial4": "integer", "int8": "bigint", "bigserial": "bigint", "serial8": "bigint", "int2": "smallint", "smallserial": "smallint"}.get(t, t)

def lint(sql, dialect="auto", ignore=()): sc = parse(sql) if dialect == "auto": dialect = "mysql" if sc.dialect_hints["mysql"] > sc.dialect_hints["postgres"] else "postgres" out = []

def add(a, *k): f = finding(a, *k) if f["code"] not in ignore: out.append(f)

The text continues at the source. Read the rest.

Source and license

Source: https://github.com/f/prompts.chat/blob/main/prompts/02732.md

Author: f, prompts.chat prompt library. License: CC0-1.0.

Shown here with formatting for the web; email addresses removed. Keep the author and license notice when you reuse it.

Related entries

There are more like this in the members library

The Business prompt library holds 3,008 entries. Members can search all of them by meaning and read every one in full.