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

added PostgreSQL Interval value variant #709

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ time = { version = "0.3", default-features = false, optional = true, features =
ipnetwork = { version = "0.20", default-features = false, optional = true }
mac_address = { version = "1.1", default-features = false, optional = true }
ordered-float = { version = "3.4", default-features = false, optional = true }
sqlx = { git = "https://github.com/yasamoka/sqlx", branch = "pg-interval-hash", default-features = false, optional = true }
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was previously no dependency on SQLx. However, PgInterval is provided by SQLx. Is this fine?


[dev-dependencies]
sea-query = { path = ".", features = ["tests-cfg"] }
Expand All @@ -60,7 +61,7 @@ derive = ["sea-query-derive"]
attr = ["sea-query-attr"]
hashable-value = ["derivative", "ordered-float"]
postgres-array = []
postgres-interval = ["proc-macro2", "quote"]
postgres-interval = ["proc-macro2", "quote", "sqlx/postgres"]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the preferred way of adding this feature dependency?

thread-safe = []
with-chrono = ["chrono"]
with-json = ["serde_json"]
Expand Down
3 changes: 2 additions & 1 deletion sea-query-binder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ rust-version = "1.60"

[dependencies]
sea-query = { version = "0.31", path = "..", default-features = false, features = ["thread-safe"] }
sqlx = { version = "0.7", default-features = false, optional = true }
sqlx = { git = "https://github.com/yasamoka/sqlx", branch = "pg-interval-hash", default-features = false, optional = true }
serde_json = { version = "1", default-features = false, optional = true, features = ["std"] }
chrono = { version = "0.4", default-features = false, optional = true, features = ["clock"] }
rust_decimal = { version = "1", default-features = false, optional = true }
Expand All @@ -42,6 +42,7 @@ with-time = ["sqlx?/time", "sea-query/with-time", "time"]
with-ipnetwork = ["sqlx?/ipnetwork", "sea-query/with-ipnetwork", "ipnetwork"]
with-mac_address = ["sqlx?/mac_address", "sea-query/with-mac_address", "mac_address"]
postgres-array = ["sea-query/postgres-array"]
postgres-interval = ["sqlx-postgres", "sqlx/chrono"]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the preferred way of adding this feature dependency?

runtime-async-std-native-tls = ["sqlx?/runtime-async-std-native-tls"]
runtime-async-std-rustls = ["sqlx?/runtime-async-std-rustls", ]
runtime-actix-native-tls = ["sqlx?/runtime-tokio-native-tls"]
Expand Down
2 changes: 2 additions & 0 deletions sea-query-binder/src/sqlx_mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ impl sqlx::IntoArguments<'_, sqlx::mysql::MySql> for SqlxValues {
Value::ChronoDateTimeWithTimeZone(t) => {
args.add(Value::ChronoDateTimeWithTimeZone(t).chrono_as_naive_utc_in_string());
}
#[cfg(feature = "postgres-interval")]
Value::Interval(_) => {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a better of doing this other than splitting the query builder or throwing an error?

#[cfg(feature = "with-time")]
Value::TimeDate(t) => {
args.add(t.as_deref());
Expand Down
12 changes: 12 additions & 0 deletions sea-query-binder/src/sqlx_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use mac_address::MacAddress;
use rust_decimal::Decimal;
#[cfg(feature = "with-json")]
use serde_json::Value as Json;
#[cfg(feature = "postgres-interval")]
use sqlx::postgres::types::PgInterval;
#[cfg(feature = "with-uuid")]
use uuid::Uuid;

Expand Down Expand Up @@ -89,6 +91,10 @@ impl sqlx::IntoArguments<'_, sqlx::postgres::Postgres> for SqlxValues {
Value::ChronoDateTimeWithTimeZone(t) => {
args.add(t.as_deref());
}
#[cfg(feature = "postgres-interval")]
Value::Interval(t) => {
args.add(t.as_deref());
}
#[cfg(feature = "with-time")]
Value::TimeDate(t) => {
args.add(t.as_deref());
Expand Down Expand Up @@ -252,6 +258,12 @@ impl sqlx::IntoArguments<'_, sqlx::postgres::Postgres> for SqlxValues {
);
args.add(value);
}
#[cfg(feature = "postgres-interval")]
ArrayType::Interval => {
let value: Option<Vec<PgInterval>> = Value::Array(ty, v)
.expect("This Value::Array should consist of Value::Interval");
args.add(value);
}
#[cfg(feature = "with-time")]
ArrayType::TimeDate => {
let value: Option<Vec<time::Date>> = Value::Array(ty, v)
Expand Down
2 changes: 2 additions & 0 deletions sea-query-binder/src/sqlx_sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ impl<'q> sqlx::IntoArguments<'q, sqlx::sqlite::Sqlite> for SqlxValues {
Value::ChronoDateTimeWithTimeZone(t) => {
args.add(t.map(|t| *t));
}
#[cfg(feature = "postgres-interval")]
Value::Interval(_) => {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a better of doing this other than splitting the query builder or throwing an error?

#[cfg(feature = "with-time")]
Value::TimeDate(t) => {
args.add(t.map(|t| *t));
Expand Down
30 changes: 30 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,8 @@ pub trait QueryBuilder:
Value::ChronoDateTimeLocal(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeWithTimeZone(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "postgres-interval")]
Value::Interval(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Value::TimeDate(None) => write!(s, "NULL").unwrap(),
#[cfg(feature = "with-time")]
Expand Down Expand Up @@ -1060,6 +1062,34 @@ pub trait QueryBuilder:
Value::ChronoDateTimeWithTimeZone(Some(v)) => {
write!(s, "'{}'", v.format("%Y-%m-%d %H:%M:%S %:z")).unwrap()
}
#[cfg(feature = "postgres-interval")]
Value::Interval(Some(v)) => {
let mut space = false;

write!(s, "'").unwrap();

if v.months > 0 {
write!(s, "{} MONTHS", v.days).unwrap();
space = true;
}

if v.days > 0 {
if space {
write!(s, " ").unwrap();
}
write!(s, "{} DAYS", v.days).unwrap();
space = true;
}

if v.microseconds > 0 {
if space {
write!(s, " ").unwrap();
}
write!(s, "{} MICROSECONDS", v.microseconds).unwrap();
}

write!(s, "'::interval").unwrap();
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall I make the units abbreviated or is this better for clarity when inspecting the built SQL statement?

#[cfg(feature = "with-time")]
Value::TimeDate(Some(v)) => {
write!(s, "'{}'", v.format(time_format::FORMAT_DATE).unwrap()).unwrap()
Expand Down
56 changes: 56 additions & 0 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ use std::net::IpAddr;
use mac_address::MacAddress;

use crate::{BlobSize, ColumnType, CommonSqlQueryBuilder, QueryBuilder};
#[cfg(feature = "postgres-interval")]
use sqlx::postgres::types::PgInterval;

/// [`Value`] types variant for Postgres array
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
Expand Down Expand Up @@ -79,6 +81,9 @@ pub enum ArrayType {
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
ChronoDateTimeWithTimeZone,

#[cfg(feature = "postgres-interval")]
Interval,

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
TimeDate,
Expand Down Expand Up @@ -202,6 +207,9 @@ pub enum Value {
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
ChronoDateTimeWithTimeZone(Option<Box<DateTime<FixedOffset>>>),

#[cfg(feature = "postgres-interval")]
Interval(Option<Box<PgInterval>>),

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
TimeDate(Option<Box<time::Date>>),
Expand Down Expand Up @@ -540,6 +548,13 @@ mod with_chrono {
}
}

#[cfg(feature = "postgres-interval")]
impl From<PgInterval> for Value {
fn from(v: PgInterval) -> Self {
Value::Interval(Some(Box::new(v)))
}
}

impl Nullable for DateTime<Utc> {
fn null() -> Value {
Value::ChronoDateTimeUtc(None)
Expand Down Expand Up @@ -594,6 +609,28 @@ mod with_chrono {
}
}

#[cfg(feature = "postgres-interval")]
impl ValueType for PgInterval {
fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
match v {
Value::Interval(Some(x)) => Ok(*x),
_ => Err(ValueTypeErr),
}
}

fn type_name() -> String {
stringify!(PgInterval).to_owned()
}

fn array_type() -> ArrayType {
ArrayType::Interval
}

fn column_type() -> ColumnType {
ColumnType::Interval(None, None)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do I pass to ColumnType::Interval, if anything?

}
}

impl Nullable for DateTime<FixedOffset> {
fn null() -> Value {
Value::ChronoDateTimeWithTimeZone(None)
Expand Down Expand Up @@ -805,6 +842,9 @@ pub mod with_array {
#[cfg(feature = "with-chrono")]
impl<Tz> NotU8 for DateTime<Tz> where Tz: chrono::TimeZone {}

#[cfg(feature = "postgres-interval")]
impl NotU8 for PgInterval {}

#[cfg(feature = "with-time")]
impl NotU8 for time::Date {}

Expand Down Expand Up @@ -1161,6 +1201,20 @@ impl Value {
}
}

#[cfg(feature = "postgres-interval")]
impl Value {
pub fn is_interval(&self) -> bool {
matches!(self, Self::Interval(_))
}

pub fn as_ref_interval(&self) -> Option<&PgInterval> {
match self {
Self::Interval(v) => box_to_opt_ref!(v),
_ => panic!("not Value::Interval"),
}
}
}

#[cfg(feature = "with-ipnetwork")]
impl Value {
pub fn is_ipnetwork(&self) -> bool {
Expand Down Expand Up @@ -1423,6 +1477,8 @@ pub fn sea_value_to_json_value(value: &Value) -> Json {
Value::ChronoDateTimeUtc(_) => CommonSqlQueryBuilder.value_to_string(value).into(),
#[cfg(feature = "with-chrono")]
Value::ChronoDateTimeLocal(_) => CommonSqlQueryBuilder.value_to_string(value).into(),
#[cfg(feature = "postgres-interval")]
Value::Interval(_) => CommonSqlQueryBuilder.value_to_string(value).into(),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this correct?

#[cfg(feature = "with-time")]
Value::TimeDate(_) => CommonSqlQueryBuilder.value_to_string(value).into(),
#[cfg(feature = "with-time")]
Expand Down
Loading