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

Value refactoring to respect sqlx::types. #5

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
37 changes: 4 additions & 33 deletions .vim/coc-settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"codeLens.enable": true,
"diagnostic.enableMessage": "always",
"languageserver": {
"clangd": {
"rootPatterns": [
Expand All @@ -15,48 +17,17 @@
"objcpp"
],
"command": "/usr/local/opt/llvm/bin/clangd"
},
"rust": {
"command": "rust-analyzer",
"filetypes": [
"rust"
],
"rootPatterns": [
"Cargo.toml",
".git"
]
}
},
"clangd.path": "/usr/local/opt/llvm/bin/clangd",
"rust-analyzer.enable": false,
"rust-analyzer.enable": true,
"rust-analyzer.server.path": "/usr/local/bin/rust-analyzer",
"rust-analyzer.updates.prompt": true,
"rust-analyzer.updates.channel": "nightly",
"rust-analyzer.cargo.autoreload": true,
"rust-analyzer.cargo.features": [
"doc",
"mssql",
"mysql",
"sqlite",
"postgres",
"json",
"uuid",
"chrono",
"bigdecimal"
],
"rust-analyzer.cargo.allFeatures": true,
"rust-analyzer.checkOnSave.features": [
"doc",
"mssql",
"mysql",
"sqlite",
"postgres",
"json",
"uuid",
"chrono",
"bigdecimal"
],
"rust-analyzer.cargo.noDefaultFeatures": false,
"rust-analyzer.checkOnSave.allFeatures": true,
"rust-analyzer.checkOnSave.noDefaultFeatures": false,
"python.pythonPath": "python",
"python.formatting.provider": "black",
Expand Down
47 changes: 22 additions & 25 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,55 +10,52 @@ keywords = ["orm", "sqlx", "sqlite", "mysql", "mssql", "postgresql"]
license = "MIT OR Apache-2.0"
readme = "README.md"

# docs.rs-specific configuration
[package.metadata.docs.rs]
features = ["docs", "all"]
# document all features
all-features = true
# defines the configuration attribute `docsrs`
rustdoc-args = ["--cfg", "docsrs"]

[lib]
name = "xiayu"

[dependencies]
xiayu-derive = { version = "0.1.0-alpha0", path = "./derive" }

thiserror = "1.0"
tracing = "0.1"
hex = "0.4"
sqlx = { version = "0.5" }
either = { version = "1.6", optional = true }
serde_json = { version = "1.0", optional = true }
async-trait = "0.1"
base64 = { version = "0.13", optional = true }
num-bigint = { version = "0.4", optional = true }
derive_more = { version = "0.99", features = ["as_ref", "as_mut", "deref", "deref_mut"] }
either = { version = "1.6", optional = true }
hex = "0.4"
indoc = { version = "1.0", optional = true }
num = { version = "0.4.0", optional = true }
async-trait = "0.1.51"
num = { version = "0.4", optional = true }
num-bigint = { version = "0.4", optional = true }
thiserror = "1.0"
tracing = "0.1"
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }
sqlx = { version = "0.5" }

[dev-dependencies]
tokio = { version = "1.10", features = ["rt"] }
tokio = { version = "1.10", features = [ "rt", "macros" ] }
entities = { path = "./entity-examples", package = "xiayu-entity-examples" }
uuid_ = { version = "0.8", package = "uuid", features = [ "v4" ] }

[features]
default = [ "sqlite", "mysql" ]
docs = [ "sqlx/runtime-tokio-rustls" ]
default = [ "uuid", "json", "chrono", "decimal", "bigdecimal" ]
_docs = [ "sqlx/runtime-tokio-rustls", "sqlx/mysql", "sqlx/mssql", "sqlx/sqlite", "sqlx/postgres", "json", "uuid", "chrono", "decimal", "bigdecimal" ]
mssql = [ "uuid", "chrono", "either", "sqlx/mssql", "indoc" ]
mysql = [ "sqlx/mysql" ]
sqlite = [ "sqlx/sqlite" ]
postgres = [ "sqlx/postgres" ]
uuid = [ "sqlx/uuid" ]
json = [ "base64", "sqlx/json", "serde_json", "num/serde" ]
json = [ "base64", "sqlx/json", "serde", "serde_json", "num/serde" ]
chrono = [ "sqlx/chrono" ]
decimal = [ "sqlx/decimal" ]
bigdecimal = [ "num", "num-bigint", "sqlx/bigdecimal" ]

