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

Add rename_all to FromRow, add camelCase and PascalCase to all rename_all #860

Merged
merged 7 commits into from
Dec 19, 2020
Merged
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
2 changes: 1 addition & 1 deletion sqlx-core/src/from_row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ use crate::row::Row;
/// ```
///
/// The supported values are `snake_case` (available if you have non-snake-case field names for some
/// reason), `lowercase`, `UPPERCASE`, `camelCase`, `SCREAMING_SNAKE_CASE` and `kebab-case`.
/// reason), `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`, `SCREAMING_SNAKE_CASE` and `kebab-case`.
/// The styling of each option is intended to be an example of its behavior.
///
/// #### `default`
Expand Down
5 changes: 4 additions & 1 deletion sqlx-macros/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub enum RenameAll {
UpperCase,
ScreamingSnakeCase,
KebabCase,
CamelCase,
PascalCase,
}

pub struct SqlxContainerAttributes {
Expand Down Expand Up @@ -77,7 +79,8 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
"UPPERCASE" => RenameAll::UpperCase,
"SCREAMING_SNAKE_CASE" => RenameAll::ScreamingSnakeCase,
"kebab-case" => RenameAll::KebabCase,

"camelCase" => RenameAll::CamelCase,
"PascalCase" => RenameAll::PascalCase,
_ => fail!(meta, "unexpected value for rename_all"),
};

Expand Down
4 changes: 3 additions & 1 deletion sqlx-macros/src/derives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub(crate) use r#type::expand_derive_type;
pub(crate) use row::expand_derive_from_row;

use self::attributes::RenameAll;
use heck::{KebabCase, ShoutySnakeCase, SnakeCase};
use heck::{CamelCase, KebabCase, MixedCase, ShoutySnakeCase, SnakeCase};
use std::iter::FromIterator;
use syn::DeriveInput;

Expand All @@ -35,5 +35,7 @@ pub(crate) fn rename_all(s: &str, pattern: RenameAll) -> String {
RenameAll::UpperCase => s.to_uppercase(),
RenameAll::ScreamingSnakeCase => s.to_shouty_snake_case(),
RenameAll::KebabCase => s.to_kebab_case(),
RenameAll::CamelCase => s.to_mixed_case(),
RenameAll::PascalCase => s.to_camel_case(),
}
}
20 changes: 15 additions & 5 deletions sqlx-macros/src/derives/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use syn::{
Fields, FieldsNamed, FieldsUnnamed, Lifetime, Stmt,
};

use super::attributes::parse_child_attributes;
use super::{
attributes::{parse_child_attributes, parse_container_attributes},
rename_all,
};

