• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

cybertec-postgresql / pg_timetable / 44278212215

18 Nov 2026 09:40AM UTC coverage: 88.346% (+0.2%) from 88.145%
44278212215

Pull #876

github

web-flow
Merge e97ea1e35 into 1fe2da852
Pull Request #876: [*] reject unknown `BUILTIN` commands for tasks, fixes #868

2 of 2 new or added lines in 1 file covered. (100.0%)

7 existing lines in 3 files now uncovered.

2297 of 2600 relevant lines covered (88.35%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.21
/internal/pgengine/sql/ddl.sql
1
CREATE TABLE timetable.chain (
2
    chain_id            BIGSERIAL   PRIMARY KEY,
3
    chain_name          TEXT        NOT NULL UNIQUE,
4
    run_at              timetable.cron,
5
    max_instances       INTEGER,
6
    timeout             INTEGER     DEFAULT 0,
7
    live                BOOLEAN     DEFAULT FALSE,
8
    self_destruct       BOOLEAN     DEFAULT FALSE,
9
    exclusive_execution BOOLEAN     DEFAULT FALSE,
10
    client_name         TEXT,
11
    on_error            TEXT
12
);
13

14
COMMENT ON TABLE timetable.chain IS
15
    'Stores information about chains schedule';
16
COMMENT ON COLUMN timetable.chain.run_at IS
17
    'Extended CRON-style time notation the chain has to be run at';
18
COMMENT ON COLUMN timetable.chain.max_instances IS
19
    'Number of instances (clients) this chain can run in parallel';
20
COMMENT ON COLUMN timetable.chain.timeout IS
21
    'Abort any chain that takes more than the specified number of milliseconds';
22
COMMENT ON COLUMN timetable.chain.live IS
23
    'Indication that the chain is ready to run, set to FALSE to pause execution';
24
COMMENT ON COLUMN timetable.chain.self_destruct IS
25
    'Indication that this chain will delete itself after successful run';
26
COMMENT ON COLUMN timetable.chain.exclusive_execution IS
27
    'All parallel chains should be paused while executing this chain';
28
COMMENT ON COLUMN timetable.chain.client_name IS
29
    'Only client with this name is allowed to run this chain, set to NULL to allow any client';    
30

31
CREATE TYPE timetable.command_kind AS ENUM ('SQL', 'PROGRAM', 'BUILTIN');
32

33
CREATE TABLE timetable.task (
34
    task_id             BIGSERIAL               PRIMARY KEY,
35
    chain_id            BIGINT                  REFERENCES timetable.chain(chain_id) ON UPDATE CASCADE ON DELETE CASCADE,
36
    task_order          DOUBLE PRECISION        NOT NULL,
37
    task_name           TEXT,
38
    kind                timetable.command_kind  NOT NULL DEFAULT 'SQL',
39
    command             TEXT                    NOT NULL,
40
    run_as              TEXT,
41
    database_connection TEXT,
42
    ignore_error        BOOLEAN                 NOT NULL DEFAULT FALSE,
43
    autonomous          BOOLEAN                 NOT NULL DEFAULT FALSE,
44
    timeout             INTEGER                 DEFAULT 0,
45
    live                BOOLEAN                 NOT NULL DEFAULT TRUE,
46
    CONSTRAINT task_builtin_command_known
47
        CHECK (kind <> 'BUILTIN' OR command IN ('NoOp', 'Sleep', 'Log', 'SendMail', 'Download',
48
            'CopyFromFile', 'CopyToFile', 'CopyToProgram', 'CopyFromProgram', 'Shutdown'))
49
);          
50

51
COMMENT ON TABLE timetable.task IS
52
    'Holds information about chain elements aka tasks';
53
COMMENT ON COLUMN timetable.task.chain_id IS
54
    'Link to the chain, if NULL task considered to be disabled';
55
COMMENT ON COLUMN timetable.task.task_order IS
56
    'Indicates the order of task within a chain';    
57
COMMENT ON COLUMN timetable.task.run_as IS
58
    'Role name to run task as. Uses SET ROLE for SQL commands';
59
COMMENT ON COLUMN timetable.task.ignore_error IS
60
    'Indicates whether a next task in a chain can be executed regardless of the success of the current one';
61
COMMENT ON COLUMN timetable.task.kind IS
62
    'Indicates whether "command" is SQL, built-in function or an external program';
63
COMMENT ON COLUMN timetable.task.command IS
64
    'Contains either an SQL command, or command string to be executed';
65
COMMENT ON COLUMN timetable.task.timeout IS
66
    'Abort any task within a chain that takes more than the specified number of milliseconds';
67
COMMENT ON COLUMN timetable.task.autonomous IS
68
    'Specify if the task should be executed out of the chain transaction. Useful for VACUUM, CREATE DATABASE, CALL etc.';
69
COMMENT ON COLUMN timetable.task.live IS
70
    'Indication that the task is ready to run, set to FALSE to skip execution';
71

72
-- parameter passing for a chain task
73
CREATE TABLE timetable.parameter(
74
    task_id     BIGINT  REFERENCES timetable.task(task_id)
75
                        ON UPDATE CASCADE ON DELETE CASCADE,
76
    order_id    INTEGER CHECK (order_id > 0),
77
    value       JSONB,
78
    PRIMARY KEY (task_id, order_id)
79
);
80

81
COMMENT ON TABLE timetable.parameter IS
82
    'Stores parameters passed as arguments to a chain task';
83

84
CREATE OR REPLACE FUNCTION timetable.parameter_shape_error(kind timetable.command_kind, command TEXT, value JSONB)
85
RETURNS TEXT AS
86
$CODE$
87
    SELECT CASE
2 ✔
88
        WHEN value IS NULL OR jsonb_typeof(value) = 'null' THEN NULL
89
        WHEN kind = 'SQL' THEN
90
            CASE WHEN jsonb_typeof(value) <> 'array' THEN 'a JSON array' END
91
        WHEN kind = 'PROGRAM' THEN
92
            CASE WHEN jsonb_typeof(value) <> 'array'
93
                OR jsonb_path_exists(value, '$[*] ? (@.type() != "string")') THEN 'a JSON array of strings' END
94
        WHEN command = 'Sleep' THEN
95
            CASE WHEN jsonb_typeof(value) <> 'number' OR value::text !~ '^-?[0-9]+$' THEN 'an integer' END
96
        WHEN command IN ('SendMail', 'Download', 'CopyFromFile', 'CopyToFile', 'CopyToProgram', 'CopyFromProgram') THEN
97
            CASE WHEN jsonb_typeof(value) <> 'object' THEN 'a JSON object' END
98
    END
99
$CODE$
100
LANGUAGE sql IMMUTABLE;
101

102
COMMENT ON FUNCTION timetable.parameter_shape_error(timetable.command_kind, TEXT, JSONB) IS
103
    'Returns the expected shape if value is invalid for the task kind and command, NULL otherwise';
104

105
CREATE OR REPLACE FUNCTION timetable.check_parameter() RETURNS trigger AS
106
$CODE$
107
DECLARE
108
    v_kind      timetable.command_kind;
109
    v_command   TEXT;
110
    v_value     JSONB;
111
    v_expected  TEXT;
112
BEGIN
113
    IF TG_TABLE_NAME = 'parameter' THEN
2 ✔
114
        SELECT t.kind, t.command INTO v_kind, v_command FROM timetable.task t WHERE t.task_id = NEW.task_id;
115
        v_value := NEW.value;
2 ✔
116
        v_expected := timetable.parameter_shape_error(v_kind, v_command, v_value);
2 ✔
117
    ELSE
1 ✔
118
        v_kind := NEW.kind;
119
        v_command := NEW.command;
1 ✔
120
        SELECT p.value, timetable.parameter_shape_error(v_kind, v_command, p.value) INTO v_value, v_expected
1 ✔
121
        FROM timetable.parameter p
122
        WHERE p.task_id = NEW.task_id AND timetable.parameter_shape_error(v_kind, v_command, p.value) IS NOT NULL
123
        LIMIT 1;
124
    END IF;
UNCOV
125
    IF v_expected IS NOT NULL THEN
×
126
        RAISE EXCEPTION 'parameter for % task % must be %',
127
            CASE WHEN v_kind = 'BUILTIN' THEN v_command ELSE v_kind::text END, NEW.task_id, v_expected
128
            USING ERRCODE = 'check_violation', DETAIL = format('value: %s', v_value);
129
    END IF;
130
    RETURN NEW;
2 ✔
131
END;
132
$CODE$
133
LANGUAGE plpgsql;
134

135
COMMENT ON FUNCTION timetable.check_parameter() IS
136
    'Rejects parameter values whose shape does not match the task kind or BUILTIN command';
137

138
CREATE TRIGGER check_parameter
139
    BEFORE INSERT OR UPDATE ON timetable.parameter
140
    FOR EACH ROW EXECUTE PROCEDURE timetable.check_parameter();
141

142
CREATE TRIGGER check_parameter
143
    BEFORE UPDATE OF kind, command ON timetable.task
144
    FOR EACH ROW EXECUTE PROCEDURE timetable.check_parameter();
145

146
CREATE UNLOGGED TABLE timetable.active_session(
147
    client_pid  BIGINT  NOT NULL,
148
    server_pid  BIGINT  NOT NULL,
149
    client_name TEXT    NOT NULL,
150
    started_at  TIMESTAMPTZ DEFAULT now()
151
);
152

153
COMMENT ON TABLE timetable.active_session IS
154
    'Stores information about active sessions';
155

156
CREATE TYPE timetable.log_type AS ENUM ('DEBUG', 'NOTICE', 'INFO', 'ERROR', 'PANIC', 'USER');
157

158
CREATE OR REPLACE FUNCTION timetable.get_client_name(integer) RETURNS TEXT AS
159
$$
160
    SELECT client_name FROM timetable.active_session WHERE server_pid = $1 LIMIT 1
1 ✔
161
$$
162
LANGUAGE sql;
163

164
CREATE TABLE timetable.log
165
(
166
    ts              TIMESTAMPTZ         DEFAULT now(),
167
    pid             INTEGER             NOT NULL,
168
    log_level       timetable.log_type  NOT NULL,
169
    client_name     TEXT                DEFAULT timetable.get_client_name(pg_backend_pid()),
170
    message         TEXT,
171
    message_data    jsonb
172
);
173

174
COMMENT ON TABLE timetable.log IS
175
    'Stores log entries of active sessions';
176

177
CREATE TABLE timetable.execution_log (
178
    chain_id        BIGINT,
179
    task_id         BIGINT,
180
    txid            BIGINT NOT NULL,
181
    last_run        TIMESTAMPTZ DEFAULT now(),
182
    finished        TIMESTAMPTZ,
183
    pid             BIGINT,
184
    returncode      INTEGER,
185
    ignore_error    BOOLEAN,
186
    kind            timetable.command_kind,
187
    command         TEXT,
188
    output          TEXT,
189
    client_name     TEXT        NOT NULL,
190
    params          TEXT
191
);
192

193
COMMENT ON TABLE timetable.execution_log IS
194
    'Stores log entries of executed tasks and chains';
195
COMMENT ON COLUMN timetable.execution_log.chain_id IS
196
    'Link to the chain executed';
197
COMMENT ON COLUMN timetable.execution_log.task_id IS
198
    'Link to the task executed';
199
COMMENT ON COLUMN timetable.execution_log.txid IS
200
    'Transaction ID of the executed task';
201
COMMENT ON COLUMN timetable.execution_log.last_run IS
202
    'Timestamp of the last execution of the task';
203
COMMENT ON COLUMN timetable.execution_log.finished IS
204
    'Timestamp of the task execution finish';
205
COMMENT ON COLUMN timetable.execution_log.pid IS
206
    'Process ID of the worker executing the task';
207
COMMENT ON COLUMN timetable.execution_log.returncode IS
208
    'Return code of the executed task';
209
COMMENT ON COLUMN timetable.execution_log.ignore_error IS
210
    'Indicates whether a next task in a chain can be executed regardless of the success of the current one';
211
COMMENT ON COLUMN timetable.execution_log.kind IS
212
    'Indicates whether "command" is SQL, built-in function or an external program';
213
COMMENT ON COLUMN timetable.execution_log.command IS
214
    'Contains either an SQL command, or command string to be executed';
215
COMMENT ON COLUMN timetable.execution_log.output IS
216
    'Contains output of the executed task';
217
COMMENT ON COLUMN timetable.execution_log.client_name IS
218
    'Name of the client executing the task';
219
COMMENT ON COLUMN timetable.execution_log.params IS
220
    'Contains parameters passed as arguments to a chain task';
221

222
CREATE INDEX execution_log_chain_id_finished_idx
223
    ON timetable.execution_log (chain_id, finished);
224

225
CREATE INDEX execution_log_finished_brin_idx
226
    ON timetable.execution_log USING brin (finished);
227

228
CREATE UNLOGGED TABLE timetable.active_chain(
229
    chain_id    BIGINT  NOT NULL,
230
    client_name TEXT    NOT NULL,
231
    started_at  TIMESTAMPTZ DEFAULT now()
232
);
233

234
COMMENT ON TABLE timetable.active_chain IS
235
    'Stores information about active chains within session';
236

237
CREATE OR REPLACE FUNCTION timetable.try_lock_client_name(worker_pid BIGINT, worker_name TEXT)
238
RETURNS bool AS
239
$CODE$
240
BEGIN
UNCOV
241
    IF pg_is_in_recovery() THEN
×
242
        RAISE NOTICE 'Cannot obtain lock on a replica. Please, use the primary node';
UNCOV
243
        RETURN FALSE;
×
244
    END IF;
245
    -- remove disconnected sessions
246
    DELETE
1 ✔
247
        FROM timetable.active_session
248
        WHERE server_pid NOT IN (
249
            SELECT pid
250
            FROM pg_catalog.pg_stat_activity
251
            WHERE application_name = 'pg_timetable'
252
        );
253
    DELETE 
1 ✔
254
        FROM timetable.active_chain 
255
        WHERE client_name NOT IN (
256
            SELECT client_name FROM timetable.active_session
257
        );
258
    -- check if there any active sessions with the client name but different client pid
259
    PERFORM 1
1 ✔
260
        FROM timetable.active_session s
261
        WHERE
262
            s.client_pid <> worker_pid
263
            AND s.client_name = worker_name
264
        LIMIT 1;
265
    IF FOUND THEN
1 ✔
266
        RAISE NOTICE 'Another client is already connected to server with name: %', worker_name;
267
        RETURN FALSE;
1 ✔
268
    END IF;
269
    -- insert current session information
270
    INSERT INTO timetable.active_session(client_pid, client_name, server_pid) VALUES (worker_pid, worker_name, pg_backend_pid());
1 ✔
271
    RETURN TRUE;
1 ✔
272
END;
273
$CODE$
274
STRICT
275
LANGUAGE plpgsql;
276

277

278
-- pg_timetable never installs any PostgreSQL extension. This block applies
279
-- unchanged on a database that has no pgcrypto installed. The extension is
280
-- looked up at call time inside resolve_secret.
281

282
CREATE TABLE timetable.secret (
283
    client_name  TEXT        NOT NULL,
284
    secret_name  TEXT        NOT NULL,
285
    value_enc    BYTEA       NOT NULL,
286
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
287
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
288
    updated_by   TEXT        NOT NULL DEFAULT session_user,
289
    PRIMARY KEY (client_name, secret_name)
290
);
291

292
ALTER TABLE timetable.secret ADD CONSTRAINT secret_name_format
293
    CHECK (secret_name ~ '^[A-Za-z0-9_.-]+$');
294

295
COMMENT ON TABLE timetable.secret IS
296
    'Write-only, named secret values referenced from task parameters and connection strings as ${secret:name}, scoped to exactly one client_name. Modeled on GitHub Actions repository secrets: no plaintext read path, no rotation, no versioning, no cross-client sharing. Requires the pgcrypto extension, which the database administrator installs; pg_timetable itself never does.';
297
COMMENT ON COLUMN timetable.secret.client_name IS
298
    'Owning client. Mandatory security boundary: resolvable only by the scheduler process running with this exact client_name (-c/--clientname). Unlike timetable.chain.client_name, NULL/global is not permitted.';
299
COMMENT ON COLUMN timetable.secret.secret_name IS
300
    'Reference key used in ${secret:name} syntax, unique within client_name. Case-sensitive, no whitespace (enforced by CHECK secret_name_format).';
301
COMMENT ON COLUMN timetable.secret.value_enc IS
302
    'Value encrypted by the operator with pgp_sym_encrypt() from the pgcrypto extension. Decrypted only by timetable.resolve_secret() when supplied the key configured as PGTT_SECRET_KEY, which the database never stores.';
303
COMMENT ON COLUMN timetable.secret.updated_by IS
304
    'session_user that last inserted or updated this row, maintained by the secret_touch trigger.';
305

306
REVOKE ALL ON timetable.secret FROM PUBLIC;
307
-- No grants to other roles. Objects are owned by the schema-creating (scheduler)
308
-- role; a separate administrative role is an operator-managed GRANT.
309

310
CREATE OR REPLACE FUNCTION timetable.secret_touch() RETURNS trigger AS
311
$CODE$
312
BEGIN
313
    NEW.updated_at := now();
1 ✔
314
    NEW.updated_by := session_user;
1 ✔
315
    RETURN NEW;
1 ✔
316
END;
317
$CODE$
318
LANGUAGE plpgsql;
319

320
COMMENT ON FUNCTION timetable.secret_touch() IS
321
    'Keeps timetable.secret.updated_at/updated_by truthful on UPDATE';
322

323
CREATE TRIGGER secret_touch
324
    BEFORE UPDATE ON timetable.secret
325
    FOR EACH ROW EXECUTE PROCEDURE timetable.secret_touch();
326

327
-- resolve_secret is LANGUAGE plpgsql so the validator does not resolve
328
-- pgp_sym_decrypt at create time; the extension schema is looked up at call
329
-- time and interpolated into dynamic SQL so any install layout (public,
330
-- custom schema, ALTER EXTENSION ... SET SCHEMA) works. A missing extension
331
-- raises SQLSTATE 0A000 without requiring pgcrypto for create time.
332
CREATE OR REPLACE FUNCTION timetable.resolve_secret(p_name TEXT, p_client TEXT, p_key TEXT)
333
RETURNS TEXT
334
LANGUAGE plpgsql
335
SECURITY DEFINER
336
STABLE
337
STRICT
338
SET search_path = pg_catalog, timetable
339
AS $CODE$
340
DECLARE
341
    v_enc        BYTEA;
342
    v_ext_schema TEXT;
343
    v_plain      TEXT;
344
BEGIN
345
    SELECT value_enc INTO v_enc
1 ✔
346
    FROM timetable.secret
347
    WHERE client_name = p_client
348
      AND secret_name = p_name;
349

350
    IF NOT FOUND THEN
1 ✔
351
        RETURN NULL;   -- unknown (client_name, secret_name): no pgcrypto needed
352
    END IF;
353

354
    SELECT n.nspname INTO v_ext_schema
1 ✔
355
    FROM pg_catalog.pg_extension e
356
    JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
357
    WHERE e.extname = 'pgcrypto';
358

UNCOV
359
    IF NOT FOUND THEN
×
360
        RAISE EXCEPTION 'pgcrypto extension is not installed, cannot decrypt timetable.secret values'
361
            USING ERRCODE = 'feature_not_supported',
362
                  HINT = 'Install it (CREATE EXTENSION pgcrypto) or stop using ${secret:...} references';
363
    END IF;
364

365
    EXECUTE format('SELECT %I.pgp_sym_decrypt($1, $2)', v_ext_schema)
1 ✔
366
       INTO v_plain
367
      USING v_enc, p_key;
368

369
    RETURN v_plain;
1 ✔
370
END;
371
$CODE$;
372

373
COMMENT ON FUNCTION timetable.resolve_secret(TEXT, TEXT, TEXT) IS
374
    'Returns the decrypted value of one secret, or NULL when the (client_name, secret_name) pair does not exist. Raises feature_not_supported when pgcrypto is not installed, and Wrong key or corrupt data when the key is wrong.';
375

376
REVOKE ALL ON FUNCTION timetable.resolve_secret(TEXT, TEXT, TEXT) FROM PUBLIC;
377

378
CREATE OR REPLACE FUNCTION timetable.secret_count()
379
RETURNS BIGINT
380
LANGUAGE sql
381
SECURITY DEFINER
382
STABLE
383
SET search_path = pg_catalog, timetable
384
AS $$
385
    SELECT count(*) FROM timetable.secret;
1 ✔
386
$$;
387

388
COMMENT ON FUNCTION timetable.secret_count() IS
389
    'Number of stored secrets, used by the scheduler startup check when no encryption key is configured. Exposes no secret material and does not require pgcrypto.';
390

391
REVOKE ALL ON FUNCTION timetable.secret_count() FROM PUBLIC;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc