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

Rename sqlx(rename) attribute to sqlx(type_name) #940

Merged
merged 4 commits into from
Jan 12, 2021
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
.fetch_all(&mut conn).await?;
```

- [[#940]] Rename the `#[sqlx(rename)]` attribute used to specify the type name on the database
side to `#[sqlx(type_name)]` [[@jplatte]].

## 0.4.2 - 2020-12-19

- [[#908]] Fix `whoami` crash on FreeBSD platform [[@fundon]] [[@AldaronLau]]
Expand Down
4 changes: 2 additions & 2 deletions sqlx-core/src/postgres/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
//!
//! ```rust,ignore
//! #[derive(sqlx::Type)]
//! #[sqlx(rename = "inventory_item")]
//! #[sqlx(type_name = "inventory_item")]
//! struct InventoryItem {
//! name: String,
//! supplier_id: i32,
Expand All @@ -142,7 +142,7 @@
//!
//! ```rust,ignore
//! #[derive(sqlx::Type)]
//! #[sqlx(rename = "mood", rename_all = "lowercase")]
//! #[sqlx(type_name = "mood", rename_all = "lowercase")]
//! enum Mood { Sad, Ok, Happy }
//! ```
//!
Expand Down
14 changes: 7 additions & 7 deletions sqlx-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ pub use json::Json;
///
/// ##### Attributes
///
/// * `#[sqlx(rename = "<SQL type name>")]` on struct definition: instead of inferring the SQL type name from the inner
/// field (in the above case, `BIGINT`), explicitly set it to `<SQL type name>` instead. May trigger
/// errors or unexpected behavior if the encoding of the given type is different than that of the
/// inferred type (e.g. if you rename the above to `VARCHAR`).
/// Affects Postgres only.
/// * `#[sqlx(type_name = "<SQL type name>")]` on struct definition: instead of inferring the SQL
/// type name from the inner field (in the above case, `BIGINT`), explicitly set it to
/// `<SQL type name>` instead. May trigger errors or unexpected behavior if the encoding of the
/// given type is different than that of the inferred type (e.g. if you rename the above to
/// `VARCHAR`). Affects Postgres only.
///
/// ### Enumeration
///
Expand All @@ -131,7 +131,7 @@ pub use json::Json;
///
/// ```rust,ignore
/// #[derive(sqlx::Type)]
/// #[sqlx(rename = "color")] // only for PostgreSQL to match a type definition
/// #[sqlx(type_name = "color")] // only for PostgreSQL to match a type definition
/// #[sqlx(rename_all = "lowercase")]
/// enum Color { Red, Green, Blue }
/// ```
Expand All @@ -144,7 +144,7 @@ pub use json::Json;
///
/// ```rust,ignore
/// #[derive(sqlx::Type)]
/// #[sqlx(rename = "interface_type")]
/// #[sqlx(type_name = "interface_type")]
/// struct InterfaceType {
/// name: String,
/// supplier_id: i32,
Expand Down
64 changes: 58 additions & 6 deletions sqlx-macros/src/derives/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use proc_macro2::Ident;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::{Attribute, DeriveInput, Field, Lit, Meta, MetaNameValue, NestedMeta, Variant};

Expand All @@ -26,6 +28,27 @@ macro_rules! try_set {
};
}

pub struct TypeName {
pub val: String,
pub span: Span,
/// Whether the old sqlx(rename) syntax was used instead of sqlx(type_name)
pub deprecated_rename: bool,
}

impl TypeName {
pub fn get(&self) -> TokenStream {
let val = &self.val;
if self.deprecated_rename {
quote_spanned!(self.span=> {
sqlx::_rename();
#val
})
} else {
quote! { #val }
}
}
}

#[derive(Copy, Clone)]
pub enum RenameAll {
LowerCase,
Expand All @@ -39,7 +62,7 @@ pub enum RenameAll {

pub struct SqlxContainerAttributes {
pub transparent: bool,
pub rename: Option<String>,
pub type_name: Option<TypeName>,
pub rename_all: Option<RenameAll>,
pub repr: Option<Ident>,
}
Expand All @@ -52,10 +75,13 @@ pub struct SqlxChildAttributes {
pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContainerAttributes> {
let mut transparent = None;
let mut repr = None;
let mut rename = None;
let mut type_name = None;
let mut rename_all = None;

for attr in input.iter().filter(|a| a.path.is_ident("sqlx") || a.path.is_ident("repr")) {
for attr in input
.iter()
.filter(|a| a.path.is_ident("sqlx") || a.path.is_ident("repr"))
{
let meta = attr
.parse_meta()
.map_err(|e| syn::Error::new_spanned(attr, e))?;
Expand Down Expand Up @@ -91,7 +117,33 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
path,
lit: Lit::Str(val),
..
}) if path.is_ident("rename") => try_set!(rename, val.value(), value),
}) if path.is_ident("type_name") => {
jplatte marked this conversation as resolved.
Show resolved Hide resolved
try_set!(
type_name,
TypeName {
val: val.value(),
span: value.span(),
deprecated_rename: false
},
value
)
}

Meta::NameValue(MetaNameValue {
path,
lit: Lit::Str(val),
..
}) if path.is_ident("rename") => {
try_set!(
type_name,
TypeName {
val: val.value(),
span: value.span(),
deprecated_rename: true
},
value
)
}

u => fail!(u, "unexpected attribute"),
},
Expand All @@ -117,7 +169,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
Ok(SqlxContainerAttributes {
transparent: transparent.unwrap_or(false),
repr,
rename,
type_name,
rename_all,
})
}
Expand Down
15 changes: 12 additions & 3 deletions sqlx-macros/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ fn expand_derive_has_sql_type_transparent(
let mut tts = proc_macro2::TokenStream::new();

if cfg!(feature = "postgres") {
let ty_name = attr.rename.unwrap_or_else(|| ident.to_string());
let ty_name = attr
.type_name
.map(|tn| tn.get())
.unwrap_or_else(|| quote! { #ident });

tts.extend(quote!(
impl sqlx::Type< sqlx::postgres::Postgres > for #ident #ty_generics {
Expand Down Expand Up @@ -142,7 +145,10 @@ fn expand_derive_has_sql_type_strong_enum(
}

if cfg!(feature = "postgres") {
let ty_name = attributes.rename.unwrap_or_else(|| ident.to_string());
let ty_name = attributes
.type_name
.map(|tn| tn.get())
.unwrap_or_else(|| quote! { #ident });

tts.extend(quote!(
impl sqlx::Type< sqlx::Postgres > for #ident {
Expand Down Expand Up @@ -180,7 +186,10 @@ fn expand_derive_has_sql_type_struct(
let mut tts = proc_macro2::TokenStream::new();

if cfg!(feature = "postgres") {
let ty_name = attributes.rename.unwrap_or_else(|| ident.to_string());
let ty_name = attributes
.type_name
.map(|tn| tn.get())
.unwrap_or_else(|| quote! { #ident });

tts.extend(quote!(
impl sqlx::Type< sqlx::Postgres > for #ident {
Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,8 @@ pub mod prelude {
pub use super::Statement;
pub use super::Type;
}

#[doc(hidden)]
#[inline(always)]
#[deprecated = "`#[sqlx(rename = \"...\")]` is now `#[sqlx(type_name = \"...\")`"]
pub fn _rename() {}
24 changes: 12 additions & 12 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ enum Weak {

// "Strong" enums can map to TEXT (25)
#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "text")]
#[sqlx(type_name = "text")]
#[sqlx(rename_all = "lowercase")]
enum Strong {
One,
Expand All @@ -33,7 +33,7 @@ enum Strong {

// rename_all variants
#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_lower")]
#[sqlx(type_name = "color_lower")]
#[sqlx(rename_all = "lowercase")]
enum ColorLower {
Red,
Expand All @@ -42,15 +42,15 @@ enum ColorLower {
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_snake")]
#[sqlx(type_name = "color_snake")]
#[sqlx(rename_all = "snake_case")]
enum ColorSnake {
RedGreen,
BlueBlack,
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_upper")]
#[sqlx(type_name = "color_upper")]
#[sqlx(rename_all = "UPPERCASE")]
enum ColorUpper {
Red,
Expand All @@ -59,31 +59,31 @@ enum ColorUpper {
}

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_screaming_snake")]
#[sqlx(type_name = "color_screaming_snake")]
#[sqlx(rename_all = "SCREAMING_SNAKE_CASE")]
enum ColorScreamingSnake {
RedGreen,
BlueBlack,
}

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

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

#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "color_camel_case")]
#[sqlx(type_name = "color_camel_case")]
#[sqlx(rename_all = "PascalCase")]
enum ColorPascalCase {
RedGreen,
Expand All @@ -92,7 +92,7 @@ enum ColorPascalCase {

// "Strong" enum can map to a custom type
#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "mood")]
#[sqlx(type_name = "mood")]
#[sqlx(rename_all = "lowercase")]
enum Mood {
Ok,
Expand All @@ -103,7 +103,7 @@ enum Mood {
// Records must map to a custom type
// Note that all types are types in Postgres
#[derive(PartialEq, Debug, sqlx::Type)]
#[sqlx(rename = "inventory_item")]
#[sqlx(type_name = "inventory_item")]
struct InventoryItem {
name: String,
supplier_id: Option<i32>,
Expand All @@ -112,12 +112,12 @@ struct InventoryItem {

// Custom range type
#[derive(sqlx::Type, Debug, PartialEq)]
#[sqlx(rename = "float_range")]
#[sqlx(type_name = "float_range")]
struct FloatRange(PgRange<f64>);

// Custom domain type
#[derive(sqlx::Type, Debug)]
#[sqlx(rename = "int4rangeL0pC")]
#[sqlx(type_name = "int4rangeL0pC")]
struct RangeInclusive(PgRange<i32>);

test_type!(transparent<Transparent>(Postgres,
Expand Down
11 changes: 11 additions & 0 deletions tests/ui/postgres/deprecated_rename.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#[derive(sqlx::Type)]
#[sqlx(rename = "foo")]
enum Foo {
One,
Two,
Three,
}

fn main() {
compile_error!("trybuild test needs to fail for stderr checking");
}
13 changes: 13 additions & 0 deletions tests/ui/postgres/deprecated_rename.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
error: trybuild test needs to fail for stderr checking
--> $DIR/deprecated_rename.rs:10:5
|
10 | compile_error!("trybuild test needs to fail for stderr checking");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: use of deprecated function `sqlx::_rename`: `#[sqlx(rename = "...")]` is now `#[sqlx(type_name = "...")`
--> $DIR/deprecated_rename.rs:2:8
|
2 | #[sqlx(rename = "foo")]
| ^^^^^^
|
= note: `#[warn(deprecated)]` on by default
Loading