pub fn expand_derive_from_row(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
match &input.data {
Expand Down Expand Up @@ -69,13 +72,20 @@ fn expand_derive_from_row_struct(

let (impl_generics, _, where_clause) = generics.split_for_impl();

let container_attributes = parse_container_attributes(&input.attrs)?;

let reads = fields.iter().filter_map(|field| -> Option<Stmt> {
let id = &field.ident.as_ref()?;
let attributes = parse_child_attributes(&field.attrs).unwrap();
let id_s = match attributes.rename {
Some(rename) => rename,
None => id.to_string().trim_start_matches("r#").to_owned(),
};
let id_s = attributes
.rename
.or_else(|| Some(id.to_string().trim_start_matches("r#").to_owned()))
.map(|s| match container_attributes.rename_all {
Some(pattern) => rename_all(&s, pattern),
None => s,
})
.unwrap();

let ty = &field.ty;

if attributes.default {
Expand Down
81 changes: 77 additions & 4 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,29 @@ enum ColorScreamingSnake {
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color-kebab-case")]
#[sqlx(rename = "color_kebab_case")]
#[sqlx(rename_all = "kebab-case")]
enum ColorKebabCase {
RedGreen,
BlueBlack,
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_mixed_case")]
#[sqlx(rename_all = "camelCase")]
enum ColorCamelCase {
RedGreen,
BlueBlack,
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_camel_case")]
#[sqlx(rename_all = "PascalCase")]
enum ColorPascalCase {
RedGreen,
BlueBlack,
}

// "Strong" enum can map to a custom type
#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "mood")]
Expand Down Expand Up @@ -141,13 +157,19 @@ DROP TYPE IF EXISTS color_lower CASCADE;
DROP TYPE IF EXISTS color_snake CASCADE;
DROP TYPE IF EXISTS color_upper CASCADE;
DROP TYPE IF EXISTS color_screaming_snake CASCADE;
DROP TYPE IF EXISTS "color-kebab-case" CASCADE;
DROP TYPE IF EXISTS color_kebab_case CASCADE;
DROP TYPE IF EXISTS color_mixed_case CASCADE;
DROP TYPE IF EXISTS color_camel_case CASCADE;


CREATE TYPE color_lower AS ENUM ( 'red', 'green', 'blue' );
CREATE TYPE color_snake AS ENUM ( 'red_green', 'blue_black' );
CREATE TYPE color_upper AS ENUM ( 'RED', 'GREEN', 'BLUE' );
CREATE TYPE color_screaming_snake AS ENUM ( 'RED_GREEN', 'BLUE_BLACK' );
CREATE TYPE "color-kebab-case" AS ENUM ( 'red-green', 'blue-black' );
CREATE TYPE color_kebab_case AS ENUM ( 'red-green', 'blue-black' );
CREATE TYPE color_mixed_case AS ENUM ( 'redGreen', 'blueBlack' );
CREATE TYPE color_camel_case AS ENUM ( 'RedGreen', 'BlueBlack' );


CREATE TABLE people (
id serial PRIMARY KEY,
Expand Down Expand Up @@ -276,7 +298,7 @@ SELECT id, mood FROM people WHERE id = $1

let rec: (bool, ColorKebabCase) = sqlx::query_as(
"
SELECT $1 = 'red-green'::\"color-kebab-case\", $1
SELECT $1 = 'red-green'::color_kebab_case, $1
",
)
.bind(&ColorKebabCase::RedGreen)
Expand All @@ -286,6 +308,30 @@ SELECT id, mood FROM people WHERE id = $1
assert!(rec.0);
assert_eq!(rec.1, ColorKebabCase::RedGreen);

let rec: (bool, ColorCamelCase) = sqlx::query_as(
"
SELECT $1 = 'redGreen'::color_mixed_case, $1
",
)
.bind(&ColorCamelCase::RedGreen)
.fetch_one(&mut conn)
.await?;

assert!(rec.0);
assert_eq!(rec.1, ColorCamelCase::RedGreen);

let rec: (bool, ColorPascalCase) = sqlx::query_as(
"
SELECT $1 = 'RedGreen'::color_camel_case, $1
",
)
.bind(&ColorPascalCase::RedGreen)
.fetch_one(&mut conn)
.await?;

assert!(rec.0);
assert_eq!(rec.1, ColorPascalCase::RedGreen);

Ok(())
}

Expand Down Expand Up @@ -426,6 +472,33 @@ async fn test_from_row_with_rename() -> anyhow::Result<()> {
Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_from_row_with_rename_all() -> anyhow::Result<()> {
#[derive(Debug, sqlx::FromRow)]
#[sqlx(rename_all = "camelCase")]
struct AccountKeyword {
user_id: i32,
user_name: String,
user_surname: String,
}

let mut conn = new::<Postgres>().await?;

let account: AccountKeyword = sqlx::query_as(
r#"SELECT * from (VALUES (1, 'foo', 'bar')) accounts("userId", "userName", "userSurname")"#,
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);

assert_eq!(1, account.user_id);
assert_eq!("foo", account.user_name);
assert_eq!("bar", account.user_surname);

Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_from_row_tuple() -> anyhow::Result<()> {
Expand Down