Skip to content
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

fix: fix alias #2

Merged
merged 2 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ curl --request POST \
curl --request POST \
--url http://127.0.0.1:3000/view \
--data '{
"sql": "select a from t;"
"sql": "select a as e from t;"
}'
```

send/recv data by mqtt broker 127.0.0.1:1883

send data topic: /yisa/data

recv data topic: /yisa/data2

## Delete the view
Expand Down
2 changes: 1 addition & 1 deletion src/connector/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ impl MqttClient {
let (client, event_loop) = AsyncClient::new(mqtt_options, 10);
MqttClient { client, event_loop }
}
}
}
8 changes: 4 additions & 4 deletions src/core/datum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ pub enum Datum {

impl Serialize for Datum {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
where
S: Serializer,
{
match self {
Datum::Int(i) => serializer.serialize_i64(*i),
Expand All @@ -34,8 +34,8 @@ impl Serialize for Datum {

impl<'de> Deserialize<'de> for Datum {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
where
D: Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
match value {
Expand Down
16 changes: 10 additions & 6 deletions src/core/tuple.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;
use std::fmt::Display;
use std::{collections::HashMap, fmt::Display};

use crate::sql::planner::binder::ProjItem;
use serde_json::Value;

use super::Datum;
Expand Down Expand Up @@ -35,13 +35,17 @@ impl Tuple {
self.values.get(index).cloned()
}

pub fn project(&self, indices: &[(usize, String)]) -> Tuple {
pub fn project(&self, indices: &[ProjItem]) -> Tuple {
let mut new_keys = Vec::new();
let mut new_values = Vec::new();

for (_, key) in indices {
if let Some(index) = self.keys.iter().position(|k| k == key) {
new_keys.push(key.clone());
for item in indices {
if let Some(index) = self.keys.iter().position(|k| *k == item.name) {
if !item.alias_name.is_empty() {
new_keys.push(item.alias_name.clone())
} else {
new_keys.push(item.name.clone())
}
new_values.push(self.values[index].clone());
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::{collections::HashMap, mem, sync::Arc};

use axum::{
extract::{self},
Json,
Router, routing::{delete, get, post},
routing::{delete, get, post},
Json, Router,
};
use log::{info, LevelFilter};
use rumqttc::QoS;
Expand All @@ -15,18 +15,18 @@ use tokio::sync::{mpsc, Mutex};

use catalog::Catalog;
use core::Tuple;
use sql::{runtime::executor::View, Session, session::context::QueryContext};
use sql::{runtime::executor::View, session::context::QueryContext, Session};
use storage::StorageManager;
use util::SimpleLogger;

use crate::connector::MqttClient;

mod catalog;
mod connector;
mod core;
mod sql;
mod storage;
mod util;
mod connector;

static LOGGER: SimpleLogger = SimpleLogger;

Expand Down Expand Up @@ -80,7 +80,11 @@ async fn execute_sql(
tokio::spawn(async move {
while let Ok(Ok(Some(v))) = receiver.recv().await {
let data = v.parse_into_json().unwrap();
sender.client.publish("/yisa/data2", QoS::AtLeastOnce, false, data).await.unwrap();
sender
.client
.publish("/yisa/data2", QoS::AtLeastOnce, false, data)
.await
.unwrap();
}
info!("Subscribers of /yisa/data2 is closed");
});
Expand Down
73 changes: 56 additions & 17 deletions src/sql/planner/binder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ use crate::{
core::{ErrorKind, SQLError, Tuple, Type},
sql::{
planner::{scalar::bind_scalar, scope::Scope},
runtime::{DDLJob},
runtime::DDLJob,
session::context::QueryContext,
},
};

use super::{
aggregate::AggregateFunctionVisitor,
bind_context::BindContext,
Column,
Plan,
scalar::bind_aggregate_function, ScalarExpr, scope::{QualifiedNamePrefix, Variable},
scalar::bind_aggregate_function,
scope::{QualifiedNamePrefix, Variable},
Column, Plan, ScalarExpr,
};

struct FlattenedSelectItem {
Expand All @@ -30,6 +30,25 @@ pub struct Binder<'a> {
ctx: &'a mut QueryContext,
}

#[derive(Clone, Debug)]
pub struct ProjItem {
pub index: usize,
pub name: String,
pub alias_name: String,
pub is_column: bool,
}

impl ProjItem {
pub fn new(index: usize, name: String, alias_name: String, is_column: bool) -> Self {
ProjItem {
index,
name,
alias_name,
is_column,
}
}
}

impl<'a> Binder<'a> {
pub fn new(ctx: &'a mut QueryContext) -> Self {
Self { ctx }
Expand Down Expand Up @@ -265,7 +284,12 @@ impl<'a> Binder<'a> {
for expr in &select_stmt.group_by {
let scalar = bind_scalar(ctx, &from_scope, expr)?;

if let ScalarExpr::Column(Column { index, name }) = &scalar {
if let ScalarExpr::Column(Column {
column_name,
table_name,
index,
}) = &scalar
{
// If the group key is a column, we don't need to evaluate it
group_scope
.variables
Expand Down Expand Up @@ -336,12 +360,27 @@ impl<'a> Binder<'a> {
let mut scalar_maps = vec![];
for select_item in flattened_select_list.iter() {
let scalar = bind_scalar(ctx, &group_scope, &select_item.expr)?;
if let ScalarExpr::Column(Column { index, name }) = scalar {
if let ScalarExpr::Column(Column {
column_name,
table_name,
index,
}) = scalar
{
// If the select item is a column, we don't need to evaluate it
output_projections.push((index, name.clone()));
output_projections.push(ProjItem::new(
index,
column_name.clone(),
select_item.alias.clone(),
true,
));
} else {
scalar_maps.push(scalar);
output_projections.push((group_scope.variables.len(), select_item.alias.clone()));
output_projections.push(ProjItem::new(
group_scope.variables.len(),
select_item.alias.clone(),
select_item.alias.clone(),
false,
));
}
}
if !scalar_maps.is_empty() {
Expand All @@ -354,14 +393,14 @@ impl<'a> Binder<'a> {
// Project the result
let plan = Plan::Project {
input: Box::new(plan),
projections: output_projections.iter().map(|(index, name)| (*index, name.clone())).collect(),
projections: output_projections.iter().map(|item| item.clone()).collect(),
};

let output_scope = Scope {
variables: output_projections
.iter()
.map(|(_, name)| Variable {
name: name.clone(),
.map(|item| Variable {
name: item.name.clone(),
prefix: None,
expr: None,
})
Expand Down Expand Up @@ -402,9 +441,9 @@ impl<'a> Binder<'a> {
Some(Ident::new(prefix.table_name.clone())),
Some(Ident::new(v.name.clone())),
]
.into_iter()
.flatten()
.collect(),
.into_iter()
.flatten()
.collect(),
),
alias: v.name.clone(),
}
Expand Down Expand Up @@ -586,9 +625,9 @@ impl<'a> Binder<'a> {
for variable in scope.variables.iter_mut() {
match &mut variable.prefix {
Some(QualifiedNamePrefix {
schema_name,
table_name,
}) => {
schema_name,
table_name,
}) => {
*schema_name = None;
*table_name = alias.name.to_string();
}
Expand Down
11 changes: 6 additions & 5 deletions src/sql/planner/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::fmt::Display;

use crate::core::Datum;
use crate::{core::Datum, sql::planner::binder::ProjItem};

use super::runtime::{DDLJob};
use super::runtime::DDLJob;

pub mod aggregate;
pub mod bind_context;
Expand All @@ -27,7 +27,7 @@ pub enum Plan {
input: Box<Plan>,
},
Project {
projections: Vec<(usize, String)>,
projections: Vec<ProjItem>,
input: Box<Plan>,
},
Filter {
Expand All @@ -54,7 +54,8 @@ pub enum Plan {

#[derive(Debug, Clone, PartialEq)]
pub struct Column {
pub name: String,
pub column_name: String,
pub table_name: String,
pub index: usize,
}

Expand Down Expand Up @@ -122,7 +123,7 @@ fn indent_format_plan(f: &mut std::fmt::Formatter, plan: &Plan, indent: usize) -
indent_str,
projections
.iter()
.map(|v| format!("#{}", v.1.clone()))
.map(|v| format!("#{}", v.name.clone()))
.collect::<Vec<_>>()
.join(", ")
)?;
Expand Down
31 changes: 12 additions & 19 deletions src/sql/planner/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,10 @@ impl Scope {

variable.1.name == column_name.to_string()
&& variable
.1
.prefix
.as_ref()
.map_or(false, |prefix| prefix.table_name == table_name.to_string())
}
_ if ident.len() == 3 => {
let schema_name = &ident[0];
let table_name = &ident[1];
let column_name = &ident[2];

variable.1.name == column_name.to_string()
&& variable.1.prefix.as_ref().map_or(false, |prefix| {
prefix.table_name == table_name.to_string()
&& prefix
.schema_name
.1
.prefix
.as_ref()
.map_or(false, |schema| schema == &schema_name.to_string())
})
.map_or(false, |prefix| prefix.table_name == table_name.to_string())
}
_ => false,
})
Expand All @@ -63,7 +49,8 @@ impl Scope {
Ok(None)
} else if candidates.len() == 1 {
Ok(Some(Column {
name: candidates[0].1.name.clone(),
column_name: candidates[0].1.name.clone(),
table_name: candidates[0].1.prefix.clone().unwrap().table_name,
index: candidates[0].0,
}))
} else {
Expand All @@ -87,7 +74,13 @@ impl Scope {
}
false
})
.map(|(index, v)| ScalarExpr::Column(Column { name: v.name.clone(), index }))
.map(|(index, v)| {
ScalarExpr::Column(Column {
column_name: v.name.clone(),
table_name: v.prefix.clone().unwrap().table_name,
index,
})
})
}
}

Expand Down
Loading