codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
"""A real PostgreSQL, read-only, through pg8000 (pure Python; install with `pip install 'codecop[postgres]'`).
|
|
2
|
+
|
|
3
|
+
On connect the session is made read-only (`default_transaction_read_only = on`, checked by reading
|
|
4
|
+
`transaction_read_only` back) and given a statement timeout, a short lock timeout and an idle timeout.
|
|
5
|
+
The server then rejects any write, and a statement that would wait on a lock gives up after two seconds.
|
|
6
|
+
Nothing here takes more than an ACCESS SHARE lock: the statements read catalogs and statistics views.
|
|
7
|
+
|
|
8
|
+
`pg_stats` is read for `n_distinct`, `null_frac`, `avg_width` and `correlation` only. The columns that hold
|
|
9
|
+
data values (`most_common_vals`, `histogram_bounds`, ...) are never selected.
|
|
10
|
+
|
|
11
|
+
Tier C here is `EXPLAIN (GENERIC_PLAN)` (PostgreSQL 16+), which plans a parameterised statement and cannot
|
|
12
|
+
execute it. Its input is the server's own normalized text from pg_stat_statements, so it sits behind an
|
|
13
|
+
explicit flag and is not part of a default pull.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
import ssl
|
|
20
|
+
import time
|
|
21
|
+
|
|
22
|
+
from . import (CATALOG_LIMITS, PULL_DEFAULTS, TLS_MODES, TLS_VERIFY_HINT, WORKLOAD_LIMITS, Audit, Connection, DbError, Limits, Refused,
|
|
23
|
+
Statement, check_statement, tls_attempts)
|
|
24
|
+
|
|
25
|
+
_USER_SCHEMAS = "n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND n.nspname NOT LIKE 'pg_temp%' AND n.nspname NOT LIKE 'pg_toast_temp%'"
|
|
26
|
+
PLAN_LIMITS = Limits(seconds=5)
|
|
27
|
+
SESSION_SETUP = (
|
|
28
|
+
"SET default_transaction_read_only = on",
|
|
29
|
+
"SET lock_timeout = 2000",
|
|
30
|
+
"SET idle_in_transaction_session_timeout = 60000",
|
|
31
|
+
"SET application_name = 'codecop-db'",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
STATEMENTS: dict[str, Statement] = {s.id: s for s in [
|
|
35
|
+
Statement("pg.check.server", "check",
|
|
36
|
+
"SELECT current_setting('server_version') AS version, current_setting('server_version_num')::int AS version_num, "
|
|
37
|
+
"current_setting('transaction_read_only') AS transaction_read_only, current_setting('statement_timeout') AS statement_timeout, "
|
|
38
|
+
"current_setting('lock_timeout') AS lock_timeout, pg_is_in_recovery() AS is_replica",
|
|
39
|
+
"Server version, and the read-only state and timeouts of this session as the server reports them."),
|
|
40
|
+
Statement("pg.check.role", "check",
|
|
41
|
+
"SELECT r.rolsuper AS superuser, r.rolcreatedb AS createdb, r.rolcreaterole AS createrole, r.rolreplication AS replication, "
|
|
42
|
+
"pg_has_role(current_user, 'pg_read_all_stats', 'USAGE') AS read_all_stats, "
|
|
43
|
+
"pg_has_role(current_user, 'pg_monitor', 'USAGE') AS monitor, "
|
|
44
|
+
"has_database_privilege(current_database(), 'CREATE') AS can_create_schema "
|
|
45
|
+
"FROM pg_roles r WHERE r.rolname = current_user",
|
|
46
|
+
"What the account is allowed to do (to report whether it could write without this tool's read-only session)."),
|
|
47
|
+
Statement("pg.check.write_access", "check",
|
|
48
|
+
"SELECT count(*) AS tables, count(*) FILTER (WHERE has_table_privilege(c.oid, 'INSERT') OR has_table_privilege(c.oid, 'UPDATE') "
|
|
49
|
+
"OR has_table_privilege(c.oid, 'DELETE') OR has_table_privilege(c.oid, 'TRUNCATE')) AS writable, "
|
|
50
|
+
"count(*) FILTER (WHERE has_table_privilege(c.oid, 'SELECT')) AS readable "
|
|
51
|
+
f"FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'p') AND {_USER_SCHEMAS}",
|
|
52
|
+
"How many tables the account may read and how many it may write."),
|
|
53
|
+
Statement("pg.check.extensions", "check",
|
|
54
|
+
"SELECT extname AS name, extversion AS version FROM pg_extension ORDER BY extname",
|
|
55
|
+
"Installed extensions (is pg_stat_statements there)."),
|
|
56
|
+
Statement("pg.check.statements_visible", "check",
|
|
57
|
+
"SELECT count(*) AS statements, count(*) FILTER (WHERE query = '<insufficient privilege>') AS hidden FROM pg_stat_statements",
|
|
58
|
+
"Whether pg_stat_statements can be read and how much of it the account may see.", optional=True),
|
|
59
|
+
Statement("pg.catalog.tables", "A",
|
|
60
|
+
"SELECT n.nspname AS schema, c.relname AS name, c.relkind::text AS kind, c.reltuples::bigint AS estimated_rows, "
|
|
61
|
+
"c.relpages::bigint AS pages, c.relispartition AS is_partition, "
|
|
62
|
+
"CASE WHEN c.relkind = 'p' THEN pg_get_partkeydef(c.oid) END AS partition_key, "
|
|
63
|
+
"(SELECT pn.nspname || '.' || pc.relname FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent "
|
|
64
|
+
"JOIN pg_namespace pn ON pn.oid = pc.relnamespace WHERE i.inhrelid = c.oid LIMIT 1) AS parent, "
|
|
65
|
+
"pg_table_size(c.oid) AS table_bytes, pg_indexes_size(c.oid) AS index_bytes, pg_total_relation_size(c.oid) AS total_bytes, "
|
|
66
|
+
"s.n_live_tup AS live_rows, s.n_dead_tup AS dead_rows, s.seq_scan, s.seq_tup_read, s.idx_scan, s.idx_tup_fetch, "
|
|
67
|
+
"s.n_tup_ins AS inserted, s.n_tup_upd AS updated, s.n_tup_del AS deleted, s.last_analyze::text AS last_analyze, "
|
|
68
|
+
"s.last_autoanalyze::text AS last_autoanalyze, s.last_autovacuum::text AS last_autovacuum "
|
|
69
|
+
"FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid "
|
|
70
|
+
f"WHERE c.relkind IN ('r', 'p', 'm') AND {_USER_SCHEMAS} ORDER BY pg_total_relation_size(c.oid) DESC LIMIT 5000",
|
|
71
|
+
"Tables with their sizes, estimated rows and how they are read (sequential scans against index scans)."),
|
|
72
|
+
Statement("pg.catalog.columns", "A",
|
|
73
|
+
"SELECT n.nspname AS schema, c.relname AS table, a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, "
|
|
74
|
+
"a.attnotnull AS not_null, a.attnum AS position, pg_get_expr(d.adbin, d.adrelid) AS default_expr, a.attidentity::text AS identity, "
|
|
75
|
+
"a.attgenerated::text AS generated, st.n_distinct, st.null_frac, st.avg_width, st.correlation "
|
|
76
|
+
"FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace "
|
|
77
|
+
"LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum "
|
|
78
|
+
"LEFT JOIN pg_stats st ON st.schemaname = n.nspname AND st.tablename = c.relname AND st.attname = a.attname AND st.inherited = (c.relkind = 'p') "
|
|
79
|
+
f"WHERE a.attnum > 0 AND NOT a.attisdropped AND c.relkind IN ('r', 'p', 'm') AND NOT c.relispartition AND {_USER_SCHEMAS} "
|
|
80
|
+
"ORDER BY n.nspname, c.relname, a.attnum LIMIT 200000",
|
|
81
|
+
"Columns with their types and four planner statistics: distinct count, null fraction, width, correlation. No data values."),
|
|
82
|
+
Statement("pg.catalog.indexes", "A",
|
|
83
|
+
"SELECT n.nspname AS schema, t.relname AS table, i.relname AS name, pg_get_indexdef(x.indexrelid) AS definition, "
|
|
84
|
+
"x.indisunique AS is_unique, x.indisprimary AS is_primary, x.indisvalid AS is_valid, pg_relation_size(x.indexrelid) AS bytes, "
|
|
85
|
+
"s.idx_scan AS scans, s.idx_tup_read AS tuples_read, s.idx_tup_fetch AS tuples_fetched "
|
|
86
|
+
"FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid "
|
|
87
|
+
"JOIN pg_namespace n ON n.oid = t.relnamespace LEFT JOIN pg_stat_user_indexes s ON s.indexrelid = x.indexrelid "
|
|
88
|
+
f"WHERE NOT t.relispartition AND {_USER_SCHEMAS} ORDER BY n.nspname, t.relname, i.relname LIMIT 50000",
|
|
89
|
+
"Indexes with their definitions, sizes and how often each is used."),
|
|
90
|
+
Statement("pg.catalog.constraints", "A",
|
|
91
|
+
"SELECT n.nspname AS schema, c.relname AS table, k.conname AS name, k.contype::text AS type, pg_get_constraintdef(k.oid) AS definition "
|
|
92
|
+
"FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace "
|
|
93
|
+
f"WHERE NOT c.relispartition AND {_USER_SCHEMAS} ORDER BY n.nspname, c.relname, k.conname LIMIT 50000",
|
|
94
|
+
"Primary keys, unique, foreign-key and check constraints."),
|
|
95
|
+
Statement("pg.catalog.enums", "A",
|
|
96
|
+
"SELECT n.nspname AS schema, t.typname AS name, array_agg(e.enumlabel::text ORDER BY e.enumsortorder) AS labels "
|
|
97
|
+
f"FROM pg_type t JOIN pg_enum e ON e.enumtypid = t.oid JOIN pg_namespace n ON n.oid = t.typnamespace WHERE {_USER_SCHEMAS} "
|
|
98
|
+
"GROUP BY n.nspname, t.typname ORDER BY 1, 2 LIMIT 2000",
|
|
99
|
+
"Enum types, needed to rebuild a table definition."),
|
|
100
|
+
Statement("pg.workload.info", "B",
|
|
101
|
+
"SELECT stats_reset::text AS since, dealloc AS evictions FROM pg_stat_statements_info",
|
|
102
|
+
"Since when pg_stat_statements has been counting.", WORKLOAD_LIMITS, optional=True),
|
|
103
|
+
Statement("pg.workload.totals", "B",
|
|
104
|
+
"SELECT count(*) AS shapes, sum(calls)::bigint AS executions, sum(total_exec_time) AS total_ms, sum(rows)::bigint AS rows, "
|
|
105
|
+
"sum(shared_blks_hit + shared_blks_read)::bigint AS blocks FROM pg_stat_statements "
|
|
106
|
+
"WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())",
|
|
107
|
+
"Totals, so each query's share of the load can be stated.", WORKLOAD_LIMITS),
|
|
108
|
+
Statement("pg.workload.top", "B",
|
|
109
|
+
"SELECT * FROM (SELECT queryid::text AS hash, calls AS executions, total_exec_time AS total_ms, mean_exec_time AS avg_ms, "
|
|
110
|
+
"max_exec_time AS max_ms, rows AS result_rows, shared_blks_hit AS blocks_hit, shared_blks_read AS blocks_read, "
|
|
111
|
+
"temp_blks_written AS temp_blocks, query AS text, "
|
|
112
|
+
"row_number() OVER (ORDER BY shared_blks_hit + shared_blks_read DESC) AS by_bytes, "
|
|
113
|
+
"row_number() OVER (ORDER BY calls DESC) AS by_executions, row_number() OVER (ORDER BY total_exec_time DESC) AS by_time "
|
|
114
|
+
"FROM pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) "
|
|
115
|
+
"AND query ~* '^\\s*(/\\*.*?\\*/\\s*)?(select|with|insert|update|delete)\\M' AND query <> '<insufficient privilege>') q "
|
|
116
|
+
"WHERE by_bytes <= :top OR by_executions <= :top OR by_time <= :top ORDER BY by_bytes",
|
|
117
|
+
"The heaviest and the most frequent statements. pg_stat_statements stores them already normalized ($1, $2 for every "
|
|
118
|
+
"constant); utility statements, which are stored as written, are left out.", WORKLOAD_LIMITS),
|
|
119
|
+
]}
|
|
120
|
+
|
|
121
|
+
# ---- the resource profile per statement --------------------------------------------------------
|
|
122
|
+
# pg_stat_statements has no CPU and no memory column. What it has beyond pg.workload.top: plan time, max and stddev of
|
|
123
|
+
# the run time, time waiting on reads and writes (track_io_timing), blocks from disk and dirtied, temp blocks, WAL bytes.
|
|
124
|
+
# Its columns follow the extension's version, which follows the server's (verified on 13, 14, 15, 16 and 17):
|
|
125
|
+
# 13, 14 blk_read_time, blk_write_time; wal_bytes
|
|
126
|
+
# 15, 16 + temp_blk_read_time, temp_blk_write_time, jit_*_time
|
|
127
|
+
# 17+ blk_read_time and blk_write_time are named shared_blk_read_time, shared_blk_write_time
|
|
128
|
+
# The form is chosen by server_version_num and, when the server says a column does not exist (an extension not
|
|
129
|
+
# updated after an upgrade), the next older form is tried.
|
|
130
|
+
_PGSS_DB = "dbid = (SELECT oid FROM pg_database WHERE datname = current_database())"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _resource_sums(form: str) -> str:
|
|
134
|
+
wait_read, wait_write = ("shared_blk_read_time", "shared_blk_write_time") if form == "v17" else ("blk_read_time", "blk_write_time")
|
|
135
|
+
newer = (", sum(temp_blk_read_time + temp_blk_write_time) AS temp_wait_ms, "
|
|
136
|
+
"sum(jit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time) AS jit_ms") if form in ("v15", "v17") else ""
|
|
137
|
+
return (f"sum(calls)::bigint AS executions, sum(total_exec_time) AS total_ms, sum(total_plan_time) AS plan_ms, "
|
|
138
|
+
f"sum({wait_read}) AS read_wait_ms, sum({wait_write}) AS write_wait_ms, "
|
|
139
|
+
"sum(shared_blks_read)::bigint AS blocks_from_disk, sum(shared_blks_dirtied)::bigint AS blocks_dirtied, "
|
|
140
|
+
"sum(local_blks_hit + local_blks_read)::bigint AS local_blocks, "
|
|
141
|
+
"sum(temp_blks_read)::bigint AS temp_blocks_read, sum(temp_blks_written)::bigint AS temp_blocks_written, "
|
|
142
|
+
f"sum(wal_bytes)::bigint AS wal_bytes{newer}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
RESOURCE_FORMS = ("v17", "v15", "") # newest first; "" is the 13 and 14 form
|
|
146
|
+
for _form in RESOURCE_FORMS:
|
|
147
|
+
_sfx = f".{_form}" if _form else ""
|
|
148
|
+
STATEMENTS[f"pg.workload.resources{_sfx}"] = Statement(
|
|
149
|
+
f"pg.workload.resources{_sfx}", "B",
|
|
150
|
+
f"SELECT queryid::text AS hash, {_resource_sums(_form)}, max(max_exec_time) AS max_ms, max(stddev_exec_time) AS stddev_ms "
|
|
151
|
+
f"FROM pg_stat_statements WHERE {_PGSS_DB} AND queryid = ANY(:hashes::bigint[]) GROUP BY queryid",
|
|
152
|
+
"Per kept statement, summed over the accounts that ran it: plan time, max and standard deviation of the run time, time "
|
|
153
|
+
"waiting on reads and writes (with track_io_timing), blocks read from disk and dirtied, temp blocks, WAL bytes"
|
|
154
|
+
+ (", temp wait and JIT time" if _form else "") + f" (PostgreSQL {'17 and later' if _form == 'v17' else '15 and 16' if _form else '13 and 14'}). "
|
|
155
|
+
"Numbers only.", WORKLOAD_LIMITS, optional=True)
|
|
156
|
+
STATEMENTS[f"pg.workload.resource_totals{_sfx}"] = Statement(
|
|
157
|
+
f"pg.workload.resource_totals{_sfx}", "B",
|
|
158
|
+
f"SELECT {_resource_sums(_form)} FROM pg_stat_statements WHERE {_PGSS_DB}",
|
|
159
|
+
"The same sums over every statement of this database, one row, so a statement's share of the time, the waits and the "
|
|
160
|
+
"spill can be stated.", WORKLOAD_LIMITS, optional=True)
|
|
161
|
+
STATEMENTS.update({s.id: s for s in [
|
|
162
|
+
Statement("pg.check.settings", "check",
|
|
163
|
+
"SELECT name, setting, unit FROM pg_settings WHERE name IN ('work_mem', 'hash_mem_multiplier', 'shared_buffers', "
|
|
164
|
+
"'max_connections', 'max_parallel_workers_per_gather', 'track_io_timing', 'pg_stat_statements.track_planning', 'jit', "
|
|
165
|
+
"'temp_file_limit', 'block_size')",
|
|
166
|
+
"Ten server settings by name: the memory a sort or hash may use, whether disk waits and planning are timed, the block "
|
|
167
|
+
"size, so a figure can be said for what it is and the sandbox can sort in the memory production gives.", optional=True),
|
|
168
|
+
Statement("pg.workload.temp", "B",
|
|
169
|
+
"SELECT temp_files, temp_bytes, blk_read_time, blk_write_time FROM pg_stat_database WHERE datname = current_database()",
|
|
170
|
+
"Temp files and bytes and the time waiting on reads and writes of this database since the statistics reset, to state a "
|
|
171
|
+
"statement's share of all spill. One row.", WORKLOAD_LIMITS, optional=True),
|
|
172
|
+
# pg_stat_kcache: the one source of CPU per statement on PostgreSQL. Only when pg.check.extensions lists it.
|
|
173
|
+
Statement("pg.workload.kcache", "B",
|
|
174
|
+
"SELECT queryid::text AS hash, sum(exec_user_time) AS user_s, sum(exec_system_time) AS system_s, "
|
|
175
|
+
"sum(exec_reads)::bigint AS disk_read_bytes, sum(exec_writes)::bigint AS disk_write_bytes, "
|
|
176
|
+
"sum(exec_majflts)::bigint AS major_faults, sum(exec_nivcsws)::bigint AS involuntary_switches "
|
|
177
|
+
f"FROM pg_stat_kcache() WHERE {_PGSS_DB} AND queryid = ANY(:hashes::bigint[]) GROUP BY queryid",
|
|
178
|
+
"CPU per kept statement from pg_stat_kcache (2.2 and later): user and system CPU seconds of execution, bytes really "
|
|
179
|
+
"read from and written to disk, major page faults, involuntary context switches. Numbers only.", WORKLOAD_LIMITS, optional=True),
|
|
180
|
+
Statement("pg.workload.kcache.v21", "B",
|
|
181
|
+
"SELECT queryid::text AS hash, sum(user_time) AS user_s, sum(system_time) AS system_s, "
|
|
182
|
+
"sum(reads)::bigint AS disk_read_bytes, sum(writes)::bigint AS disk_write_bytes, "
|
|
183
|
+
"sum(majflts)::bigint AS major_faults, sum(nivcsws)::bigint AS involuntary_switches "
|
|
184
|
+
f"FROM pg_stat_kcache() WHERE {_PGSS_DB} AND queryid = ANY(:hashes::bigint[]) GROUP BY queryid",
|
|
185
|
+
"The same for pg_stat_kcache before 2.2.", WORKLOAD_LIMITS, optional=True),
|
|
186
|
+
]})
|
|
187
|
+
KCACHE = "pg_stat_kcache"
|
|
188
|
+
SETTING_UNITS = {"kB": 1024, "8kB": 8192, "MB": 1024 ** 2, "B": 1}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def setting_value(row: dict):
|
|
192
|
+
"""A pg_settings row as a number in bytes (memory settings), a number, or on/off as a boolean."""
|
|
193
|
+
text, unit = str(row.get("setting") or ""), str(row.get("unit") or "")
|
|
194
|
+
if text in ("on", "off"):
|
|
195
|
+
return text == "on"
|
|
196
|
+
try:
|
|
197
|
+
value = float(text)
|
|
198
|
+
except ValueError:
|
|
199
|
+
return text[:40]
|
|
200
|
+
return int(value * SETTING_UNITS[unit]) if unit in SETTING_UNITS and value >= 0 else (int(value) if value.is_integer() else value)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def resource_form(version_num: int) -> str:
|
|
204
|
+
return "v17" if version_num >= 170000 else "v15" if version_num >= 150000 else ""
|
|
205
|
+
|
|
206
|
+
EXPLAINABLE = re.compile(r"^\s*(?:SELECT|WITH)\b", re.I)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def explain_statement(text: str) -> Statement:
|
|
210
|
+
"""Tier C: plan a normalized statement without running it. Only a single SELECT is accepted."""
|
|
211
|
+
body = text.strip().rstrip(";")
|
|
212
|
+
if not EXPLAINABLE.match(body) or ";" in body or re.search(r"\bINTO\b|\bFOR\s+(?:UPDATE|SHARE|NO\s+KEY)\b|\bnextval\s*\(|\bsetval\s*\(|\bpg_\w*(?:sleep|terminate|cancel|advisory|reload|rotate|switch|promote|read_file|ls_dir|stat_reset)\w*\s*\(|\blo_\w+\s*\(|\bdblink\w*\s*\(|\bcopy\b", body, re.I):
|
|
213
|
+
raise DbError("Only a plain SELECT is explained.")
|
|
214
|
+
return Statement("pg.plan.generic", "C", f"EXPLAIN (GENERIC_PLAN, FORMAT JSON) {body}",
|
|
215
|
+
"The plan the server would choose for a statement from its own workload, without executing it.", PLAN_LIMITS)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def quote_ident(name: str) -> str:
|
|
219
|
+
return '"' + name.replace('"', '""') + '"'
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# PostgreSQL's reserved key words and the ones that can not be a table name unquoted (Appendix C, "reserved" and
|
|
223
|
+
# "reserved (can be function or type)"): a table named `user` or `order` is written quoted, or CREATE TABLE fails
|
|
224
|
+
RESERVED = frozenset("""all analyse analyze and any array as asc asymmetric authorization binary both case cast check collate
|
|
225
|
+
collation column concurrently constraint create cross current_catalog current_date current_role current_schema current_time
|
|
226
|
+
current_timestamp current_user default deferrable desc distinct do else end except false fetch for foreign freeze from full
|
|
227
|
+
grant group having ilike in initially inner intersect into is isnull join lateral leading left like limit localtime
|
|
228
|
+
localtimestamp natural not notnull null offset on only or order outer overlaps placing primary references returning right
|
|
229
|
+
select session_user similar some symmetric system_user table tablesample then to trailing true union unique user using
|
|
230
|
+
variadic verbose when where window with""".split())
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def name_sql(name: str) -> str:
|
|
234
|
+
"""A table name as SQL: bare when PostgreSQL reads it back as written (lower case, a plain word, not reserved),
|
|
235
|
+
quoted otherwise. `schema.table` is quoted part by part."""
|
|
236
|
+
return ".".join(p if re.fullmatch(r"[a-z_][a-z0-9_$]*", p) and p not in RESERVED else quote_ident(p) for p in name.split("."))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def quote_created_table(create_sql: str) -> str:
|
|
240
|
+
"""The CREATE TABLE of a pulled script with its table name quoted where it must be (a catalog file pulled before
|
|
241
|
+
name_sql wrote `CREATE TABLE user (`)."""
|
|
242
|
+
def one(m: re.Match) -> str:
|
|
243
|
+
return m.group(1) + name_sql(m.group(2))
|
|
244
|
+
return re.sub(r"(?im)^(\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?)((?:[A-Za-z_][\w$]*\.)?[A-Za-z_][\w$]*)(?=\s*\()", one, create_sql or "")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def table_script(table: dict, enums: dict[tuple[str, str], list[str]]) -> str:
|
|
248
|
+
"""A CREATE script for one table from the catalog rows: types it needs, the table, then its indexes."""
|
|
249
|
+
lines = []
|
|
250
|
+
used = {c["type"].split("[")[0] for c in table["columns"]}
|
|
251
|
+
for (schema, name), labels in enums.items():
|
|
252
|
+
if name in used or f"{schema}.{name}" in used:
|
|
253
|
+
values = ", ".join("'" + v.replace("'", "''") + "'" for v in labels)
|
|
254
|
+
lines.append(f"CREATE TYPE {quote_ident(name)} AS ENUM ({values})")
|
|
255
|
+
cols = []
|
|
256
|
+
for c in table["columns"]:
|
|
257
|
+
text = f" {quote_ident(c['name'])} {c['type']}"
|
|
258
|
+
if c.get("generated") == "s" and c.get("default_expr"):
|
|
259
|
+
text += f" GENERATED ALWAYS AS ({c['default_expr']}) STORED"
|
|
260
|
+
elif c.get("identity") in ("a", "d"):
|
|
261
|
+
text += " GENERATED " + ("ALWAYS" if c["identity"] == "a" else "BY DEFAULT") + " AS IDENTITY"
|
|
262
|
+
elif c.get("default_expr"):
|
|
263
|
+
text += f" DEFAULT {c['default_expr']}"
|
|
264
|
+
if c.get("not_null"):
|
|
265
|
+
text += " NOT NULL"
|
|
266
|
+
cols.append(text)
|
|
267
|
+
for k in table.get("constraints") or []:
|
|
268
|
+
if k["type"] in ("p", "u"):
|
|
269
|
+
cols.append(f" CONSTRAINT {quote_ident(k['name'])} {k['definition']}")
|
|
270
|
+
name = name_sql(table["name"] if table["schema"] == "public" else f"{table['schema']}.{table['name']}")
|
|
271
|
+
create = f"CREATE TABLE {name} (\n" + ",\n".join(cols) + "\n)"
|
|
272
|
+
if table.get("partition_key"):
|
|
273
|
+
create += f" PARTITION BY {table['partition_key']}"
|
|
274
|
+
lines.append(create)
|
|
275
|
+
backing = {k["name"] for k in table.get("constraints") or [] if k["type"] in ("p", "u")}
|
|
276
|
+
lines += [ix["definition"] for ix in table.get("indexes") or [] if ix["name"] not in backing and ix.get("is_valid", True)]
|
|
277
|
+
return ";\n".join(lines)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class PostgresReader:
|
|
281
|
+
engine = "postgres"
|
|
282
|
+
|
|
283
|
+
def __init__(self, connection: Connection, audit: Audit, *, timeout: int = 30, dry_run: bool = False, allow_plaintext: bool = False,
|
|
284
|
+
settings: dict | None = None):
|
|
285
|
+
self.connection, self.audit, self.timeout, self.dry_run = connection, audit, timeout, dry_run
|
|
286
|
+
self.allow_plaintext = allow_plaintext
|
|
287
|
+
self.settings = {**PULL_DEFAULTS, **(settings or {})} # of the pull settings only the resource switches apply here
|
|
288
|
+
self.extensions: dict[str, str] = {}
|
|
289
|
+
self.last_refusal = ""
|
|
290
|
+
self.con = None
|
|
291
|
+
self.notes: list[str] = []
|
|
292
|
+
self.version_num = 0
|
|
293
|
+
self.tls_mode = ""
|
|
294
|
+
|
|
295
|
+
# ---- session ---------------------------------------------------------
|
|
296
|
+
def _connect(self):
|
|
297
|
+
try:
|
|
298
|
+
import pg8000.native
|
|
299
|
+
except ImportError:
|
|
300
|
+
raise DbError("PostgreSQL needs the pg8000 driver: pip install 'codecop[postgres]'") from None
|
|
301
|
+
c = self.connection
|
|
302
|
+
args = dict(user=c.user, host=c.host, port=c.port, database=c.database or c.user, password=c.password.reveal(),
|
|
303
|
+
timeout=self.timeout, application_name="codecop-db")
|
|
304
|
+
# never silently: the mode connected with is in the check output and on every audit line (realdb.tls_attempts)
|
|
305
|
+
attempts = list(tls_attempts(c))
|
|
306
|
+
if not c.secure or c.local() or self.allow_plaintext:
|
|
307
|
+
attempts.append((None, TLS_MODES["plain"] + (" (a local server)" if c.local() and c.secure else "")))
|
|
308
|
+
last = None
|
|
309
|
+
for context, mode in attempts:
|
|
310
|
+
try:
|
|
311
|
+
con = pg8000.native.Connection(ssl_context=context, **args)
|
|
312
|
+
self.tls_mode = mode
|
|
313
|
+
self.audit.tls = mode
|
|
314
|
+
return con
|
|
315
|
+
except Exception as e: # the driver raises its own types, ssl errors and OSError
|
|
316
|
+
last = e
|
|
317
|
+
if not isinstance(e, (ssl.SSLError, OSError)) and "SSL" not in str(e).upper():
|
|
318
|
+
break
|
|
319
|
+
hint = ""
|
|
320
|
+
if isinstance(last, ssl.SSLCertVerificationError):
|
|
321
|
+
hint = TLS_VERIFY_HINT
|
|
322
|
+
raise DbError(c.scrub(f"Could not connect: {type(last).__name__}: {str(last)[:200]}") + hint) from None
|
|
323
|
+
|
|
324
|
+
def __enter__(self) -> "PostgresReader":
|
|
325
|
+
if not self.dry_run:
|
|
326
|
+
self.con = self._connect()
|
|
327
|
+
try:
|
|
328
|
+
for stmt in SESSION_SETUP:
|
|
329
|
+
self.con.run(stmt)
|
|
330
|
+
state = self.con.run("SHOW transaction_read_only")[0][0]
|
|
331
|
+
except Exception as e:
|
|
332
|
+
self.close()
|
|
333
|
+
raise DbError(self.connection.scrub(f"Could not make the session read-only: {str(e)[:200]}")) from None
|
|
334
|
+
if state != "on":
|
|
335
|
+
self.close()
|
|
336
|
+
raise DbError("The server did not confirm a read-only session; nothing was sent.")
|
|
337
|
+
return self
|
|
338
|
+
|
|
339
|
+
def close(self) -> None:
|
|
340
|
+
if self.con is not None:
|
|
341
|
+
try:
|
|
342
|
+
self.con.close()
|
|
343
|
+
except Exception:
|
|
344
|
+
pass
|
|
345
|
+
self.con = None
|
|
346
|
+
|
|
347
|
+
def __exit__(self, *exc) -> None:
|
|
348
|
+
self.close()
|
|
349
|
+
|
|
350
|
+
# ---- one statement ---------------------------------------------------
|
|
351
|
+
def run(self, statement_id: str, **params) -> list[dict]:
|
|
352
|
+
return self.run_statement(STATEMENTS[statement_id], params)
|
|
353
|
+
|
|
354
|
+
def run_statement(self, stmt: Statement, params: dict) -> list[dict]:
|
|
355
|
+
check_statement(stmt)
|
|
356
|
+
started = time.monotonic()
|
|
357
|
+
if self.dry_run:
|
|
358
|
+
self.audit.record(stmt, params, started=started, sent=False)
|
|
359
|
+
return []
|
|
360
|
+
try:
|
|
361
|
+
self.con.run(f"SET statement_timeout = {int(stmt.limits.seconds) * 1000}")
|
|
362
|
+
rows = self.con.run(stmt.sql, **params)
|
|
363
|
+
names = [c["name"] for c in self.con.columns or []]
|
|
364
|
+
except Exception as e:
|
|
365
|
+
text = self.connection.scrub(_message(e))
|
|
366
|
+
self.audit.record(stmt, params, started=started, error=text)
|
|
367
|
+
try:
|
|
368
|
+
self.con.run("ROLLBACK")
|
|
369
|
+
except Exception:
|
|
370
|
+
pass
|
|
371
|
+
raise Refused(text) from None
|
|
372
|
+
out = [dict(zip(names, row)) for row in (rows or [])][:stmt.limits.result_rows]
|
|
373
|
+
self.audit.record(stmt, params, started=started, rows=len(out))
|
|
374
|
+
return out
|
|
375
|
+
|
|
376
|
+
def try_run(self, statement_id: str, **params) -> list[dict] | None:
|
|
377
|
+
try:
|
|
378
|
+
return self.run(statement_id, **params)
|
|
379
|
+
except Refused as e:
|
|
380
|
+
# the server's code and nothing else (the message can name a table or an account): 42703 a column that does not
|
|
381
|
+
# exist, 42883 a function that does not, 42501 a privilege
|
|
382
|
+
code = re.match(r"([0-9A-Z]{5})\b", str(e))
|
|
383
|
+
self.last_refusal = f"the server refused it ({code.group(1)})" if code else "the server refused it"
|
|
384
|
+
return None
|
|
385
|
+
|
|
386
|
+
# ---- check -----------------------------------------------------------
|
|
387
|
+
def check(self) -> dict:
|
|
388
|
+
server = self.run("pg.check.server")[0]
|
|
389
|
+
self.version_num = int(server["version_num"])
|
|
390
|
+
role = (self.run("pg.check.role") or [{}])[0]
|
|
391
|
+
access = self.run("pg.check.write_access")[0]
|
|
392
|
+
extensions = {e["name"]: e["version"] for e in self.run("pg.check.extensions")}
|
|
393
|
+
self.extensions = extensions
|
|
394
|
+
visible = self.try_run("pg.check.statements_visible") if "pg_stat_statements" in extensions else None
|
|
395
|
+
workload = "pg_stat_statements" if visible is not None and self.version_num >= 130000 else \
|
|
396
|
+
"pg_stat_statements needs PostgreSQL 13 or later" if visible is not None else \
|
|
397
|
+
"pg_stat_statements is installed but not readable by this account" if "pg_stat_statements" in extensions else \
|
|
398
|
+
"pg_stat_statements is not installed in this database"
|
|
399
|
+
return {
|
|
400
|
+
"engine": "postgres", "version": server["version"],
|
|
401
|
+
"read_only_enforced": server["transaction_read_only"] == "on",
|
|
402
|
+
"read_only_how": "default_transaction_read_only = on for the session, confirmed by the server",
|
|
403
|
+
"limits_applied": {"statement_timeout": server["statement_timeout"], "lock_timeout": server["lock_timeout"]},
|
|
404
|
+
"limits_refused": [], "transport": [self.tls_mode] if self.tls_mode else [], "tls": self.tls_mode,
|
|
405
|
+
"is_replica": bool(server["is_replica"]),
|
|
406
|
+
"catalog": int(access["readable"] or 0) > 0 or int(access["tables"] or 0) == 0,
|
|
407
|
+
"tables_visible": int(access["tables"] or 0), "tables_readable": int(access["readable"] or 0),
|
|
408
|
+
"workload": visible is not None and self.version_num >= 130000, "workload_source": workload,
|
|
409
|
+
"workload_hidden_statements": int(visible[0]["hidden"]) if visible else None,
|
|
410
|
+
"plans": "EXPLAIN (GENERIC_PLAN), behind --plans" if self.version_num >= 160000 else "needs PostgreSQL 16 for EXPLAIN (GENERIC_PLAN)",
|
|
411
|
+
"account_can_write": bool(role.get("superuser")) or int(access["writable"] or 0) > 0 or bool(role.get("can_create_schema")),
|
|
412
|
+
"write_access_kinds": [k for k, v in (("superuser", role.get("superuser")), ("create role", role.get("createrole")),
|
|
413
|
+
("create database", role.get("createdb")), ("create schema", role.get("can_create_schema")),
|
|
414
|
+
(f"write to {int(access['writable'] or 0)} of {int(access['tables'] or 0)} tables",
|
|
415
|
+
int(access["writable"] or 0) > 0)) if v],
|
|
416
|
+
"read_all_stats": bool(role.get("read_all_stats")),
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
# ---- tier A ----------------------------------------------------------
|
|
420
|
+
def catalog(self, databases: list[str] | None = None, max_databases: int = 20) -> dict:
|
|
421
|
+
tables = self.run("pg.catalog.tables")
|
|
422
|
+
columns = self.run("pg.catalog.columns")
|
|
423
|
+
indexes = self.run("pg.catalog.indexes")
|
|
424
|
+
constraints = self.run("pg.catalog.constraints")
|
|
425
|
+
enums = {(e["schema"], e["name"]): list(e["labels"] or []) for e in self.run("pg.catalog.enums")}
|
|
426
|
+
group = lambda rows: _group(rows, lambda r: (r["schema"], r["table"])) # noqa: E731
|
|
427
|
+
cols, idx, cons = group(columns), group(indexes), group(constraints)
|
|
428
|
+
out = []
|
|
429
|
+
for t in tables:
|
|
430
|
+
key = (t["schema"], t["name"])
|
|
431
|
+
entry = {
|
|
432
|
+
"schema": t["schema"], "name": t["name"], "kind": {"r": "table", "p": "partitioned table", "m": "materialized view"}.get(t["kind"], t["kind"]),
|
|
433
|
+
"engine": "postgres", "rows": max(int(t["live_rows"] or 0), int(t["estimated_rows"] or 0), 0),
|
|
434
|
+
"estimated_rows": int(t["estimated_rows"] or 0), "live_rows": int(t["live_rows"] or 0), "dead_rows": int(t["dead_rows"] or 0),
|
|
435
|
+
"bytes_on_disk": int(t["total_bytes"] or 0), "table_bytes": int(t["table_bytes"] or 0), "index_bytes": int(t["index_bytes"] or 0),
|
|
436
|
+
"is_partition": bool(t["is_partition"]), "parent": t["parent"] or "", "partition_key": t["partition_key"] or "",
|
|
437
|
+
"seq_scans": int(t["seq_scan"] or 0), "seq_rows_read": int(t["seq_tup_read"] or 0), "index_scans": int(t["idx_scan"] or 0),
|
|
438
|
+
"index_rows_fetched": int(t["idx_tup_fetch"] or 0), "inserted": int(t["inserted"] or 0), "updated": int(t["updated"] or 0),
|
|
439
|
+
"deleted": int(t["deleted"] or 0), "last_analyze": t["last_analyze"] or t["last_autoanalyze"] or "",
|
|
440
|
+
"columns": [{"name": c["name"], "type": c["type"], "not_null": bool(c["not_null"]), "default_expr": c["default_expr"] or "",
|
|
441
|
+
"identity": c["identity"] or "", "generated": c["generated"] or "",
|
|
442
|
+
"n_distinct": _num(c["n_distinct"]), "null_frac": _num(c["null_frac"]), "avg_width": _num(c["avg_width"]),
|
|
443
|
+
"correlation": _num(c["correlation"])} for c in cols.get(key, [])],
|
|
444
|
+
"indexes": [{"name": i["name"], "definition": i["definition"], "is_unique": bool(i["is_unique"]), "is_primary": bool(i["is_primary"]),
|
|
445
|
+
"is_valid": bool(i["is_valid"]), "bytes": int(i["bytes"] or 0), "scans": int(i["scans"] or 0),
|
|
446
|
+
"tuples_read": int(i["tuples_read"] or 0)} for i in idx.get(key, [])],
|
|
447
|
+
"constraints": [{"name": k["name"], "type": k["type"], "definition": k["definition"]} for k in cons.get(key, [])],
|
|
448
|
+
}
|
|
449
|
+
# partitions inherit their parent's columns: the parent is the table a query names
|
|
450
|
+
if not entry["is_partition"]:
|
|
451
|
+
entry["create_sql"] = table_script(entry, enums)
|
|
452
|
+
out.append(entry)
|
|
453
|
+
parents = {f"{t['schema']}.{t['name']}": t for t in out if t["kind"] == "partitioned table"}
|
|
454
|
+
summed = ("rows", "bytes_on_disk", "table_bytes", "index_bytes", "live_rows", "seq_scans", "seq_rows_read", "index_scans")
|
|
455
|
+
for t in out: # a partitioned table holds nothing itself: it gets its partitions' totals
|
|
456
|
+
p = parents.get(t["parent"])
|
|
457
|
+
if p is not None:
|
|
458
|
+
if "partitions" not in p:
|
|
459
|
+
p.update(dict.fromkeys(summed, 0), partitions=0)
|
|
460
|
+
for k in summed:
|
|
461
|
+
p[k] += t[k]
|
|
462
|
+
p["partitions"] += 1
|
|
463
|
+
return {"engine": "postgres", "databases_described": [self.connection.database], "databases": [],
|
|
464
|
+
"tables": [t for t in out if not t["is_partition"]],
|
|
465
|
+
"partitions": [{"schema": t["schema"], "name": t["name"], "parent": t["parent"], "rows": t["rows"], "bytes_on_disk": t["bytes_on_disk"]}
|
|
466
|
+
for t in out if t["is_partition"]],
|
|
467
|
+
"dictionaries": []}
|
|
468
|
+
|
|
469
|
+
# ---- tier B ----------------------------------------------------------
|
|
470
|
+
def workload(self, *, hours: int = 24, top: int = 500, **_) -> dict:
|
|
471
|
+
if not self.version_num:
|
|
472
|
+
self.version_num = int(self.run("pg.check.server")[0]["version_num"])
|
|
473
|
+
if self.version_num < 130000:
|
|
474
|
+
return {"engine": "postgres", "available": False, "reason": "pg_stat_statements needs PostgreSQL 13 or later for this", "queries": []}
|
|
475
|
+
try:
|
|
476
|
+
totals = self.run("pg.workload.totals")[0]
|
|
477
|
+
except Refused as e:
|
|
478
|
+
return {"engine": "postgres", "available": False, "queries": [],
|
|
479
|
+
"reason": "pg_stat_statements is not installed or not readable by this account" if re.search(r"does not exist|permission|must be loaded", str(e)) else str(e)[:200]}
|
|
480
|
+
info = self.try_run("pg.workload.info") or [{}]
|
|
481
|
+
rows = self.run("pg.workload.top", top=top)
|
|
482
|
+
block = 8192
|
|
483
|
+
notes = ["counters are cumulative since the last statistics reset, not a time window",
|
|
484
|
+
"read bytes are shared buffers touched (hit + read) x 8 kB"]
|
|
485
|
+
per, resource_facts = self.resources(rows, notes)
|
|
486
|
+
return {
|
|
487
|
+
"engine": "postgres", "available": True, "source": "pg_stat_statements",
|
|
488
|
+
"since": (info[0] or {}).get("since") or "", "window_hours": None, "top": top,
|
|
489
|
+
"notes": notes,
|
|
490
|
+
# resources {shapes, totals}, settings, temp, facts; absent when not pulled
|
|
491
|
+
**resource_facts,
|
|
492
|
+
"totals": {"select": {"executions": int(totals["executions"] or 0), "shapes": int(totals["shapes"] or 0),
|
|
493
|
+
"read_rows": int(totals["rows"] or 0), "read_bytes": int(totals["blocks"] or 0) * block,
|
|
494
|
+
"total_ms": int(float(totals["total_ms"] or 0))}, "by_kind": []},
|
|
495
|
+
"queries": [{
|
|
496
|
+
"hash": r["hash"], "kind": (r["text"] or "").lstrip().split(None, 1)[0].lower() if r["text"] else "",
|
|
497
|
+
"executions": int(r["executions"]), "total_ms": int(float(r["total_ms"])), "avg_ms": round(float(r["avg_ms"]), 2),
|
|
498
|
+
"p95_ms": None, "max_ms": round(float(r["max_ms"]), 1), "read_rows": int(r["result_rows"]),
|
|
499
|
+
"read_bytes": (int(r["blocks_hit"]) + int(r["blocks_read"])) * block, "result_rows": int(r["result_rows"]),
|
|
500
|
+
"temp_blocks": int(r["temp_blocks"]), "users": None, "tables": [],
|
|
501
|
+
"rank_by_bytes": int(r["by_bytes"]), "rank_by_executions": int(r["by_executions"]), "rank_by_time": int(r["by_time"]),
|
|
502
|
+
"text": self.connection.mask_secret((r["text"] or "")[:20000]), "text_truncated": len(r["text"] or "") > 20000,
|
|
503
|
+
**per.get(str(r["hash"]), {}),
|
|
504
|
+
} for r in rows],
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
def _formed(self, base: str, params: dict, notes: list[str], what: str) -> list[dict] | None:
|
|
508
|
+
"""The resource statement in the form this server's version has, else the next older one (an extension not updated
|
|
509
|
+
after the server was). None, with a note, when no form is answered."""
|
|
510
|
+
forms = list(RESOURCE_FORMS[RESOURCE_FORMS.index(resource_form(self.version_num)):])
|
|
511
|
+
for form in forms:
|
|
512
|
+
rows = self.try_run(f"{base}.{form}" if form else base, **params)
|
|
513
|
+
if rows is not None:
|
|
514
|
+
return rows
|
|
515
|
+
if "42703" not in self.last_refusal: # not a missing column: an older form will not help
|
|
516
|
+
break
|
|
517
|
+
notes.append(f"{what} is not available ({self.last_refusal}): not in this pull")
|
|
518
|
+
return None
|
|
519
|
+
|
|
520
|
+
def resources(self, rows: list[dict], notes: list[str]) -> tuple[dict[str, dict], dict]:
|
|
521
|
+
"""(hash -> {plan_ms, max_ms, stddev_ms, read_wait_ms, write_wait_ms, busy_ms, temp_bytes, wal_bytes, ...; cpu when
|
|
522
|
+
pg_stat_kcache is there}, top-level {resources, settings, temp, facts}). pg_stat_statements has no CPU and no memory:
|
|
523
|
+
busy time (run time minus read and write waits) is an upper bound of CPU that includes lock waits, said so, and only
|
|
524
|
+
when track_io_timing is on; real CPU only from pg_stat_kcache. Every statement is optional."""
|
|
525
|
+
s = self.settings
|
|
526
|
+
per: dict[str, dict] = {}
|
|
527
|
+
top: dict = {}
|
|
528
|
+
conf: dict = {}
|
|
529
|
+
if s.get("capacity"):
|
|
530
|
+
got = self.try_run("pg.check.settings")
|
|
531
|
+
if got is None:
|
|
532
|
+
notes.append(f"the server's memory settings are not available ({self.last_refusal})")
|
|
533
|
+
else:
|
|
534
|
+
conf = {str(r["name"]): setting_value(r) for r in got}
|
|
535
|
+
top["settings"] = {k2: conf[k1] for k1, k2 in (
|
|
536
|
+
("work_mem", "work_mem_bytes"), ("hash_mem_multiplier", "hash_mem_multiplier"), ("shared_buffers", "shared_buffers_bytes"),
|
|
537
|
+
("max_connections", "max_connections"), ("max_parallel_workers_per_gather", "max_parallel_workers_per_gather"),
|
|
538
|
+
("track_io_timing", "track_io_timing"), ("pg_stat_statements.track_planning", "track_planning"), ("jit", "jit"),
|
|
539
|
+
("temp_file_limit", "temp_file_limit_bytes"), ("block_size", "block_size")) if k1 in conf}
|
|
540
|
+
block = int(conf.get("block_size") or 8192)
|
|
541
|
+
timed = conf.get("track_io_timing") is True
|
|
542
|
+
hashes = [int(r["hash"]) for r in rows if str(r.get("hash") or "").lstrip("-").isdigit()]
|
|
543
|
+
if s.get("cpu") and hashes:
|
|
544
|
+
got = self._formed("pg.workload.resources", {"hashes": hashes}, notes, "run time detail per statement")
|
|
545
|
+
for r in got or []:
|
|
546
|
+
f = lambda k: float(r.get(k) or 0) # noqa: E731
|
|
547
|
+
execs = max(int(r.get("executions") or 0), 1)
|
|
548
|
+
per[str(r["hash"])] = {
|
|
549
|
+
"plan_ms": round(f("plan_ms"), 1), "max_ms": round(f("max_ms"), 1), "stddev_ms": round(f("stddev_ms"), 2),
|
|
550
|
+
"read_wait_ms": round(f("read_wait_ms"), 1) if timed else None, "write_wait_ms": round(f("write_wait_ms"), 1) if timed else None,
|
|
551
|
+
# an upper bound of CPU: run time minus disk waits still holds lock waits and time spent sending rows
|
|
552
|
+
"busy_ms": round(max(f("total_ms") - f("read_wait_ms") - f("write_wait_ms"), 0), 1) if timed else None,
|
|
553
|
+
"blocks_from_disk": int(f("blocks_from_disk")), "blocks_dirtied": int(f("blocks_dirtied")), "local_blocks": int(f("local_blocks")),
|
|
554
|
+
"temp_bytes": int(f("temp_blocks_written")) * block, "temp_read_bytes": int(f("temp_blocks_read")) * block,
|
|
555
|
+
"wal_bytes": int(f("wal_bytes")), "executions_summed": execs,
|
|
556
|
+
**({"temp_wait_ms": round(f("temp_wait_ms"), 1) if timed else None, "jit_ms": round(f("jit_ms"), 1)} if "jit_ms" in r else {})}
|
|
557
|
+
if got is not None:
|
|
558
|
+
totals = self._formed("pg.workload.resource_totals", {}, notes, "the totals of those figures")
|
|
559
|
+
t = (totals or [{}])[0] if totals else None
|
|
560
|
+
top["resources"] = {"shapes": len(per), "since_reset": True,
|
|
561
|
+
**({"totals": {"executions": int(t.get("executions") or 0), "total_ms": round(float(t.get("total_ms") or 0), 1),
|
|
562
|
+
"read_wait_ms": round(float(t.get("read_wait_ms") or 0), 1) if timed else None,
|
|
563
|
+
"write_wait_ms": round(float(t.get("write_wait_ms") or 0), 1) if timed else None,
|
|
564
|
+
"temp_bytes": int(t.get("temp_blocks_written") or 0) * block,
|
|
565
|
+
"wal_bytes": int(t.get("wal_bytes") or 0)}} if t else {})}
|
|
566
|
+
temp = self.try_run("pg.workload.temp")
|
|
567
|
+
if temp:
|
|
568
|
+
r = temp[0]
|
|
569
|
+
top["temp"] = {"temp_files": int(r.get("temp_files") or 0), "temp_bytes": int(r.get("temp_bytes") or 0),
|
|
570
|
+
"read_wait_ms": round(float(r.get("blk_read_time") or 0), 1) if timed else None,
|
|
571
|
+
"write_wait_ms": round(float(r.get("blk_write_time") or 0), 1) if timed else None}
|
|
572
|
+
kcache = self.extensions.get(KCACHE)
|
|
573
|
+
cpu_source = "none"
|
|
574
|
+
if s.get("kcache") and kcache and hashes:
|
|
575
|
+
old = [int(x) for x in re.findall(r"\d+", kcache)[:2]] < [2, 2]
|
|
576
|
+
got = self.try_run("pg.workload.kcache.v21" if old else "pg.workload.kcache", hashes=hashes)
|
|
577
|
+
if got is None:
|
|
578
|
+
notes.append(f"pg_stat_kcache is installed but not readable ({self.last_refusal}): no CPU per statement")
|
|
579
|
+
else:
|
|
580
|
+
cpu_source = KCACHE
|
|
581
|
+
for r in got:
|
|
582
|
+
per.setdefault(str(r["hash"]), {}).update({
|
|
583
|
+
"cpu": {"user_us": int(float(r.get("user_s") or 0) * 1e6), "system_us": int(float(r.get("system_s") or 0) * 1e6),
|
|
584
|
+
"counted": True, "source": KCACHE},
|
|
585
|
+
"disk_read_bytes": int(r.get("disk_read_bytes") or 0), "disk_write_bytes": int(r.get("disk_write_bytes") or 0),
|
|
586
|
+
"major_faults": int(r.get("major_faults") or 0), "involuntary_switches": int(r.get("involuntary_switches") or 0)})
|
|
587
|
+
elif s.get("kcache") and not kcache:
|
|
588
|
+
notes.append("CPU per statement is not counted by this server: it needs the pg_stat_kcache extension")
|
|
589
|
+
top["facts"] = {"cpu": cpu_source, "memory": "none", "io_wait": timed}
|
|
590
|
+
return per, top
|
|
591
|
+
|
|
592
|
+
# ---- tier C ----------------------------------------------------------
|
|
593
|
+
def plans(self, workload: dict, limit: int = 50) -> dict:
|
|
594
|
+
"""EXPLAIN (GENERIC_PLAN) for the heaviest SELECTs of the workload. Never ANALYZE: nothing is executed."""
|
|
595
|
+
if not self.version_num:
|
|
596
|
+
self.version_num = int(self.run("pg.check.server")[0]["version_num"])
|
|
597
|
+
if self.version_num < 160000:
|
|
598
|
+
return {"engine": "postgres", "available": False, "plans": [], "reason": "EXPLAIN (GENERIC_PLAN) needs PostgreSQL 16 or later."}
|
|
599
|
+
plans, skipped = [], 0
|
|
600
|
+
for q in (workload.get("queries") or [])[:limit]:
|
|
601
|
+
try:
|
|
602
|
+
stmt = explain_statement(q.get("text") or "")
|
|
603
|
+
except DbError:
|
|
604
|
+
skipped += 1
|
|
605
|
+
continue
|
|
606
|
+
try:
|
|
607
|
+
rows = self.run_statement(stmt, {})
|
|
608
|
+
except Refused as e:
|
|
609
|
+
plans.append({"hash": q["hash"], "ok": False, "error": str(e)[:200]})
|
|
610
|
+
continue
|
|
611
|
+
plan = rows[0][next(iter(rows[0]))] if rows else None
|
|
612
|
+
plan = plan[0]["Plan"] if isinstance(plan, list) and plan else None
|
|
613
|
+
plans.append({"hash": q["hash"], "ok": plan is not None, "nodes": _plan_nodes(plan) if plan else [],
|
|
614
|
+
"total_cost": plan.get("Total Cost") if plan else None, "plan_rows": plan.get("Plan Rows") if plan else None})
|
|
615
|
+
return {"engine": "postgres", "available": True, "plans": plans, "skipped": skipped,
|
|
616
|
+
"reason": "EXPLAIN (GENERIC_PLAN, FORMAT JSON): planned, never executed."}
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _plan_nodes(node: dict, depth: int = 0) -> list[dict]:
|
|
620
|
+
out = [{"depth": depth, "node": node.get("Node Type", ""), "relation": node.get("Relation Name", ""), "index": node.get("Index Name", ""),
|
|
621
|
+
"rows": node.get("Plan Rows"), "cost": node.get("Total Cost"),
|
|
622
|
+
"cond": str(node.get("Index Cond") or node.get("Recheck Cond") or "")[:200], "filter": str(node.get("Filter") or "")[:200]}]
|
|
623
|
+
for child in node.get("Plans") or []:
|
|
624
|
+
out += _plan_nodes(child, depth + 1)
|
|
625
|
+
return out
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _group(rows: list[dict], key) -> dict:
|
|
629
|
+
out: dict = {}
|
|
630
|
+
for r in rows:
|
|
631
|
+
out.setdefault(key(r), []).append(r)
|
|
632
|
+
return out
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def _num(value):
|
|
636
|
+
return None if value is None else round(float(value), 4)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _message(e: Exception) -> str:
|
|
640
|
+
arg = e.args[0] if e.args else ""
|
|
641
|
+
if isinstance(arg, dict): # pg8000 DatabaseError carries the server's fields: M message, C code
|
|
642
|
+
return f"{arg.get('C', '')} {arg.get('M', '')}".strip()
|
|
643
|
+
return f"{type(e).__name__}: {str(e)[:300]}"
|