Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
franklx committed Nov 13, 2023
2 parents 22d0825 + 0c91408 commit 2a8bb34
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 81 deletions.
118 changes: 59 additions & 59 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion attr/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ormlite-attr"
version = "0.17.1"
version = "0.17.3"
edition = "2021"
description = "See `ormlite`."
authors = ["Kurt Wolf <kurtwolfbuilds@gmail.com>"]
Expand Down
21 changes: 13 additions & 8 deletions attr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ mod ext;
mod syndecode;

use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::{env, fs};
use std::path::{Path, PathBuf};
use anyhow::Context;
use syn::{DeriveInput, Item};
use ignore::Walk;
Expand Down Expand Up @@ -58,19 +58,20 @@ impl Intermediate {
Item::Struct(s) => {
let attrs = Attributes2::from(s.attrs.as_slice());
if attrs.has_derive("Model") {
tracing::debug!(model=s.ident.to_string(), "Found");
tracing::debug!(model=%s.ident.to_string(), "Found");
model_structs.push((s, attrs));
} else if attrs.has_derive("Type") {
tracing::debug!(r#type=s.ident.to_string(), "Found");
tracing::debug!(r#type=%s.ident.to_string(), "Found");
type_structs.push((s, attrs));
} else if attrs.has_derive("ManualType") {
tracing::debug!(r#type=s.ident.to_string(), "Found");
tracing::debug!(r#type=%s.ident.to_string(), "Found");
type_structs.push((s, attrs));
}
}
Item::Enum(e) => {
let attrs = Attributes2::from(e.attrs.as_slice());
if attrs.has_derive("Type") || attrs.has_derive("ManualType") {
tracing::debug!(r#type=%e.ident.to_string(), "Found");
type_enums.push((e, attrs));
}
}
Expand All @@ -86,12 +87,16 @@ impl Intermediate {
}

pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {
let cwd = env::var("PWD").unwrap_or_default();
let cwd = PathBuf::from(cwd);
let paths = paths.iter().map(|p| cwd.join(p)).collect::<Vec<_>>();
let invalid_paths = paths.iter().filter(|p| fs::metadata(p).is_err()).collect::<Vec<_>>();
if !invalid_paths.is_empty() {
for path in invalid_paths {
for path in &invalid_paths {
tracing::error!(path=path.display().to_string(), "Does not exist");
}
anyhow::bail!("Provided paths that did not exist.");
let paths = invalid_paths.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ");
anyhow::bail!("Provided paths that did not exist: {}", paths);
}

let walk = paths.iter().flat_map(Walk::new);
Expand All @@ -111,7 +116,7 @@ pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {
let contents = fs::read_to_string(&entry)
.context(format!("failed to read file: {}", entry.display()))?;
tracing::debug!(file=entry.display().to_string(), "Checking for Model, Type, ManualType derive attrs");
if !contents.contains("Model") {
if !(contents.contains("Model") || contents.contains("Type") || contents.contains("ManualType")) {
continue;
}
let ast = syn::parse_file(&contents)
Expand Down
88 changes: 85 additions & 3 deletions attr/src/syndecode.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use proc_macro2::{TokenStream};
use proc_macro2::{TokenStream, TokenTree};
use syn::Meta;

#[derive(Debug)]
Expand Down Expand Up @@ -26,8 +26,6 @@ impl Attributes2 {
}

fn decode_traits_from_derive_tokens(derives: &mut Derives, tokens: &TokenStream) {
use proc_macro2::TokenTree;

let mut iter = tokens.clone().into_iter().peekable();

while let Some(tok) = iter.next() {
Expand All @@ -51,6 +49,12 @@ fn decode_traits_from_derive_tokens(derives: &mut Derives, tokens: &TokenStream)
}
_ = iter.next(); // consume the colon
_ = iter.next(); // consume another colon
let p = iter.peek();
if matches!(p, Some(TokenTree::Ident(i)) if i.to_string() == "types") {
_ = iter.next(); // consume the type
_ = iter.next(); // consume a colon
_ = iter.next(); // consume another colon
}
continue;
} else {
panic!("Unexpected token in derive attribute: {:?}", p);
Expand Down Expand Up @@ -78,6 +82,20 @@ impl From<&[syn::Attribute]> for Attributes2 {
} else if ident == "repr" {
let ident = l.tokens.clone().into_iter().next().expect("Encountered a repr attribute without an argument.");
repr = Some(ident.to_string());
} else if ident == "cfg_attr" {
let mut iter = l.tokens.clone().into_iter().skip_while(|tok| !matches!(tok, TokenTree::Punct(p) if p.as_char() == ','));
iter.next(); // skip the ,
while let Some(tok) = iter.next() {
match tok {
TokenTree::Ident(i) => {
if i.to_string() == "derive" {
let Some(TokenTree::Group(toks)) = iter.next() else { panic!("Expected a token group after derive") };
decode_traits_from_derive_tokens(&mut derives, &toks.stream());
}
}
_ => {}
}
}
}
}
_ => {}
Expand Down Expand Up @@ -130,6 +148,70 @@ pub struct QuerySet {
assert_eq!(attr.derives.is_model, true);
assert_eq!(attr.derives.is_type, true);
assert_eq!(attr.derives.is_manual_type, false);
}

#[test]
fn test_cfg_attr() {
// the doc string is the regression test
let code = r#"
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(
target_arch = "wasm32",
derive(tsify::Tsify),
tsify(into_wasm_abi, from_wasm_abi)
)]
#[cfg_attr(
not(target_arch = "wasm32"),
derive(
sqlx::Type,
strum::IntoStaticStr,
strum::EnumString,
),
strum(serialize_all = "snake_case")
)]
#[serde(rename_all = "snake_case")]
pub enum Privacy {
Private,
Team,
Public,
}
"#;
let file: syn::File = syn::parse_str(code).unwrap();
let syn::Item::Enum(item) = file.items.first().unwrap() else { panic!() };
let attr = Attributes2::from(item.attrs.as_slice());
assert_eq!(attr.repr, None);
assert_eq!(attr.derives.is_model, false);
assert_eq!(attr.derives.is_type, true);
assert_eq!(attr.derives.is_manual_type, false);
}

#[test]
fn test_cfg_attr2() {
let code = r#"
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(
target_arch = "wasm32",
derive(tsify::Tsify),
tsify(into_wasm_abi, from_wasm_abi)
)]
#[cfg_attr(
not(target_arch = "wasm32"),
derive(ormlite::types::ManualType, strum::IntoStaticStr, strum::EnumString),
strum(serialize_all = "snake_case")
)]
#[serde(rename_all = "snake_case")]
pub enum Privacy {
Private,
Team,
Public,
}
"#;
let file: syn::File = syn::parse_str(code).unwrap();
let syn::Item::Enum(item) = file.items.first().unwrap() else { panic!() };
let attr = Attributes2::from(item.attrs.as_slice());
assert_eq!(attr.repr, None);
assert_eq!(attr.derives.is_model, false);
assert_eq!(attr.derives.is_type, false);
assert_eq!(attr.derives.is_manual_type, true);
}
}
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ormlite-cli"
version = "0.17.1"
version = "0.17.3"
edition = "2021"
description = "An ORM for people who love SQL. Use the `ormlite` crate, not this one."
authors = ["Kurt Wolf <kurtwolfbuilds@gmail.com>"]
Expand Down
7 changes: 4 additions & 3 deletions cli/src/command/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,9 @@ impl Migrate {
file_name.push_str(&self.name);
let migration_body = migration.as_ref().map(|m| {
m.statements.iter()
.map(|s| s.to_sql(Dialect::Postgres))
.map(|s| s.to_sql(Dialect::Postgres) + ";")
.collect::<Vec<_>>()
.join(";\n")
.join("\n")
}).unwrap_or_default();
if self.reversible {
create_migration(&folder, file_name.clone(), MigrationType::Up, &migration_body)?;
Expand All @@ -261,9 +261,10 @@ impl Migrate {
println!("It auto-generated the following actions:");
for statement in &migration.statements {
match statement {
Statement::CreateTable(t) => println!("Create table {} with columns: {}", &t.name, t.columns.iter().map(|c| c.name.to_string()).collect::<Vec<_>>().join(", ")),
Statement::CreateTable(s) => println!("Create table {} with columns: {}", &s.name, s.columns.iter().map(|c| c.name.to_string()).collect::<Vec<_>>().join(", ")),
Statement::CreateIndex(s) => println!("Create index {} on {}", &s.name, &s.table),
Statement::AlterTable(s) => println!("Alter table {}", &s.name),
Statement::Update(s) => println!("Update table {}", &s.table),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ormlite-core"
version = "0.17.1"
version = "0.17.3"
edition = "2021"
description = "An ORM for people who love SQL. Use the `ormlite` crate, not this one."
authors = ["Kurt Wolf <kurtwolfbuilds@gmail.com>"]
Expand Down
4 changes: 2 additions & 2 deletions macro/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ormlite-macro"
version = "0.17.1"
version = "0.17.3"
edition = "2021"
description = "An ORM for people who love SQL. Use the `ormlite` crate, not this one."
authors = ["Kurt Wolf <kurtwolfbuilds@gmail.com>"]
Expand All @@ -24,7 +24,7 @@ default-mysql = ["mysql"]
syn = { version = "2", features = ["derive", "parsing"] }
quote = "1"
proc-macro2 = "1"
ormlite-core = { path = "../core", version = "0.17.1"}
ormlite-core = { path = "../core", version = "0.17.3"}
ormlite-attr = { path = "../attr", version = "0.17" }
sqlx = "0.7"
lazy_static = "1"
Expand Down
6 changes: 3 additions & 3 deletions ormlite/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ormlite"
version = "0.17.1"
version = "0.17.3"
edition = "2021"
authors = ["Kurt Wolf <kurtwolfbuilds@gmail.com>"]
description = "An ORM for people who love SQL"
Expand Down Expand Up @@ -49,8 +49,8 @@ default-mysql = ["mysql", "ormlite-macro/default-mysql"]
[dependencies]
sqlx = { version = "0.7" }
tokio = { version = "1.24.1", features = ["full"] }
ormlite-macro = { path = "../macro" , version = "0.17.1"}
ormlite-core = { path = "../core" , version = "0.17.1"}
ormlite-macro = { path = "../macro" , version = "0.17.3"}
ormlite-core = { path = "../core" , version = "0.17.3"}
sqlx-core = "0.7"
sqlmo = "0.16"
tokio-stream = "0.1.14"
Expand Down

0 comments on commit 2a8bb34

Please sign in to comment.