{"modulePath":"github.com/diffsec/agentmon","version":"v0.0.0-20261111001054-230ac962f687","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package postgres\n\nPackage 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).\n\nSpec table (§7.3 + Appendix B):\n\n\tCOPY t TO STDOUT       → bulk_export(copy_to_stdout) + read\n\tCOPY t FROM STDIN      → bulk_load(copy_from_stdin)\n\tCOPY t TO '/path'      → unsafe_io(copy_to_path) + bulk_export + read\n\tCOPY t FROM '/path'    → unsafe_io(copy_from_path) + bulk_load\n\tCOPY t TO PROGRAM 'c'  → unsafe_io(copy_to_program) + bulk_export\n\tCOPY t FROM PROGRAM 'c'→ unsafe_io(copy_from_program) + bulk_load\n\tCOPY (q) TO STDOUT     → bulk_export(copy_to_stdout) + inner verb effects\n\nPackage 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).\n\nEach handler follows the same pattern:\n\n  - encode any TEMP/MATERIALIZED hint into RawVerb so applyTempLifecycle and downstream consumers can route on it;\n  - call extractRelation / extractQualifiedName to build ObjectRef + resolution;\n  - emit one Effect per spec §7.3 row (group + optional subtype + objects).\n\nGeneric 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.\n\nPackage 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.\n\nPackage 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.\n\nPackage 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).\n\nVACUUM and ANALYZE both arrive as Node\\_VacuumStmt; the IsVacuumcmd flag distinguishes the two for RawVerb purposes only — both classify as maintenance.\n\nLISTEN / 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.\n\nPackage postgres — ast\\_privilege.go owns the §7.3 privilege handlers: GRANT/REVOKE (table \u0026 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.\n\nPer spec §20 disambiguation:\n\n  - ALTER SYSTEM emits primary group=privilege, subtype=alter\\_system — NOT schema\\_alter (which is what AlterTableStmt would suggest).\n  - 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.\n\nPackage 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.\n\nThe 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.\n\nPackage 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).\n\nPhase 1 deliberately skips:\n\n  - xml2 / pgxml URL fetch (\\`xpath\\_table\\`, etc.) — deferred to Phase 2 per the design doc.\n  - FDW-relation access detection — requires catalog lookup; left as a TODO for Phase 2 per Task 11 Step 3 of the plan.\n\nThe 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.\n\nPackage 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.\n\nPackage 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.\n\nlibpq accepts two on-the-wire forms (see PostgreSQL docs §34.1):\n\n  - URI form: postgresql://\\[user\\[:password]@]\\[host\\[:port]]\\[/dbname]\\[?param=value\u0026…] (postgres:// is an accepted alias; multi-host is allowed in the host component but Plan 03 keeps only the first).\n  - 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.\n\nThe 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.\n\nPackage 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).\n\nWhen 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.\n\nThe 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.\n\nPackage 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.\n\nPackage 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.\n\n## Types\n\n```go\ntype Dialect uint8\n```\nDialect dispatches between Postgres-family parsers per spec §7.7.\n\n```go\nconst (\n\tDialectPostgres Dialect = iota + 1\n\tDialectAuroraPostgres\n\tDialectCockroachDB\n\tDialectRedshift\n)\n```\n\n```go\nfunc ParseDialect(s string) (Dialect, bool)\n```\nParseDialect resolves the spec's lowercase dialect name. Returns ok=false on unknown input.\n\n```go\nfunc (d Dialect) String() string\n```\n\n```go\ntype Options struct {\n\t// EscalateUnknownFunctions toggles §7.6: when true, SELECT calling a\n\t// function NOT in SafeFunctionAllowlist classifies as procedural rather\n\t// than read.\n\tEscalateUnknownFunctions bool\n\t// SafeFunctionAllowlist is consulted only when EscalateUnknownFunctions\n\t// is true. Lookup is case-insensitive on the canonical lowercase name\n\t// (e.g. \"now\", \"to_tsvector\"). Schema-qualified names use \"schema.name\".\n\tSafeFunctionAllowlist map[string]struct{}\n}\n```\nOptions carries per-call tunables. Defaults are zero-valued and safe.\n\n```go\ntype Parser interface {\n\tClassify(sql string, sess SessionState, opts Options) ([]effects.ClassifiedStatement, error)\n\t// Normalize returns SQL with all literal values replaced by $N placeholders.\n\t// On parse failure returns the parser error verbatim; callers degrade to\n\t// the verbatim trimmed SQL for digest computation.\n\tNormalize(sql string) (string, error)\n}\n```\nParser is the single public surface. Implementations are returned by New.\n\n```go\nfunc New(d Dialect) Parser\n```\nNew returns the parser for the given dialect, using whichever libpg\\_query embedding the active build tag selected. Panics on unknown dialect; the dialect set is closed and a typo at construction time is a programmer error.\n\n```go\ntype RewriteBackend interface {\n\tParse(sql string) (*pg_query.ParseResult, error)\n\tDeparse(tree *pg_query.ParseResult) (string, error)\n\tBackend() effects.ParserBackend\n}\n```\nRewriteBackend exposes parse/deparse primitives for SQL rewrite callers.\n\n```go\nfunc NewRewriteBackend(d Dialect) RewriteBackend\n```\nNewRewriteBackend returns parse/deparse primitives for the given dialect, using the same build-tag-selected backend as New.\n\n```go\ntype SessionState struct {\n\tSearchPath        []string            // lowercased identifiers, in order\n\tDefaultSearchPath []string            // restored by RESET search_path / DISCARD ALL\n\tTempTables        map[string]struct{} // unqualified names\n\tRole              string              // SET ROLE / SET SESSION AUTHORIZATION; \"\" = default\n\tDefaultRole       string\n\tInTransaction     bool // hint only; Plan 05 owns authoritative tx state\n}\n```\nSessionState 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.\n\n```go\nfunc ApplyStatement(s SessionState, c effects.ClassifiedStatement) SessionState\n```\nApplyStatement evolves session state after the proxy has confirmed the statement succeeded upstream. Pure function; see ast\\_session.go for the per-statement rules.\n\n```go\nfunc (s SessionState) Clone() SessionState\n```\nClone 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).\n\n","path":"github.com/diffsec/agentmon/internal/db/classify/postgres","name":"postgres","synopsis":"Package postgres — ast_copy.go owns the §7.3 COPY family.","isRedistributable":true}
