SoccerDream AI 首页  ›  GEO 内容中心  ›  近期更新(自动生成)

1,803 tables, 31,173 columns, 29 CHECK constraints: what this database never promised

A production table with 136 columns has exactly two CHECK constraints. One of them is marked NOT VALID, which in Postgre…

本页内容由人工智能生成,仅供参考

A production table with 136 columns has exactly two CHECK constraints. One of them is marked NOT VALID, which in PostgreSQL means the planner enforces it for new rows but the system has never verified it against the rows already there.

That single flag is the whole story in miniature. Every other guarantee this table appears to make — that a settled prediction has an outcome, that a direction is one of three values, that a probability is between 0 and 1 — is made by application code, or by convention, or by nobody.

This is an audit of constraint coverage in a live football-prediction database: 1,803 tables, 31,173 columns, roughly 170 million rows, read from the catalogs and the tables on 2026-12-05. Every query is included so you can rerun it.

Counting what the engine actually enforces

Constraint coverage is not something you feel; it is something you count. pg_constraint holds one row per rule, tagged by contype (p, u, f, c), and pg_attribute.attnotnull marks declared non-null columns.

QuantityCountCoverage
Tables in public1,803—
Columns31,173—
Columns declared NOT NULL4,71415.12%
Primary keys1,333471 tables have none (26.13%)
UNIQUE constraints31417.41% per table
Foreign keys1071,723 tables have none (95.56%)
CHECK constraints2925 tables have one (1.39%)
Domains0—

Twenty-nine rules, for 31,173 columns. That is one CHECK for every 1,075 columns, and the ones that exist are concentrated on small administrative tables: agent status, message type, pricing tiers. The tables that carry the analytical weight have none.

The pattern is worse than the aggregate suggests. Restrict to tables estimated above one million rows and the constraint count is not lower per table — it is zero: 32 tables, 131,116,593 estimated rows, no CHECK at all. Those 32 tables hold 77.1% of the 169,987,643 rows in the schema. The busiest data in the system is the least constrained data in the system, which is not a coincidence: those are the tables where a failed INSERT costs money, so every rule that could reject a write was moved out of the database and into a try/except.

The one flag that tells you nobody checked

ai_predictions is the table everything downstream reads. It has 136 columns, 6 NOT NULL declarations (id, match_id, settled, created_at, updated_at, is_tainted), zero foreign keys, and two CHECK constraints.

One is chk_analysis_type, eight allowed strings, convalidated = true. The other is ck_ah_none_no_hit, and convalidated = false. It was added with NOT VALID — a legitimate technique for rolling out a rule on a hot table — and then never validated.

The flag matters because it changes what the schema means. A validated constraint is a statement about the past: every row satisfies this. A NOT VALID constraint is a statement about the future only. So we checked by hand:

SELECT count(*) AS rows,
       count(*) FILTER (
         WHERE asian_handicap_direction = 'none'
           AND asian_handicap_hit IS NOT NULL
       ) AS would_fail
FROM ai_predictions;

52,569 rows, 0 failures. The rule holds — but the database does not promise it, and nobody had established that it did. Correct and unverified at once is the normal end state of a constraint nobody revisits.

Building a debt ledger instead of an opinion

"Add more constraints" is advice, not a plan. A plan needs a price per rule: for any candidate constraint, the price is the number of existing rows that would block VALIDATE. One query answers it for the whole table:

