mz_expr/scalar/func/impls/
oid.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use mz_expr_derive::sqlfunc;
11use mz_ore::cast::ReinterpretCast;
12use mz_pgrepr::Type;
13use mz_repr::adt::system::{Oid, RegClass, RegProc, RegType};
14use mz_repr::strconv;
15
16#[sqlfunc(
17    sqlname = "oid_to_text",
18    preserves_uniqueness = true,
19    inverse = to_unary!(super::CastStringToOid)
20)]
21fn cast_oid_to_string(a: Oid) -> String {
22    let mut buf = String::new();
23    strconv::format_uint32(&mut buf, a.0);
24    buf
25}
26
27#[sqlfunc(
28    sqlname = "oid_to_integer",
29    preserves_uniqueness = true,
30    inverse = to_unary!(super::CastInt32ToOid)
31)]
32fn cast_oid_to_int32(a: Oid) -> i32 {
33    // For historical reasons in PostgreSQL, the bytes of the `u32` are
34    // reinterpreted as an `i32` without bounds checks, so very large
35    // positive OIDs become negative `i32`s.
36    //
37    // Do not use this as a model for behavior in other contexts. OIDs
38    // should not in general be thought of as freely convertible to `i32`s.
39    i32::reinterpret_cast(a.0)
40}
41
42#[sqlfunc(
43    sqlname = "oid_to_bigint",
44    preserves_uniqueness = true,
45    inverse = to_unary!(super::CastInt64ToOid)
46)]
47fn cast_oid_to_int64(a: Oid) -> i64 {
48    i64::from(a.0)
49}
50
51#[sqlfunc(
52    sqlname = "oidtoregclass",
53    preserves_uniqueness = true,
54    inverse = to_unary!(super::CastRegClassToOid)
55)]
56fn cast_oid_to_reg_class(a: Oid) -> RegClass {
57    RegClass(a.0)
58}
59
60#[sqlfunc(
61    sqlname = "oidtoregproc",
62    preserves_uniqueness = true,
63    inverse = to_unary!(super::CastRegProcToOid)
64)]
65fn cast_oid_to_reg_proc(a: Oid) -> RegProc {
66    RegProc(a.0)
67}
68
69#[sqlfunc(
70    sqlname = "oidtoregtype",
71    preserves_uniqueness = true,
72    inverse = to_unary!(super::CastRegTypeToOid)
73)]
74fn cast_oid_to_reg_type(a: Oid) -> RegType {
75    RegType(a.0)
76}
77
78#[sqlfunc]
79fn mz_type_name(oid: Oid) -> Option<String> {
80    if let Ok(t) = Type::from_oid(oid.0) {
81        Some(t.name().to_string())
82    } else {
83        None
84    }
85}