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

feat: Add dynamic query builder #1120

Closed
Closed
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
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"sqlx-test",
"sqlx-cli",
"sqlx-bench",
"sqlx-query-builder",
"examples/mysql/todos",
"examples/postgres/json",
"examples/postgres/listen",
Expand Down
47 changes: 47 additions & 0 deletions sqlx-query-builder/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
[package]
name = "sqlx-query-builder"
version = "0.1.0"
authors = ["Anit Nilay <anit.nilay20@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
sqlx-core = { version = "0.5.1", default-features = false, path = "../sqlx-core" }
thiserror = "1.0"

[features]
default = [ "runtime-async-std-native-tls" ]

# runtimes
runtime-actix-native-tls = [ "sqlx-core/runtime-actix-native-tls", "_rt-actix" ]
runtime-async-std-native-tls = [ "sqlx-core/runtime-async-std-native-tls", "_rt-async-std" ]
runtime-tokio-native-tls = [ "sqlx-core/runtime-tokio-native-tls", "_rt-tokio" ]

runtime-actix-rustls = [ "sqlx-core/runtime-actix-rustls", "_rt-actix" ]
runtime-async-std-rustls = [ "sqlx-core/runtime-async-std-rustls", "_rt-async-std" ]
runtime-tokio-rustls = [ "sqlx-core/runtime-tokio-rustls", "_rt-tokio" ]

# for conditional compilation
_rt-actix = []
_rt-async-std = []
_rt-tokio = []

# offline building support
# offline = ["sqlx-core/offline", "hex", "once_cell", "serde", "serde_json", "sha2"]

# database
mysql = [ "sqlx-core/mysql" ]
postgres = [ "sqlx-core/postgres" ]
sqlite = [ "sqlx-core/sqlite" ]
mssql = [ "sqlx-core/mssql" ]

# type
# bigdecimal = [ "sqlx-core/bigdecimal" ]
# decimal = [ "sqlx-core/decimal" ]
# chrono = [ "sqlx-core/chrono" ]
# time = [ "sqlx-core/time" ]
# ipnetwork = [ "sqlx-core/ipnetwork" ]
# uuid = [ "sqlx-core/uuid" ]
# bit-vec = [ "sqlx-core/bit-vec" ]
# json = [ "sqlx-core/json" ]
9 changes: 9 additions & 0 deletions sqlx-query-builder/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
#[error("Error in query: {}", _0)]
InvalidQuery(String)
}

pub type Result<T> = std::result::Result<T, Error>;
46 changes: 46 additions & 0 deletions sqlx-query-builder/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use select::Select;
use table::Table;

mod error;
mod mysql;
mod query;
mod select;
mod table;

pub trait QueryBuilder {
const SYSTEM_IDENTIFIER_START: &'static str;
const SYSTEM_IDENTIFIER_END: &'static str;

fn build<T>(query: T) -> error::Result<(String, Vec<String>)>
where
T: Into<query::QueryType>;

fn build_select(select: Select) -> error::Result<(String, Vec<String>)>;
fn build_table(table: Table) -> error::Result<String>;
}

#[cfg(test)]
mod tests {
use crate::{select::Select, QueryBuilder};
use sqlx_core::mysql::MySql;

#[test]
fn simple_select_statement() {
let (query, _) =
MySql::build(Select::new().and_select("*".into()).and_from("sqlx")).unwrap();

assert_eq!(query, "SELECT * FROM sqlx;".to_string());
}
#[test]
fn select_with_table_alias() {
let (query, _) = MySql::build(Select::new().and_select("*".into()).and_from(("sqlx", "s", "sqlx_db"))).unwrap();
assert_eq!(query, "SELECT * FROM sqlx_db.sqlx as s;");
}

#[test]
fn select_statement_with_column_names() {
let (query, _) = MySql::build(Select::new().and_select("name".into()).from("sqlx")).unwrap();

assert_eq!(query, "SELECT name FROM sqlx;".to_string());
}
}
58 changes: 58 additions & 0 deletions sqlx-query-builder/src/mysql.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::fmt::Write;

use sqlx_core::mysql::MySql;
use crate::{QueryBuilder, error, query, select::Select, table::{Table, TableType}};

