2017-04-07 21:35:48 +08:00
|
|
|
-- Internal function to generate stats for a table if they don't exist
|
2019-05-31 21:29:28 +08:00
|
|
|
CREATE OR REPLACE FUNCTION @extschema@._CDB_GenerateStats(reloid REGCLASS)
|
2017-04-07 21:35:48 +08:00
|
|
|
RETURNS VOID
|
|
|
|
AS $$
|
|
|
|
DECLARE
|
2017-04-10 14:08:59 +08:00
|
|
|
has_stats BOOLEAN;
|
2017-04-07 21:35:48 +08:00
|
|
|
BEGIN
|
2017-04-10 14:08:59 +08:00
|
|
|
SELECT EXISTS (
|
|
|
|
SELECT * FROM pg_catalog.pg_statistic WHERE starelid = reloid
|
|
|
|
) INTO has_stats;
|
|
|
|
IF NOT has_stats THEN
|
2017-04-07 21:35:48 +08:00
|
|
|
EXECUTE Format('ANALYZE %s;', reloid);
|
|
|
|
END IF;
|
|
|
|
END
|
2018-07-18 18:13:31 +08:00
|
|
|
$$ LANGUAGE 'plpgsql' VOLATILE STRICT PARALLEL UNSAFE SECURITY DEFINER;
|
2017-04-07 21:35:48 +08:00
|
|
|
|
|
|
|
-- Return a row count estimate of the result of a query using statistics
|
2019-05-31 21:29:28 +08:00
|
|
|
CREATE OR REPLACE FUNCTION @extschema@.CDB_EstimateRowCount(query text)
|
2017-04-07 21:35:48 +08:00
|
|
|
RETURNS Numeric
|
|
|
|
AS $$
|
|
|
|
DECLARE
|
|
|
|
plan JSON;
|
|
|
|
BEGIN
|
|
|
|
-- Make sure statistics exist for all the tables of the query
|
2019-05-31 21:29:28 +08:00
|
|
|
PERFORM @extschema@._CDB_GenerateStats(tabname) FROM unnest(@extschema@.CDB_QueryTablesText(query)) AS tabname;
|
2017-04-07 21:35:48 +08:00
|
|
|
|
|
|
|
-- Use the query planner to obtain an estimate of the number of result rows
|
|
|
|
EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO STRICT plan;
|
|
|
|
RETURN plan->0->'Plan'->'Plan Rows';
|
|
|
|
END
|
2018-07-18 18:13:31 +08:00
|
|
|
$$ LANGUAGE 'plpgsql' VOLATILE STRICT PARALLEL UNSAFE;
|