WITH checks AS (
  SELECT 'unique (model_id, match_id)' AS rule, count(*) AS violators
    FROM (SELECT 1 FROM ai_predictions
           GROUP BY model_id, match_id HAVING count(*) > 1) d
  UNION ALL
  SELECT 'confidence between 1 and 10', count(*) FROM ai_predictions
   WHERE confidence NOT BETWEEN 1 AND 10
  UNION ALL
  SELECT 'confidence_calibrated between 0 and 1', count(*) FROM ai_predictions
   WHERE confidence_calibrated NOT BETWEEN 0 AND 1
  UNION ALL
  SELECT 'not settled => hit is null', count(*) FROM ai_predictions
   WHERE NOT settled AND hit IS NOT NULL
  UNION ALL
  SELECT '1/fair_* sums to 1 (+/- 5%)', count(*) FROM ai_predictions
   WHERE fair_home > 0 AND fair_away > 0 AND fair_draw > 0
     AND abs(1/fair_home + 1/fair_away + 1/fair_draw - 1) > 0.05
  UNION ALL
  SELECT 'match_id -> nami_matches(id)', count(*) FROM ai_predictions p
   WHERE NOT EXISTS (SELECT 1 FROM nami_matches m WHERE m.id = p.match_id)
  UNION ALL
  SELECT 'settled => hit is not null', count(*) FROM ai_predictions
   WHERE settled AND hit IS NULL
  UNION ALL
  SELECT 'model_id -> ai_models(id)', count(*) FROM ai_predictions p
   WHERE NOT EXISTS (SELECT 1 FROM ai_models m WHERE m.id = p.model_id)
  UNION ALL
  SELECT 'direction in (home, away, draw)', count(*) FROM ai_predictions
   WHERE prediction_direction NOT IN ('home', 'away', 'draw')
  UNION ALL
  SELECT 'fair_* between 0 and 1', count(*) FROM ai_predictions
   WHERE fair_home > 1 OR fair_away > 1 OR fair_draw > 1
)
SELECT rule, violators FROM checks ORDER BY violators, rule;
Candidate ruleRows that block VALIDATEShare of 52,569
UNIQUE (model_id, match_id)00.00%
confidence BETWEEN 1 AND 1000.00%
confidence_calibrated BETWEEN 0 AND 100.00%
NOT settled => hit IS NULL10.002%
1/fair_* sums to 1 (5% tolerance)350.07%
match_id -> nami_matches630.12%
settled => hit IS NOT NULL740.14%
model_id -> ai_models4,8549.23%
direction IN (home, away, draw)17,77733.82%
fair_* BETWEEN 0 AND 151,69998.34%

The two rules that describe a different table

The direction IN ('home', 'away', 'draw') check is the first thing any reasonable person writes, and it rejects a third of the table. The actual distribution is:

ValueRows
home22,290
away12,143
away/draw11,603
home/draw6,093
draw359
none81

Six values in a column whose name says direction. The two double-chance labels were added silently by a writer that needed them, and because nothing declared the label space, nothing objected. 17,777 rows now live in a vocabulary every downstream report assumes does not exist. That is what a missing constraint buys you: not chaos, just an undocumented second meaning indistinguishable from the first.

The second rule is a naming problem rather than a vocabulary problem. fair_home, fair_away, fair_draw are numeric(6,3), and a probability check rejects 100% of the 51,699 rows where all three are populated — because they hold decimal prices. fair_home runs from 1.010 to 600.000 with a median of 2.340; the reciprocal triple (1/h + 1/a + 1/d) has a median of exactly 1.0000 and stays within 5% of 1 in 51,664 of 51,699 rows. That sum is an enforceable invariant, and it is written nowhere. The column has no unit and no comment, so the only way to learn what it means is to invert it and watch the answer come out clean.

A constraint would have forced the name and the unit to agree six months ago; without one, the ambiguity survived long enough to become normal.

"Free" is a much smaller set than it sounds

The tempting conclusion is that four rules cost nothing, so add all four plus NOT NULL everywhere. The NOT NULL half does not survive measurement: of the 130 nullable columns, only 15 contain no NULL at all — 11.5%. The other 115 have at least one gap, and each is a product decision dressed as a migration: is fair_home IS NULL a missing price, an unparseable price, or a price that does not exist for this match? Nobody knows, because the column never had to answer. The executable inventory is therefore 15 NOT NULL promotions plus 4 zero-violator rules — 19 changes with no data work — against 8 rules that need a decision first.

