我希望能够记录运行大量SQL命令的脚本需要多长时间。我查看了EXPLAIN
,但这仅限于一个命令,并且不想使用PL / PGSQL,因为它似乎没有给我我需要的功能。我不会在 psql 客户端中运行这些脚本,因此\set
命令对我来说也不起作用。
这个伪代码块应该让你知道我想要做什么:
-- beginning of script
SET begin_time = NOW();
... execute a bunch of SQL commands
-- end of script
SET end_time = NOW();
INSERT INTO execute_log (script_run_time)
SELECT (end_time - start_time);
有没有简单的方法在PostgreSQL中使用SQL做到这一点?如果没有,我怎样才能得到相同的结果?
答案 0 :(得分:1)
CREATE TABLE timenow
( seq serial NOT NULL PRIMARY KEY
, starttime timestamptz NOT NULL
, stoptime timestamptz NOT NULL
);
BEGIN;
INSERT INTO timenow( starttime, stoptime) SELECT now(), clock_timestamp();
SELECT COUNT(*) from pg_class;
INSERT INTO timenow( starttime, stoptime) SELECT now(), clock_timestamp();
COMMIT;
SELECT * FROM timenow;
输出:
CREATE TABLE
BEGIN
INSERT 0 1
count
-------
577
(1 row)
INSERT 0 1
COMMIT
seq | starttime | stoptime
-----+-------------------------------+-------------------------------
1 | 2016-05-22 17:20:12.206513+02 | 2016-05-22 17:20:12.207037+02
2 | 2016-05-22 17:20:12.206513+02 | 2016-05-22 17:20:12.207918+02
(2 rows)
答案 1 :(得分:0)
使用自定义配置参数:
Pooling=False;
请注意,名称中的点是必需的。
答案 2 :(得分:0)
感谢你们双方的大力投入!我决定采用混合方法,因为:
CREATE TABLE timenow (
seq SERIAL NOT NULL PRIMARY KEY,
starttime TIMESTAMP NOT NULL,
stoptime TIMESTAMP NULL,
runtime INTERVAL (3) NULL
);
-- set execution begin time
INSERT INTO timenow (starttime) SELECT clock_timestamp();
... execute a bunch of SQL commands
-- set execution end time
UPDATE timenow
SET stoptime = clock_timestamp();
UPDATE timenow
SET runtime = stoptime - starttime;
SELECT * FROM timenow;
输出:
seq | starttime | stoptime | runtime
-----+-------------------------------+-------------------------------+--------------
1 | 2016-05-22 12:09:47.049678-04 | 2016-05-22 12:11:00.610502-04 | 00:01:13.561
(1 row)
Time: 0.338 ms
当然,我会替换
CREATE TABLE timenow:
代替:
TRUNCATE timenow;
在生产环境中。
编辑:
为了捕获时间并将其插入日志中,我使用了:
INSERT INTO script_run_log (entry)
SELECT 'Script #1 run time: ' ||
TO_CHAR((SELECT runtime FROM timenow), 'MI:SS:MS');
输出:
| Script #1 run time: 01:11:554 |