-
Notifications
You must be signed in to change notification settings - Fork 1.4k
#[derive(Serialize)] for Record #1073
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
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
da48cec
#[derive(Serialize)] for Record
rich-murphey fc85382
put cfg(feature = "json") outside quote!{}
rich-murphey a89207a
add "serialize" feature,and it_row_serializes_to_json() test
rich-murphey 21e0c1b
fmt
rich-murphey 815c94f
add examples/postgres/serialize demo of serialize feature
rich-murphey f6af889
remove stale comments
rich-murphey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
[package] | ||
name = "serialize" | ||
version = "0.1.0" | ||
edition = "2018" | ||
workspace = "../../../" | ||
|
||
[dependencies] | ||
anyhow = "1.0" | ||
async-std = { version = "1.6.0", features = [ "attributes" ] } | ||
dotenv = "0.15.0" | ||
futures = "0.3" | ||
paw = "1.0" | ||
serde = { version = "1", features = ["derive"] } | ||
serde_json = "1" | ||
sqlx = { path = "../../../", features = ["runtime-async-std-rustls", "postgres", "json", "serialize"] } | ||
structopt = { version = "0.3", features = ["paw"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# JSON Example using serialize feature | ||
|
||
When the serialize feature is enabled, the query!() macro returns a | ||
struct that implements serde::Serialize. This means that each 'Row' | ||
value can be converted to json text using serde_json::to_string(&row). | ||
This includes nested 'jsonb', such as the person column in this | ||
example. | ||
|
||
## Setup | ||
|
||
1. Declare the database URL | ||
|
||
``` | ||
export DATABASE_URL="postgres://postgres:password@localhost/serialize" | ||
``` | ||
|
||
2. Create the database. | ||
|
||
``` | ||
$ sqlx db create | ||
``` | ||
|
||
3. Run sql migrations | ||
|
||
``` | ||
$ sqlx migrate run | ||
``` | ||
|
||
## Usage | ||
|
||
Add a person | ||
|
||
``` | ||
echo '{ "name": "John Doe", "age": 30 }' | cargo run -- add | ||
``` | ||
|
||
or with extra keys | ||
|
||
``` | ||
echo '{ "name": "Jane Doe", "age": 25, "array": ["string", true, 0] }' | cargo run -- add | ||
``` | ||
|
||
List all people | ||
|
||
``` | ||
cargo run | ||
``` |
5 changes: 5 additions & 0 deletions
5
examples/postgres/serialize/migrations/20200824190010_json.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
CREATE TABLE IF NOT EXISTS people | ||
( | ||
id BIGSERIAL PRIMARY KEY, | ||
person JSONB NOT NULL | ||
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
use serde::{Deserialize, Serialize}; | ||
use serde_json::{Map, Value}; | ||
use sqlx::postgres::PgPool; | ||
use sqlx::types::Json; | ||
use std::io::{self, Read}; | ||
use std::num::NonZeroU8; | ||
use structopt::StructOpt; | ||
|
||
#[derive(StructOpt)] | ||
struct Args { | ||
#[structopt(subcommand)] | ||
cmd: Option<Command>, | ||
} | ||
|
||
#[derive(StructOpt)] | ||
enum Command { | ||
Add, | ||
} | ||
|
||
#[derive(Deserialize, Serialize)] | ||
struct Person { | ||
name: String, | ||
age: NonZeroU8, | ||
#[serde(flatten)] | ||
extra: Map<String, Value>, | ||
} | ||
|
||
#[async_std::main] | ||
#[paw::main] | ||
async fn main(args: Args) -> anyhow::Result<()> { | ||
let pool = PgPool::connect(&dotenv::var("DATABASE_URL")?).await?; | ||
|
||
match args.cmd { | ||
Some(Command::Add) => { | ||
let mut json = String::new(); | ||
io::stdin().read_to_string(&mut json)?; | ||
|
||
let person: Person = serde_json::from_str(&json)?; | ||
println!( | ||
"Adding new person: {}", | ||
&serde_json::to_string_pretty(&person)? | ||
); | ||
|
||
let person_id = add_person(&pool, person).await?; | ||
println!("Added new person with ID {}", person_id); | ||
} | ||
None => { | ||
println!("{}", list_people(&pool).await?); | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
async fn add_person(pool: &PgPool, person: Person) -> anyhow::Result<i64> { | ||
let rec = sqlx::query!( | ||
r#" | ||
INSERT INTO people ( person ) | ||
VALUES ( $1 ) | ||
RETURNING id | ||
"#, | ||
Json(person) as _ | ||
) | ||
.fetch_one(pool) | ||
.await?; | ||
|
||
Ok(rec.id) | ||
} | ||
|
||
async fn list_people(pool: &PgPool) -> anyhow::Result<String> { | ||
let mut buf = String::from("["); | ||
for (i, row) in sqlx::query!( | ||
r#" | ||
SELECT id, person | ||
FROM people | ||
ORDER BY id | ||
"# | ||
) | ||
.fetch_all(pool) | ||
.await? | ||
.iter() | ||
.enumerate() | ||
{ | ||
if i > 0 { | ||
buf.push_str(",\n"); | ||
} | ||
buf.push_str(&serde_json::to_string_pretty(&row)?); | ||
} | ||
buf.push_str("]\n"); | ||
Ok(buf) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This isn't a sufficient test to ensure that the codegen works for external users. Maybe add a small project in
examples/postgres/
to demonstrate (which will be covered whenever we get around to turning on CI for examples).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK, I'll do the equivalent of examples/postgres/json unless you have more preferences.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @abonander, thanks for clarifying the concern that the feature flag would cause compile time errors for users' existing code. And also thanks for the pointer to #916.
We might consider using a visually similar syntax for specifying the derives, such as:
sqlx::query!("SELECT * FROM foo", derive(Serialize))
Given that the feature flag appears to be unworkable, I'm ready to close this PR in favor of a configurable
query!()
macro.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That old conflict with a call to a function named derive, though not sure whether that's a problem 😄
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point. Even though it could be disambiguated by matching derive(($id:ident),*), yea, that would still break any code that might pass
derive(a,b,c...)
as a bound SQL parameter.