定时任务
@leonbloy 说了什么。
另外,您还可以将 cronjob 放在postgres 系统用户的 crontab 中并简化调用:
psql mydb -c 'select maint.f_mv_update()'
自动刷新物化视图
这是为这样一种环境设计的,在这种环境中,您可以在下班时间锁定表一段时间。如果您没有那么奢侈,您可能希望并行创建新表,然后删除原始表并重命名副本以将阻塞降至最低。
我为我的 mv 机制中的所有对象保留了一个单独的模式maint
。
我刷新它们的功能:
CREATE OR REPLACE FUNCTION maint.f_mv_update()
RETURNS void AS
$func$
DECLARE
_r record;
BEGIN
SET LOCAL work_mem='256MB'; -- more memory for sorting et al?
SET LOCAL client_min_messages=warning; -- suppress index creation notices
-- With concurrent load you may need to lock some tables to avoid deadlocks
-- LOCK tbl1, tbl2;
FOR _r IN
-- cast to regclass asserts table name is valid
SELECT (mv_schema || '.' || mv_tab)::regclass AS tbl
,drop_index
,mv_query
,create_index
FROM maint.mv
WHERE active
ORDER BY mv_id
LOOP
IF _r.drop_index IS NOT NULL THEN -- drop indexes (for performance!)
EXECUTE _r.drop_index;
END IF;
EXECUTE 'TRUNCATE TABLE ' || _r.tbl;
EXECUTE 'INSERT INTO ' || _r.tbl || ' ' || _r.mv_query;
IF _r.create_index IS NOT NULL THEN -- recreate Indexes (also CLUSTER?)
EXECUTE _r.create_index;
END IF;
EXECUTE 'ANALYZE ' || _r.tbl; -- ANALYZE to refresh statistics
END LOOP;
RESET client_min_messages;
UPDATE maint.mv
SET last_up = localtimestamp(0) WHERE active; -- remember update
END
$func$ LANGUAGE plpgsql VOLATILE SET search_path=maint,pg_temp;
REVOKE ALL ON FUNCTION maint.f_mv_update() FROM public;
COMMENT ON FUNCTION maint.f_mv_update() IS 'Update materialized Views.
Uses table maint.mv';
结合这个表,所有物化视图都被注册,希望属于这个制度。
CREATE TABLE maint.mv
(
mv_id integer PRIMARY KEY, -- surrogate primary key...
active boolean NOT NULL DEFAULT true,
last_up timestamp(0) NOT NULL DEFAULT '2000-1-1 0:0'::timestamp, -- last update
log_up timestamp(0) NOT NULL DEFAULT now()::timestamp(0), -- last change of row
mv_schema text NOT NULL, -- Schema of mv table
mv_tab text NOT NULL, -- Name of mv table
mv_query text NOT NULL, -- SQL-query to fill mv
drop_index text, -- SQL to drop indexes before refill
create_index text, -- SQL to recreate indexes after refill
note text
);
REVOKE ALL ON TABLE maint.mv FROM public;
示例行:
INSERT INTO maint.mv
(mv_id, mv_schema, mv_tab, mv_query, drop_index, create_index)
VALUES ( 17, 'mv', 'mytbl'
,'SELECT mytbl_id, count(*) FROM mytbl GROUP BY 1;'
,'DROP INDEX IF EXISTS mv.mytbl_mytbl_id_idx;'
,'CREATE INDEX mytbl_mytbl_id_idx ON mv.mytbl (my_tbl_id);');
称呼:
SELECT maint.f_mv_update();