Documentation
¶
Overview ¶
Package postgres — ast_copy.go owns the §7.3 COPY family. COPY is unique in that it can carry up to three effects: a primary unsafe_io effect for the PATH/PROGRAM forms, a secondary bulk_load/bulk_export effect for the data direction, and (for COPY (query) TO STDOUT) the inner verb's effects per the §20 effect-set bypass. PATH attaches a filesystem_path object; PROGRAM attaches a program object whose Argv0 is the first whitespace-split token (the binary that would be exec'd before any shell pipeline).
Spec table (§7.3 + Appendix B):
COPY t TO STDOUT → bulk_export(copy_to_stdout) + read COPY t FROM STDIN → bulk_load(copy_from_stdin) COPY t TO '/path' → unsafe_io(copy_to_path) + bulk_export + read COPY t FROM '/path' → unsafe_io(copy_from_path) + bulk_load COPY t TO PROGRAM 'c' → unsafe_io(copy_to_program) + bulk_export COPY t FROM PROGRAM 'c'→ unsafe_io(copy_from_program) + bulk_load COPY (q) TO STDOUT → bulk_export(copy_to_stdout) + inner verb effects
Package postgres — ast_ddl.go owns the DDL handlers (CREATE / ALTER / DROP / TRUNCATE / RENAME / COMMENT ON) for the schema_create, schema_alter, and schema_destroy taxonomy blocks (spec §7.3).
Each handler follows the same pattern:
- encode any TEMP/MATERIALIZED hint into RawVerb so applyTempLifecycle and downstream consumers can route on it;
- call extractRelation / extractQualifiedName to build ObjectRef + resolution;
- emit one Effect per spec §7.3 row (group + optional subtype + objects).
Generic DropStmt covers most DROP shapes; the OBJECT_FOREIGN_SERVER branch delegates to classifyDropServer in ast_external.go so the unsafe_io effect for that family lights up. OBJECT_SUBSCRIPTION / OBJECT_USER_MAPPING / OBJECT_TABLESPACE never reach DropStmt — pg_query parses each into its own dedicated node, dispatched directly from ast_walk.go.
Package postgres — ast_dml.go owns the DML and composition handlers (SELECT, INSERT, UPDATE, DELETE, MERGE, EXPLAIN, PREPARE, EXECUTE, DEALLOCATE) plus the relation-walking helpers shared with DDL/COPY.
Package postgres — ast_external.go owns the §7.3 external-IO DDL family. SUBSCRIPTION / SERVER / USER MAPPING / TABLESPACE statements all open the door to traffic that escapes the database (logical replication, FDW connections, on-disk file paths). Per spec they emit a primary unsafe_io effect plus a secondary schema_create / schema_alter / schema_destroy / privilege effect. Where the SQL exposes the destination (CONNECTION 'host=… port=…', OPTIONS (host '…', port '…'), LOCATION '/path'), the primary effect carries an ObjectExternalEndpoint or ObjectFilesystemPath so policies can match per-target.
Package postgres — ast_misc.go owns the procedural/maintenance/lock/notify handlers. These statements have no shared structural shape with DML — each one maps to a single Effect with a fixed Group/Subtype, with the exception of LOCK (which carries ObjectTable refs from its Relations list).
VACUUM and ANALYZE both arrive as Node_VacuumStmt; the IsVacuumcmd flag distinguishes the two for RawVerb purposes only — both classify as maintenance.
LISTEN / NOTIFY / UNLISTEN do not yet have a dedicated channel object kind in Phase 1; the channel name is recorded in RawVerb so policy authors can inspect it without us having to mint a new ObjectKind.
Package postgres — ast_privilege.go owns the §7.3 privilege handlers: GRANT/REVOKE (table & role-membership), CREATE/ALTER/DROP ROLE (and the CREATE USER / ALTER USER / DROP USER spellings that pg_query parses to the same nodes), ALTER SYSTEM, and SECURITY LABEL.
Per spec §20 disambiguation:
- ALTER SYSTEM emits primary group=privilege, subtype=alter_system — NOT schema_alter (which is what AlterTableStmt would suggest).
- GRANT pg_read_server_files TO role is a role-membership grant, NOT a function call; it parses to GrantRoleStmt and stays in this file.
Package postgres — ast_session.go owns the session/transaction handlers (SET / SET LOCAL / SET ROLE / SET SESSION AUTHORIZATION / RESET / DISCARD / SHOW / BEGIN / COMMIT / ROLLBACK) plus the `applySession` state-evolution rules called by ApplyStatement.
The classifier renders a SET's value list into the RawVerb (e.g. "SET_SEARCH_PATH=app,public"); applySession parses that string back to mutate SessionState. The round-trip avoids carrying structured payloads on effects.Effect — a deliberate Phase 1 simplification per Plan 03.
Package postgres — ast_unsafe_io.go owns the unsafe-IO function-call detector per spec Appendix B. SELECT / INSERT-SELECT / UPDATE / DELETE / COPY can all embed FuncCall expressions whose names are server-side IO primitives (pg_read_file, pg_ls_dir, pg_stat_file, lo_import, lo_export, dblink*); when any of those appear we append an unsafe_io effect with the appropriate subtype and a filesystem_path object carrying the literal path argument (or empty path + unresolved resolution when the argument is dynamic).
Phase 1 deliberately skips:
- xml2 / pgxml URL fetch (`xpath_table`, etc.) — deferred to Phase 2 per the design doc.
- FDW-relation access detection — requires catalog lookup; left as a TODO for Phase 2 per Task 11 Step 3 of the plan.
The shared AST walker lives in walkFuncCalls (escalation.go). Adding new expression carriers (e.g. a new FuncCall-bearing node) means extending the switch there; FuncCall is matched only on the Node type itself so a column reference named "pg_read_file" cannot trip the detector.
Package postgres — ast_walk.go owns the central RawStmt → handler dispatch. Each one-of variant of pg_query.Node maps to a per-family classifier living in its own ast_*.go file (ast_dml.go, ast_session.go, ast_ddl.go, ast_privilege.go, ast_copy.go, ast_external.go, ast_misc.go, ast_unsafe_io.go). Unmapped node types fall through to an unknown effect with a diagnostic Error — see classifyRawStmt below.
Package postgres — connstring.go owns the libpq connection-string parser used by external-IO DDL handlers (CREATE/ALTER SUBSCRIPTION). Plan 03 only needs host and port — those drive the ObjectExternalEndpoint that policies match on. Everything else (user, password, dbname, sslmode, …) is parsed far enough to skip but not retained.
libpq accepts two on-the-wire forms (see PostgreSQL docs §34.1):
- URI form: postgresql://[user[:password]@][host[:port]][/dbname][?param=value&…] (postgres:// is an accepted alias; multi-host is allowed in the host component but Plan 03 keeps only the first).
- Keyword/value form: whitespace-separated key=value pairs, where values may be wrapped in single quotes to embed spaces. Backslash-escaped quotes (\') are preserved as part of the value rather than terminating it.
The parser is deliberately tolerant — garbage input returns ("", 0) rather than an error. The classifier is best-effort metadata extraction and must not break the pipeline on malformed conninfo.
Package postgres — escalation.go owns the §7.6 "escalate unknown function calls" knob and the shared FuncCall AST walker used by both the escalation detector and the unsafe-IO detector (ast_unsafe_io.go).
When Options.EscalateUnknownFunctions is true, classifySelect calls collectFuncCallsAny over the SELECT body. If any FuncCall's canonical lowercase name is NOT a member of the supplied allowlist, a secondary `procedural` effect (no Subtype) is appended; canonical ordering then promotes it ahead of `read` so callers see the elevated classification.
The walker (walkFuncCalls) is stack-based over the relevant pg_query Node one-of variants. It is shared with appendUnsafeIO so any new FuncCall- bearing AST node only has to be added in one place.
Package postgres — object.go owns the RangeVar→ObjectRef extractor and the §6.1 resolution-tag rule. Kept here so DML, DDL, COPY, etc. share one path.
Package postgres classifies PostgreSQL-family SQL into effects.ClassifiedStatement per docs/agentmon-db-access-spec.md §7. The package exposes a Parser interface (one implementation per build-tag-selected backend) plus pure helpers for session-state evolution. No I/O, no goroutines.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dialect ¶
type Dialect uint8
Dialect dispatches between Postgres-family parsers per spec §7.7.
func ParseDialect ¶
ParseDialect resolves the spec's lowercase dialect name. Returns ok=false on unknown input.
type Options ¶
type Options struct {
// EscalateUnknownFunctions toggles §7.6: when true, SELECT calling a
// function NOT in SafeFunctionAllowlist classifies as procedural rather
// than read.
EscalateUnknownFunctions bool
// SafeFunctionAllowlist is consulted only when EscalateUnknownFunctions
// is true. Lookup is case-insensitive on the canonical lowercase name
// (e.g. "now", "to_tsvector"). Schema-qualified names use "schema.name".
SafeFunctionAllowlist map[string]struct{}
}
Options carries per-call tunables. Defaults are zero-valued and safe.
type Parser ¶
type Parser interface {
Classify(sql string, sess SessionState, opts Options) ([]effects.ClassifiedStatement, error)
// Normalize returns SQL with all literal values replaced by $N placeholders.
// On parse failure returns the parser error verbatim; callers degrade to
// the verbatim trimmed SQL for digest computation.
Normalize(sql string) (string, error)
}
Parser is the single public surface. Implementations are returned by New.
type RewriteBackend ¶
type RewriteBackend interface {
Parse(sql string) (*pg_query.ParseResult, error)
Deparse(tree *pg_query.ParseResult) (string, error)
Backend() effects.ParserBackend
}
RewriteBackend exposes parse/deparse primitives for SQL rewrite callers.
func NewRewriteBackend ¶
func NewRewriteBackend(d Dialect) RewriteBackend
NewRewriteBackend returns parse/deparse primitives for the given dialect, using the same build-tag-selected backend as New.
type SessionState ¶
type SessionState struct {
SearchPath []string // lowercased identifiers, in order
DefaultSearchPath []string // restored by RESET search_path / DISCARD ALL
TempTables map[string]struct{} // unqualified names
Role string // SET ROLE / SET SESSION AUTHORIZATION; "" = default
DefaultRole string
InTransaction bool // hint only; Plan 05 owns authoritative tx state
}
SessionState is the per-connection state the classifier consults to assign resolution tags per §6.1. Owned by Plan 04+ proxies; the classifier reads it only — ApplyStatement (a free function) evolves it after upstream success.
func ApplyStatement ¶
func ApplyStatement(s SessionState, c effects.ClassifiedStatement) SessionState
ApplyStatement evolves session state after the proxy has confirmed the statement succeeded upstream. Pure function; see ast_session.go for the per-statement rules.
func (SessionState) Clone ¶
func (s SessionState) Clone() SessionState
Clone returns a deep copy of s — call this before applying mutations if the caller needs to retain the pre-mutation state (corpus harness uses this).