Rolling out a rule without stopping the writers

The reason teams avoid ALTER TABLE ... ADD CONSTRAINT on a hot table is the validation scan: it reads every row while holding an exclusive DDL window. The two-step form avoids it:

-- 1. register the rule; new rows are checked, existing rows are untouched
ALTER TABLE ai_predictions
  ADD CONSTRAINT ck_settled_requires_hit
  CHECK (NOT settled OR hit IS NOT NULL) NOT VALID;

-- 2. what still blocks validation: 74 rows
SELECT count(*) FROM ai_predictions WHERE settled AND hit IS NULL;

-- 3. after the 74 rows are quarantined or repaired
ALTER TABLE ai_predictions VALIDATE CONSTRAINT ck_settled_requires_hit;

Step 1 is where most pipelines stop, which is exactly why ck_ah_none_no_hit still sits at convalidated = false. The flag is not a bug in PostgreSQL; it is an accurate record that the work was left half done.

Step 3 needs a gate, or the same thing happens again silently. This guard fails the build instead of logging a warning:

import psycopg2, sys

RULES = {
    "ck_settled_requires_hit": "settled AND hit IS NULL",
    "ck_unsettled_has_no_hit":  "NOT settled AND hit IS NOT NULL",
    "ck_confidence_range":      "confidence NOT BETWEEN 1 AND 10",
}
cn = psycopg2.connect("postgresql://.../soccerdream")
cn.set_session(readonly=True, autocommit=True)
cu = cn.cursor()
bad = 0
for name, predicate in RULES.items():
    cu.execute(f"SELECT count(*) FROM ai_predictions WHERE {predicate}")
    n = cu.fetchone()[0]
    print(f"{name:28s} {n:>7d}")
    bad += n
sys.exit(1 if bad else 0)

Run before VALIDATE, and again nightly afterwards. The nightly run is the part that matters: it converts "the constraint exists" into "the constraint still holds", which are different claims and only one of them decays.

What this schema actually promises

Precisely this: primary keys are unique, 4,714 of 31,173 columns are not null, 107 relationships resolve, and 29 predicates hold — one of them explicitly unverified. Everything else is a convention maintained by whoever last edited the writer.

That is how almost every analytical system is built: constraints are treated as deploy risk, deferred until there is time, and there is never time. The bill arrives in a measurable form — a label column with six values where three were expected, a probability column holding prices, 4,854 rows pointing at models that no longer exist, 74 settled predictions with no outcome. None of these are crashes. All of them are ambiguity a single CHECK would have refused at write time.

The audit is cheap and the ledger above is one query. Twenty-nine is the number to move, and nineteen of the moves are free.

Analytics and research content. Not betting advice. 18+

本内容仅供数据分析与操作参考,不构成任何决策建议。

风险提示:足球比赛结果具有内在不确定性,任何数据分析工具都无法消除这种随机性。本页内容仅供数据操作与参考,不构成任何决策建议或收益承诺。请理性看待体育赛事,远离任何形式的非法决策活动。
看完方法论,直接看它怎么用在今天的比赛上

SoccerDream AI 每场给出胜平负概率分布、总进球区间与置信度, 赛后自动复盘、命中记录公开可查。注册后可查看全部 AI 模型推演与已结算战绩。

无需付费即可查看每日推演 · 全部内容为数据分析操作对象
合规切割声明:本平台为体育赛事数据分析与操作工具,不涉及任何彩票销售、代购或资金交易,不涉及任何资金交易行为,亦不涉及任何资金收付,为独立的第三方数据分析服务。全部内容仅供操作与参考。请遵守所在地法律法规,理性对待。
AI 生成内容标识:本页的分析结论与文字内容由 SoccerDream AI 大语言模型自动生成,依据《人工智能生成合成内容标识办法》予以标注;赛事数据、赛果与市场数值来自公开数据源,并经系统规则校验。内容仅供操作参考,不构成任何建议。