Skip to content

Commit

Permalink
issues-336 Init new Value type
Browse files Browse the repository at this point in the history
  • Loading branch information
ikrivosheev committed Aug 11, 2022
1 parent 6a30dbc commit fb44aa9
Show file tree
Hide file tree
Showing 16 changed files with 302 additions and 1,831 deletions.
1 change: 1 addition & 0 deletions src/backend/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Translating the SQL AST into engine-specific SQL statements.

use crate::*;
use std::fmt::Write;

#[cfg(feature = "backend-mysql")]
#[cfg_attr(docsrs, doc(cfg(feature = "backend-mysql")))]
Expand Down
2 changes: 1 addition & 1 deletion src/backend/mysql/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl TableBuilder for MysqlQueryBuilder {
match column_spec {
ColumnSpec::Null => write!(sql, "NULL"),
ColumnSpec::NotNull => write!(sql, "NOT NULL"),
ColumnSpec::Default(value) => write!(sql, "DEFAULT {}", self.value_to_string(value)),
ColumnSpec::Default(value) => write!(sql, "DEFAULT {}", value.to_sql_string()),
ColumnSpec::AutoIncrement => write!(sql, "AUTO_INCREMENT"),
ColumnSpec::UniqueKey => write!(sql, "UNIQUE"),
ColumnSpec::PrimaryKey => write!(sql, "PRIMARY KEY"),
Expand Down
4 changes: 1 addition & 3 deletions src/backend/postgres/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,7 @@ impl TableBuilder for PostgresQueryBuilder {
match column_spec {
ColumnSpec::Null => write!(sql, "NULL"),
ColumnSpec::NotNull => write!(sql, "NOT NULL"),
ColumnSpec::Default(value) => {
write!(sql, "DEFAULT {}", self.value_to_string(value))
}
ColumnSpec::Default(value) => write!(sql, "DEFAULT {}", value.to_sql_string()),
ColumnSpec::AutoIncrement => write!(sql, ""),
ColumnSpec::UniqueKey => write!(sql, "UNIQUE"),
ColumnSpec::PrimaryKey => write!(sql, "PRIMARY KEY"),
Expand Down
148 changes: 4 additions & 144 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -958,8 +958,7 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {
write!(sql, " WHEN ").unwrap();
self.prepare_simple_expr(&order_expr.expr, sql, collector);
write!(sql, "=").unwrap();
let value = self.value_to_string(value);
write!(sql, "{}", value).unwrap();
write!(sql, "{}", value.to_sql_string()).unwrap();
write!(sql, " THEN {} ", i).unwrap();
i += 1;
}
Expand All @@ -975,8 +974,7 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {

/// Write [`Value`] inline.
fn prepare_constant(&self, value: &Value, sql: &mut SqlWriter) {
let string = self.value_to_string(value);
write!(sql, "{}", string).unwrap();
write!(sql, "{}", value.to_sql_string()).unwrap();
}

/// Translate a `&[ValueTuple]` into a VALUES list.
Expand Down Expand Up @@ -1048,144 +1046,6 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {
}
}

/// Convert a SQL value into syntax-specific string
fn value_to_string(&self, v: &Value) -> String {
let mut s = String::new();
match v {
Value::Bool(None)
| Value::TinyInt(None)
| Value::SmallInt(None)
| Value::Int(None)
| Value::BigInt(None)
| Value::TinyUnsigned(None)
| Value::SmallUnsigned(None)
| Value::Unsigned(None)
| Value::BigUnsigned(None)
| Value::Float(None)
| Value::Double(None)
| Value::String(None)
| Value::Char(None)
| Value::Bytes(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-json")]
Value::Json(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDate(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoTime(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTime(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeUtc(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeLocal(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeWithTimeZone(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Value::TimeDate(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Value::TimeTime(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Value::TimeDateTime(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Value::TimeDateTimeWithTimeZone(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-rust_decimal")]
Value::Decimal(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-bigdecimal")]
Value::BigDecimal(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-uuid")]
Value::Uuid(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-ipnetwork")]
Value::IpNetwork(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-mac_address")]
Value::MacAddress(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "postgres-array")]
Value::Array(None) => write!(s, "NULL").unwrap(),
Value::Bool(Some(b)) => write!(s, "{}", if *b { "TRUE" } else { "FALSE" }).unwrap(),
Value::TinyInt(Some(v)) => write!(s, "{}", v).unwrap(),
Value::SmallInt(Some(v)) => write!(s, "{}", v).unwrap(),
Value::Int(Some(v)) => write!(s, "{}", v).unwrap(),
Value::BigInt(Some(v)) => write!(s, "{}", v).unwrap(),
Value::TinyUnsigned(Some(v)) => write!(s, "{}", v).unwrap(),
Value::SmallUnsigned(Some(v)) => write!(s, "{}", v).unwrap(),
Value::Unsigned(Some(v)) => write!(s, "{}", v).unwrap(),
Value::BigUnsigned(Some(v)) => write!(s, "{}", v).unwrap(),
Value::Float(Some(v)) => write!(s, "{}", v).unwrap(),
Value::Double(Some(v)) => write!(s, "{}", v).unwrap(),
Value::String(Some(v)) => self.write_string_quoted(v, &mut s),
Value::Char(Some(v)) => {
self.write_string_quoted(std::str::from_utf8(&[*v as u8]).unwrap(), &mut s)
}
Value::Bytes(Some(v)) => write!(
s,
"x'{}'",
v.iter().map(|b| format!("{:02X}", b)).collect::<String>()
)
.unwrap(),
#[cfg(feature = "with-json")]
Value::Json(Some(v)) => self.write_string_quoted(&v.to_string(), &mut s),
#[cfg(feature = "with-chrono")]
Value::ChronoDate(Some(v)) => write!(s, "'{}'", v.format("%Y-%m-%d")).unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoTime(Some(v)) => write!(s, "'{}'", v.format("%H:%M:%S")).unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTime(Some(v)) => {
write!(s, "'{}'", v.format("%Y-%m-%d %H:%M:%S")).unwrap()
}
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeUtc(Some(v)) => {
write!(s, "'{}'", v.format("%Y-%m-%d %H:%M:%S %:z")).unwrap()
}
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeLocal(Some(v)) => {
write!(s, "'{}'", v.format("%Y-%m-%d %H:%M:%S %:z")).unwrap()
}
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeWithTimeZone(Some(v)) => {
write!(s, "'{}'", v.format("%Y-%m-%d %H:%M:%S %:z")).unwrap()
}
#[cfg(feature = "with-time")]
Value::TimeDate(Some(v)) => {
write!(s, "'{}'", v.format(time_format::FORMAT_DATE).unwrap()).unwrap()
}
#[cfg(feature = "with-time")]
Value::TimeTime(Some(v)) => {
write!(s, "'{}'", v.format(time_format::FORMAT_TIME).unwrap()).unwrap()
}
#[cfg(feature = "with-time")]
Value::TimeDateTime(Some(v)) => {
write!(s, "'{}'", v.format(time_format::FORMAT_DATETIME).unwrap()).unwrap()
}
#[cfg(feature = "with-time")]
Value::TimeDateTimeWithTimeZone(Some(v)) => write!(
s,
"'{}'",
v.format(time_format::FORMAT_DATETIME_TZ).unwrap()
)
.unwrap(),
#[cfg(feature = "with-rust_decimal")]
Value::Decimal(Some(v)) => write!(s, "{}", v).unwrap(),
#[cfg(feature = "with-bigdecimal")]
Value::BigDecimal(Some(v)) => write!(s, "{}", v).unwrap(),
#[cfg(feature = "with-uuid")]
Value::Uuid(Some(v)) => write!(s, "'{}'", v).unwrap(),
#[cfg(feature = "postgres-array")]
Value::Array(Some(v)) => write!(
s,
"'{{{}}}'",
v.iter()
.map(|element| self.value_to_string(element))
.collect::<Vec<String>>()
.join(",")
)
.unwrap(),
#[cfg(feature = "with-ipnetwork")]
Value::IpNetwork(Some(v)) => write!(s, "'{}'", v).unwrap(),
#[cfg(feature = "with-mac_address")]
Value::MacAddress(Some(v)) => write!(s, "'{}'", v).unwrap(),
};
s
}

#[doc(hidden)]
/// Write ON CONFLICT expression
fn prepare_on_conflict(
Expand Down Expand Up @@ -1414,12 +1274,12 @@ pub trait QueryBuilder: QuotedBuilder + EscapeBuilder + TableRefBuilder {
match *frame {
Frame::UnboundedPreceding => write!(sql, " UNBOUNDED PRECEDING ").unwrap(),
Frame::Preceding(v) => {
self.prepare_value(&Some(v).into(), sql, collector);
self.prepare_value(&v.into(), sql, collector);
write!(sql, " PRECEDING ").unwrap();
}
Frame::CurrentRow => write!(sql, " CURRENT ROW ").unwrap(),
Frame::Following(v) => {
self.prepare_value(&Some(v).into(), sql, collector);
self.prepare_value(&v.into(), sql, collector);
write!(sql, " FOLLOWING ").unwrap();
}
Frame::UnboundedFollowing => write!(sql, " UNBOUNDED FOLLOWING ").unwrap(),
Expand Down
2 changes: 1 addition & 1 deletion src/backend/sqlite/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl TableBuilder for SqliteQueryBuilder {
match column_spec {
ColumnSpec::Null => write!(sql, "NULL"),
ColumnSpec::NotNull => write!(sql, "NOT NULL"),
ColumnSpec::Default(value) => write!(sql, "DEFAULT {}", self.value_to_string(value)),
ColumnSpec::Default(value) => write!(sql, "DEFAULT {}", value.to_sql_string()),
ColumnSpec::AutoIncrement => write!(sql, "AUTOINCREMENT"),
ColumnSpec::UniqueKey => write!(sql, "UNIQUE"),
ColumnSpec::PrimaryKey => write!(sql, "PRIMARY KEY"),
Expand Down
4 changes: 2 additions & 2 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,14 +1159,14 @@ impl Expr {
}

fn like_like(self, op: BinOper, like: LikeExpr) -> SimpleExpr {
let value = SimpleExpr::Value(Value::String(Some(Box::new(like.pattern))));
let value = SimpleExpr::Value(like.pattern.into());
self.bin_oper(
op,
match like.escape {
Some(escape) => SimpleExpr::Binary(
Box::new(value),
BinOper::Escape,
Box::new(SimpleExpr::Constant(Value::Char(Some(escape)))),
Box::new(SimpleExpr::Constant(escape.into())),
),
None => value,
},
Expand Down
51 changes: 24 additions & 27 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,30 @@
html_logo_url = "https://raw.githubusercontent.com/SeaQL/sea-query/master/docs/SeaQL icon dark.png"
)]

pub use backend::*;
pub use driver::*;
// pub use error::*;
pub use expr::*;
//pub use extension::*;
pub use foreign_key::*;
pub use func::*;
pub use index::*;
pub use prepare::*;
pub use query::*;
pub use schema::*;
#[cfg(feature = "attr")]
pub use sea_query_attr::enum_def;
#[cfg(feature = "derive")]
pub use sea_query_derive::Iden;
#[cfg(feature = "sea-query-driver")]
pub use sea_query_driver::*;
pub use table::*;
//pub use shim::*;
//pub use tests_cfg::*;
pub use token::*;
pub use types::*;
pub use value::*;

pub mod backend;
pub mod driver;
pub mod error;
Expand All @@ -763,30 +787,3 @@ pub mod tests_cfg;
pub mod token;
pub mod types;
pub mod value;

pub use backend::*;
pub use driver::*;
//pub use extension::*;
pub use foreign_key::*;
pub use index::*;
pub use query::*;
pub use table::*;
// pub use error::*;
pub use expr::*;
pub use func::*;
pub use prepare::*;
pub use schema::*;
//pub use shim::*;
//pub use tests_cfg::*;
pub use token::*;
pub use types::*;
pub use value::*;

#[cfg(feature = "derive")]
pub use sea_query_derive::Iden;

#[cfg(feature = "attr")]
pub use sea_query_attr::enum_def;

#[cfg(feature = "sea-query-driver")]
pub use sea_query_driver::*;
14 changes: 7 additions & 7 deletions src/prepare.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Helper for preparing SQL statements.

use crate::*;
pub use std::fmt::Write;
use crate::{QueryBuilder, Token, Tokenizer, Value};
pub use std::fmt::{self, Write};

#[derive(Debug, Default)]
pub struct SqlWriter {
Expand All @@ -24,7 +24,7 @@ where
match token {
Token::Punctuation(mark) => {
if (mark.as_ref(), false) == query_builder.placeholder() {
output.push(query_builder.value_to_string(&params[counter]));
output.push(params[counter].to_sql_string());
counter += 1;
i += 1;
continue;
Expand All @@ -33,7 +33,7 @@ where
{
if let Token::Unquoted(next) = &tokens[i + 1] {
if let Ok(num) = next.parse::<usize>() {
output.push(query_builder.value_to_string(&params[num - 1]));
output.push(params[num - 1].to_sql_string());
i += 2;
continue;
}
Expand Down Expand Up @@ -79,8 +79,8 @@ impl SqlWriter {
}
}

impl std::fmt::Write for SqlWriter {
fn write_str(&mut self, s: &str) -> std::result::Result<(), std::fmt::Error> {
impl Write for SqlWriter {
fn write_str(&mut self, s: &str) -> fmt::Result {
write!(
self.string,
"{}",
Expand All @@ -96,7 +96,7 @@ impl std::fmt::Write for SqlWriter {
#[cfg(test)]
#[cfg(feature = "backend-mysql")]
mod tests {
use super::*;
use crate::*;

#[test]
fn inject_parameters_1() {
Expand Down
2 changes: 1 addition & 1 deletion src/query/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl DeleteStatement {

/// Limit number of updated rows.
pub fn limit(&mut self, limit: u64) -> &mut Self {
self.limit = Some(Value::BigUnsigned(Some(limit)));
self.limit = Some(limit.into());
self
}

Expand Down
4 changes: 2 additions & 2 deletions src/query/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1907,7 +1907,7 @@ impl SelectStatement {
/// );
/// ```
pub fn limit(&mut self, limit: u64) -> &mut Self {
self.limit = Some(Value::BigUnsigned(Some(limit)));
self.limit = Some(limit.into());
self
}

Expand Down Expand Up @@ -1945,7 +1945,7 @@ impl SelectStatement {
/// );
/// ```
pub fn offset(&mut self, offset: u64) -> &mut Self {
self.offset = Some(Value::BigUnsigned(Some(offset)));
self.offset = Some(offset.into());
self
}

Expand Down
2 changes: 1 addition & 1 deletion src/query/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ impl UpdateStatement {

/// Limit number of updated rows.
pub fn limit(&mut self, limit: u64) -> &mut Self {
self.limit = Some(Value::BigUnsigned(Some(limit)));
self.limit = Some(limit.into());
self
}

Expand Down
2 changes: 1 addition & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ pub enum JoinOn {
}

/// Ordering options
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone)]
pub enum Order {
Asc,
Desc,
Expand Down
Loading

0 comments on commit fb44aa9

Please sign in to comment.