rupg-func 0.1.84

The 3,414 built-in functions, the 805 operators, the 249 casts, the aggregates and window functions, the regular expression engine.
Documentation
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! The functions of the statistics of the whole server, from `pgstatfuncs.c`: the background writer, the checkpointer, WAL, I/O, the archiver, the SLRU caches, the prefetch of recovery and the locks, which the views `pg_stat_bgwriter`, `pg_stat_checkpointer`, `pg_stat_wal`, `pg_stat_io`, `pg_stat_archiver`, `pg_stat_slru`, `pg_stat_recovery_prefetch` and `pg_stat_lock` show.
//!
//! rupg does not keep these counters yet, so each counter is 0, each time is 0 and each name of a WAL file and its time is null, as on a server that has not done the work. The rows and the null cells are those of PostgreSQL. `stats_reset` is the time that the store of the server started its statistics, which is the start of its first session.

use rupg_common::Result;
use rupg_types::{Numeric, Value};

use crate::{Call, Kernel};

/// The SLRU caches of `pgstat_get_slru_name`, in their order.
const SLRUS: [&str; 8] = [
    "commit_timestamp",
    "multixact_member",
    "multixact_offset",
    "notify",
    "serializable",
    "subtransaction",
    "transaction",
    "other",
];

/// `LockTagTypeNames`, in the order of `LockTagType`.
const LOCK_TYPES: [&str; 12] = [
    "relation",
    "extend",
    "frozenid",
    "page",
    "tuple",
    "transactionid",
    "virtualxid",
    "spectoken",
    "object",
    "userlock",
    "advisory",
    "applytransaction",
];

/// The counters of the background writer and of the checkpointer, after `pg_stat_get_`.
const COUNTERS: [&str; 11] = [
    "bgwriter_buf_written_clean",
    "bgwriter_maxwritten_clean",
    "buf_alloc",
    "checkpointer_num_timed",
    "checkpointer_num_requested",
    "checkpointer_num_performed",
    "checkpointer_restartpoints_timed",
    "checkpointer_restartpoints_requested",
    "checkpointer_restartpoints_performed",
    "checkpointer_buffers_written",
    "checkpointer_slru_written",
];

/// The 20 columns of `pg_stat_get_io`.
const IO_COLUMNS: usize = 20;

/// The 10 columns of `pg_stat_get_recovery_prefetch`, after `stats_reset`: six counts of the type `bigint` and three of the type `integer`.
const PREFETCH_COUNTS: usize = 6;
const PREFETCH_DEPTHS: usize = 3;

/// The types of processes in `BackendType` that count their I/O, in its order: `pgstat_tracks_io_bktype`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Process {
    Client,
    AutovacuumLauncher,
    AutovacuumWorker,
    BackgroundWorker,
    WalSender,
    SlotsyncWorker,
    Standalone,
    BackgroundWriter,
    Checkpointer,
    IoWorker,
    Startup,
    WalReceiver,
    WalSummarizer,
    WalWriter,
}

/// Each type of process with the name of `GetBackendTypeDesc`.
const PROCESSES: [(Process, &str); 14] = [
    (Process::Client, "client backend"),
    (Process::AutovacuumLauncher, "autovacuum launcher"),
    (Process::AutovacuumWorker, "autovacuum worker"),
    (Process::BackgroundWorker, "background worker"),
    (Process::WalSender, "walsender"),
    (Process::SlotsyncWorker, "slotsync worker"),
    (Process::Standalone, "standalone backend"),
    (Process::BackgroundWriter, "background writer"),
    (Process::Checkpointer, "checkpointer"),
    (Process::IoWorker, "io worker"),
    (Process::Startup, "startup"),
    (Process::WalReceiver, "walreceiver"),
    (Process::WalSummarizer, "walsummarizer"),
    (Process::WalWriter, "walwriter"),
];

/// `IOObject`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Object {
    Relation,
    TempRelation,
    Wal,
}

const OBJECTS: [(Object, &str); 3] =
    [(Object::Relation, "relation"), (Object::TempRelation, "temp relation"), (Object::Wal, "wal")];

/// `IOContext`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Context {
    BulkRead,
    BulkWrite,
    Init,
    Normal,
    Vacuum,
}

const CONTEXTS: [(Context, &str); 5] = [
    (Context::BulkRead, "bulkread"),
    (Context::BulkWrite, "bulkwrite"),
    (Context::Init, "init"),
    (Context::Normal, "normal"),
    (Context::Vacuum, "vacuum"),
];

/// `IOOp`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    Evict,
    Fsync,
    Hit,
    Reuse,
    Writeback,
    Extend,
    Read,
    Write,
}

