Skip to main content

common_function/system/
database.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 datafusion::arrow::datatypes::DataType;
16use datafusion_common::ScalarValue;
17use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature, Volatility};
18
19use crate::function::{Function, find_function_context};
20use crate::system::define_nullary_udf;
21
22define_nullary_udf!(DatabaseFunction);
23define_nullary_udf!(SchemaFunction);
24define_nullary_udf!(UserFunction);
25define_nullary_udf!(CurrentUserFunction);
26define_nullary_udf!(SystemUserFunction);
27define_nullary_udf!(ReadPreferenceFunction);
28define_nullary_udf!(PgBackendPidFunction);
29define_nullary_udf!(ConnectionIdFunction);
30
31const DATABASE_FUNCTION_NAME: &str = "database";
32const SCHEMA_FUNCTION_NAME: &str = "schema";
33const USER_FUNCTION_NAME: &str = "user";
34const CURRENT_USER_FUNCTION_NAME: &str = "current_user";
35const SYSTEM_USER_FUNCTION_NAME: &str = "system_user";
36const READ_PREFERENCE_FUNCTION_NAME: &str = "read_preference";
37const PG_BACKEND_PID: &str = "pg_backend_pid";
38const CONNECTION_ID: &str = "connection_id";
39
40macro_rules! impl_current_schema_function {
41    ($name: ident, $fn_name: expr) => {
42        impl Function for $name {
43            fn name(&self) -> &str {
44                $fn_name
45            }
46
47            fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
48                Ok(DataType::Utf8View)
49            }
50
51            fn signature(&self) -> &Signature {
52                &self.signature
53            }
54
55            fn invoke_with_args(
56                &self,
57                args: ScalarFunctionArgs,
58            ) -> datafusion_common::Result<ColumnarValue> {
59                let func_ctx = find_function_context(&args)?;
60                let db = func_ctx.query_ctx.current_schema();
61
62                Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(
63                    (!db.is_empty()).then_some(db),
64                )))
65            }
66        }
67    };
68}
69
70impl_current_schema_function!(DatabaseFunction, DATABASE_FUNCTION_NAME);
71// MySQL's `SCHEMA()` is a synonym for `DATABASE()`.
72impl_current_schema_function!(SchemaFunction, SCHEMA_FUNCTION_NAME);
73
74macro_rules! impl_current_user_function {
75    ($name: ident, $fn_name: expr) => {
76        impl Function for $name {
77            fn name(&self) -> &str {
78                $fn_name
79            }
80
81            fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
82                Ok(DataType::Utf8View)
83            }
84
85            fn signature(&self) -> &Signature {
86                &self.signature
87            }
88
89            fn invoke_with_args(
90                &self,
91                args: ScalarFunctionArgs,
92            ) -> datafusion_common::Result<ColumnarValue> {
93                let func_ctx = find_function_context(&args)?;
94                let user = func_ctx.query_ctx.current_user();
95
96                Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(Some(
97                    user.username().to_string(),
98                ))))
99            }
100        }
101    };
102}
103
104// GreptimeDB has no notion of a user switching identity mid-session, so `USER()`,
105// `CURRENT_USER()` and `SYSTEM_USER()` all report the authenticated user.
106impl_current_user_function!(UserFunction, USER_FUNCTION_NAME);
107impl_current_user_function!(CurrentUserFunction, CURRENT_USER_FUNCTION_NAME);
108impl_current_user_function!(SystemUserFunction, SYSTEM_USER_FUNCTION_NAME);
109
110impl Function for ReadPreferenceFunction {
111    fn name(&self) -> &str {
112        READ_PREFERENCE_FUNCTION_NAME
113    }
114
115    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
116        Ok(DataType::Utf8View)
117    }
118
119    fn signature(&self) -> &Signature {
120        &self.signature
121    }
122
123    fn invoke_with_args(
124        &self,
125        args: ScalarFunctionArgs,
126    ) -> datafusion_common::Result<ColumnarValue> {
127        let func_ctx = find_function_context(&args)?;
128        let read_preference = func_ctx.query_ctx.read_preference();
129
130        Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(Some(
131            read_preference.to_string(),
132        ))))
133    }
134}
135
136impl Function for PgBackendPidFunction {
137    fn name(&self) -> &str {
138        PG_BACKEND_PID
139    }
140
141    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
142        Ok(DataType::UInt64)
143    }
144
145    fn signature(&self) -> &Signature {
146        &self.signature
147    }
148
149    fn invoke_with_args(
150        &self,
151        args: ScalarFunctionArgs,
152    ) -> datafusion_common::Result<ColumnarValue> {
153        let func_ctx = find_function_context(&args)?;
154        let pid = func_ctx.query_ctx.process_id();
155
156        Ok(ColumnarValue::Scalar(ScalarValue::UInt64(Some(pid as u64))))
157    }
158}
159
160impl Function for ConnectionIdFunction {
161    fn name(&self) -> &str {
162        CONNECTION_ID
163    }
164
165    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
166        Ok(DataType::UInt32)
167    }
168
169    fn signature(&self) -> &Signature {
170        &self.signature
171    }
172
173    fn invoke_with_args(
174        &self,
175        args: ScalarFunctionArgs,
176    ) -> datafusion_common::Result<ColumnarValue> {
177        let func_ctx = find_function_context(&args)?;
178        let pid = func_ctx.query_ctx.process_id();
179
180        Ok(ColumnarValue::Scalar(ScalarValue::UInt32(Some(pid))))
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use std::sync::Arc;
187
188    use arrow_schema::Field;
189    use datafusion_common::config::ConfigOptions;
190    use session::context::QueryContextBuilder;
191
192    use super::*;
193    use crate::function::FunctionContext;
194    #[test]
195    fn test_build_function() {
196        let build = DatabaseFunction::default();
197        assert_eq!("database", build.name());
198        assert_eq!(DataType::Utf8View, build.return_type(&[]).unwrap());
199
200        let query_ctx = QueryContextBuilder::default()
201            .current_schema("test_db".to_string())
202            .build()
203            .into();
204
205        let mut config_options = ConfigOptions::default();
206        config_options.extensions.insert(FunctionContext {
207            query_ctx,
208            ..Default::default()
209        });
210        let config_options = Arc::new(config_options);
211
212        let args = ScalarFunctionArgs {
213            args: vec![],
214            arg_fields: vec![],
215            number_rows: 0,
216            return_field: Arc::new(Field::new("x", DataType::UInt64, false)),
217            config_options,
218        };
219        let result = build.invoke_with_args(args).unwrap();
220        let ColumnarValue::Scalar(ScalarValue::Utf8View(Some(s))) = result else {
221            unreachable!()
222        };
223        assert_eq!(s, "test_db");
224    }
225}