#ifndef DBMS_STATS_COMMON_HPP #define DBMS_STATS_COMMON_HPP extern "C" { #include "postgres.h" #include "fmgr.h" #include "access/attnum.h" #include "lib/stringinfo.h" #include "nodes/pg_list.h" } // extern "C" namespace dbms_stats { Oid resolve_relation_oid(const char* ownname, const char* tabname); Oid resolve_index_oid(const char* ownname, const char* indname, Oid* parent_oid); /* * Resolve an optional ownname to a schema name. * * A non-NULL ownname is returned unchanged. NULL means the first schema in the * current search_path, matching the DBMS_STATS get procedures. Raises an * internal error when the search path cannot be resolved. */ char* resolve_ownname(const char* ownname, const char* caller); /* * Resolve the schema that owns a statistics table. * * NULL ownname means the first schema in the current search_path, matching * resolve_ownname(). Raises ERRCODE_UNDEFINED_SCHEMA when the named schema * does not exist or the search path cannot be resolved. */ Oid resolve_stat_table_schema(const char* ownname, const char* caller); /* * True when the caller may create objects in nspoid (schema owner or CREATE * privilege on the namespace). */ bool check_schema_create_privilege(Oid nspoid); /* * The Oracle generic statistics-table column definitions used by every * DBMS_STATS user statistics table (CREATE_STAT_TABLE, export/import). */ const char* stat_table_columns_ddl(); /* * Validate a statistics-table name: non-NULL, non-empty, and at most * NAMEDATALEN - 1 bytes so PostgreSQL cannot silently truncate it. */ void validate_stat_table_name(const char* stattab); /* * True when a relation (of any relkind) with stattab already exists in nspoid. */ bool stat_table_relation_exists(Oid nspoid, const char* stattab); /* * Validate an optional tablespace name. NULL or an empty string means the * default tablespace; any other value must name an existing tablespace. */ void validate_stat_table_tablespace(const char* tblspace); /* * Create a statistics table in nspoid using the generic Oracle layout. * nspname must be the schema's name; identifiers are quoted before the DDL is * executed through SPI. */ void create_stat_table_relation(Oid nspoid, const char* nspname, const char* stattab, const char* tblspace); /* * Drop an already-validated statistics table through non-cascading DDL. * statrelid must identify a relation that resolve_stat_table_relation() * accepted; schema and relation names are taken from the catalog. */ void drop_stat_table_relation(Oid statrelid, const char* stattab); /* * Resolve an existing statistics table in statown. NULL statown means the * first schema in the current search path. The relation must be a table with * the expected DBMS_STATS column layout and c1-c5 slots of at least 63 * characters; otherwise a "bad user statistics table" error is raised. */ Oid resolve_stat_table_relation(const char* statown, const char* stattab, const char* caller); /* * True when the caller may delete from and insert into a statistics table. */ bool check_stat_table_write_privilege(Oid statrelid); /* * Resolve partname to a partition or subpartition of parentrelid. * * NULL partname returns parentrelid unchanged. Otherwise the partition tree * below parentrelid is searched for a true partition descendant with the given * relation name. Raises an error when no such descendant exists or when the * name is ambiguous. */ Oid resolve_partition_oid(Oid parentrelid, const char* partname); /* * Expand a DELETE_TABLE_STATS / DELETE_COLUMN_STATS request into the relation * targets whose statistics must be removed. * * partname selects exactly one partition or subpartition and ignores * cascade_parts. Otherwise the parent relation is always returned, and when * cascade_parts is true every true partition/subpartition descendant is added. * The result is de-duplicated and sorted by OID so callers can acquire locks in * a deterministic order. */ List* collect_delete_targets(Oid relid, const char* partname, bool cascade_parts); /* * Return the OIDs of indexes defined directly on relid, sorted by OID. * * For a partitioned table this includes the partitioned index root; for a * partition it includes that partition's child index. */ List* collect_relation_indexes(Oid relid); /* * Acquire ShareUpdateExclusiveLock on every relation OID in relids in sorted * order. Used before mutating catalog statistics to serialize against ANALYZE * and avoid deadlocks with concurrent delete calls. */ void lock_relations_in_oid_order(List* relids); /* * Reset a table's pg_class estimates to the not-analyzed state. The caller * must already hold ShareUpdateExclusiveLock on the relation. */ void delete_table_statistics(Oid relid); /* * Remove the pg_statistic rows for one column of relid. attnum == 0 removes * every column statistic of the relation. The caller must already hold * ShareUpdateExclusiveLock on the relation. */ void delete_column_statistics(Oid relid, AttrNumber attnum); /* * Remove an index's pg_statistic rows and reset its pg_class estimates. The * caller must already hold ShareUpdateExclusiveLock on the index. */ void delete_index_statistics(Oid indexrelid); /* * Oracle granularity levels supported by the DBMS_STATS gather procedures. * * AUTO covers the default whole-table ANALYZE behavior. GLOBAL and * APPROX_GLOBAL are intentionally absent because PostgreSQL cannot express * those scopes without core changes; parse_granularity() rejects them. */ enum class Granularity { AUTO, ALL, PARTITION, SUBPARTITION, GLOBAL_AND_PARTITION }; /* * Parse and validate an Oracle granularity value. * * NULL/empty input means AUTO. Comparison is case-insensitive and ignores * surrounding whitespace. GLOBAL and APPROX_GLOBAL raise a * feature-not-supported error; any other unknown value raises an * invalid-parameter error. */ Granularity parse_granularity(const char* value); /* Direct true-partition children of parentrelid, in catalog order. */ List* get_direct_partitions(Oid parentrelid); /* Direct partition children of each direct partition (second level). */ List* get_subpartitions(Oid parentrelid); /* 0 for a non-partition, 1 for a top-level partition, 2 for a subpartition. */ int get_partition_depth(Oid relid); /* * Expand granularity/partname into the relation targets that must be passed * to ANALYZE. Returns a de-duplicated list of relation OIDs. */ List* collect_table_targets(Oid relid, Granularity granularity, const char* partname); /* * Expand an EXPORT_TABLE_STATS request into the relation levels whose * statistics must be serialized. partname selects exactly one partition or * subpartition; otherwise a non-partitioned table yields itself and a * partitioned table yields the root plus every partition and subpartition. * The result is de-duplicated and sorted by OID. */ List* collect_export_targets(Oid relid, const char* partname); /* * Append "ANALYZE " followed by a comma-separated list of quoted qualified * relation names to buf. An empty target list leaves buf unchanged. */ void append_analyze_targets(StringInfo buf, List* relids); /* * True when the partitioned index idxrelid has a descendant child index on * part_tableoid. Used to validate partname for index statistics. */ bool index_has_partition(Oid idxrelid, Oid part_tableoid); bool check_analyze_privilege(Oid relid); bool check_schema_privilege(Oid nspoid); List* get_relations_in_namespace(Oid nspoid); /* * Parsed arguments common to every DBMS_STATS.GET_TABLE_STATS overload. * * ownname/tabname/partname are palloc'd copies of the input arguments (NULL * when the argument was not supplied). partname changes the effective relation * that statistics are read from. The remaining fields only record whether the * Oracle-only arguments were supplied; they never change the read behavior. */ struct GetTableStatsArgs { char* ownname; char* tabname; char* partname; bool has_stattab; bool has_statid; bool has_statown; //bool has_realtime_stats; bool realtime_stats; }; /* * Extract the shared GET_TABLE_STATS arguments and emit a NOTICE for every * non-NULL Oracle-only argument that this implementation accepts but ignores. * Notices are raised for non-NULL stattab/statid/statown, and for * realtime_stats only when it is false (its default true is accepted silently, * since PostgreSQL materializes the default on every call). */ GetTableStatsArgs parse_get_table_stats_args(FunctionCallInfo fcinfo, bool is_ovr3); /* * Read the table-level metrics exposed by GET_TABLE_STATS from pg_class. * * numrows <- pg_class.reltuples (0 when reltuples <= 0) * numblks <- pg_class.relpages * avgrlen <- relpages * BLCKSZ / reltuples (0 when reltuples <= 0) */ void read_table_stats(Oid relid, double* numrows, double* numblks, double* avgrlen); /* * Parsed arguments common to every DBMS_STATS.GET_COLUMN_STATS overload. * * ownname/tabname/colname/partname are palloc'd copies of the input arguments * (NULL when the argument was not supplied). partname changes the effective * relation that statistics are read from. The remaining fields only record * whether the Oracle-only arguments were supplied; they never change the * read behavior. realtime_stats is only meaningful for the overload that * carries it (has_realtime == true); it defaults to true otherwise. */ struct GetColumnStatsArgs { char* ownname; char* tabname; char* colname; char* partname; bool has_stattab; bool has_statid; bool has_statown; bool realtime_stats; }; /* * Extract the shared GET_COLUMN_STATS arguments and emit a NOTICE for every * non-NULL Oracle-only argument that this implementation accepts but ignores. * has_realtime tells whether the last input argument is realtime_stats * (overload 1) or absent (overload 2). */ GetColumnStatsArgs parse_get_column_stats_args(FunctionCallInfo fcinfo, bool has_realtime); /* * Resolve ownname.tabname.colname to a relation OID and column attribute * number, raising the Oracle-style "object does not exist or insufficient * privileges" error when the schema, table, or column is missing. */ void resolve_column_target(const GetColumnStatsArgs& args, Oid* relid, AttrNumber* attnum); /* * Column statistics snapshot shared by GET_COLUMN_STATS and EXPORT_TABLE_STATS. * * distcnt, density, nullcnt, avgclen mirror the GET_COLUMN_STATS outputs. * num_buckets is the histogram endpoint count (0 when the column has no * histogram). low_value/high_value are palloc'd output-function strings for * the first and last histogram endpoints, or NULL when no histogram exists. * srec is the JSON min/max/histogram payload, or NULL. */ struct ColumnStats { double distcnt; double density; double nullcnt; double avgclen; int32 num_buckets; char* low_value; char* high_value; text* srec; }; /* * Read column statistics without raising when the column has no pg_statistic * row. Returns false in that case; otherwise fills stats and returns true. */ bool read_column_stats_optional(Oid relid, AttrNumber attnum, ColumnStats* stats); /* * Read the column-level metrics exposed by GET_COLUMN_STATS. * * distcnt <- pg_statistic.stadistinct (sign-decoded against reltuples) * density <- 1 / distcnt (0 when distcnt <= 0; callers treat that as NULL) * nullcnt <- round(pg_statistic.stanullfrac * pg_class.reltuples) * avgclen <- pg_statistic.stawidth * srec <- text serialization of min/max/histogram (NULL when no histogram) * * Raises an ORA-20000-style error when the column has no pg_statistic row. */ void read_column_stats(Oid relid, AttrNumber attnum, double* distcnt, double* density, double* nullcnt, double* avgclen, text** srec); /* * Assemble an OUT record from the given values/isnull arrays, matching the * record-returning idiom used by the DBMS_STATS get_* procedures. */ Datum build_record(FunctionCallInfo fcinfo, Datum* values, bool* isnull); } // namespace dbms_stats #endif