/// Each operation with the columns of its count, its time and its bytes in `pg_stat_get_io`: `pgstat_get_io_op_index`, `pgstat_get_io_time_index` and `pgstat_get_io_byte_index`.
const OPS: [(Op, usize, Option<usize>, Option<usize>); 8] = [
    (Op::Evict, 15, None, None),
    (Op::Fsync, 17, Some(18), None),
    (Op::Hit, 14, None, None),
    (Op::Reuse, 16, None, None),
    (Op::Writeback, 9, Some(10), None),
    (Op::Extend, 11, Some(13), Some(12)),
    (Op::Read, 3, Some(5), Some(4)),
    (Op::Write, 6, Some(8), Some(7)),
];

/// `pgstat_tracks_io_object`: true when the process can do I/O on the object in the context, so that the view has a row for them.
fn tracks_object(process: Process, object: Object, context: Context) -> bool {
    if object == Object::Wal && !matches!(context, Context::Normal | Context::Init) {
        return false;
    }
    if object == Object::TempRelation && context != Context::Normal {
        return false;
    }
    let no_temp_relation = matches!(
        process,
        Process::AutovacuumLauncher
            | Process::BackgroundWriter
            | Process::Checkpointer
            | Process::AutovacuumWorker
            | Process::Standalone
            | Process::Startup
            | Process::WalSummarizer
            | Process::WalWriter
            | Process::WalReceiver
    );
    if no_temp_relation && object == Object::TempRelation {
        return false;
    }
    if matches!(process, Process::WalSummarizer | Process::WalReceiver | Process::WalWriter)
        && object != Object::Wal
    {
        return false;
    }
    let strategy = matches!(context, Context::BulkRead | Context::BulkWrite | Context::Vacuum);
    if matches!(process, Process::Checkpointer | Process::BackgroundWriter) && strategy {
        return false;
    }
    if process == Process::AutovacuumLauncher && context == Context::Vacuum {
        return false;
    }
    !(matches!(process, Process::AutovacuumWorker | Process::AutovacuumLauncher)
        && context == Context::BulkWrite)
}

/// `pgstat_tracks_io_op`: true when the process can do the operation on the object in the context, so that the cell of the view is not null.
fn tracks_op(process: Process, object: Object, context: Context, op: Op) -> bool {
    if !tracks_object(process, object, context) {
        return false;
    }
    if process == Process::BackgroundWriter && matches!(op, Op::Read | Op::Evict | Op::Hit) {
        return false;
    }
    if process == Process::Checkpointer
        && ((object != Object::Wal && op == Op::Read) || matches!(op, Op::Evict | Op::Hit))
    {
        return false;
    }
    if matches!(process, Process::BackgroundWriter | Process::Checkpointer) && op == Op::Extend {
        return false;
    }
    if object == Object::Wal
        && op == Op::Read
        && matches!(
            process,
            Process::WalReceiver
                | Process::BackgroundWriter
                | Process::AutovacuumLauncher
                | Process::AutovacuumWorker
                | Process::WalWriter
        )
    {
        return false;
    }
    if object == Object::TempRelation && matches!(op, Op::Fsync | Op::Writeback) {
        return false;
    }
    if context == Context::BulkRead && op == Op::Extend {
        return false;
    }
    let strategy = matches!(context, Context::BulkRead | Context::BulkWrite | Context::Vacuum);
    if !strategy && op == Op::Reuse {
        return false;
    }
    if object == Object::Wal && context == Context::Init && !matches!(op, Op::Write | Op::Fsync) {
        return false;
    }
    if object == Object::Wal
        && context == Context::Normal
        && !matches!(op, Op::Write | Op::Read | Op::Fsync)
    {
        return false;
    }
    !(strategy && op == Op::Fsync)
}

/// The time of the last reset of the statistics, or null when it is 0, as most of the functions give it.
fn reset_or_null(call: &Call<'_>) -> Value {
    match call.session.stats_reset() {
        0 => Value::Null,
        at => Value::TimestampTz(at),
    }
}

/// A count of 0 bytes, of the type `numeric`.
fn no_bytes() -> Value {
    Value::Numeric(Numeric::from_integer(0))
}

/// A counter of the background writer or of the checkpointer.
fn counter(_: &Call<'_>, _: &[Value]) -> Result<Value> {
    Ok(Value::Int8(0))
}

/// `pg_stat_get_checkpointer_write_time` and `pg_stat_get_checkpointer_sync_time`, in milliseconds.
fn time(_: &Call<'_>, _: &[Value]) -> Result<Value> {
    Ok(Value::Float8(0.0))
}

/// `pg_stat_get_bgwriter_stat_reset_time` and `pg_stat_get_checkpointer_stat_reset_time`, which give the time even when it is 0.
fn reset_time(call: &Call<'_>, _: &[Value]) -> Result<Value> {
    Ok(Value::TimestampTz(call.session.stats_reset()))
}

