catalog/system_schema/pg_catalog/pg_namespace/oid_map.rs
1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::hash::BuildHasher;
16use std::sync::Arc;
17
18use dashmap::DashMap;
19use rustc_hash::FxSeededState;
20
21pub type PGNamespaceOidMapRef = Arc<PGNamespaceOidMap>;
22// Workaround to convert schema_name to a numeric id,
23// remove this when we have numeric schema id in greptime
24pub struct PGNamespaceOidMap {
25 oid_map: DashMap<String, u32>,
26
27 // Rust use SipHasher by default, which provides resistance against DOS attacks.
28 // This will produce different hash value between each greptime instance. This will
29 // cause the sqlness test fail. We need a deterministic hash here to provide
30 // same oid for the same schema name with best effort and DOS attacks aren't concern here.
31 hasher: FxSeededState,
32}
33
34impl PGNamespaceOidMap {
35 pub fn new() -> Self {
36 Self {
37 oid_map: DashMap::new(),
38 hasher: FxSeededState::with_seed(0), // PLEASE DO NOT MODIFY THIS SEED VALUE!!!
39 }
40 }
41
42 fn oid_is_used(&self, oid: u32) -> bool {
43 self.oid_map.iter().any(|e| *e.value() == oid)
44 }
45
46 pub fn get_oid(&self, schema_name: &str) -> u32 {
47 if let Some(oid) = self.oid_map.get(schema_name) {
48 *oid
49 } else {
50 let mut oid = self.hasher.hash_one(schema_name) as u32;
51 while self.oid_is_used(oid) {
52 oid = self.hasher.hash_one(oid) as u32;
53 }
54 self.oid_map.insert(schema_name.to_string(), oid);
55 oid
56 }
57 }
58}
59
60#[cfg(test)]
61mod tests {
62
63 use super::*;
64
65 #[test]
66 fn oid_is_stable() {
67 let oid_map_1 = PGNamespaceOidMap::new();
68 let oid_map_2 = PGNamespaceOidMap::new();
69
70 let schema = "schema";
71 let oid = oid_map_1.get_oid(schema);
72
73 // oid keep stable in the same instance
74 assert_eq!(oid, oid_map_1.get_oid(schema));
75
76 // oid keep stable between different instances
77 assert_eq!(oid, oid_map_2.get_oid(schema));
78 }
79
80 #[test]
81 fn oid_collision() {
82 let oid_map = PGNamespaceOidMap::new();
83
84 let key1 = "3178510";
85 let key2 = "4215648";
86
87 // insert them into oid_map
88 let oid1 = oid_map.get_oid(key1);
89 let oid2 = oid_map.get_oid(key2);
90
91 // they should have different id
92 assert_ne!(oid1, oid2);
93 }
94}