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

cybertec-postgresql / pg_timetable / 43354634477

13 Nov 2026 02:47AM UTC coverage: 88.355% (+0.2%) from 88.145%
43354634477

Pull #876

github

web-flow
Merge 8fc72bade into 25a919f7a
Pull Request #876: Reject unknown BUILTIN command names in timetable.task

3 of 4 new or added lines in 2 files covered. (75.0%)

2 existing lines in 1 file now uncovered.

2299 of 2602 relevant lines covered (88.36%)

0.91 hits per line

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

83.87
/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
);          
47

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

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

78
COMMENT ON TABLE timetable.parameter IS
79
    'Stores parameters passed as arguments to a chain task';
80

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

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

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

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

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

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

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

151
COMMENT ON TABLE timetable.active_session IS
152
    'Stores information about active sessions';
153

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

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

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

172
COMMENT ON TABLE timetable.log IS
173
    'Stores log entries of active sessions';
174

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

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

220
CREATE INDEX execution_log_chain_id_finished_idx
221
    ON timetable.execution_log (chain_id, finished);
222

223
CREATE INDEX execution_log_finished_brin_idx
224
    ON timetable.execution_log USING brin (finished);
225

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

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

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

275

276
-- 00820 Add timetable.secret store (mirrors migrations/00820.sql).
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

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;
392

393
-- 00868 Reject unknown BUILTIN command names (mirrors migrations/00868.sql).
394
CREATE OR REPLACE FUNCTION timetable.check_builtin_command() RETURNS trigger AS
395
$CODE$
396
BEGIN
NEW
397
    IF NEW.kind = 'BUILTIN' AND NOT COALESCE(NEW.command = ANY (ARRAY[
×
398
        'NoOp', 'Sleep', 'Log', 'SendMail', 'Download',
399
        'CopyFromFile', 'CopyToFile', 'CopyToProgram', 'CopyFromProgram', 'Shutdown']), FALSE) THEN
400
        RAISE EXCEPTION 'unknown BUILTIN command "%" in task %', NEW.command, NEW.task_id
401
            USING ERRCODE = 'check_violation',
402
                  HINT = 'Known commands: NoOp, Sleep, Log, SendMail, Download, CopyFromFile, CopyToFile, CopyToProgram, CopyFromProgram, Shutdown';
403
    END IF;
404
    RETURN NEW;
2 ✔
405
END;
406
$CODE$
407
LANGUAGE plpgsql;
408

409
COMMENT ON FUNCTION timetable.check_builtin_command() IS
410
    'Rejects BUILTIN tasks whose command is not handled by pg_timetable (keep in sync with BuiltinTasks in internal/scheduler/tasks.go)';
411

412
CREATE TRIGGER check_builtin_command
413
    BEFORE INSERT OR UPDATE OF kind, command ON timetable.task
414
    FOR EACH ROW EXECUTE PROCEDURE timetable.check_builtin_command();
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