sqlx
Written
— Updated
Deserializing JSON
Custom Types
- This is largely unintuitive if you don't want to go through a
serde_json::Value
. The trick is to rename the column in the query to include type information, which sqlx will use to sqlx_json_decode!; async
- I also have a crate sqlx-transparent-json-decode, that provides a macro to implement the
Decode
trait for JSON columns for any structure that implementsDeserialize
. - With this crate, you can import the
sqlx_json_decode
macro, then addsqlx_json_decode!(SomeJsonField)
to the above code, and then you won't have to wrap the type insqlx::types::Json
anymore. This can be convenient when using one of these structures for both database results and other purposes.
- This is largely unintuitive if you don't want to go through a
Box<RawValue>
- Sometimes you just want to get the raw JSON out of a field without needing to create a bunch of objects from it. For example, a web server that is passing the JSON straight down to the client without even looking at it.
serde_json
provides theRawValue
type for this, but it is a reference type, and so needs to be wrapped in aBox
or something to be usable once the database connection is released. sqlx
provides an implementation to decode a&RawValue
, but not aBox<RawValue>
, and so thesqlx-transparent-json-decode
crate also offers a wrapper type aroundBox<RawValue>
that implementsDecode
.
- Sometimes you just want to get the raw JSON out of a field without needing to create a bunch of objects from it. For example, a web server that is passing the JSON straight down to the client without even looking at it.
Migrations
- To update the checksum of a migration when the file changed, you can recalculate the hash
cat migrations/FILENAME.sql | openssl dgst -sha384 | cut -d ' ' -f 2
- Then change the checksum for that row in the database:
update _sqlx_migrations set checksum='\x<the checksum>' where version ='<the version>';
- To update the checksum of a migration when the file changed, you can recalculate the hash