-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaster.sql
More file actions
99 lines (95 loc) · 2.5 KB
/
Copy pathmaster.sql
File metadata and controls
99 lines (95 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
CREATE OR REPLACE FUNCTION init_master()
RETURNS VOID
AS $$
BEGIN
-- Create the master table if it doesn't exist
CREATE TABLE IF NOT EXISTS master (
id INTEGER PRIMARY KEY DEFAULT 1,
worker_id BIGINT DEFAULT 0,
worker_rid UUID,
settings JSONB DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create indexes for efficient querying
CREATE INDEX IF NOT EXISTS idx_master_worker_id ON master (worker_id);
CREATE INDEX IF NOT EXISTS idx_master_worker_rid ON master (worker_rid);
-- Insert initial master record if it doesn't exist
INSERT INTO master DEFAULT VALUES
ON CONFLICT (id) DO NOTHING;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION update_master(
input_worker_id BIGINT,
input_worker_rid UUID,
input_settings JSONB,
input_lock_timeout_minutes INT
)
RETURNS TABLE (
output_id INTEGER,
output_worker_id BIGINT,
output_worker_rid UUID,
output_settings JSONB,
output_created_at TIMESTAMP,
output_updated_at TIMESTAMP
)
AS $$
BEGIN
RETURN QUERY
WITH current_master AS (
SELECT
m.id,
m.worker_id,
m.worker_rid,
m.settings,
m.created_at,
m.updated_at
FROM master m
WHERE m.id = 1
AND (
m.updated_at < (CURRENT_TIMESTAMP - (input_lock_timeout_minutes * INTERVAL '1 minute'))
OR m.worker_id = input_worker_id
OR m.worker_id = 0
)
FOR UPDATE SKIP LOCKED
)
UPDATE master
SET
worker_id = input_worker_id,
worker_rid = input_worker_rid,
settings = input_settings,
updated_at = CURRENT_TIMESTAMP
FROM current_master
WHERE master.id = current_master.id
RETURNING
current_master.id,
current_master.worker_id,
current_master.worker_rid,
current_master.settings,
current_master.created_at,
current_master.updated_at;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION select_master()
RETURNS TABLE (
output_id INTEGER,
output_worker_id BIGINT,
output_worker_rid UUID,
output_settings JSONB,
output_created_at TIMESTAMP,
output_updated_at TIMESTAMP
)
AS $$
BEGIN
RETURN QUERY
SELECT
m.id,
m.worker_id,
m.worker_rid,
m.settings,
m.created_at,
m.updated_at
FROM master m
WHERE m.id = 1;
END;
$$ LANGUAGE plpgsql;