Skip to content

Commit

Permalink
chore: clean macro
Browse files Browse the repository at this point in the history
  • Loading branch information
KKould committed Aug 27, 2024
1 parent 713bc56 commit b83db3d
Show file tree
Hide file tree
Showing 15 changed files with 566 additions and 474 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,5 @@ pprof = { version = "0.13", features = ["flamegraph", "criterion"] }
[workspace]
members = [
"tests/sqllogictest",
"tests/macros-test"
]
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ kould23333/fncksql:latest
~~~

### Features
- ORM Mapping: `features = ["marcos"]`
- ORM Mapping: `features = ["macros"]`
```rust
#[derive(Default, Debug, PartialEq)]
struct MyStruct {
Expand All @@ -114,7 +114,7 @@ implement_from_tuple!(
)
);
```
- User-Defined Function: `features = ["marcos"]`
- User-Defined Function: `features = ["macros"]`
```rust
function!(TestFunction::test(LogicalType::Integer, LogicalType::Integer) -> LogicalType::Integer => |v1: ValueRef, v2: ValueRef| {
let plus_binary_evaluator = EvaluatorFactory::binary_create(LogicalType::Integer, BinaryOperator::Plus)?;
Expand Down
2 changes: 0 additions & 2 deletions examples/hello_world.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use fnck_sql::db::DataBaseBuilder;
use fnck_sql::errors::DatabaseError;
use fnck_sql::implement_from_tuple;
use fnck_sql::types::tuple::{SchemaRef, Tuple};
use fnck_sql::types::value::DataValue;
use fnck_sql::types::LogicalType;
use itertools::Itertools;

#[derive(Default, Debug, PartialEq)]
Expand Down
12 changes: 6 additions & 6 deletions src/catalog/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ pub struct ColumnSummary {
}

impl ColumnCatalog {
pub(crate) fn new(
column_name: String,
nullable: bool,
column_desc: ColumnDesc,
) -> ColumnCatalog {
pub fn new(column_name: String, nullable: bool, column_desc: ColumnDesc) -> ColumnCatalog {
ColumnCatalog {
summary: ColumnSummary {
id: None,
Expand Down Expand Up @@ -87,6 +83,10 @@ impl ColumnCatalog {
self.summary.name = name;
}

pub fn set_id(&mut self, id: ColumnId) {
self.summary.id = Some(id);
}

pub fn set_table_name(&mut self, table_name: TableName) {
self.summary.table_name = Some(table_name);
}
Expand Down Expand Up @@ -119,7 +119,7 @@ pub struct ColumnDesc {
}

impl ColumnDesc {
pub(crate) const fn new(
pub const fn new(
column_datatype: LogicalType,
is_primary: bool,
is_unique: bool,
Expand Down
4 changes: 2 additions & 2 deletions src/catalog/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
pub(crate) use self::column::*;
pub(crate) use self::table::*;

mod column;
mod table;
pub mod column;
pub mod table;
4 changes: 2 additions & 2 deletions src/catalog/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl TableCatalog {
self.indexes.iter()
}

pub(crate) fn schema_ref(&self) -> &SchemaRef {
pub fn schema_ref(&self) -> &SchemaRef {
&self.schema_ref
}

Expand Down Expand Up @@ -139,7 +139,7 @@ impl TableCatalog {
Ok(self.indexes.last().unwrap())
}

pub(crate) fn new(
pub fn new(
name: TableName,
columns: Vec<ColumnCatalog>,
) -> Result<TableCatalog, DatabaseError> {
Expand Down
33 changes: 6 additions & 27 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,20 +303,12 @@ impl<S: Storage> DBTransaction<'_, S> {

#[cfg(test)]
mod test {
use crate::catalog::{ColumnCatalog, ColumnDesc, ColumnRef};
use crate::catalog::{ColumnCatalog, ColumnDesc};
use crate::db::{DataBaseBuilder, DatabaseError};
use crate::expression::function::scala::{FuncMonotonicity, ScalarFunctionImpl};
use crate::expression::function::FunctionSummary;
use crate::expression::ScalarExpression;
use crate::expression::{BinaryOperator, UnaryOperator};
use crate::scala_function;
use crate::storage::{Storage, TableCache, Transaction};
use crate::types::evaluator::EvaluatorFactory;
use crate::types::tuple::{create_table, Tuple};
use crate::types::value::{DataValue, ValueRef};
use crate::types::tuple::create_table;
use crate::types::value::DataValue;
use crate::types::LogicalType;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
use tempfile::TempDir;

Expand Down Expand Up @@ -356,25 +348,12 @@ mod test {
Ok(())
}

scala_function!(TestFunction::test(LogicalType::Integer, LogicalType::Integer) -> LogicalType::Integer => (|v1: ValueRef, v2: ValueRef| {
let plus_binary_evaluator = EvaluatorFactory::binary_create(LogicalType::Integer, BinaryOperator::Plus)?;
let value = plus_binary_evaluator.binary_eval(&v1, &v2);

let plus_unary_evaluator = EvaluatorFactory::unary_create(LogicalType::Integer, UnaryOperator::Minus)?;
Ok(plus_unary_evaluator.unary_eval(&value))
}));

/// use [CurrentDate](crate::function::current_date::CurrentDate) on this case
#[test]
fn test_udf() -> Result<(), DatabaseError> {
let temp_dir = TempDir::new().expect("unable to create temporary working directory");
let fnck_sql = DataBaseBuilder::path(temp_dir.path())
.register_scala_function(TestFunction::new())
.build()?;
let _ = fnck_sql
.run("CREATE TABLE test (id int primary key, c1 int, c2 int default test(1, 2));")?;
let _ = fnck_sql
.run("INSERT INTO test VALUES (1, 2, 2), (0, 1, 1), (2, 1, 1), (3, 3, default);")?;
let (schema, tuples) = fnck_sql.run("select test(c1, 1), c2 from test")?;
let fnck_sql = DataBaseBuilder::path(temp_dir.path()).build()?;
let (schema, tuples) = fnck_sql.run("select current_date()")?;
println!("{}", create_table(&schema, &tuples));

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions src/expression/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ pub mod table;

#[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize)]
pub struct FunctionSummary {
pub(crate) name: String,
pub(crate) arg_types: Vec<LogicalType>,
pub name: String,
pub arg_types: Vec<LogicalType>,
}
47 changes: 43 additions & 4 deletions src/function/current_date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::expression::function::scala::FuncMonotonicity;
use crate::expression::function::scala::ScalarFunctionImpl;
use crate::expression::function::FunctionSummary;
use crate::expression::ScalarExpression;
use crate::scala_function;
use crate::types::tuple::Tuple;
use crate::types::value::DataValue;
use crate::types::LogicalType;
Expand All @@ -13,6 +12,46 @@ use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;

scala_function!(CurrentDate::current_date() -> LogicalType::Date => (|| {
Ok(DataValue::Date32(Some(Local::now().num_days_from_ce())))
}));
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct CurrentDate {
summary: FunctionSummary,
}

impl CurrentDate {
#[allow(unused_mut)]
pub(crate) fn new() -> Arc<Self> {
let function_name = "current_date".to_lowercase();

Arc::new(Self {
summary: FunctionSummary {
name: function_name,
arg_types: Vec::new(),
},
})
}
}

#[typetag::serde]
impl ScalarFunctionImpl for CurrentDate {
#[allow(unused_variables, clippy::redundant_closure_call)]
fn eval(
&self,
_: &[ScalarExpression],
_: &Tuple,
_: &[ColumnRef],
) -> Result<DataValue, DatabaseError> {
Ok(DataValue::Date32(Some(Local::now().num_days_from_ce())))
}

fn monotonicity(&self) -> Option<FuncMonotonicity> {
todo!()
}

fn return_type(&self) -> &LogicalType {
&LogicalType::Date
}

fn summary(&self) -> &FunctionSummary {
&self.summary
}
}
83 changes: 72 additions & 11 deletions src/function/numbers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,85 @@ use crate::errors::DatabaseError;
use crate::expression::function::table::TableFunctionImpl;
use crate::expression::function::FunctionSummary;
use crate::expression::ScalarExpression;
use crate::table_function;
use crate::types::tuple::SchemaRef;
use crate::types::tuple::Tuple;
use crate::types::value::{DataValue, ValueRef};
use crate::types::value::DataValue;
use crate::types::LogicalType;
use lazy_static::lazy_static;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;

table_function!(Numbers::numbers(LogicalType::Integer) -> [number: LogicalType::Integer] => (|v1: ValueRef| {
let num = v1.i32().ok_or_else(|| DatabaseError::NotNull)?;
lazy_static! {
static ref NUMBERS: TableCatalog = {
TableCatalog::new(
Arc::new("numbers".to_lowercase()),
vec![ColumnCatalog::new(
"number".to_lowercase(),
true,
ColumnDesc::new(LogicalType::Integer, false, false, None),
)],
)
.unwrap()
};
}

Ok(Box::new((0..num)
.map(|i| Ok(Tuple {
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct Numbers {
summary: FunctionSummary,
}

impl Numbers {
#[allow(unused_mut)]
pub(crate) fn new() -> Arc<Self> {
let function_name = "numbers".to_lowercase();

Arc::new(Self {
summary: FunctionSummary {
name: function_name,
arg_types: vec![LogicalType::Integer],
},
})
}
}

#[typetag::serde]
impl TableFunctionImpl for Numbers {
#[allow(unused_variables, clippy::redundant_closure_call)]
fn eval(
&self,
args: &[ScalarExpression],
) -> Result<Box<dyn Iterator<Item = Result<Tuple, DatabaseError>>>, DatabaseError> {
let tuple = Tuple {
id: None,
values: vec![
Arc::new(DataValue::Int32(Some(i))),
]
}))) as Box<dyn Iterator<Item = Result<Tuple, DatabaseError>>>)
}));
values: Vec::new(),
};

let mut value = args[0].eval(&tuple, &[])?;

if value.logical_type() != LogicalType::Integer {
value = Arc::new(DataValue::clone(&value).cast(&LogicalType::Integer)?);
}
let num = value.i32().ok_or_else(|| DatabaseError::NotNull)?;

Ok(Box::new((0..num).map(|i| {
Ok(Tuple {
id: None,
values: vec![Arc::new(DataValue::Int32(Some(i)))],
})
}))
as Box<dyn Iterator<Item = Result<Tuple, DatabaseError>>>)
}

fn output_schema(&self) -> &SchemaRef {
NUMBERS.schema_ref()
}

fn summary(&self) -> &FunctionSummary {
&self.summary
}

fn table(&self) -> &'static TableCatalog {
&NUMBERS
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
//! )
//! );
//!
//! #[cfg(feature = "marcos")]
//! #[cfg(feature = "macros")]
//! fn main() -> Result<(), DatabaseError> {
//! let database = DataBaseBuilder::path("./hello_world").build()?;
//!
Expand Down Expand Up @@ -104,7 +104,7 @@ pub mod execution;
pub mod expression;
mod function;
#[cfg(feature = "marcos")]
pub mod marcos;
pub mod macros;
mod optimizer;
pub mod parser;
pub mod planner;
Expand Down
Loading

0 comments on commit b83db3d

Please sign in to comment.