all = [
"mssql",
"mysql",
"sqlite",
"postgres",
"json",
"uuid",
"chrono",
"bigdecimal",
]
time = [ "sqlx/time" ]
ipnetwork = [ "sqlx/ipnetwork" ]

[workspace]
members = [
Expand Down
3 changes: 3 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
println!("cargo:rustc-cfg=docsrs");
}
4 changes: 3 additions & 1 deletion derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,9 +272,10 @@ pub fn derive_entity(input: TokenStream) -> TokenStream {
// let orig_generics = &entity_def.generics;
tokens.extend(quote! {
impl #ident {
#[allow(non_snake_case)]
const _table: #namespace::Table<'static> = #table_def;

#(pub const #names: #namespace::ColumnOptions<#types> = #column_options;) *
#(#[allow(non_snake_case)] pub const #names: #namespace::ColumnOptions<#types> = #column_options;) *
}

impl #namespace::Entity for #ident {
Expand Down Expand Up @@ -302,6 +303,7 @@ pub fn derive_entity(input: TokenStream) -> TokenStream {
// impl HasPrimaryKey if PrimaryKey exists.
let token = quote! {
impl #ident {
#[allow(non_snake_case)]
const _primary_key: <Self as #namespace::HasPrimaryKey>::PrimaryKey = #primary_key_column;
}

Expand Down
28 changes: 18 additions & 10 deletions entity-examples/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,39 @@
#![allow(dead_code)]

use xiayu::prelude::*;

#[derive(Entity)]
pub struct User {
id: i32,
pub id: i32,
}

#[derive(Entity)]
pub struct Post {
id: i32,
user_id: i32,
pub id: i32,
pub user_id: i32,
}

#[derive(Entity)]
pub struct Recipe {
name: String,
ingredients: String,
pub name: String,
pub ingredients: String,
}

#[derive(Entity)]
pub struct Cat {
master_id: i32,
ingredients: String,
pub master_id: i32,
pub ingredients: String,
}

#[derive(Entity)]
pub struct Dog {
slave_id: i32,
age: i32,
ingredients: String,
pub slave_id: i32,
pub age: i32,
pub ingredients: String,
}

#[derive(Debug, Entity)]
pub struct Bar {
pub id: i32,
pub uniq_val: i32,
}
20 changes: 2 additions & 18 deletions examples/basic.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,15 @@
#[macro_use]
extern crate xiayu_derive;

use std::marker::PhantomData;

use xiayu::prelude::*;
use xiayu::visitors::Visitor;
use xiayu_derive::*;

#[derive(Debug)]
pub struct Relation<T> {
_phantom: PhantomData<T>,
}

impl<T> Relation<T> {
fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}

#[derive(Debug, Entity)]
#[tablename = "entities"]
pub struct AnEntity {
#[column(primary_key, autoincrement, comment = "some comments")]
pub id: i32,
pub another_entity_id: Relation<AnotherEntity>,
pub another_entity_id: i32,
pub maybe_float: Option<f32>,
}

Expand All @@ -43,7 +27,7 @@ fn main() {

let entity = AnEntity {
id: 2,
another_entity_id: Relation::<AnotherEntity>::new(),
another_entity_id: 1,
maybe_float: None,
};
assert_eq!(entity.id, 2);
Expand Down
7 changes: 6 additions & 1 deletion src/ast/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,11 @@ impl<'a> Expression<'a> {

#[allow(dead_code)]
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub(crate) fn into_json_value(self) -> Option<serde_json::Value> {
match self.kind {
#[cfg(feature = "json")]
ExpressionKind::Parameterized(Value::Json(Json::JsonValue(json_val))) => json_val,
ExpressionKind::Parameterized(Value::Json(json_val)) => serde_json::to_value(json_val).ok(),
#[cfg(feature = "json")]
ExpressionKind::Value(expr) => expr.into_json_value(),
_ => None,
Expand All @@ -78,10 +79,12 @@ impl<'a> Expression<'a> {
}
}

/*
#[allow(dead_code)]
pub(crate) fn is_xml_value(&self) -> bool {
self.kind.is_xml_value()
}
*/

#[allow(dead_code)]
pub fn is_asterisk(&self) -> bool {
Expand Down Expand Up @@ -212,13 +215,15 @@ pub enum ExpressionKind<'a> {
}

impl<'a> ExpressionKind<'a> {
/*
pub(crate) fn is_xml_value(&self) -> bool {
match self {
Self::Parameterized(Value::Xml(_)) => true,
Self::Value(expr) => expr.is_xml_value(),
_ => false,
}
}
*/
}

/// A quick alias to create an asterisk to a table.
Expand Down
4 changes: 2 additions & 2 deletions src/ast/function/row_to_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::Function;
use crate::ast::Table;

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "docs", doc(cfg(feature = "postgres")))]
#[cfg_attr(docsrs, doc(cfg(feature = "postgres")))]
#[cfg(all(feature = "json", feature = "postgres"))]
/// A representation of the `ROW_TO_JSON` function in the database.
/// Only for `postgres`
Expand Down Expand Up @@ -39,7 +39,7 @@ pub struct RowToJson<'a> {
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "postgres")))]
#[cfg_attr(docsrs, doc(cfg(feature = "postgres")))]
#[cfg(all(feature = "json", feature = "postgres"))]
pub fn row_to_json<'a, T>(expr: T, pretty_print: bool) -> Function<'a>
where
Expand Down
2 changes: 1 addition & 1 deletion src/ast/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl<'a> Insert<'a> {
/// ```
#[cfg(any(feature = "postgres", feature = "mssql", feature = "sqlite"))]
#[cfg_attr(
feature = "docs",
docsrs,
doc(cfg(any(feature = "postgres", feature = "mssql", feature = "sqlite")))
)]
pub fn returning<K, I>(mut self, columns: I) -> Self
Expand Down
3 changes: 0 additions & 3 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,4 @@ pub use select::Select;
pub use table::*;
pub use union::Union;
pub use update::*;
#[cfg(feature = "json")]
pub use values::Json;
pub(crate) use values::Params;
pub use values::{IntoRaw, Raw, Value, Values};
15 changes: 9 additions & 6 deletions src/ast/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ impl<'a> Update<'a> {
/// Add another column value assignment to the query
///
/// ```rust
/// # use xiayu::{ast::*, visitors::{Visitor, Sqlite}};
/// # use xiayu::{prelude::*, visitors::{Visitor, Sqlite}};
/// # use entities::User;
/// # fn main() -> Result<(), xiayu::error::Error> {
/// let query = Update::table("users").set("foo", 10).set("bar", false);
/// let query = Update::table(User::table()).set(User::foo, 10).set(User::bar, false);
/// let (sql, params) = Sqlite::build(query)?;
///
/// assert_eq!("UPDATE `users` SET `foo` = ?, `bar` = ?", sql);
Expand Down Expand Up @@ -64,9 +65,10 @@ impl<'a> Update<'a> {
/// [Comparable](trait.Comparable.html#required-methods) for more examples.
///
/// ```rust
/// # use xiayu::{ast::*, visitors::{Visitor, Sqlite}};
/// # use xiayu::{prelude::*, visitors::{Visitor, Sqlite}};
/// # use entities::User;
/// # fn main() -> Result<(), xiayu::error::Error> {
/// let query = Update::table("users").set("foo", 1).so_that("bar".equals(false));
/// let query = Update::table(User::table()).set(User::foo, 1).so_that(User::bar.equals(false));
/// let (sql, params) = Sqlite::build(query)?;
///
/// assert_eq!("UPDATE `users` SET `foo` = ? WHERE `bar` = ?", sql);
Expand All @@ -86,9 +88,10 @@ impl<'a> Update<'a> {
///
/// ```rust
/// # use xiayu::{ast::*, visitors::{Visitor, Sqlite}};
/// # use entities::Bar;
/// # fn main() -> Result<(), xiayu::error::Error> {
/// let select = Select::from_table("bars").column("id").so_that("uniq_val".equals(3));
/// let query = Update::table("users").set("foo", 1).so_that("bar".equals(select));
/// let select = Select::from_table(Bar::table()).column(Bar::id).so_that(Bar::uniq_val.equals(3));
/// let query = Update::table(User::table()).set(User::foo, 1).so_that(User::bar.equals(select));
/// let (sql, params) = Sqlite::build(query)?;
///
/// assert_eq!(
Expand Down
Loading