-
Notifications
You must be signed in to change notification settings - Fork 335
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: support sleep function #5448
Draft
yihong0618
wants to merge
3
commits into
GreptimeTeam:main
Choose a base branch
from
yihong0618:hy/support_select_time
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+235
−0
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
// Copyright 2023 Greptime Team | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
use std::sync::Arc; | ||
use std::time::Duration; | ||
use std::{fmt, thread}; | ||
|
||
use common_query::error::{InvalidFuncArgsSnafu, Result}; | ||
use common_query::prelude::{Signature, Volatility}; | ||
use datatypes::prelude::ConcreteDataType; | ||
use datatypes::value::Value; | ||
use datatypes::vectors::{Int64Vector, VectorRef}; | ||
use snafu::ensure; | ||
|
||
use crate::function::{Function, FunctionContext}; | ||
use crate::function_registry::FunctionRegistry; | ||
|
||
/// Sleep function that pauses execution for specified seconds | ||
#[derive(Clone, Debug, Default)] | ||
pub(crate) struct SleepFunction; | ||
|
||
impl SleepFunction { | ||
pub fn register(registry: &FunctionRegistry) { | ||
registry.register(Arc::new(SleepFunction)); | ||
} | ||
} | ||
|
||
const NAME: &str = "sleep"; | ||
|
||
impl Function for SleepFunction { | ||
fn name(&self) -> &str { | ||
NAME | ||
} | ||
|
||
fn return_type(&self, _input_types: &[ConcreteDataType]) -> Result<ConcreteDataType> { | ||
Ok(ConcreteDataType::int64_datatype()) | ||
} | ||
|
||
fn signature(&self) -> Signature { | ||
// Accept int32, int64 and float64 types | ||
Signature::uniform( | ||
1, | ||
vec![ | ||
ConcreteDataType::int32_datatype(), | ||
ConcreteDataType::int64_datatype(), | ||
ConcreteDataType::float64_datatype(), | ||
], | ||
Volatility::Volatile, | ||
) | ||
} | ||
|
||
fn eval(&self, _func_ctx: FunctionContext, columns: &[VectorRef]) -> Result<VectorRef> { | ||
ensure!( | ||
columns.len() == 1, | ||
InvalidFuncArgsSnafu { | ||
err_msg: format!( | ||
"The length of the args is not correct, expect exactly one, have: {}", | ||
columns.len() | ||
), | ||
} | ||
); | ||
|
||
let vector = &columns[0]; | ||
let mut result = Vec::with_capacity(vector.len()); | ||
|
||
for i in 0..vector.len() { | ||
let secs = match vector.get(i) { | ||
Value::Int64(x) => x as f64, | ||
Value::Int32(x) => x as f64, | ||
Value::Float64(x) => x.into_inner(), | ||
_ => { | ||
result.push(None); | ||
continue; | ||
} | ||
}; | ||
// Sleep for the specified seconds TODO: use tokio::time::sleep when the scalars are async | ||
thread::sleep(Duration::from_secs_f64(secs)); | ||
Comment on lines
+87
to
+88
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd suggest not to sleep in a scalar function. This pauses the runtime thread which is risky. |
||
result.push(Some(secs as i64)); | ||
} | ||
|
||
Ok(Arc::new(Int64Vector::from(result))) | ||
} | ||
} | ||
|
||
impl fmt::Display for SleepFunction { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "SLEEP") | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::time::Instant; | ||
|
||
use datatypes::value::Value; | ||
use datatypes::vectors::{Float64Vector, Int32Vector}; | ||
|
||
use super::*; | ||
|
||
#[test] | ||
fn test_sleep() { | ||
let f = SleepFunction; | ||
assert_eq!("sleep", f.name()); | ||
assert_eq!( | ||
ConcreteDataType::int64_datatype(), | ||
f.return_type(&[]).unwrap() | ||
); | ||
|
||
let times = vec![Some(1_i64), None, Some(2_i64)]; | ||
let args: Vec<VectorRef> = vec![Arc::new(Int64Vector::from(times.clone()))]; | ||
|
||
let start = Instant::now(); | ||
let vector = f.eval(FunctionContext::default(), &args).unwrap(); | ||
let elapsed = start.elapsed(); | ||
|
||
assert_eq!(3, vector.len()); | ||
assert!(elapsed.as_secs() >= 3); // Should sleep for total of 3 seconds | ||
|
||
assert_eq!(vector.get(0), Value::Int64(1)); | ||
assert_eq!(vector.get(1), Value::Null); | ||
assert_eq!(vector.get(2), Value::Int64(2)); | ||
} | ||
|
||
#[test] | ||
fn test_sleep_float64() { | ||
let f = SleepFunction; | ||
let times = vec![Some(0.5_f64), None, Some(1.5_f64)]; | ||
let args: Vec<VectorRef> = vec![Arc::new(Float64Vector::from(times))]; | ||
|
||
let start = Instant::now(); | ||
let vector = f.eval(FunctionContext::default(), &args).unwrap(); | ||
let elapsed = start.elapsed(); | ||
|
||
assert_eq!(3, vector.len()); | ||
assert!(elapsed.as_secs_f64() >= 2.0); | ||
|
||
assert_eq!(vector.get(0), Value::Int64(0)); | ||
assert_eq!(vector.get(1), Value::Null); | ||
assert_eq!(vector.get(2), Value::Int64(1)); | ||
} | ||
|
||
#[test] | ||
fn test_sleep_int32() { | ||
let f = SleepFunction; | ||
let times = vec![Some(1_i32), None, Some(2_i32)]; | ||
let args: Vec<VectorRef> = vec![Arc::new(Int32Vector::from(times))]; | ||
|
||
let start = Instant::now(); | ||
let vector = f.eval(FunctionContext::default(), &args).unwrap(); | ||
let elapsed = start.elapsed(); | ||
|
||
assert_eq!(3, vector.len()); | ||
assert!(elapsed.as_secs() >= 3); | ||
|
||
assert_eq!(vector.get(0), Value::Int64(1)); | ||
assert_eq!(vector.get(1), Value::Null); | ||
assert_eq!(vector.get(2), Value::Int64(2)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
select sleep(0.1); | ||
|
||
+---------------------+ | ||
| sleep(Float64(0.1)) | | ||
+---------------------+ | ||
| 0 | | ||
+---------------------+ | ||
|
||
select sleep(1) as a; | ||
|
||
+---+ | ||
| a | | ||
+---+ | ||
| 1 | | ||
+---+ | ||
|
||
-- should fail it is for postgres | ||
select pg_sleep(0.1); | ||
|
||
Error: 3000(PlanQuery), Failed to plan SQL: Error during planning: Invalid function 'pg_sleep'. | ||
Did you mean 'sleep'? | ||
|
||
-- SQLNESS PROTOCOL POSTGRES | ||
select pg_sleep(0.5); | ||
|
||
+---------------------+ | ||
| sleep(Float64(0.5)) | | ||
+---------------------+ | ||
| 0 | | ||
+---------------------+ | ||
|
||
-- SQLNESS PROTOCOL POSTGRES | ||
select pg_sleep(2) as b; | ||
|
||
+---+ | ||
| b | | ||
+---+ | ||
| 2 | | ||
+---+ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
select sleep(0.1); | ||
|
||
select sleep(1) as a; | ||
|
||
-- should fail it is for postgres | ||
select pg_sleep(0.1); | ||
|
||
-- SQLNESS PROTOCOL POSTGRES | ||
select pg_sleep(0.5); | ||
|
||
-- SQLNESS PROTOCOL POSTGRES | ||
select pg_sleep(2) as b; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm hesitant about whether to provide a sleep function. We may only provide a sleep function under the admin statement if we really need this.
admin sleep(60);
If our final goal is to support kill query, the sleep function may not be the first thing we need to implement. We can implement a way to cancel a query first.