/// `pg_stat_get_wal`: the counts of the WAL records, the full page images, the bytes and the waits for a full WAL buffer.
pub(crate) fn wal(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    Ok(vec![vec![
        Value::Int8(0),
        Value::Int8(0),
        no_bytes(),
        no_bytes(),
        Value::Int8(0),
        reset_or_null(call),
    ]])
}

/// `pg_stat_get_io`: a row for each type of process, object and context that `pgstat_tracks_io_object` allows, with a null cell for each operation that `pgstat_tracks_io_op` does not allow.
pub(crate) fn io(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    let reset = reset_or_null(call);
    let mut rows = Vec::new();
    for (process, process_name) in PROCESSES {
        for (object, object_name) in OBJECTS {
            for (context, context_name) in CONTEXTS {
                if !tracks_object(process, object, context) {
                    continue;
                }
                let mut row = vec![Value::Null; IO_COLUMNS];
                row[0] = Value::text(process_name);
                row[1] = Value::text(object_name);
                row[2] = Value::text(context_name);
                row[IO_COLUMNS - 1] = reset.clone();
                for (op, count, time, bytes) in OPS {
                    if !tracks_op(process, object, context, op) {
                        continue;
                    }
                    row[count] = Value::Int8(0);
                    if let Some(time) = time {
                        row[time] = Value::Float8(0.0);
                    }
                    if let Some(bytes) = bytes {
                        row[bytes] = no_bytes();
                    }
                }
                rows.push(row);
            }
        }
    }
    Ok(rows)
}

/// `pg_stat_get_archiver`: no archived or failed WAL files.
pub(crate) fn archiver(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    Ok(vec![vec![
        Value::Int8(0),
        Value::Null,
        Value::Null,
        Value::Int8(0),
        Value::Null,
        Value::Null,
        reset_or_null(call),
    ]])
}

/// `pg_stat_get_slru`: a row for each SLRU cache.
pub(crate) fn slru(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    let reset = Value::TimestampTz(call.session.stats_reset());
    Ok(SLRUS
        .iter()
        .map(|name| {
            let mut row = vec![Value::text(*name)];
            row.extend(std::iter::repeat_n(Value::Int8(0), 7));
            row.push(reset.clone());
            row
        })
        .collect())
}

/// `pg_stat_get_recovery_prefetch`: the counts of the prefetch of recovery, which are 0 on a server that is not in recovery.
pub(crate) fn recovery_prefetch(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    let mut row = vec![reset_or_null(call)];
    row.extend(std::iter::repeat_n(Value::Int8(0), PREFETCH_COUNTS));
    row.extend(std::iter::repeat_n(Value::Int4(0), PREFETCH_DEPTHS));
    Ok(vec![row])
}

/// `pg_stat_get_lock`: a row for each type of lock tag.
pub(crate) fn lock(call: &Call<'_>, _: &[Value]) -> Result<Vec<Vec<Value>>> {
    let reset = Value::TimestampTz(call.session.stats_reset());
    Ok(LOCK_TYPES
        .iter()
        .map(|name| {
            vec![
                Value::text(*name),
                Value::Int8(0),
                Value::Float8(0.0),
                Value::Int8(0),
                reset.clone(),
            ]
        })
        .collect())
}

/// The kernel of a function of this module by its `prosrc`.
pub(crate) fn by_src(src: &str) -> Option<Kernel> {
    let name = src.strip_prefix("pg_stat_get_")?;
    Some(match name {
        "checkpointer_write_time" | "checkpointer_sync_time" => time,
        "bgwriter_stat_reset_time" | "checkpointer_stat_reset_time" => reset_time,
        _ if COUNTERS.contains(&name) => counter,
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The module has the 15 functions of the background writer and of the checkpointer in `pg_proc`, each with no arguments.
    #[test]
    fn covers_the_functions_of_the_writers() {
        let mut found = 0;
        for proc in rupg_pgcatalog::builtin::procs() {
            if by_src(proc.src).is_none() {
                continue;
            }
            found += 1;
            assert!(proc.argtypes.is_empty(), "{}", proc.src);
            assert!(matches!(proc.rettype, 20 | 701 | 1184), "{}", proc.src);
        }
        assert_eq!(found, 15);
    }

    /// `pg_stat_get_io` has 79 rows, as in PostgreSQL 19, and a client backend has a row for each context of a relation.
    #[test]
    fn the_rows_of_io() {
        let rows: Vec<_> = PROCESSES
            .iter()
            .flat_map(|&(process, _)| {
                OBJECTS.iter().flat_map(move |&(object, _)| {
                    CONTEXTS
                        .iter()
                        .filter(move |&&(context, _)| tracks_object(process, object, context))
                })
            })
            .collect();
        assert_eq!(rows.len(), 79);
        assert!(CONTEXTS.iter().all(|&(context, _)| tracks_object(
            Process::Client,
            Object::Relation,
            context
        )));
    }
}