impl QueryBuilder for MySql {
const SYSTEM_IDENTIFIER_START: &'static str = "`";
const SYSTEM_IDENTIFIER_END: &'static str = "`";

fn build<T>(query: T) -> error::Result<(String, Vec<String>)>
where
T: Into<query::QueryType>,
{
match query.into() {
query::QueryType::Select(select) => Self::build_select(select),
_ => Ok(("*".into(), vec![])),
}
}

fn build_select(select: Select) -> error::Result<(String, Vec<String>)> {
let mut query = String::new();
query.push_str("SELECT ");
query.push_str(&select.columns.join(", "));
query.push_str(" FROM ");
query.push_str(
&select
.tables
.into_iter()
.map(|f| Self::build_table(f).unwrap())
.collect::<Vec<String>>()
.join(", "),
);
query.push_str(";");
Ok((query, vec![]))
}

fn build_table(table: Table) -> error::Result<String> {
let mut table_sql = String::new();

if let Some(database) = table.database {
table_sql.write_str(&database).unwrap();
table_sql.write_str(".").unwrap();
}

match table.table_type {
TableType::Table(s) => table_sql.write_str(&s).unwrap(),
};

if let Some(alias) = table.alias {
table_sql.write_str(" as ").unwrap();
table_sql.write_str(&alias).unwrap();
}

Ok(table_sql)
}


}
8 changes: 8 additions & 0 deletions sqlx-query-builder/src/query.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use crate::select::Select;

pub enum QueryType {
Select(Select),
Update,
Alter,
Delete,
}
59 changes: 59 additions & 0 deletions sqlx-query-builder/src/select.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use crate::{query::QueryType, table::Table};

#[derive(Clone, Default)]
pub struct Select {
pub(crate) tables: Vec<Table>,
pub(crate) columns: Vec<String>,
pub(crate) conditions: Option<String>,
pub(crate) ordering: Option<String>,
pub(crate) grouping: Option<String>,
pub(crate) having: Option<String>,
pub(crate) limit: Option<String>,
pub(crate) offset: Option<String>,
pub(crate) joins: Option<String>,
pub(crate) ctes: Option<String>,
pub(crate) distinct: bool,
}

impl Select {
pub fn new() -> Self {
Self { ..Self::default() }
}

pub fn select(mut self, colums: Vec<String>) -> Self {
self.columns = colums;
self
}

pub fn and_select(mut self, column: String) -> Self {
self.columns.push(column);
self
}

pub fn from<T>(mut self, table: T) -> Self
where
T: Into<Table>,
{
self.tables = vec![table.into()];
self
}

pub fn and_from<T>(mut self, table: T) -> Self
where
T: Into<Table>,
{
self.tables.push(table.into());
self
}

pub fn condition(mut self, condition: Option<String>) -> Self {
self.conditions = condition;
self
}
}

impl Into<QueryType> for Select {
fn into(self) -> QueryType {
QueryType::Select(self)
}
}
55 changes: 55 additions & 0 deletions sqlx-query-builder/src/table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#[derive(Clone)]
pub enum TableType {
Table(String),
}

impl Default for TableType {
fn default() -> Self {
TableType::Table(String::default())
}
}

#[derive(Clone, Default)]
pub struct Table {
pub(crate) table_type: TableType,
pub(crate) alias: Option<String>,
pub(crate) database: Option<String>,
}

impl From<String> for Table {
fn from(s: String) -> Table {
Table {
table_type: TableType::Table(s),
..Table::default()
}
}
}

impl<'a> From<&'a str> for Table {
fn from(s: &'a str) -> Table {
Table {
table_type: TableType::Table(s.into()),
..Table::default()
}
}
}

impl<'a> From<(&'a str, &'a str)> for Table {
fn from(s: (&'a str, &'a str)) -> Table {
Table {
table_type: TableType::Table(s.0.into()),
alias: Some(s.1.into()),
..Table::default()
}
}
}

impl<'a> From<(&'a str, &'a str, &'a str)> for Table {
fn from(s: (&'a str, &'a str, &'a str)) -> Table {
Table {
table_type: TableType::Table(s.0.into()),
alias: Some(s.1.into()),
database: Some(s.2.into()),
}
}
}