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 support for QueryValue #214

Closed
wants to merge 3 commits into from
Closed

Add support for QueryValue #214

wants to merge 3 commits into from

Conversation

tqwewe
Copy link
Contributor

@tqwewe tqwewe commented Sep 30, 2021

This PR is related to SeaQL/sea-query#146

With these changes, users can implement QueryValue on their own types and use them in all queries including inserts and selects.

Three derive macros have been added to help generate implementations:

  • DeriveType
  • DeriveDecode
  • DeriveEncode

A lot of the source code from the sqlx::Type derive was copied, with attributes renamed to sea_orm, and a new attribute cast added to type_name = ..., which wraps the value in CAST(value as type) in queries.

See https://docs.rs/sqlx/0.5.7/sqlx/trait.Type.html#attributes for more info on the attributes.

Implementing an enum would look like this:

#[derive(Copy, Clone, Debug, PartialEq, Eq, DeriveType, DeriveEncode, DeriveDecode)]
#[sea_orm(type_name = "plan", cast)]
#[sea_orm(rename_all = "lowercase")]
pub enum Plan {
    Free,
    Basic,
    Pro,
}

Another example for a custom email domain type in postgres:

CREATE DOMAIN email AS citext CHECK (
  VALUE ~ '^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$'
);
#[derive(Clone, Debug, PartialEq, Eq, DeriveType, DeriveEncode, DeriveDecode)]
#[sea_orm(type_name = "citext")]
pub struct Email(pub String);

@tqwewe tqwewe marked this pull request as ready for review September 30, 2021 23:40
@tyt2y3
Copy link
Member

tyt2y3 commented Oct 1, 2021

It really seems cool! At least for the API it offers.

Why the cast attribute is needed? In what cases where a cast is not needed?

@tqwewe
Copy link
Contributor Author

tqwewe commented Oct 1, 2021

Why the cast attribute is needed? In what cases where a cast is not needed?

The cast will wrap your type in a sql cast. In the case of the plan example, CAST('free' as plan).
I think cast is only needed for CREATE TYPE, but CREATE DOMAIN does not require a cast.

@tqwewe
Copy link
Contributor Author

tqwewe commented Oct 17, 2021

With the new issue made #252, I wil close this PR for now. If needed it can be reopened.

@tqwewe tqwewe closed this Oct 17, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants