#include "dbms_stats_common.hpp"
|
|
extern "C"
|
{
|
#include "postgres.h"
|
#include "fmgr.h"
|
#include "utils/builtins.h"
|
#include "utils/elog.h"
|
#include "utils/syscache.h"
|
#include "access/htup_details.h"
|
#include "access/multixact.h"
|
#include "access/relation.h"
|
#include "catalog/heap.h"
|
#include "catalog/index.h"
|
#include "catalog/namespace.h"
|
#include "catalog/partition.h"
|
#include "catalog/pg_class.h"
|
#include "catalog/pg_index.h"
|
#include "catalog/pg_inherits.h"
|
#include "catalog/pg_statistic.h"
|
#include "catalog/pg_type.h"
|
#include "commands/vacuum.h"
|
#include "executor/spi.h"
|
#include "funcapi.h"
|
#include "miscadmin.h"
|
#include "lib/stringinfo.h"
|
#include "storage/lmgr.h"
|
#include "utils/lsyscache.h"
|
#include "utils/acl.h"
|
#include "utils/memutils.h"
|
#include "utils/rel.h"
|
#include "utils/relcache.h"
|
#include "catalog/pg_database.h"
|
#include "catalog/pg_namespace.h"
|
#include "commands/tablespace.h"
|
#include "mb/pg_wchar.h"
|
} // extern "C"
|
|
#include <math.h>
|
|
namespace dbms_stats {
|
|
Oid resolve_relation_oid(const char* ownname, const char* tabname)
|
{
|
Oid nspoid;
|
Oid relid = InvalidOid;
|
|
// maintaining rights check would be here
|
|
nspoid = LookupNamespaceNoError(ownname);
|
if (!OidIsValid(nspoid))
|
return InvalidOid;
|
|
relid = get_relname_relid(tabname, nspoid);
|
|
return relid;
|
}
|
|
char* resolve_ownname(const char* ownname, const char* caller)
|
{
|
Oid nspoid = InvalidOid;
|
List* search_path;
|
|
if (ownname != NULL)
|
return (char*) ownname;
|
|
search_path = fetch_search_path(false);
|
if (search_path != NIL)
|
nspoid = linitial_oid(search_path);
|
list_free(search_path);
|
|
if (!OidIsValid(nspoid))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("Fetch search path failed in %s", caller)));
|
|
return get_namespace_name(nspoid);
|
}
|
|
Oid
|
resolve_stat_table_schema(const char* ownname, const char* caller)
|
{
|
Oid nspoid = InvalidOid;
|
List* search_path;
|
|
if (ownname != NULL)
|
{
|
nspoid = LookupNamespaceNoError(ownname);
|
if (!OidIsValid(nspoid))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_SCHEMA),
|
errmsg("Schema \"%s\" does not exist", ownname)));
|
|
return nspoid;
|
}
|
|
search_path = fetch_search_path(false);
|
if (search_path != NIL)
|
nspoid = linitial_oid(search_path);
|
list_free(search_path);
|
|
if (!OidIsValid(nspoid))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("Fetch search path failed in %s", caller)));
|
|
return nspoid;
|
}
|
|
bool
|
check_schema_create_privilege(Oid nspoid)
|
{
|
return object_ownercheck(NamespaceRelationId, nspoid, GetUserId()) ||
|
object_aclcheck(NamespaceRelationId, nspoid, GetUserId(),
|
ACL_CREATE) == ACLCHECK_OK;
|
}
|
|
/*
|
* Oracle's user statistics table is a generic name/value carrier, not the
|
* denormalized object-statistics view described in create_table_stats.md.
|
* EXPORT_TABLE_STATS writes RuDB format version 1 into these slots:
|
*
|
* statid varchar2(30) caller's statistics-set identifier; NULL allowed
|
* type char(1) row kind: 'T' table/partition, 'C' column, 'I' index
|
* version number format version; currently 1
|
* flags number reserved bitmask; currently 0
|
*
|
* Character identity slots (varchar2(63), enough for NAMEDATALEN - 1):
|
* c1 owner schema name
|
* c2 table name for T/C rows; index name for I rows
|
* c3 partition/subpartition name; NULL at the global table level
|
* c4 column name for C rows; NULL otherwise
|
* c5 parent table name for I rows; NULL otherwise
|
*
|
* Numeric slots (number):
|
* T rows: n1=numrows, n2=numblks, n3=avgrlen; n4-n13 reserved/NULL
|
* C rows: n1=numdist, n2=density, n3=numnulls, n4=average column length,
|
* n5=histogram bucket count; n6-n13 reserved/NULL
|
* I rows: n1=numrows, n2=numblks, n3=distinct keys when available,
|
* n4=leaf blocks, n5=clustering factor, n6=index level when
|
* available; n7-n13 reserved/NULL
|
*
|
* d1 timestamp(0) last-analyze timestamp when available, else NULL
|
* r1 raw(1000) C rows: low value as RAW bytes; NULL otherwise
|
* r2 raw(1000) C rows: high value as RAW bytes; NULL otherwise
|
* r3 raw(1000) reserved for extended/expression statistics; NULL
|
* ch1 varchar2(1000) C rows: JSON min/max/histogram payload; NULL
|
*
|
* A value that does not fit its slot is stored as NULL with a NOTICE rather
|
* than truncated.
|
*/
|
const char*
|
stat_table_columns_ddl()
|
{
|
return "statid varchar2(30), "
|
"type char(1), "
|
"version number, "
|
"flags number, "
|
"c1 varchar2(63), c2 varchar2(63), c3 varchar2(63), "
|
"c4 varchar2(63), c5 varchar2(63), "
|
"n1 number, n2 number, n3 number, n4 number, n5 number, "
|
"n6 number, n7 number, n8 number, n9 number, n10 number, "
|
"n11 number, n12 number, n13 number, "
|
"d1 timestamp(0), "
|
"r1 raw(1000), r2 raw(1000), r3 raw(1000), "
|
"ch1 varchar2(1000)";
|
}
|
|
void
|
validate_stat_table_name(const char* stattab)
|
{
|
int len;
|
|
if (stattab == NULL || stattab[0] == '\0')
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Statistics table must be specified")));
|
|
len = (int) strlen(stattab);
|
if (pg_mbcliplen(stattab, len, NAMEDATALEN - 1) < len)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Statistics table name is too long")));
|
}
|
|
bool
|
stat_table_relation_exists(Oid nspoid, const char* stattab)
|
{
|
return OidIsValid(get_relname_relid(stattab, nspoid));
|
}
|
|
void
|
validate_stat_table_tablespace(const char* tblspace)
|
{
|
if (tblspace == NULL || tblspace[0] == '\0')
|
return;
|
|
if (!OidIsValid(get_tablespace_oid(tblspace, true)))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("Tablespace %s does not exist", tblspace)));
|
}
|
|
void
|
create_stat_table_relation(Oid nspoid, const char* nspname, const char* stattab,
|
const char* tblspace)
|
{
|
StringInfoData cmd;
|
|
// if (!OidIsValid(nspoid) || nspname == NULL)
|
// ereport(ERROR,
|
// (errcode(ERRCODE_INTERNAL_ERROR),
|
// errmsg("invalid schema for statistics table creation")));
|
|
initStringInfo(&cmd);
|
appendStringInfo(&cmd, "CREATE TABLE %s.%s (%s)",
|
quote_identifier(nspname), quote_identifier(stattab),
|
stat_table_columns_ddl());
|
|
if (tblspace != NULL && tblspace[0] != '\0')
|
appendStringInfo(&cmd, " TABLESPACE %s", quote_identifier(tblspace));
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
{
|
pfree(cmd.data);
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in "
|
"dbms_stats_create_stat_table")));
|
}
|
|
PG_TRY();
|
{
|
int ret = SPI_execute(cmd.data, false, 0);
|
|
if (ret != SPI_OK_UTILITY)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("CREATE TABLE execution failed in "
|
"dbms_stats_create_stat_table")));
|
}
|
PG_FINALLY();
|
{
|
SPI_finish();
|
}
|
PG_END_TRY();
|
|
pfree(cmd.data);
|
}
|
|
void
|
drop_stat_table_relation(Oid statrelid, const char* stattab)
|
{
|
StringInfoData cmd;
|
Oid nspoid;
|
char* nspname;
|
char* relname;
|
|
if (!OidIsValid(statrelid))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("Unable to drop table %s: does not exist", stattab)));
|
|
nspoid = get_rel_namespace(statrelid);
|
nspname = get_namespace_name(nspoid);
|
relname = get_rel_name(statrelid);
|
|
if (nspname == NULL || relname == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("Unable to drop table : does not exist")));
|
|
/*
|
* The DDL resolves the relation by name, while validation resolved it by
|
* OID. Keep the relation identity stable until the DROP executes.
|
*/
|
LockRelationOid(statrelid, AccessExclusiveLock);
|
|
initStringInfo(&cmd);
|
appendStringInfo(&cmd, "DROP TABLE %s.%s",
|
quote_identifier(nspname), quote_identifier(relname));
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
{
|
pfree(cmd.data);
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in "
|
"dbms_stats_drop_stat_table")));
|
}
|
|
PG_TRY();
|
{
|
int ret = SPI_execute(cmd.data, false, 0);
|
|
if (ret != SPI_OK_UTILITY)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("DROP TABLE execution failed in "
|
"dbms_stats_drop_stat_table")));
|
}
|
PG_FINALLY();
|
{
|
SPI_finish();
|
}
|
PG_END_TRY();
|
|
pfree(cmd.data);
|
}
|
|
/*
|
* Check whether relid has the statistics-table layout that export expects.
|
*
|
* The function verifies two things:
|
* 1. Every column used by the export writer exists in the relation. Column
|
* order does not matter because export inserts with an explicit column
|
* list, not with positional VALUES.
|
* 2. The identity slots c1-c5 are varchar2 and can hold at least
|
* NAMEDATALEN - 1 characters. This is what lets owner, table, partition,
|
* column, and index names be stored without truncation.
|
*/
|
static bool
|
stat_table_layout_is_supported(Oid relid)
|
{
|
static const char* expected_columns[] =
|
{
|
"statid", "type", "version", "flags",
|
"c1", "c2", "c3", "c4", "c5",
|
"n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9", "n10",
|
"n11", "n12", "n13",
|
"d1", "r1", "r2", "r3", "ch1"
|
};
|
static const char* character_columns[] = { "c1", "c2", "c3", "c4", "c5" };
|
|
/*
|
* First pass: all 27 slots of format version 1 must exist. Missing slots
|
* mean the caller pointed stattab at an unrelated relation, so export
|
* cannot safely interpret or write it.
|
*/
|
for (int i = 0; i < (int) lengthof(expected_columns); i++)
|
{
|
if (get_attnum(relid, expected_columns[i]) == InvalidAttrNumber)
|
return false;
|
}
|
|
/*
|
* Second pass: c1-c5 are the identifier-carrying slots. Check both the
|
* type and the typmod. varchar2 typmods include VARHDRSZ, so subtract it
|
* before comparing against the 63-character identifier limit.
|
*/
|
for (int i = 0; i < (int) lengthof(character_columns); i++)
|
{
|
AttrNumber attnum = get_attnum(relid, character_columns[i]);
|
Oid typid;
|
int32 typmod;
|
Oid collid;
|
|
if (attnum == InvalidAttrNumber)
|
return false;
|
|
get_atttypetypmodcoll(relid, attnum, &typid, &typmod, &collid);
|
if (typid != VARCHAR2OID || typmod < 0 ||
|
typmod - VARHDRSZ < 63)
|
return false;
|
}
|
|
/* Both checks passed: the relation is a usable format-version-1 table. */
|
return true;
|
}
|
|
Oid
|
resolve_stat_table_relation(const char* statown, const char* stattab,
|
const char* caller)
|
{
|
Oid nspoid;
|
Oid relid;
|
char relkind;
|
|
nspoid = resolve_stat_table_schema(statown, caller);
|
relid = get_relname_relid(stattab, nspoid);
|
|
if (!OidIsValid(relid))
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("Table \"%s\".\"%s\" does not exist or insufficient"
|
" privileges", statown, stattab)));
|
|
relkind = get_rel_relkind(relid);
|
if (relkind != RELKIND_RELATION &&
|
relkind != RELKIND_PARTITIONED_TABLE)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Bad user statistics table \"%s\"", stattab)));
|
|
if (!stat_table_layout_is_supported(relid))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Bad user statistics table \"%s\"", stattab)));
|
|
return relid;
|
}
|
|
bool
|
check_stat_table_write_privilege(Oid statrelid)
|
{
|
return pg_class_aclcheck(statrelid, GetUserId(), ACL_INSERT) == ACLCHECK_OK &&
|
pg_class_aclcheck(statrelid, GetUserId(), ACL_DELETE) == ACLCHECK_OK;
|
}
|
|
Oid resolve_index_oid(const char* ownname, const char* indname, Oid* parent_oid)
|
{
|
Oid nspoid;
|
Oid idxrelid = InvalidOid;
|
HeapTuple htup;
|
char relkind;
|
|
*parent_oid = InvalidOid;
|
|
nspoid = LookupNamespaceNoError(ownname);
|
if (!OidIsValid(nspoid))
|
return InvalidOid;
|
|
idxrelid = get_relname_relid(indname, nspoid);
|
if (!OidIsValid(idxrelid))
|
return InvalidOid;
|
|
relkind = get_rel_relkind(idxrelid);
|
if (relkind != RELKIND_INDEX && relkind != RELKIND_PARTITIONED_INDEX)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("\"%s\" is not an index", indname)));
|
}
|
|
htup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(idxrelid));
|
if (!HeapTupleIsValid(htup))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("cache lookup failed for index %u", idxrelid)));
|
|
*parent_oid = ((Form_pg_index) GETSTRUCT(htup))->indrelid;
|
ReleaseSysCache(htup);
|
|
return idxrelid;
|
}
|
|
Oid resolve_partition_oid(Oid parentrelid, const char* partname)
|
{
|
List* descendants;
|
ListCell* lc;
|
Oid found = InvalidOid;
|
//char* parentname;
|
//char* nspname;
|
|
if (partname == NULL)
|
return parentrelid;
|
|
descendants = find_all_inheritors(parentrelid, AccessShareLock, NULL);
|
|
// search for partition in all descendants
|
foreach(lc, descendants)
|
{
|
Oid child = lfirst_oid(lc);
|
char* relname;
|
|
if (child == parentrelid || !get_rel_relispartition(child))
|
continue;
|
|
relname = get_rel_name(child);
|
if (relname == NULL)
|
continue;
|
|
if (strcmp(relname, partname) == 0)
|
{
|
if (OidIsValid(found) && found != child)
|
{
|
pfree(relname);
|
list_free(descendants);
|
//parentname = get_rel_name(parentrelid);
|
//nspname = get_namespace_name(get_rel_namespace(parentrelid));
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("%s invalid partition name", partname)));
|
}
|
found = child;
|
}
|
|
pfree(relname);
|
}
|
|
list_free(descendants);
|
|
if (!OidIsValid(found))
|
{
|
//parentname = get_rel_name(parentrelid);
|
//nspname = get_namespace_name(get_rel_namespace(parentrelid));
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("%s invalid partition name", partname)));
|
}
|
|
return found;
|
}
|
|
static int
|
compare_oid_cells(const ListCell* a, const ListCell* b)
|
{
|
Oid oid_a = lfirst_oid(a);
|
Oid oid_b = lfirst_oid(b);
|
|
if (oid_a < oid_b)
|
return -1;
|
if (oid_a > oid_b)
|
return 1;
|
return 0;
|
}
|
|
List* collect_delete_targets(Oid relid, const char* partname,
|
bool cascade_parts)
|
{
|
List* targets = NIL;
|
|
if (partname != NULL)
|
{
|
targets = lappend_oid(targets,
|
resolve_partition_oid(relid, partname));
|
}
|
else
|
{
|
List* descendants;
|
ListCell* lc;
|
|
targets = lappend_oid(targets, relid);
|
|
if (cascade_parts)
|
{
|
descendants = find_all_inheritors(relid, AccessShareLock, NULL);
|
|
foreach(lc, descendants)
|
{
|
Oid child = lfirst_oid(lc);
|
|
if (child == relid || !get_rel_relispartition(child))
|
continue;
|
|
if (!list_member_oid(targets, child))
|
targets = lappend_oid(targets, child);
|
}
|
|
list_free(descendants);
|
}
|
}
|
|
list_sort(targets, compare_oid_cells);
|
|
return targets;
|
}
|
|
List* collect_relation_indexes(Oid relid)
|
{
|
List* indexes = NIL;
|
List* indexlist;
|
ListCell* lc;
|
Relation rel;
|
|
rel = relation_open(relid, AccessShareLock);
|
indexlist = RelationGetIndexList(rel);
|
|
foreach(lc, indexlist)
|
{
|
Oid indexoid = lfirst_oid(lc);
|
|
if (!list_member_oid(indexes, indexoid))
|
indexes = lappend_oid(indexes, indexoid);
|
}
|
|
relation_close(rel, AccessShareLock);
|
|
list_sort(indexes, compare_oid_cells);
|
|
return indexes;
|
}
|
|
void lock_relations_in_oid_order(List* relids)
|
{
|
List* sorted = list_copy(relids);
|
ListCell* lc;
|
|
list_sort(sorted, compare_oid_cells);
|
|
foreach(lc, sorted)
|
LockRelationOid(lfirst_oid(lc), ShareUpdateExclusiveLock);
|
|
list_free(sorted);
|
}
|
|
void delete_table_statistics(Oid relid)
|
{
|
Relation rel;
|
BlockNumber relpages = 0;
|
|
rel = relation_open(relid, ShareUpdateExclusiveLock);
|
|
if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
|
relpages = (BlockNumber) -1;
|
|
vac_update_relstats(rel,
|
relpages,
|
-1,
|
0,
|
0,
|
rel->rd_rel->relhasindex,
|
InvalidTransactionId,
|
InvalidMultiXactId,
|
NULL,
|
NULL,
|
true);
|
|
relation_close(rel, NoLock);
|
}
|
|
void delete_column_statistics(Oid relid, AttrNumber attnum)
|
{
|
RemoveStatistics(relid, attnum);
|
}
|
|
void delete_index_statistics(Oid indexrelid)
|
{
|
Relation rel;
|
|
rel = relation_open(indexrelid, ShareUpdateExclusiveLock);
|
|
RemoveStatistics(indexrelid, 0);
|
|
vac_update_relstats(rel,
|
0,
|
-1,
|
0,
|
0,
|
false,
|
InvalidTransactionId,
|
InvalidMultiXactId,
|
NULL,
|
NULL,
|
true);
|
|
relation_close(rel, NoLock);
|
}
|
|
static bool
|
is_space_char(char c)
|
{
|
return c == ' ' || c == '\t' || c == '\n' || c == '\r' ||
|
c == '\f' || c == '\v';
|
}
|
|
Granularity parse_granularity(const char* value)
|
{
|
const char* start;
|
const char* end;
|
char* normalized;
|
char* out;
|
bool last_space = false;
|
Granularity result = Granularity::AUTO;
|
|
if (value == NULL)
|
return Granularity::AUTO;
|
|
start = value;
|
while (*start != '\0' && is_space_char(*start))
|
start++;
|
|
end = start + strlen(start);
|
while (end > start && is_space_char(end[-1]))
|
end--;
|
|
if (start == end)
|
return Granularity::AUTO;
|
|
normalized = (char*) palloc((end - start) + 1);
|
out = normalized;
|
|
for (const char* p = start; p < end; p++)
|
{
|
char c = *p;
|
|
if (is_space_char(c))
|
{
|
if (!last_space)
|
{
|
*out++ = ' ';
|
last_space = true;
|
}
|
}
|
else
|
{
|
if (c >= 'A' && c <= 'Z')
|
c = (char) (c - 'A' + 'a');
|
*out++ = c;
|
last_space = false;
|
}
|
}
|
*out = '\0';
|
|
if (strcmp(normalized, "auto") == 0 ||
|
strcmp(normalized, "all") == 0 ||
|
strcmp(normalized, "default") == 0)
|
result = Granularity::AUTO;
|
else if (strcmp(normalized, "partition") == 0)
|
result = Granularity::PARTITION;
|
else if (strcmp(normalized, "subpartition") == 0)
|
result = Granularity::SUBPARTITION;
|
else if (strcmp(normalized, "global and partition") == 0)
|
result = Granularity::GLOBAL_AND_PARTITION;
|
else if (strcmp(normalized, "global") == 0 ||
|
strcmp(normalized, "approx_global") == 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("granularity \"%s\" is not supported in this version",
|
value)));
|
else
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Illegal granularity \"%s\": must be AUTO | ALL | "
|
"GLOBAL | PARTITION | SUBPARTITION | GLOBAL AND "
|
"PARTITION | APPROX_GLOBAL AND PARTITION", value)));
|
|
pfree(normalized);
|
return result;
|
}
|
|
List* get_direct_partitions(Oid parentrelid)
|
{
|
List* children;
|
List* result = NIL;
|
ListCell* lc;
|
|
children = find_inheritance_children(parentrelid, AccessShareLock);
|
|
foreach(lc, children)
|
{
|
Oid child = lfirst_oid(lc);
|
|
if (get_rel_relispartition(child))
|
result = lappend_oid(result, child);
|
}
|
|
list_free(children);
|
return result;
|
}
|
|
List* get_subpartitions(Oid parentrelid)
|
{
|
List* partitions;
|
List* result = NIL;
|
ListCell* lc;
|
|
partitions = get_direct_partitions(parentrelid);
|
|
foreach(lc, partitions)
|
{
|
List* children = get_direct_partitions(lfirst_oid(lc));
|
ListCell* child_lc;
|
|
foreach(child_lc, children)
|
result = list_append_unique_oid(result, lfirst_oid(child_lc));
|
|
list_free(children);
|
}
|
|
list_free(partitions);
|
return result;
|
}
|
|
int get_partition_depth(Oid relid)
|
{
|
List* ancestors;
|
int depth;
|
|
if (!get_rel_relispartition(relid))
|
return 0;
|
|
ancestors = get_partition_ancestors(relid);
|
depth = list_length(ancestors);
|
list_free(ancestors);
|
|
return depth;
|
}
|
|
List* collect_table_targets(Oid relid, Granularity granularity,
|
const char* partname)
|
{
|
List* targets = NIL;
|
|
if (partname != NULL)
|
{
|
Oid resolved = resolve_partition_oid(relid, partname);
|
|
if (granularity == Granularity::SUBPARTITION)
|
return get_direct_partitions(resolved);
|
|
return lappend_oid(targets, resolved);
|
}
|
|
/*
|
* Oracle ignores granularity for non-partitioned tables, so every
|
* supported level degrades to a normal whole-table ANALYZE.
|
*/
|
if (get_rel_relkind(relid) != RELKIND_PARTITIONED_TABLE)
|
return lappend_oid(targets, relid);
|
|
switch (granularity)
|
{
|
case Granularity::PARTITION:
|
targets = get_direct_partitions(relid);
|
break;
|
case Granularity::SUBPARTITION:
|
targets = get_subpartitions(relid);
|
break;
|
case Granularity::AUTO:
|
case Granularity::ALL:
|
case Granularity::GLOBAL_AND_PARTITION:
|
default:
|
targets = lappend_oid(targets, relid);
|
break;
|
}
|
|
return targets;
|
}
|
|
List* collect_export_targets(Oid relid, const char* partname)
|
{
|
List* targets = NIL;
|
List* partitions;
|
List* subpartitions;
|
ListCell* lc;
|
|
if (partname != NULL)
|
{
|
targets = lappend_oid(targets, resolve_partition_oid(relid, partname));
|
return targets;
|
}
|
|
targets = lappend_oid(targets, relid);
|
|
if (get_rel_relkind(relid) != RELKIND_PARTITIONED_TABLE)
|
return targets;
|
|
partitions = get_direct_partitions(relid);
|
subpartitions = get_subpartitions(relid);
|
|
foreach(lc, partitions)
|
{
|
if (!list_member_oid(targets, lfirst_oid(lc)))
|
targets = lappend_oid(targets, lfirst_oid(lc));
|
}
|
|
foreach(lc, subpartitions)
|
{
|
if (!list_member_oid(targets, lfirst_oid(lc)))
|
targets = lappend_oid(targets, lfirst_oid(lc));
|
}
|
|
list_free(partitions);
|
list_free(subpartitions);
|
list_sort(targets, compare_oid_cells);
|
|
return targets;
|
}
|
|
void append_analyze_targets(StringInfo buf, List* relids)
|
{
|
ListCell* lc;
|
bool first = true;
|
|
if (relids == NIL)
|
return;
|
|
foreach(lc, relids)
|
{
|
Oid relid = lfirst_oid(lc);
|
char* nspname = get_namespace_name(get_rel_namespace(relid));
|
char* relname = get_rel_name(relid);
|
|
if (nspname == NULL || relname == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
errmsg("could not resolve relation %u for ANALYZE",
|
relid)));
|
|
if (first)
|
{
|
appendStringInfoString(buf, "ANALYZE ");
|
first = false;
|
}
|
else
|
appendStringInfoString(buf, ", ");
|
|
appendStringInfo(buf, "%s.%s", quote_identifier(nspname),
|
quote_identifier(relname));
|
|
pfree(nspname);
|
pfree(relname);
|
}
|
}
|
|
bool index_has_partition(Oid idxrelid, Oid part_tableoid)
|
{
|
List* descendants;
|
ListCell* lc;
|
bool found = false;
|
|
descendants = find_all_inheritors(idxrelid, AccessShareLock, NULL);
|
|
foreach(lc, descendants)
|
{
|
Oid child = lfirst_oid(lc);
|
|
if (child == idxrelid)
|
continue;
|
|
if (IndexGetRelation(child, true) == part_tableoid)
|
{
|
found = true;
|
break;
|
}
|
}
|
|
list_free(descendants);
|
return found;
|
}
|
|
bool check_analyze_privilege(Oid relid)
|
{
|
HeapTuple tuple;
|
Form_pg_class classForm;
|
bool relisshared;
|
bool permitted;
|
|
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
|
if (!HeapTupleIsValid(tuple))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("cache lookup failed for relation %u", relid)));
|
|
classForm = (Form_pg_class) GETSTRUCT(tuple);
|
relisshared = classForm->relisshared;
|
ReleaseSysCache(tuple);
|
|
permitted = (object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) &&
|
!relisshared) ||
|
pg_class_aclcheck(relid, GetUserId(), ACL_MAINTAIN) == ACLCHECK_OK;
|
|
return permitted;
|
}
|
|
bool check_schema_privilege(Oid nspoid)
|
{
|
return object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) ||
|
object_aclcheck(NamespaceRelationId, nspoid, GetUserId(),
|
ACL_USAGE) == ACLCHECK_OK;
|
}
|
|
List* get_relations_in_namespace(Oid nspoid)
|
{ List *relids = NIL;
|
MemoryContext caller_cxt = CurrentMemoryContext;
|
StringInfoData query;
|
int ret;
|
uint64 nrows;
|
SPITupleTable *tuptable;
|
|
initStringInfo(&query);
|
appendStringInfo(&query,
|
"SELECT oid FROM pg_class "
|
"WHERE relnamespace = %u "
|
"AND relkind IN ('r','m','p','f') "
|
"AND relpersistence <> 't' "
|
"ORDER BY relname",
|
nspoid);
|
|
if (SPI_connect() != SPI_OK_CONNECT)
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI_connect failed in get_relations_in_namespace")));
|
|
ret = SPI_execute(query.data, true, 0);
|
if (ret != SPI_OK_SELECT)
|
{
|
SPI_finish();
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("SPI query failed in get_relations_in_namespace")));
|
}
|
|
nrows = SPI_processed;
|
tuptable = SPI_tuptable;
|
|
if (nrows > 0 && tuptable != NULL)
|
{
|
TupleDesc tupdesc = tuptable->tupdesc;
|
|
MemoryContextSwitchTo(caller_cxt);
|
|
for (uint64 i = 0; i < nrows; i++)
|
{
|
HeapTuple tup = tuptable->vals[i];
|
bool isnull;
|
Datum id = heap_getattr(tup, 1, tupdesc, &isnull);
|
|
if (!isnull)
|
relids = lappend_oid(relids, DatumGetObjectId(id));
|
}
|
}
|
|
SPI_finish();
|
pfree(query.data);
|
|
return relids;
|
}
|
|
GetTableStatsArgs parse_get_table_stats_args(FunctionCallInfo fcinfo, bool is_ovr3)
|
{
|
GetTableStatsArgs args;
|
|
memset(&args, 0, sizeof(args));
|
|
args.ownname = !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0))
|
: NULL;
|
args.tabname = !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1))
|
: NULL;
|
|
args.partname = !PG_ARGISNULL(2)
|
? text_to_cstring(PG_GETARG_TEXT_PP(2))
|
: NULL;
|
args.has_stattab = !PG_ARGISNULL(3);
|
args.has_statid = !PG_ARGISNULL(4);
|
if (!is_ovr3)
|
{
|
args.has_statown = !PG_ARGISNULL(5);
|
//args.realtime_stats = !PG_ARGISNULL(6) ? PG_GETARG_BOOL(6) : true;
|
}
|
else
|
{
|
//args.realtime_stats = !PG_ARGISNULL(5) ? PG_GETARG_BOOL(5) : true;
|
}
|
|
if (args.has_stattab)
|
ereport(NOTICE,
|
(errmsg("stattab is not supported in this version, ignored")));
|
if (args.has_statid)
|
ereport(NOTICE,
|
(errmsg("statid is not supported in this version, ignored")));
|
if (args.has_statown)
|
ereport(NOTICE,
|
(errmsg("statown is not supported in this version, ignored")));
|
/*
|
* PostgreSQL doesn't have in-memory/realtime stats so we can't support
|
* this option and there is no difference what value it is
|
*/
|
// if (!args.realtime_stats)
|
// ereport(NOTICE,
|
// (errmsg("realtime_stats is not supported in this version, ignored")));
|
|
return args;
|
}
|
|
void read_table_stats(Oid relid, double* numrows, double* numblks,
|
double* avgrlen)
|
{
|
HeapTuple tuple;
|
Form_pg_class classForm;
|
float4 reltuples;
|
int32 relpages;
|
|
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
|
if (!HeapTupleIsValid(tuple))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("cache lookup failed for relation %u", relid)));
|
|
classForm = (Form_pg_class) GETSTRUCT(tuple);
|
reltuples = classForm->reltuples;
|
relpages = classForm->relpages;
|
ReleaseSysCache(tuple);
|
|
*numblks = (double) relpages;
|
|
if (reltuples > 0)
|
{
|
*numrows = (double) reltuples;
|
|
/*
|
* Partitioned parents have relpages = -1 because they have no storage
|
* of their own. Their average row length cannot be derived from the
|
* parent's page count, so report 0 instead of a negative value.
|
*/
|
if (relpages > 0)
|
*avgrlen = round(((double) relpages * (double) BLCKSZ) /
|
(double) reltuples);
|
else
|
*avgrlen = 0.0;
|
}
|
else
|
{
|
*numrows = 0.0;
|
*avgrlen = 0.0;
|
}
|
}
|
|
GetColumnStatsArgs parse_get_column_stats_args(FunctionCallInfo fcinfo,
|
bool has_realtime)
|
{
|
GetColumnStatsArgs args;
|
|
memset(&args, 0, sizeof(args));
|
|
args.ownname = !PG_ARGISNULL(0) ? text_to_cstring(PG_GETARG_TEXT_PP(0))
|
: NULL;
|
args.tabname = !PG_ARGISNULL(1) ? text_to_cstring(PG_GETARG_TEXT_PP(1))
|
: NULL;
|
args.colname = !PG_ARGISNULL(2) ? text_to_cstring(PG_GETARG_TEXT_PP(2))
|
: NULL;
|
|
args.partname = !PG_ARGISNULL(3)
|
? text_to_cstring(PG_GETARG_TEXT_PP(3))
|
: NULL;
|
args.has_stattab = !PG_ARGISNULL(4);
|
args.has_statid = !PG_ARGISNULL(5);
|
args.has_statown = !PG_ARGISNULL(6);
|
if (has_realtime)
|
{
|
args.realtime_stats = !PG_ARGISNULL(7) ? PG_GETARG_BOOL(7) : true;
|
}
|
|
if (args.has_stattab)
|
ereport(NOTICE,
|
(errmsg("stattab is not supported in this version, ignored")));
|
if (args.has_statid)
|
ereport(NOTICE,
|
(errmsg("statid is not supported in this version, ignored")));
|
if (args.has_statown)
|
ereport(NOTICE,
|
(errmsg("statown is not supported in this version, ignored")));
|
/*
|
* PostgreSQL doesn't have in-memory/realtime stats so we can't support
|
* this option and there is no difference what value it is
|
*/
|
// if (!args.realtime_stats)
|
// ereport(NOTICE,
|
// (errmsg("realtime_stats is not supported in this version, ignored")));
|
|
return args;
|
}
|
|
void resolve_column_target(const GetColumnStatsArgs& args, Oid* relid,
|
AttrNumber* attnum)
|
{
|
char* ownname = args.ownname;
|
Oid nspoid;
|
List* search_path;
|
AttrNumber att;
|
|
*relid = InvalidOid;
|
*attnum = InvalidAttrNumber;
|
|
// Resolve the target schema; NULL ownname means the current session schema.
|
if (ownname == NULL)
|
{
|
nspoid = InvalidOid;
|
search_path = fetch_search_path(false);
|
if (search_path != NIL)
|
nspoid = linitial_oid(search_path);
|
|
if (!OidIsValid(nspoid))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("Fetch search path failed in "
|
"dbms_stats_get_column_stats")));
|
|
ownname = get_namespace_name(nspoid);
|
}
|
|
if (args.colname == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Invalid or missing input values")));
|
|
if (args.tabname == NULL)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("TABLE \"%s\".\"\" does not exist or "
|
"insufficient privileges", ownname)));
|
|
*relid = resolve_relation_oid(ownname, args.tabname);
|
if (!OidIsValid(*relid))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("TABLE \"%s\".\"%s\" does not exist or "
|
"insufficient privileges", ownname, args.tabname)));
|
|
att = get_attnum(*relid, args.colname);
|
if (att == InvalidAttrNumber)
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("Unable to get values for column \"%s\"", args.colname)));
|
|
*attnum = att;
|
}
|
|
/*
|
* Append a C string to a StringInfo as a double-quoted, JSON-escaped token.
|
*/
|
static void
|
append_quoted_value(StringInfo buf, const char* value)
|
{
|
appendStringInfoChar(buf, '"');
|
for (const char* p = value; *p; p++)
|
{
|
if (*p == '"' || *p == '\\')
|
appendStringInfoChar(buf, '\\');
|
appendStringInfoChar(buf, *p);
|
}
|
appendStringInfoChar(buf, '"');
|
}
|
|
/*
|
* Render the histogram slot of a column into the srec text form:
|
*
|
* {"min": <v>, "max": <v>, "histogram": [<v>, ...]}
|
*
|
* Values are rendered with the column type's output function and quoted.
|
* Returns NULL when the column has no histogram slot.
|
*/
|
static text*
|
build_srec(HeapTuple statstuple, int32* num_buckets,
|
char** low_value, char** high_value)
|
{
|
AttStatsSlot sslot;
|
StringInfoData buf;
|
Oid outfunc;
|
bool isvarlena;
|
|
*num_buckets = 0;
|
*low_value = NULL;
|
*high_value = NULL;
|
|
if (!get_attstatsslot(&sslot, statstuple, STATISTIC_KIND_HISTOGRAM,
|
InvalidOid, ATTSTATSSLOT_VALUES))
|
return NULL;
|
|
getTypeOutputInfo(sslot.valuetype, &outfunc, &isvarlena);
|
|
*num_buckets = sslot.nvalues;
|
*low_value = OidOutputFunctionCall(outfunc, sslot.values[0]);
|
*high_value = OidOutputFunctionCall(outfunc,
|
sslot.values[sslot.nvalues - 1]);
|
|
initStringInfo(&buf);
|
appendStringInfoString(&buf, "{\"min\": ");
|
append_quoted_value(&buf, *low_value);
|
appendStringInfoString(&buf, ", \"max\": ");
|
append_quoted_value(&buf, *high_value);
|
appendStringInfoString(&buf, ", \"histogram\": [");
|
for (int i = 0; i < sslot.nvalues; i++)
|
{
|
if (i > 0)
|
appendStringInfoString(&buf, ", ");
|
append_quoted_value(&buf,
|
OidOutputFunctionCall(outfunc, sslot.values[i]));
|
}
|
appendStringInfoString(&buf, "]}");
|
|
free_attstatsslot(&sslot);
|
|
return cstring_to_text(buf.data);
|
}
|
|
bool
|
read_column_stats_optional(Oid relid, AttrNumber attnum, ColumnStats* stats)
|
{
|
HeapTuple statstuple;
|
Form_pg_statistic stat;
|
HeapTuple reltuple;
|
float4 reltuples;
|
float4 stadistinct;
|
float4 stanullfrac;
|
|
memset(stats, 0, sizeof(*stats));
|
|
statstuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(relid),
|
Int16GetDatum(attnum), BoolGetDatum(false));
|
if (!HeapTupleIsValid(statstuple))
|
return false;
|
|
stat = (Form_pg_statistic) GETSTRUCT(statstuple);
|
stadistinct = stat->stadistinct;
|
stanullfrac = stat->stanullfrac;
|
stats->avgclen = round((double) stat->stawidth);
|
|
/* srec and RAW endpoints must be built while the tuple is still pinned. */
|
stats->srec = build_srec(statstuple, &stats->num_buckets,
|
&stats->low_value, &stats->high_value);
|
|
ReleaseSysCache(statstuple);
|
|
reltuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
|
if (!HeapTupleIsValid(reltuple))
|
ereport(ERROR,
|
(errcode(ERRCODE_INTERNAL_ERROR),
|
errmsg("Cache lookup failed for relation %u", relid)));
|
reltuples = ((Form_pg_class) GETSTRUCT(reltuple))->reltuples;
|
ReleaseSysCache(reltuple);
|
|
if (reltuples > 0)
|
{
|
stats->nullcnt = round(stanullfrac * (double) reltuples);
|
|
if (stadistinct > 0)
|
stats->distcnt = (double) stadistinct;
|
else if (stadistinct < 0)
|
stats->distcnt = -(double) stadistinct * (double) reltuples;
|
else
|
stats->distcnt = 0.0;
|
}
|
else
|
{
|
stats->nullcnt = 0.0;
|
stats->distcnt = (stadistinct > 0) ? (double) stadistinct : 0.0;
|
}
|
|
stats->density = (stats->distcnt > 0) ? (1.0 / stats->distcnt) : 0.0;
|
|
return true;
|
}
|
|
void
|
read_column_stats(Oid relid, AttrNumber attnum, double* distcnt,
|
double* density, double* nullcnt, double* avgclen,
|
text** srec)
|
{
|
ColumnStats stats;
|
|
if (!read_column_stats_optional(relid, attnum, &stats))
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("No statistics have been stored for requested object")));
|
|
*distcnt = stats.distcnt;
|
*density = stats.density;
|
*nullcnt = stats.nullcnt;
|
*avgclen = stats.avgclen;
|
*srec = stats.srec;
|
}
|
|
Datum build_record(FunctionCallInfo fcinfo, Datum* values, bool* isnull)
|
{
|
TupleDesc tupdesc;
|
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("Invalid call context: cannot return record!")));
|
|
tupdesc = BlessTupleDesc(tupdesc);
|
|
return HeapTupleGetDatum(heap_form_tuple(tupdesc, values, isnull));
|
}
|
|
} // namespace dbms_stats
|