Serialisation improvements for sql::Value (#4255)

This commit is contained in:
Rushmore Mushambi 2024-08-13 10:29:43 +02:00 committed by GitHub
parent 828f1c50d8
commit 57c7f5ec03
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
227 changed files with 1430 additions and 19423 deletions

29
Cargo.lock generated
View file

@ -1103,6 +1103,15 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "castaway"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5"
dependencies = [
"rustversion",
]
[[package]]
name = "cc"
version = "1.0.90"
@ -5351,13 +5360,22 @@ checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]]
name = "serde"
version = "1.0.197"
version = "1.0.204"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde-content"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e255eaf9f3814135df4f959c9f404ebb2e67238bae0ed412da10518d0629e7c9"
dependencies = [
"serde",
]
[[package]]
name = "serde_bytes"
version = "0.11.15"
@ -5369,9 +5387,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.197"
version = "1.0.204"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222"
dependencies = [
"proc-macro2",
"quote",
@ -5859,6 +5877,7 @@ dependencies = [
"rustls-pki-types",
"semver",
"serde",
"serde-content",
"serde_json",
"serial_test",
"surrealdb-core",
@ -5898,6 +5917,7 @@ dependencies = [
"bcrypt",
"bincode",
"bytes",
"castaway",
"cedar-policy",
"chrono",
"ciborium",
@ -5953,6 +5973,7 @@ dependencies = [
"scrypt",
"semver",
"serde",
"serde-content",
"serde_json",
"serial_test",
"sha1",

View file

@ -1358,3 +1358,6 @@ allow_unsafe = true
[pkg.rustls-pki-types]
allow_unsafe = true
[pkg.castaway]
allow_unsafe = true

View file

@ -145,6 +145,8 @@ trice = "0.4.0"
ulid = { version = "1.1.0", features = ["serde"] }
unicase = "2.7.0"
url = "2.5.0"
castaway = "0.2.3"
serde-content = "0.1.0"
[dev-dependencies]
criterion = { version = "0.5.1", features = ["async_tokio"] }

View file

@ -635,11 +635,11 @@ mod tests {
#[test]
fn is_uuid() {
let input = (String::from("123e4567-e89b-12d3-a456-426614174000").into(),);
let input = (String::from("123e4567-e89b-12d3-a456-426614174000"),);
let value = super::is::uuid(input).unwrap();
assert_eq!(value, Value::Bool(true));
let input = (String::from("foo-bar").into(),);
let input = (String::from("foo-bar"),);
let value = super::is::uuid(input).unwrap();
assert_eq!(value, Value::Bool(false));
}

View file

@ -435,6 +435,7 @@ mod tests {
use crate::syn::Parse;
use std::collections::HashSet;
#[allow(clippy::mutable_key_type)]
#[test]
fn test_hash_index_option() {
let mut set = HashSet::new();

View file

@ -40,6 +40,12 @@ impl From<Duration> for time::Duration {
}
}
impl From<time::Duration> for Value {
fn from(value: time::Duration) -> Self {
Self::Duration(value.into())
}
}
impl FromStr for Duration {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {

View file

@ -149,9 +149,9 @@ pub use self::thing::Thing;
pub use self::timeout::Timeout;
pub use self::tokenizer::Tokenizer;
pub use self::uuid::Uuid;
pub use self::value::serde::to_value;
#[doc(hidden)]
pub use self::value::serde::{from_value, FromValueError};
pub use self::value::serde::from_value;
pub use self::value::serde::to_value;
pub use self::value::Value;
pub use self::value::Values;
pub use self::version::Version;

View file

@ -27,8 +27,11 @@ use std::collections::HashMap;
#[cfg(feature = "ml")]
const ARGUMENTS: &str = "The model expects 1 argument. The argument can be either a number, an object, or an array of numbers.";
pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Model";
#[revisioned(revision = 1)]
#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[serde(rename = "$surrealdb::private::sql::Model")]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct Model {

View file

@ -0,0 +1,550 @@
use crate::sql;
use crate::sql::constant::ConstantValue;
use crate::sql::Number;
use crate::sql::Value;
use serde::Serialize;
use serde_json::json;
use serde_json::Map;
use serde_json::Value as JsonValue;
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
match value {
// These value types are simple values which
// can be used in query responses sent to
// the client.
Value::None | Value::Null => JsonValue::Null,
Value::Bool(boolean) => boolean.into(),
Value::Number(number) => match number {
Number::Int(int) => int.into(),
Number::Float(float) => float.into(),
Number::Decimal(decimal) => json!(decimal),
},
Value::Strand(strand) => strand.0.into(),
Value::Duration(duration) => duration.to_raw().into(),
Value::Datetime(datetime) => json!(datetime.0),
Value::Uuid(uuid) => json!(uuid.0),
Value::Array(array) => JsonValue::Array(Array::from(array).0),
Value::Object(object) => JsonValue::Object(Object::from(object).0),
Value::Geometry(geo) => Geometry::from(geo).0,
Value::Bytes(bytes) => json!(bytes.0),
Value::Thing(thing) => thing.to_string().into(),
// These Value types are un-computed values
// and are not used in query responses sent
// to the client.
Value::Param(param) => json!(param),
Value::Idiom(idiom) => json!(idiom),
Value::Table(table) => json!(table),
Value::Mock(mock) => json!(mock),
Value::Regex(regex) => json!(regex),
Value::Block(block) => json!(block),
Value::Range(range) => json!(range),
Value::Edges(edges) => json!(edges),
Value::Future(future) => json!(future),
Value::Constant(constant) => match constant.value() {
ConstantValue::Datetime(datetime) => json!(datetime.0),
ConstantValue::Float(float) => float.into(),
},
Value::Cast(cast) => json!(cast),
Value::Function(function) => json!(function),
Value::Model(model) => json!(model),
Value::Query(query) => json!(query),
Value::Subquery(subquery) => json!(subquery),
Value::Expression(expression) => json!(expression),
Value::Closure(closure) => json!(closure),
}
}
}
#[derive(Serialize)]
struct Array(Vec<JsonValue>);
impl From<sql::Array> for Array {
fn from(arr: sql::Array) -> Self {
let mut vec = Vec::with_capacity(arr.len());
for value in arr {
vec.push(value.into());
}
Self(vec)
}
}
#[derive(Serialize)]
struct Object(Map<String, JsonValue>);
impl From<sql::Object> for Object {
fn from(obj: sql::Object) -> Self {
let mut map = Map::with_capacity(obj.len());
for (key, value) in obj {
map.insert(key.to_owned(), value.into());
}
Self(map)
}
}
#[derive(Serialize)]
enum CoordinatesType {
Point,
LineString,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
}
#[derive(Serialize)]
struct Coordinates {
#[serde(rename = "type")]
typ: CoordinatesType,
coordinates: JsonValue,
}
struct GeometryCollection;
impl Serialize for GeometryCollection {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.serialize_str("GeometryCollection")
}
}
#[derive(Serialize)]
struct Geometries {
#[serde(rename = "type")]
typ: GeometryCollection,
geometries: Vec<JsonValue>,
}
#[derive(Serialize)]
struct Geometry(JsonValue);
impl From<sql::Geometry> for Geometry {
fn from(geo: sql::Geometry) -> Self {
Self(match geo {
sql::Geometry::Point(v) => json!(Coordinates {
typ: CoordinatesType::Point,
coordinates: vec![json!(v.x()), json!(v.y())].into(),
}),
sql::Geometry::Line(v) => json!(Coordinates {
typ: CoordinatesType::LineString,
coordinates: v
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
.into(),
}),
sql::Geometry::Polygon(v) => json!(Coordinates {
typ: CoordinatesType::Polygon,
coordinates: vec![v
.exterior()
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()]
.into_iter()
.chain(
v.interiors()
.iter()
.map(|i| {
i.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>(),
)
.collect::<Vec<Vec<JsonValue>>>()
.into(),
}),
sql::Geometry::MultiPoint(v) => json!(Coordinates {
typ: CoordinatesType::MultiPoint,
coordinates: v
.0
.iter()
.map(|v| vec![json!(v.x()), json!(v.y())].into())
.collect::<Vec<JsonValue>>()
.into()
}),
sql::Geometry::MultiLine(v) => json!(Coordinates {
typ: CoordinatesType::MultiLineString,
coordinates: v
.0
.iter()
.map(|v| {
v.points()
.map(|v| vec![json!(v.x()), json!(v.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>()
.into()
}),
sql::Geometry::MultiPolygon(v) => json!(Coordinates {
typ: CoordinatesType::MultiPolygon,
coordinates: v
.0
.iter()
.map(|v| {
vec![v
.exterior()
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()]
.into_iter()
.chain(
v.interiors()
.iter()
.map(|i| {
i.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>(),
)
.collect::<Vec<Vec<JsonValue>>>()
})
.collect::<Vec<Vec<Vec<JsonValue>>>>()
.into(),
}),
sql::Geometry::Collection(v) => json!(Geometries {
typ: GeometryCollection,
geometries: v.into_iter().map(Geometry::from).map(|x| x.0).collect(),
}),
})
}
}
#[cfg(test)]
mod tests {
mod into_json {
use crate::sql;
use crate::sql::from_value;
use crate::sql::Value;
use chrono::DateTime;
use chrono::Utc;
use geo::line_string;
use geo::point;
use geo::polygon;
use geo::LineString;
use geo::MultiLineString;
use geo::MultiPoint;
use geo::MultiPolygon;
use geo::Point;
use geo::Polygon;
use rust_decimal::Decimal;
use serde_json::json;
use serde_json::Value as Json;
use std::collections::BTreeMap;
use std::time::Duration;
use uuid::Uuid;
#[test]
fn none_or_null() {
for value in [Value::None, Value::Null] {
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(null));
let response: Option<String> = from_value(value).unwrap();
assert_eq!(response, None);
}
}
#[test]
fn bool() {
for boolean in [true, false] {
let value = Value::Bool(boolean);
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(boolean));
let response: bool = from_value(value).unwrap();
assert_eq!(response, boolean);
}
}
#[test]
fn number_int() {
for num in [i64::MIN, 0, i64::MAX] {
let value = Value::Number(sql::Number::Int(num));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(num));
let response: i64 = from_value(value).unwrap();
assert_eq!(response, num);
}
}
#[test]
fn number_float() {
for num in [f64::NEG_INFINITY, f64::MIN, 0.0, f64::MAX, f64::INFINITY, f64::NAN] {
let value = Value::Number(sql::Number::Float(num));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(num));
let response: f64 = from_value(value).unwrap();
if response.is_finite() {
// Infinity numbers are not comparable
assert_eq!(response, num);
}
}
}
#[test]
fn number_decimal() {
for num in [i64::MIN, 0, i64::MAX] {
let num = Decimal::new(num, 0);
let value = Value::Number(sql::Number::Decimal(num));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(num.to_string()));
let response: Decimal = from_value(value).unwrap();
assert_eq!(response, num);
}
}
#[test]
fn strand() {
for str in ["", "foo"] {
let value = Value::Strand(str.into());
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(str));
let response: String = from_value(value).unwrap();
assert_eq!(response, str);
}
}
#[test]
fn duration() {
for duration in [Duration::ZERO, Duration::MAX] {
let value = Value::Duration(duration.into());
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(sql::Duration(duration).to_raw()));
let response: Duration = from_value(value).unwrap();
assert_eq!(response, duration);
}
}
#[test]
fn datetime() {
for datetime in [DateTime::<Utc>::MIN_UTC, DateTime::<Utc>::MAX_UTC] {
let value = Value::Datetime(datetime.into());
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(datetime));
let response: DateTime<Utc> = from_value(value).unwrap();
assert_eq!(response, datetime);
}
}
#[test]
fn uuid() {
for uuid in [Uuid::nil(), Uuid::max()] {
let value = Value::Uuid(uuid.into());
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(uuid));
let response: Uuid = from_value(value).unwrap();
assert_eq!(response, uuid);
}
}
#[test]
fn array() {
for vec in [vec![], vec![true, false]] {
let value =
Value::Array(sql::Array(vec.iter().copied().map(Value::from).collect()));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(vec));
let response: Vec<bool> = from_value(value).unwrap();
assert_eq!(response, vec);
}
}
#[test]
fn object() {
for map in [BTreeMap::new(), map!("done".to_owned() => true)] {
let value = Value::Object(sql::Object(
map.iter().map(|(key, value)| (key.clone(), Value::from(*value))).collect(),
));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(map));
let response: BTreeMap<String, bool> = from_value(value).unwrap();
assert_eq!(response, map);
}
}
#[test]
fn geometry_point() {
let point = point! { x: 10., y: 20. };
let value = Value::Geometry(sql::Geometry::Point(point));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!({ "type": "Point", "coordinates": [10., 20.]}));
let response: Point = from_value(value).unwrap();
assert_eq!(response, point);
}
#[test]
fn geometry_line() {
let line_string = line_string![
( x: 0., y: 0. ),
( x: 10., y: 0. ),
];
let value = Value::Geometry(sql::Geometry::Line(line_string.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({ "type": "LineString", "coordinates": [[0., 0.], [10., 0.]]})
);
let response: LineString = from_value(value).unwrap();
assert_eq!(response, line_string);
}
#[test]
fn geometry_polygon() {
let polygon = polygon![
(x: -111., y: 45.),
(x: -111., y: 41.),
(x: -104., y: 41.),
(x: -104., y: 45.),
];
let value = Value::Geometry(sql::Geometry::Polygon(polygon.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({ "type": "Polygon", "coordinates": [[
[-111., 45.],
[-111., 41.],
[-104., 41.],
[-104., 45.],
[-111., 45.],
]]})
);
let response: Polygon = from_value(value).unwrap();
assert_eq!(response, polygon);
}
#[test]
fn geometry_multi_point() {
let multi_point: MultiPoint =
vec![point! { x: 0., y: 0. }, point! { x: 1., y: 2. }].into();
let value = Value::Geometry(sql::Geometry::MultiPoint(multi_point.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({ "type": "MultiPoint", "coordinates": [[0., 0.], [1., 2.]]})
);
let response: MultiPoint = from_value(value).unwrap();
assert_eq!(response, multi_point);
}
#[test]
fn geometry_multi_line() {
let multi_line = MultiLineString::new(vec![line_string![
( x: 0., y: 0. ),
( x: 1., y: 2. ),
]]);
let value = Value::Geometry(sql::Geometry::MultiLine(multi_line.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({ "type": "MultiLineString", "coordinates": [[[0., 0.], [1., 2.]]]})
);
let response: MultiLineString = from_value(value).unwrap();
assert_eq!(response, multi_line);
}
#[test]
fn geometry_multi_polygon() {
let multi_polygon: MultiPolygon = vec![polygon![
(x: -111., y: 45.),
(x: -111., y: 41.),
(x: -104., y: 41.),
(x: -104., y: 45.),
]]
.into();
let value = Value::Geometry(sql::Geometry::MultiPolygon(multi_polygon.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({ "type": "MultiPolygon", "coordinates": [[[
[-111., 45.],
[-111., 41.],
[-104., 41.],
[-104., 45.],
[-111., 45.],
]]]})
);
let response: MultiPolygon = from_value(value).unwrap();
assert_eq!(response, multi_polygon);
}
#[test]
fn geometry_collection() {
for geometries in [vec![], vec![sql::Geometry::Point(point! { x: 10., y: 20. })]] {
let value = Value::Geometry(geometries.clone().into());
let simple_json = Json::from(value.clone());
assert_eq!(
simple_json,
json!({
"type": "GeometryCollection",
"geometries": geometries.clone().into_iter().map(|geo| Json::from(Value::from(geo))).collect::<Vec<_>>(),
})
);
let response: Vec<sql::Geometry> = from_value(value).unwrap();
assert_eq!(response, geometries);
}
}
#[test]
fn bytes() {
for bytes in [vec![], b"foo".to_vec()] {
let value = Value::Bytes(sql::Bytes(bytes.clone()));
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(bytes));
let sql::Bytes(response) = from_value(value).unwrap();
assert_eq!(response, bytes);
}
}
#[test]
fn thing() {
let record_id = "foo:bar";
let thing = sql::thing(record_id).unwrap();
let value = Value::Thing(thing.clone());
let simple_json = Json::from(value.clone());
assert_eq!(simple_json, json!(record_id));
let response: sql::Thing = from_value(value).unwrap();
assert_eq!(response, thing);
}
}
}

View file

@ -24,6 +24,7 @@ mod generate;
mod get;
mod inc;
mod increment;
mod into_json;
mod last;
mod merge;
mod patch;

View file

@ -1,701 +1,83 @@
use crate::sql::constant::ConstantValue;
use crate::err::Error;
use crate::sql;
use crate::sql::Value;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;
use serde_json::Map;
use serde_json::Value as JsonValue;
use serde_content::Deserializer;
use serde_content::Number;
use serde_content::Serializer;
use serde_content::Value as Content;
use std::borrow::Cow;
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
into_json(value, true)
}
}
fn into_json(value: Value, simplify: bool) -> JsonValue {
use crate::sql;
use crate::sql::Number;
#[derive(Serialize)]
struct Array(Vec<JsonValue>);
impl From<(sql::Array, bool)> for Array {
fn from((arr, simplify): (sql::Array, bool)) -> Self {
let mut vec = Vec::with_capacity(arr.0.len());
for value in arr.0 {
vec.push(into_json(value, simplify));
}
Self(vec)
}
}
#[derive(Serialize)]
struct Object(Map<String, JsonValue>);
impl From<(sql::Object, bool)> for Object {
fn from((obj, simplify): (sql::Object, bool)) -> Self {
let mut map = Map::with_capacity(obj.0.len());
for (key, value) in obj.0 {
map.insert(key.to_owned(), into_json(value, simplify));
}
Self(map)
}
}
#[derive(Serialize)]
enum CoordinatesType {
Point,
LineString,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
}
#[derive(Serialize)]
struct Coordinates {
#[serde(rename = "type")]
typ: CoordinatesType,
coordinates: JsonValue,
}
struct GeometryCollection;
impl Serialize for GeometryCollection {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.serialize_str("GeometryCollection")
}
}
#[derive(Serialize)]
struct Geometries {
#[serde(rename = "type")]
typ: GeometryCollection,
geometries: Vec<JsonValue>,
}
#[derive(Serialize)]
struct Geometry(JsonValue);
impl From<sql::Geometry> for Geometry {
fn from(geo: sql::Geometry) -> Self {
Self(match geo {
sql::Geometry::Point(v) => json!(Coordinates {
typ: CoordinatesType::Point,
coordinates: vec![json!(v.x()), json!(v.y())].into(),
}),
sql::Geometry::Line(v) => json!(Coordinates {
typ: CoordinatesType::LineString,
coordinates: v
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
.into(),
}),
sql::Geometry::Polygon(v) => json!(Coordinates {
typ: CoordinatesType::Polygon,
coordinates: vec![v
.exterior()
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()]
.into_iter()
.chain(
v.interiors()
.iter()
.map(|i| {
i.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>(),
)
.collect::<Vec<Vec<JsonValue>>>()
.into(),
}),
sql::Geometry::MultiPoint(v) => json!(Coordinates {
typ: CoordinatesType::MultiPoint,
coordinates: v
.0
.iter()
.map(|v| vec![json!(v.x()), json!(v.y())].into())
.collect::<Vec<JsonValue>>()
.into()
}),
sql::Geometry::MultiLine(v) => json!(Coordinates {
typ: CoordinatesType::MultiLineString,
coordinates: v
.0
.iter()
.map(|v| {
v.points()
.map(|v| vec![json!(v.x()), json!(v.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>()
.into()
}),
sql::Geometry::MultiPolygon(v) => json!(Coordinates {
typ: CoordinatesType::MultiPolygon,
coordinates: v
.0
.iter()
.map(|v| {
vec![v
.exterior()
.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()]
.into_iter()
.chain(
v.interiors()
.iter()
.map(|i| {
i.points()
.map(|p| vec![json!(p.x()), json!(p.y())].into())
.collect::<Vec<JsonValue>>()
})
.collect::<Vec<Vec<JsonValue>>>(),
)
.collect::<Vec<Vec<JsonValue>>>()
})
.collect::<Vec<Vec<Vec<JsonValue>>>>()
.into(),
}),
sql::Geometry::Collection(v) => json!(Geometries {
typ: GeometryCollection,
geometries: v.into_iter().map(Geometry::from).map(|x| x.0).collect(),
}),
})
}
}
// TODO: Checkout blame for why these are here.
/*
#[derive(Serialize)]
enum Id {
Number(i64),
String(String),
Array(Array),
Object(Object),
}
impl From<(sql::Id, bool)> for Id {
fn from((id, simplify): (sql::Id, bool)) -> Self {
match id {
sql::Id::Number(n) => Id::Number(n),
sql::Id::String(s) => Id::String(s),
sql::Id::Array(arr) => Id::Array((arr, simplify).into()),
sql::Id::Object(obj) => Id::Object((obj, simplify).into()),
sql::Id::Generate(v) => match v {
Gen::Rand => Id::from((sql::Id::rand(), simplify)),
Gen::Ulid => Id::from((sql::Id::ulid(), simplify)),
Gen::Uuid => Id::from((sql::Id::uuid(), simplify)),
},
}
}
}
#[derive(Serialize)]
struct Thing {
tb: String,
id: Id,
}
impl From<(sql::Thing, bool)> for Thing {
fn from((thing, simplify): (sql::Thing, bool)) -> Self {
Self {
tb: thing.tb,
id: (thing.id, simplify).into(),
}
}
}
*/
match value {
// These value types are simple values which
// can be used in query responses sent to
// the client.
Value::None | Value::Null => JsonValue::Null,
Value::Bool(boolean) => boolean.into(),
Value::Number(number) => match number {
Number::Int(int) => int.into(),
Number::Float(float) => float.into(),
Number::Decimal(decimal) => json!(decimal),
},
Value::Strand(strand) => strand.0.into(),
Value::Duration(duration) => match simplify {
true => duration.to_raw().into(),
false => json!(duration.0),
},
Value::Datetime(datetime) => json!(datetime.0),
Value::Uuid(uuid) => json!(uuid.0),
Value::Array(array) => JsonValue::Array(Array::from((array, simplify)).0),
Value::Object(object) => JsonValue::Object(Object::from((object, simplify)).0),
Value::Geometry(geo) => match simplify {
true => Geometry::from(geo).0,
false => match geo {
sql::Geometry::Point(geo) => json!(geo),
sql::Geometry::Line(geo) => json!(geo),
sql::Geometry::Polygon(geo) => json!(geo),
sql::Geometry::MultiPoint(geo) => json!(geo),
sql::Geometry::MultiLine(geo) => json!(geo),
sql::Geometry::MultiPolygon(geo) => json!(geo),
sql::Geometry::Collection(geo) => json!(geo),
impl Value {
fn into_content(self) -> Result<Content<'static>, Error> {
let serializer = Serializer::new();
match self {
Value::None => Ok(Content::Option(None)),
Value::Null => Ok(Content::Option(None)),
Value::Bool(v) => Ok(Content::Bool(v)),
Value::Number(v) => match v {
sql::Number::Int(v) => Ok(Content::Number(Number::I64(v))),
sql::Number::Float(v) => Ok(Content::Number(Number::F64(v))),
sql::Number::Decimal(v) => serializer.serialize(v).map_err(Into::into),
},
},
Value::Bytes(bytes) => json!(bytes.0),
Value::Thing(thing) => match simplify {
true => thing.to_string().into(),
false => json!(thing),
},
// These Value types are un-computed values
// and are not used in query responses sent
// to the client.
Value::Param(param) => json!(param),
Value::Idiom(idiom) => json!(idiom),
Value::Table(table) => json!(table),
Value::Mock(mock) => json!(mock),
Value::Regex(regex) => json!(regex),
Value::Block(block) => json!(block),
Value::Range(range) => json!(range),
Value::Edges(edges) => json!(edges),
Value::Future(future) => json!(future),
Value::Constant(constant) => match simplify {
true => match constant.value() {
ConstantValue::Datetime(datetime) => json!(datetime.0),
ConstantValue::Float(float) => float.into(),
Value::Strand(sql::Strand(v)) => Ok(Content::String(Cow::Owned(v))),
Value::Duration(sql::Duration(v)) => serializer.serialize(v).map_err(Into::into),
Value::Datetime(sql::Datetime(v)) => serializer.serialize(v).map_err(Into::into),
Value::Uuid(sql::Uuid(v)) => serializer.serialize(v).map_err(Into::into),
Value::Array(sql::Array(v)) => {
let mut vec = Vec::with_capacity(v.len());
for value in v {
vec.push(value.into_content()?);
}
Ok(Content::Seq(vec))
}
Value::Object(sql::Object(v)) => {
let mut vec = Vec::with_capacity(v.len());
for (key, value) in v {
let key = Content::String(Cow::Owned(key));
let value = value.into_content()?;
vec.push((key, value));
}
Ok(Content::Map(vec))
}
Value::Geometry(v) => match v {
sql::Geometry::Point(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::Line(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::Polygon(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::MultiPoint(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::MultiLine(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::MultiPolygon(v) => serializer.serialize(v).map_err(Into::into),
sql::Geometry::Collection(v) => serializer.serialize(v).map_err(Into::into),
},
false => json!(constant),
},
Value::Cast(cast) => json!(cast),
Value::Function(function) => json!(function),
Value::Model(model) => json!(model),
Value::Query(query) => json!(query),
Value::Subquery(subquery) => json!(subquery),
Value::Expression(expression) => json!(expression),
Value::Closure(closure) => json!(closure),
Value::Bytes(sql::Bytes(v)) => Ok(Content::Bytes(Cow::Owned(v))),
Value::Thing(v) => serializer.serialize(v).map_err(Into::into),
Value::Param(sql::Param(v)) => serializer.serialize(v).map_err(Into::into),
Value::Idiom(sql::Idiom(v)) => serializer.serialize(v).map_err(Into::into),
Value::Table(sql::Table(v)) => serializer.serialize(v).map_err(Into::into),
Value::Mock(v) => serializer.serialize(v).map_err(Into::into),
Value::Regex(v) => serializer.serialize(v).map_err(Into::into),
Value::Cast(v) => serializer.serialize(v).map_err(Into::into),
Value::Block(v) => serializer.serialize(v).map_err(Into::into),
Value::Range(v) => serializer.serialize(v).map_err(Into::into),
Value::Edges(v) => serializer.serialize(v).map_err(Into::into),
Value::Future(v) => serializer.serialize(v).map_err(Into::into),
Value::Constant(v) => serializer.serialize(v).map_err(Into::into),
Value::Function(v) => serializer.serialize(v).map_err(Into::into),
Value::Subquery(v) => serializer.serialize(v).map_err(Into::into),
Value::Expression(v) => serializer.serialize(v).map_err(Into::into),
Value::Query(v) => serializer.serialize(v).map_err(Into::into),
Value::Model(v) => serializer.serialize(v).map_err(Into::into),
Value::Closure(v) => serializer.serialize(v).map_err(Into::into),
}
}
}
#[derive(Debug, Clone)]
#[doc(hidden)]
#[non_exhaustive]
pub struct FromValueError {
pub value: Value,
pub error: String,
}
/// Deserializes a value `T` from `SurrealDB` [`Value`]
#[doc(hidden)]
pub fn from_value<T>(value: Value) -> Result<T, FromValueError>
pub fn from_value<T>(value: Value) -> Result<T, Error>
where
T: DeserializeOwned,
{
let json = into_json(value.clone(), false);
serde_json::from_value(json).map_err(|error| FromValueError {
value,
error: error.to_string(),
})
}
#[cfg(test)]
mod tests {
mod into_json {
use crate::sql;
use crate::sql::value::serde::de::from_value;
use crate::sql::value::serde::de::into_json;
use crate::sql::Value;
use chrono::DateTime;
use chrono::Utc;
use geo::line_string;
use geo::point;
use geo::polygon;
use geo::LineString;
use geo::MultiLineString;
use geo::MultiPoint;
use geo::MultiPolygon;
use geo::Point;
use geo::Polygon;
use rust_decimal::Decimal;
use serde_json::json;
use std::collections::BTreeMap;
use std::time::Duration;
use uuid::Uuid;
#[test]
fn none_or_null() {
for value in [Value::None, Value::Null] {
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(null));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(null));
let response: Option<String> = from_value(value).unwrap();
assert_eq!(response, None);
}
}
#[test]
fn bool() {
for boolean in [true, false] {
let value = Value::Bool(boolean);
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(boolean));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(boolean));
let response: bool = from_value(value).unwrap();
assert_eq!(response, boolean);
}
}
#[test]
fn number_int() {
for num in [i64::MIN, 0, i64::MAX] {
let value = Value::Number(sql::Number::Int(num));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(num));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(num));
let response: i64 = from_value(value).unwrap();
assert_eq!(response, num);
}
}
#[test]
fn number_float() {
for num in [f64::NEG_INFINITY, f64::MIN, 0.0, f64::MAX, f64::INFINITY, f64::NAN] {
let value = Value::Number(sql::Number::Float(num));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(num));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(num));
if num.is_finite() {
let response: f64 = from_value(value).unwrap();
assert_eq!(response, num);
} else {
let response: Option<f64> = from_value(value).unwrap();
assert_eq!(response, None);
}
}
}
#[test]
fn number_decimal() {
for num in [i64::MIN, 0, i64::MAX] {
let num = Decimal::new(num, 0);
let value = Value::Number(sql::Number::Decimal(num));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(num.to_string()));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(num));
let response: Decimal = from_value(value).unwrap();
assert_eq!(response, num);
}
}
#[test]
fn strand() {
for str in ["", "foo"] {
let value = Value::Strand(str.into());
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(str));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(str));
let response: String = from_value(value).unwrap();
assert_eq!(response, str);
}
}
#[test]
fn duration() {
for duration in [Duration::ZERO, Duration::MAX] {
let value = Value::Duration(duration.into());
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(sql::Duration(duration).to_raw()));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(duration));
let response: Duration = from_value(value).unwrap();
assert_eq!(response, duration);
}
}
#[test]
fn datetime() {
for datetime in [DateTime::<Utc>::MIN_UTC, DateTime::<Utc>::MAX_UTC] {
let value = Value::Datetime(datetime.into());
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(datetime));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(datetime));
let response: DateTime<Utc> = from_value(value).unwrap();
assert_eq!(response, datetime);
}
}
#[test]
fn uuid() {
for uuid in [Uuid::nil(), Uuid::max()] {
let value = Value::Uuid(uuid.into());
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(uuid));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(uuid));
let response: Uuid = from_value(value).unwrap();
assert_eq!(response, uuid);
}
}
#[test]
fn array() {
for vec in [vec![], vec![true, false]] {
let value =
Value::Array(sql::Array(vec.iter().copied().map(Value::from).collect()));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(vec));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(vec));
let response: Vec<bool> = from_value(value).unwrap();
assert_eq!(response, vec);
}
}
#[test]
fn object() {
for map in [BTreeMap::new(), map!("done".to_owned() => true)] {
let value = Value::Object(sql::Object(
map.iter().map(|(key, value)| (key.clone(), Value::from(*value))).collect(),
));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(map));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(map));
let response: BTreeMap<String, bool> = from_value(value).unwrap();
assert_eq!(response, map);
}
}
#[test]
fn geometry_point() {
let point = point! { x: 10., y: 20. };
let value = Value::Geometry(sql::Geometry::Point(point));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!({ "type": "Point", "coordinates": [10., 20.]}));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(point));
let response: Point = from_value(value).unwrap();
assert_eq!(response, point);
}
#[test]
fn geometry_line() {
let line_string = line_string![
( x: 0., y: 0. ),
( x: 10., y: 0. ),
];
let value = Value::Geometry(sql::Geometry::Line(line_string.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({ "type": "LineString", "coordinates": [[0., 0.], [10., 0.]]})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(line_string));
let response: LineString = from_value(value).unwrap();
assert_eq!(response, line_string);
}
#[test]
fn geometry_polygon() {
let polygon = polygon![
(x: -111., y: 45.),
(x: -111., y: 41.),
(x: -104., y: 41.),
(x: -104., y: 45.),
];
let value = Value::Geometry(sql::Geometry::Polygon(polygon.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({ "type": "Polygon", "coordinates": [[
[-111., 45.],
[-111., 41.],
[-104., 41.],
[-104., 45.],
[-111., 45.],
]]})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(polygon));
let response: Polygon = from_value(value).unwrap();
assert_eq!(response, polygon);
}
#[test]
fn geometry_multi_point() {
let multi_point: MultiPoint =
vec![point! { x: 0., y: 0. }, point! { x: 1., y: 2. }].into();
let value = Value::Geometry(sql::Geometry::MultiPoint(multi_point.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({ "type": "MultiPoint", "coordinates": [[0., 0.], [1., 2.]]})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(multi_point));
let response: MultiPoint = from_value(value).unwrap();
assert_eq!(response, multi_point);
}
#[test]
fn geometry_multi_line() {
let multi_line = MultiLineString::new(vec![line_string![
( x: 0., y: 0. ),
( x: 1., y: 2. ),
]]);
let value = Value::Geometry(sql::Geometry::MultiLine(multi_line.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({ "type": "MultiLineString", "coordinates": [[[0., 0.], [1., 2.]]]})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(multi_line));
let response: MultiLineString = from_value(value).unwrap();
assert_eq!(response, multi_line);
}
#[test]
fn geometry_multi_polygon() {
let multi_polygon: MultiPolygon = vec![polygon![
(x: -111., y: 45.),
(x: -111., y: 41.),
(x: -104., y: 41.),
(x: -104., y: 45.),
]]
.into();
let value = Value::Geometry(sql::Geometry::MultiPolygon(multi_polygon.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({ "type": "MultiPolygon", "coordinates": [[[
[-111., 45.],
[-111., 41.],
[-104., 41.],
[-104., 45.],
[-111., 45.],
]]]})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(multi_polygon));
let response: MultiPolygon = from_value(value).unwrap();
assert_eq!(response, multi_polygon);
}
#[test]
fn geometry_collection() {
for geometries in [vec![], vec![sql::Geometry::Point(point! { x: 10., y: 20. })]] {
let value = Value::Geometry(geometries.clone().into());
let simple_json = into_json(value.clone(), true);
assert_eq!(
simple_json,
json!({
"type": "GeometryCollection",
"geometries": geometries.clone().into_iter().map(|geo| into_json(Value::from(geo), true)).collect::<Vec<_>>(),
})
);
let json = into_json(value.clone(), false);
assert_eq!(json, json!(geometries));
let response: Vec<sql::Geometry> = from_value(value).unwrap();
assert_eq!(response, geometries);
}
}
#[test]
fn bytes() {
for bytes in [vec![], b"foo".to_vec()] {
let value = Value::Bytes(sql::Bytes(bytes.clone()));
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(bytes));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(bytes));
let response: Vec<u8> = from_value(value).unwrap();
assert_eq!(response, bytes);
}
}
#[test]
fn thing() {
let record_id = "foo:bar";
let thing = sql::thing(record_id).unwrap();
let value = Value::Thing(thing.clone());
let simple_json = into_json(value.clone(), true);
assert_eq!(simple_json, json!(record_id));
let json = into_json(value.clone(), false);
assert_eq!(json, json!(thing));
let response: sql::Thing = from_value(value).unwrap();
assert_eq!(response, thing);
}
}
let content = value.into_content()?;
let deserializer = Deserializer::new(content).coerce_numbers();
T::deserialize(deserializer).map_err(Into::into)
}

View file

@ -1,5 +1,5 @@
mod de;
mod ser;
pub use de::{from_value, FromValueError};
pub use de::from_value;
pub use ser::to_value;

View file

@ -1,2 +0,0 @@
pub(super) mod opt;
pub(super) mod vec;

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Access;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Access>;
type Error = Error;
type SerializeSeq = Impossible<Option<Access>, Error>;
type SerializeTuple = Impossible<Option<Access>, Error>;
type SerializeTupleStruct = Impossible<Option<Access>, Error>;
type SerializeTupleVariant = Impossible<Option<Access>, Error>;
type SerializeMap = Impossible<Option<Access>, Error>;
type SerializeStruct = Impossible<Option<Access>, Error>;
type SerializeStructVariant = Impossible<Option<Access>, Error>;
const EXPECTED: &'static str = "an `Option<Access>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(Access(value.serialize(ser::string::Serializer.wrap())?)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Access> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Access::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,79 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Access;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Access>;
type Error = Error;
type SerializeSeq = SerializeAccessVec;
type SerializeTuple = Impossible<Vec<Access>, Error>;
type SerializeTupleStruct = Impossible<Vec<Access>, Error>;
type SerializeTupleVariant = Impossible<Vec<Access>, Error>;
type SerializeMap = Impossible<Vec<Access>, Error>;
type SerializeStruct = Impossible<Vec<Access>, Error>;
type SerializeStructVariant = Impossible<Vec<Access>, Error>;
const EXPECTED: &'static str = "a `Access` sequence";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeAccessVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeAccessVec(Vec<Access>);
impl serde::ser::SerializeSeq for SerializeAccessVec {
type Ok = Vec<Access>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Access(value.serialize(ser::string::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Access> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Access("foo".to_owned())];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,457 +0,0 @@
use crate::err::Error;
use crate::sql::access_type::{
AccessType, JwtAccess, JwtAccessIssue, JwtAccessVerify, JwtAccessVerifyJwks,
JwtAccessVerifyKey, RecordAccess,
};
use crate::sql::value::serde::ser;
use crate::sql::Algorithm;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
// Serialize Access Method
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = AccessType;
type Error = Error;
type SerializeSeq = Impossible<AccessType, Error>;
type SerializeTuple = Impossible<AccessType, Error>;
type SerializeTupleStruct = Impossible<AccessType, Error>;
type SerializeTupleVariant = Impossible<AccessType, Error>;
type SerializeMap = Impossible<AccessType, Error>;
type SerializeStruct = Impossible<AccessType, Error>;
type SerializeStructVariant = Impossible<AccessType, Error>;
const EXPECTED: &'static str = "a `AccessType`";
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
match variant {
"Record" => Ok(AccessType::Record(value.serialize(SerializerRecord.wrap())?)),
"Jwt" => Ok(AccessType::Jwt(value.serialize(SerializerJwt.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
// Serialize Record Access
pub struct SerializerRecord;
impl ser::Serializer for SerializerRecord {
type Ok = RecordAccess;
type Error = Error;
type SerializeSeq = Impossible<RecordAccess, Error>;
type SerializeTuple = Impossible<RecordAccess, Error>;
type SerializeTupleStruct = Impossible<RecordAccess, Error>;
type SerializeTupleVariant = Impossible<RecordAccess, Error>;
type SerializeMap = Impossible<RecordAccess, Error>;
type SerializeStruct = SerializeRecord;
type SerializeStructVariant = Impossible<RecordAccess, Error>;
const EXPECTED: &'static str = "a struct `RecordAccess`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeRecord::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeRecord {
pub signup: Option<Value>,
pub signin: Option<Value>,
pub jwt: JwtAccess,
// TODO(gguillemas): Field kept to gracefully handle breaking change.
// Remove when "revision" crate allows doing so.
pub authenticate: Option<Value>,
}
impl serde::ser::SerializeStruct for SerializeRecord {
type Ok = RecordAccess;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"signup" => {
self.signup = value.serialize(ser::value::opt::Serializer.wrap())?;
}
"signin" => {
self.signin = value.serialize(ser::value::opt::Serializer.wrap())?;
}
"jwt" => {
self.jwt = value.serialize(SerializerJwt.wrap())?;
}
// TODO(gguillemas): Field kept to gracefully handle breaking change.
// Remove when "revision" crate allows doing so.
"authenticate" => {
self.authenticate = value.serialize(ser::value::opt::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `RecordAccess::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(RecordAccess {
signup: self.signup,
signin: self.signin,
jwt: self.jwt,
// TODO(gguillemas): Field kept to gracefully handle breaking change.
// Remove when "revision" crate allows doing so.
authenticate: None,
})
}
}
// Serialize JWT Access
pub struct SerializerJwt;
impl ser::Serializer for SerializerJwt {
type Ok = JwtAccess;
type Error = Error;
type SerializeSeq = Impossible<JwtAccess, Error>;
type SerializeTuple = Impossible<JwtAccess, Error>;
type SerializeTupleStruct = Impossible<JwtAccess, Error>;
type SerializeTupleVariant = Impossible<JwtAccess, Error>;
type SerializeMap = Impossible<JwtAccess, Error>;
type SerializeStruct = SerializeJwt;
type SerializeStructVariant = Impossible<JwtAccess, Error>;
const EXPECTED: &'static str = "a struct `JwtAccess`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeJwt::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeJwt {
pub verify: JwtAccessVerify,
pub issue: Option<JwtAccessIssue>,
}
impl serde::ser::SerializeStruct for SerializeJwt {
type Ok = JwtAccess;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"verify" => {
self.verify = value.serialize(SerializerJwtVerify.wrap())?;
}
"issue" => {
self.issue = value.serialize(SerializerJwtIssueOpt.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `JwtAccess::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(JwtAccess {
verify: self.verify,
issue: self.issue,
})
}
}
// Serialize JWT Access Verify
pub struct SerializerJwtVerify;
impl ser::Serializer for SerializerJwtVerify {
type Ok = JwtAccessVerify;
type Error = Error;
type SerializeSeq = Impossible<JwtAccessVerify, Error>;
type SerializeTuple = Impossible<JwtAccessVerify, Error>;
type SerializeTupleStruct = Impossible<JwtAccessVerify, Error>;
type SerializeTupleVariant = Impossible<JwtAccessVerify, Error>;
type SerializeMap = Impossible<JwtAccessVerify, Error>;
type SerializeStruct = Impossible<JwtAccessVerify, Error>;
type SerializeStructVariant = Impossible<JwtAccessVerify, Error>;
const EXPECTED: &'static str = "a `JwtAccessVerify`";
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
match variant {
"Key" => Ok(JwtAccessVerify::Key(value.serialize(SerializerJwtVerifyKey.wrap())?)),
"Jwks" => Ok(JwtAccessVerify::Jwks(value.serialize(SerializerJwtVerifyJwks.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
// Serialize JWT Access Verify Key
pub struct SerializerJwtVerifyKey;
impl ser::Serializer for SerializerJwtVerifyKey {
type Ok = JwtAccessVerifyKey;
type Error = Error;
type SerializeSeq = Impossible<JwtAccessVerifyKey, Error>;
type SerializeTuple = Impossible<JwtAccessVerifyKey, Error>;
type SerializeTupleStruct = Impossible<JwtAccessVerifyKey, Error>;
type SerializeTupleVariant = Impossible<JwtAccessVerifyKey, Error>;
type SerializeMap = Impossible<JwtAccessVerifyKey, Error>;
type SerializeStruct = SerializeJwtVerifyKey;
type SerializeStructVariant = Impossible<JwtAccessVerifyKey, Error>;
const EXPECTED: &'static str = "a struct `JwtAccessVerifyKey`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeJwtVerifyKey::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeJwtVerifyKey {
pub alg: Algorithm,
pub key: String,
}
impl serde::ser::SerializeStruct for SerializeJwtVerifyKey {
type Ok = JwtAccessVerifyKey;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"alg" => {
self.alg = value.serialize(ser::algorithm::Serializer.wrap())?;
}
"key" => {
self.key = value.serialize(ser::string::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `JwtAccessVerifyKey::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(JwtAccessVerifyKey {
alg: self.alg,
key: self.key,
})
}
}
// Serialize JWT Access Verify JWKS
pub struct SerializerJwtVerifyJwks;
impl ser::Serializer for SerializerJwtVerifyJwks {
type Ok = JwtAccessVerifyJwks;
type Error = Error;
type SerializeSeq = Impossible<JwtAccessVerifyJwks, Error>;
type SerializeTuple = Impossible<JwtAccessVerifyJwks, Error>;
type SerializeTupleStruct = Impossible<JwtAccessVerifyJwks, Error>;
type SerializeTupleVariant = Impossible<JwtAccessVerifyJwks, Error>;
type SerializeMap = Impossible<JwtAccessVerifyJwks, Error>;
type SerializeStruct = SerializeJwtVerifyJwks;
type SerializeStructVariant = Impossible<JwtAccessVerifyJwks, Error>;
const EXPECTED: &'static str = "a struct `JwtAccessVerifyJwks`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeJwtVerifyJwks::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeJwtVerifyJwks {
pub url: String,
}
impl serde::ser::SerializeStruct for SerializeJwtVerifyJwks {
type Ok = JwtAccessVerifyJwks;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"url" => {
self.url = value.serialize(ser::string::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!(
"unexpected field `JwtAccessVerifyJwks::{key}`"
)));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(JwtAccessVerifyJwks {
url: self.url,
})
}
}
// Serialize JWT Access Issue
pub struct SerializerJwtIssueOpt;
impl ser::Serializer for SerializerJwtIssueOpt {
type Ok = Option<JwtAccessIssue>;
type Error = Error;
type SerializeSeq = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeTuple = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeTupleStruct = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeTupleVariant = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeMap = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeStruct = Impossible<Option<JwtAccessIssue>, Error>;
type SerializeStructVariant = Impossible<Option<JwtAccessIssue>, Error>;
const EXPECTED: &'static str = "an `Option<JwtAccessIssue>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(SerializerJwtIssue.wrap())?))
}
}
pub struct SerializerJwtIssue;
impl ser::Serializer for SerializerJwtIssue {
type Ok = JwtAccessIssue;
type Error = Error;
type SerializeSeq = Impossible<JwtAccessIssue, Error>;
type SerializeTuple = Impossible<JwtAccessIssue, Error>;
type SerializeTupleStruct = Impossible<JwtAccessIssue, Error>;
type SerializeTupleVariant = Impossible<JwtAccessIssue, Error>;
type SerializeMap = Impossible<JwtAccessIssue, Error>;
type SerializeStruct = SerializeJwtIssue;
type SerializeStructVariant = Impossible<JwtAccessIssue, Error>;
const EXPECTED: &'static str = "a struct `JwtAccessIssue`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeJwtIssue::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeJwtIssue {
pub alg: Algorithm,
pub key: String,
}
impl serde::ser::SerializeStruct for SerializeJwtIssue {
type Ok = JwtAccessIssue;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"alg" => {
self.alg = value.serialize(ser::algorithm::Serializer.wrap())?;
}
"key" => {
self.key = value.serialize(ser::string::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `JwtAccessIssue::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(JwtAccessIssue {
alg: self.alg,
key: self.key,
})
}
}

View file

@ -1,145 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Algorithm;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Algorithm;
type Error = Error;
type SerializeSeq = Impossible<Algorithm, Error>;
type SerializeTuple = Impossible<Algorithm, Error>;
type SerializeTupleStruct = Impossible<Algorithm, Error>;
type SerializeTupleVariant = Impossible<Algorithm, Error>;
type SerializeMap = Impossible<Algorithm, Error>;
type SerializeStruct = Impossible<Algorithm, Error>;
type SerializeStructVariant = Impossible<Algorithm, Error>;
const EXPECTED: &'static str = "an enum `Algorithm`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"EdDSA" => Ok(Algorithm::EdDSA),
"Es256" => Ok(Algorithm::Es256),
"Es384" => Ok(Algorithm::Es384),
"Es512" => Ok(Algorithm::Es512),
"Hs256" => Ok(Algorithm::Hs256),
"Hs384" => Ok(Algorithm::Hs384),
"Hs512" => Ok(Algorithm::Hs512),
"Ps256" => Ok(Algorithm::Ps256),
"Ps384" => Ok(Algorithm::Ps384),
"Ps512" => Ok(Algorithm::Ps512),
"Rs256" => Ok(Algorithm::Rs256),
"Rs384" => Ok(Algorithm::Rs384),
"Rs512" => Ok(Algorithm::Rs512),
variant => Err(Error::custom(format!("unknown variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn ed_dsa() {
let algo = Algorithm::EdDSA;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn es256() {
let algo = Algorithm::Es256;
let serialized: Algorithm = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn es384() {
let algo = Algorithm::Es384;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn es512() {
let algo = Algorithm::Es512;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn hs256() {
let algo = Algorithm::Hs256;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn hs384() {
let algo = Algorithm::Hs384;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn hs512() {
let algo = Algorithm::Hs512;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn ps256() {
let algo = Algorithm::Ps256;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn ps384() {
let algo = Algorithm::Ps384;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn ps512() {
let algo = Algorithm::Ps512;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn rs256() {
let algo = Algorithm::Rs256;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn rs384() {
let algo = Algorithm::Rs384;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
#[test]
fn rs512() {
let algo = Algorithm::Rs512;
let serialized = algo.serialize(Serializer.wrap()).unwrap();
assert_eq!(algo, serialized);
}
}

View file

@ -1,94 +0,0 @@
pub(super) mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Base;
use crate::sql::Ident;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Base;
type Error = Error;
type SerializeSeq = Impossible<Base, Error>;
type SerializeTuple = Impossible<Base, Error>;
type SerializeTupleStruct = Impossible<Base, Error>;
type SerializeTupleVariant = Impossible<Base, Error>;
type SerializeMap = Impossible<Base, Error>;
type SerializeStruct = Impossible<Base, Error>;
type SerializeStructVariant = Impossible<Base, Error>;
const EXPECTED: &'static str = "an enum `Base`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Root" => Ok(Base::Root),
"Ns" => Ok(Base::Ns),
"Db" => Ok(Base::Db),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Sc" => Ok(Base::Sc(Ident(value.serialize(ser::string::Serializer.wrap())?))),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn root() {
let base = Base::Root;
let serialized = base.serialize(Serializer.wrap()).unwrap();
assert_eq!(base, serialized);
}
#[test]
fn ns() {
let base = Base::Ns;
let serialized = base.serialize(Serializer.wrap()).unwrap();
assert_eq!(base, serialized);
}
#[test]
fn db() {
let base = Base::Db;
let serialized = base.serialize(Serializer.wrap()).unwrap();
assert_eq!(base, serialized);
}
#[test]
fn sc() {
let base = Base::Sc(Default::default());
let serialized = base.serialize(Serializer.wrap()).unwrap();
assert_eq!(base, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Base;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Base>;
type Error = Error;
type SerializeSeq = Impossible<Option<Base>, Error>;
type SerializeTuple = Impossible<Option<Base>, Error>;
type SerializeTupleStruct = Impossible<Option<Base>, Error>;
type SerializeTupleVariant = Impossible<Option<Base>, Error>;
type SerializeMap = Impossible<Option<Base>, Error>;
type SerializeStruct = Impossible<Option<Base>, Error>;
type SerializeStructVariant = Impossible<Option<Base>, Error>;
const EXPECTED: &'static str = "an `Option<Base>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Base> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Base::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,168 +0,0 @@
pub mod vec;
use crate::err::Error;
use crate::sql::block::Entry;
use crate::sql::value::serde::ser;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Entry;
type Error = Error;
type SerializeSeq = Impossible<Entry, Error>;
type SerializeTuple = Impossible<Entry, Error>;
type SerializeTupleStruct = Impossible<Entry, Error>;
type SerializeTupleVariant = Impossible<Entry, Error>;
type SerializeMap = Impossible<Entry, Error>;
type SerializeStruct = Impossible<Entry, Error>;
type SerializeStructVariant = Impossible<Entry, Error>;
const EXPECTED: &'static str = "an enum `Entry`";
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Value" => Ok(Entry::Value(value.serialize(ser::value::Serializer.wrap())?)),
"Set" => Ok(Entry::Set(value.serialize(ser::statement::set::Serializer.wrap())?)),
"Throw" => Ok(Entry::Throw(value.serialize(ser::statement::throw::Serializer.wrap())?)),
"Alter" => Ok(Entry::Alter(value.serialize(ser::statement::alter::Serializer.wrap())?)),
"Break" => {
Ok(Entry::Break(value.serialize(ser::statement::r#break::Serializer.wrap())?))
}
"Ifelse" => {
Ok(Entry::Ifelse(value.serialize(ser::statement::ifelse::Serializer.wrap())?))
}
"Select" => {
Ok(Entry::Select(value.serialize(ser::statement::select::Serializer.wrap())?))
}
"Create" => {
Ok(Entry::Create(value.serialize(ser::statement::create::Serializer.wrap())?))
}
"Upsert" => {
Ok(Entry::Upsert(value.serialize(ser::statement::upsert::Serializer.wrap())?))
}
"Update" => {
Ok(Entry::Update(value.serialize(ser::statement::update::Serializer.wrap())?))
}
"Delete" => {
Ok(Entry::Delete(value.serialize(ser::statement::delete::Serializer.wrap())?))
}
"Relate" => {
Ok(Entry::Relate(value.serialize(ser::statement::relate::Serializer.wrap())?))
}
"Insert" => {
Ok(Entry::Insert(value.serialize(ser::statement::insert::Serializer.wrap())?))
}
"Output" => {
Ok(Entry::Output(value.serialize(ser::statement::output::Serializer.wrap())?))
}
"Define" => {
Ok(Entry::Define(value.serialize(ser::statement::define::Serializer.wrap())?))
}
"Remove" => {
Ok(Entry::Remove(value.serialize(ser::statement::remove::Serializer.wrap())?))
}
"Continue" => {
Ok(Entry::Continue(value.serialize(ser::statement::r#continue::Serializer.wrap())?))
}
variant => Err(Error::custom(format!("unexpected variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn value() {
let entry = Entry::Value(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn set() {
let entry = Entry::Set(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn ifelse() {
let entry = Entry::Ifelse(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn select() {
let entry = Entry::Select(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn create() {
let entry = Entry::Create(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn upsert() {
let entry = Entry::Upsert(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn update() {
let entry = Entry::Update(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn delete() {
let entry = Entry::Delete(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn relate() {
let entry = Entry::Relate(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn insert() {
let entry = Entry::Insert(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
#[test]
fn output() {
let entry = Entry::Output(Default::default());
let serialized = entry.serialize(Serializer.wrap()).unwrap();
assert_eq!(entry, serialized);
}
}

View file

@ -1,79 +0,0 @@
use crate::err::Error;
use crate::sql::block::Entry;
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Entry>;
type Error = Error;
type SerializeSeq = SerializeEntryVec;
type SerializeTuple = Impossible<Vec<Entry>, Error>;
type SerializeTupleStruct = Impossible<Vec<Entry>, Error>;
type SerializeTupleVariant = Impossible<Vec<Entry>, Error>;
type SerializeMap = Impossible<Vec<Entry>, Error>;
type SerializeStruct = Impossible<Vec<Entry>, Error>;
type SerializeStructVariant = Impossible<Vec<Entry>, Error>;
const EXPECTED: &'static str = "a `Vec<Entry>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeEntryVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeEntryVec(Vec<Entry>);
impl serde::ser::SerializeSeq for SerializeEntryVec {
type Ok = Vec<Entry>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(super::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Entry> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Entry::Value(Default::default())];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod entry;

View file

@ -1,85 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Cast;
use crate::sql::Kind;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Serialize;
#[derive(Default)]
pub(super) struct SerializeCast {
index: usize,
kind: Option<Kind>,
value: Option<Value>,
}
impl serde::ser::SerializeTupleStruct for SerializeCast {
type Ok = Cast;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match self.index {
0 => {
self.kind = Some(value.serialize(ser::kind::Serializer.wrap())?);
}
1 => {
self.value = Some(value.serialize(ser::value::Serializer.wrap())?);
}
index => {
return Err(Error::custom(format!("unexpected `Cast` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.kind, self.value) {
(Some(kind), Some(value)) => Ok(Cast(kind, value)),
_ => Err(Error::custom("`Cast` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Cast;
type Error = Error;
type SerializeSeq = Impossible<Cast, Error>;
type SerializeTuple = Impossible<Cast, Error>;
type SerializeTupleStruct = SerializeCast;
type SerializeTupleVariant = Impossible<Cast, Error>;
type SerializeMap = Impossible<Cast, Error>;
type SerializeStruct = Impossible<Cast, Error>;
type SerializeStructVariant = Impossible<Cast, Error>;
const EXPECTED: &'static str = "an struct `Cast`";
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Error> {
Ok(SerializeCast::default())
}
}
#[test]
fn cast() {
let cast = Cast(Default::default(), Default::default());
let serialized = cast.serialize(Serializer.wrap()).unwrap();
assert_eq!(cast, serialized);
}
}

View file

@ -1,86 +0,0 @@
pub(super) mod opt;
use crate::err::Error;
use crate::sql::changefeed::ChangeFeed;
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
use std::time::Duration;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = ChangeFeed;
type Error = Error;
type SerializeSeq = Impossible<ChangeFeed, Error>;
type SerializeTuple = Impossible<ChangeFeed, Error>;
type SerializeTupleStruct = Impossible<ChangeFeed, Error>;
type SerializeTupleVariant = Impossible<ChangeFeed, Error>;
type SerializeMap = Impossible<ChangeFeed, Error>;
type SerializeStruct = SerializeChangeFeed;
type SerializeStructVariant = Impossible<ChangeFeed, Error>;
const EXPECTED: &'static str = "a struct `ChangeFeed`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeChangeFeed::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializeChangeFeed {
expiry: Duration,
store_diff: bool,
}
impl serde::ser::SerializeStruct for SerializeChangeFeed {
type Ok = ChangeFeed;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"expiry" => {
self.expiry = value.serialize(ser::duration::Serializer.wrap())?;
}
"store_diff" => {
self.store_diff = value.serialize(ser::primitive::bool::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `ChangeFeed::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(ChangeFeed {
expiry: self.expiry,
store_diff: self.store_diff,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let stmt = ChangeFeed::default();
let value: ChangeFeed = stmt.serialize(Serializer.wrap()).unwrap();
assert_eq!(value, stmt);
}
}

View file

@ -1,59 +0,0 @@
use crate::err::Error;
use crate::sql::changefeed::ChangeFeed;
use crate::sql::value::serde::ser;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[allow(clippy::module_inception)]
pub mod opt;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<ChangeFeed>;
type Error = Error;
type SerializeSeq = Impossible<Option<ChangeFeed>, Error>;
type SerializeTuple = Impossible<Option<ChangeFeed>, Error>;
type SerializeTupleStruct = Impossible<Option<ChangeFeed>, Error>;
type SerializeTupleVariant = Impossible<Option<ChangeFeed>, Error>;
type SerializeMap = Impossible<Option<ChangeFeed>, Error>;
type SerializeStruct = Impossible<Option<ChangeFeed>, Error>;
type SerializeStructVariant = Impossible<Option<ChangeFeed>, Error>;
const EXPECTED: &'static str = "an `Option<ChangeFeed>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<ChangeFeed> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(ChangeFeed::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::changefeed::ChangeFeed;
use crate::sql::value::serde::ser;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Option<ChangeFeed>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeTuple = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeTupleStruct = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeTupleVariant = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeMap = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeStruct = Impossible<Option<Option<ChangeFeed>>, Error>;
type SerializeStructVariant = Impossible<Option<Option<ChangeFeed>>, Error>;
const EXPECTED: &'static str = "an `Option<ChangeFeed>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Option<ChangeFeed>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Some(ChangeFeed::default()));
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,98 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Closure;
use crate::sql::Ident;
use crate::sql::Kind;
use crate::sql::Value;
use ser::statement::define::function::IdentKindVecSerializer;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Serialize;
#[derive(Default)]
pub(super) struct SerializeClosure {
args: Option<Vec<(Ident, Kind)>>,
returns: Option<Option<Kind>>,
body: Option<Value>,
}
impl serde::ser::SerializeStruct for SerializeClosure {
type Ok = Closure;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"args" => {
self.args = Some(value.serialize(IdentKindVecSerializer.wrap())?);
}
"returns" => {
self.returns = Some(value.serialize(ser::kind::opt::Serializer.wrap())?);
}
"body" => {
self.body = Some(value.serialize(ser::value::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected field `Closure::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.args, self.returns, self.body) {
(Some(args), Some(returns), Some(body)) => Ok(Closure {
args,
returns,
body,
}),
_ => Err(Error::custom("`Closure` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Closure;
type Error = Error;
type SerializeSeq = Impossible<Closure, Error>;
type SerializeTuple = Impossible<Closure, Error>;
type SerializeTupleStruct = Impossible<Closure, Error>;
type SerializeTupleVariant = Impossible<Closure, Error>;
type SerializeMap = Impossible<Closure, Error>;
type SerializeStruct = SerializeClosure;
type SerializeStructVariant = Impossible<Closure, Error>;
const EXPECTED: &'static str = "a struct `Closure`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeClosure::default())
}
}
#[test]
fn closure() {
let closure = Closure {
args: Vec::new(),
returns: None,
body: Value::default(),
};
let serialized = closure.serialize(Serializer.wrap()).unwrap();
assert_eq!(closure, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod opt;

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Cond;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Cond>;
type Error = Error;
type SerializeSeq = Impossible<Option<Cond>, Error>;
type SerializeTuple = Impossible<Option<Cond>, Error>;
type SerializeTupleStruct = Impossible<Option<Cond>, Error>;
type SerializeTupleVariant = Impossible<Option<Cond>, Error>;
type SerializeMap = Impossible<Option<Cond>, Error>;
type SerializeStruct = Impossible<Option<Cond>, Error>;
type SerializeStructVariant = Impossible<Option<Cond>, Error>;
const EXPECTED: &'static str = "an `Option<Cond>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(Cond(value.serialize(ser::value::Serializer.wrap())?)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Cond> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Cond::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,217 +0,0 @@
use crate::err::Error;
use crate::sql::constant::Constant;
use crate::sql::value::serde::ser;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Constant;
type Error = Error;
type SerializeSeq = Impossible<Constant, Error>;
type SerializeTuple = Impossible<Constant, Error>;
type SerializeTupleStruct = Impossible<Constant, Error>;
type SerializeTupleVariant = Impossible<Constant, Error>;
type SerializeMap = Impossible<Constant, Error>;
type SerializeStruct = Impossible<Constant, Error>;
type SerializeStructVariant = Impossible<Constant, Error>;
const EXPECTED: &'static str = "an enum `Constant`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"MathE" => Ok(Constant::MathE),
"MathFrac1Pi" => Ok(Constant::MathFrac1Pi),
"MathFrac1Sqrt2" => Ok(Constant::MathFrac1Sqrt2),
"MathFrac2Pi" => Ok(Constant::MathFrac2Pi),
"MathFrac2SqrtPi" => Ok(Constant::MathFrac2SqrtPi),
"MathFracPi2" => Ok(Constant::MathFracPi2),
"MathFracPi3" => Ok(Constant::MathFracPi3),
"MathFracPi4" => Ok(Constant::MathFracPi4),
"MathFracPi6" => Ok(Constant::MathFracPi6),
"MathFracPi8" => Ok(Constant::MathFracPi8),
"MathInf" => Ok(Constant::MathInf),
"MathLn10" => Ok(Constant::MathLn10),
"MathLn2" => Ok(Constant::MathLn2),
"MathLog102" => Ok(Constant::MathLog102),
"MathLog10E" => Ok(Constant::MathLog10E),
"MathLog210" => Ok(Constant::MathLog210),
"MathLog2E" => Ok(Constant::MathLog2E),
"MathNegInf" => Ok(Constant::MathNegInf),
"MathPi" => Ok(Constant::MathPi),
"MathSqrt2" => Ok(Constant::MathSqrt2),
"MathTau" => Ok(Constant::MathTau),
"TimeEpoch" => Ok(Constant::TimeEpoch),
variant => Err(Error::custom(format!("unknown variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn math_e() {
let constant = Constant::MathE;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_1pi() {
let constant = Constant::MathFrac1Pi;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_1sqrt2() {
let constant = Constant::MathFrac1Sqrt2;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_2pi() {
let constant = Constant::MathFrac2Pi;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_2sqrt_pi() {
let constant = Constant::MathFrac2SqrtPi;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_pi2() {
let constant = Constant::MathFracPi2;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_pi3() {
let constant = Constant::MathFracPi3;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_pi4() {
let constant = Constant::MathFracPi4;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_pi6() {
let constant = Constant::MathFracPi6;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_frac_pi8() {
let constant = Constant::MathFracPi8;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_inf() {
let constant = Constant::MathInf;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_ln10() {
let constant = Constant::MathLn10;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_ln2() {
let constant = Constant::MathLn2;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_log102() {
let constant = Constant::MathLog102;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_log10_e() {
let constant = Constant::MathLog10E;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_log210() {
let constant = Constant::MathLog210;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_log2_e() {
let constant = Constant::MathLog2E;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_neg_inf() {
let constant = Constant::MathNegInf;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_pi() {
let constant = Constant::MathPi;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_sqrt2() {
let constant = Constant::MathSqrt2;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn math_tau() {
let constant = Constant::MathTau;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
#[test]
fn time_epoch() {
let constant = Constant::TimeEpoch;
let serialized = constant.serialize(Serializer.wrap()).unwrap();
assert_eq!(constant, serialized);
}
}

View file

@ -1,457 +0,0 @@
pub(super) mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Data;
use crate::sql::Idiom;
use crate::sql::Operator;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Data;
type Error = Error;
type SerializeSeq = Impossible<Data, Error>;
type SerializeTuple = Impossible<Data, Error>;
type SerializeTupleStruct = Impossible<Data, Error>;
type SerializeTupleVariant = Impossible<Data, Error>;
type SerializeMap = Impossible<Data, Error>;
type SerializeStruct = Impossible<Data, Error>;
type SerializeStructVariant = Impossible<Data, Error>;
const EXPECTED: &'static str = "an enum `Data`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"EmptyExpression" => Ok(Data::EmptyExpression),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"SetExpression" => {
Ok(Data::SetExpression(value.serialize(IdiomOperatorValueVecSerializer.wrap())?))
}
"UnsetExpression" => {
Ok(Data::UnsetExpression(value.serialize(IdiomVecSerializer.wrap())?))
}
"PatchExpression" => {
Ok(Data::PatchExpression(value.serialize(ser::value::Serializer.wrap())?))
}
"MergeExpression" => {
Ok(Data::MergeExpression(value.serialize(ser::value::Serializer.wrap())?))
}
"ReplaceExpression" => {
Ok(Data::ReplaceExpression(value.serialize(ser::value::Serializer.wrap())?))
}
"ContentExpression" => {
Ok(Data::ContentExpression(value.serialize(ser::value::Serializer.wrap())?))
}
"SingleExpression" => {
Ok(Data::SingleExpression(value.serialize(ser::value::Serializer.wrap())?))
}
"ValuesExpression" => {
Ok(Data::ValuesExpression(value.serialize(IdiomValueVecVecSerializer.wrap())?))
}
"UpdateExpression" => {
Ok(Data::UpdateExpression(value.serialize(IdiomOperatorValueVecSerializer.wrap())?))
}
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
struct IdiomVecSerializer;
impl ser::Serializer for IdiomVecSerializer {
type Ok = Vec<Idiom>;
type Error = Error;
type SerializeSeq = SerializeIdiomVec;
type SerializeTuple = Impossible<Vec<Idiom>, Error>;
type SerializeTupleStruct = Impossible<Vec<Idiom>, Error>;
type SerializeTupleVariant = Impossible<Vec<Idiom>, Error>;
type SerializeMap = Impossible<Vec<Idiom>, Error>;
type SerializeStruct = Impossible<Vec<Idiom>, Error>;
type SerializeStructVariant = Impossible<Vec<Idiom>, Error>;
const EXPECTED: &'static str = "an `Vec<Idiom>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdiomVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
struct SerializeIdiomVec(Vec<Idiom>);
impl serde::ser::SerializeSeq for SerializeIdiomVec {
type Ok = Vec<Idiom>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
type IdiomOperatorValueTuple = (Idiom, Operator, Value);
struct IdiomOperatorValueVecSerializer;
impl ser::Serializer for IdiomOperatorValueVecSerializer {
type Ok = Vec<IdiomOperatorValueTuple>;
type Error = Error;
type SerializeSeq = SerializeIdiomOperatorValueVec;
type SerializeTuple = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
type SerializeTupleStruct = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
type SerializeTupleVariant = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
type SerializeMap = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
type SerializeStruct = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
type SerializeStructVariant = Impossible<Vec<IdiomOperatorValueTuple>, Error>;
const EXPECTED: &'static str = "an `(Idiom, Operator, Value)`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdiomOperatorValueVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
struct SerializeIdiomOperatorValueVec(Vec<IdiomOperatorValueTuple>);
impl serde::ser::SerializeSeq for SerializeIdiomOperatorValueVec {
type Ok = Vec<IdiomOperatorValueTuple>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(IdiomOperatorValueTupleSerializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
struct IdiomOperatorValueTupleSerializer;
impl ser::Serializer for IdiomOperatorValueTupleSerializer {
type Ok = IdiomOperatorValueTuple;
type Error = Error;
type SerializeSeq = Impossible<IdiomOperatorValueTuple, Error>;
type SerializeTuple = SerializeIdiomOperatorValueTuple;
type SerializeTupleStruct = Impossible<IdiomOperatorValueTuple, Error>;
type SerializeTupleVariant = Impossible<IdiomOperatorValueTuple, Error>;
type SerializeMap = Impossible<IdiomOperatorValueTuple, Error>;
type SerializeStruct = Impossible<IdiomOperatorValueTuple, Error>;
type SerializeStructVariant = Impossible<IdiomOperatorValueTuple, Error>;
const EXPECTED: &'static str = "an `(Idiom, Operator, Value)`";
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(SerializeIdiomOperatorValueTuple::default())
}
}
#[derive(Default)]
struct SerializeIdiomOperatorValueTuple {
index: usize,
idiom: Option<Idiom>,
operator: Option<Operator>,
value: Option<Value>,
}
impl serde::ser::SerializeTuple for SerializeIdiomOperatorValueTuple {
type Ok = IdiomOperatorValueTuple;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match self.index {
0 => {
self.idiom = Some(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
}
1 => {
self.operator = Some(value.serialize(ser::operator::Serializer.wrap())?);
}
2 => {
self.value = Some(value.serialize(ser::value::Serializer.wrap())?);
}
index => {
return Err(Error::custom(format!(
"unexpected tuple index `{index}` for `(Idiom, Operator, Value)`"
)));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.idiom, self.operator, self.value) {
(Some(idiom), Some(operator), Some(value)) => Ok((idiom, operator, value)),
_ => Err(Error::custom("`(Idiom, Operator, Value)` missing required value(s)")),
}
}
}
type IdiomValueTuple = (Idiom, Value);
struct IdiomValueVecVecSerializer;
impl ser::Serializer for IdiomValueVecVecSerializer {
type Ok = Vec<Vec<IdiomValueTuple>>;
type Error = Error;
type SerializeSeq = SerializeIdiomValueVecVec;
type SerializeTuple = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
type SerializeTupleStruct = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
type SerializeTupleVariant = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
type SerializeMap = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
type SerializeStruct = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
type SerializeStructVariant = Impossible<Vec<Vec<IdiomValueTuple>>, Error>;
const EXPECTED: &'static str = "a `Vec<Vec<(Idiom, Value)>>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdiomValueVecVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
struct SerializeIdiomValueVecVec(Vec<Vec<IdiomValueTuple>>);
impl serde::ser::SerializeSeq for SerializeIdiomValueVecVec {
type Ok = Vec<Vec<IdiomValueTuple>>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(IdiomValueVecSerializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
struct IdiomValueVecSerializer;
impl ser::Serializer for IdiomValueVecSerializer {
type Ok = Vec<IdiomValueTuple>;
type Error = Error;
type SerializeSeq = SerializeIdiomValueVec;
type SerializeTuple = Impossible<Vec<IdiomValueTuple>, Error>;
type SerializeTupleStruct = Impossible<Vec<IdiomValueTuple>, Error>;
type SerializeTupleVariant = Impossible<Vec<IdiomValueTuple>, Error>;
type SerializeMap = Impossible<Vec<IdiomValueTuple>, Error>;
type SerializeStruct = Impossible<Vec<IdiomValueTuple>, Error>;
type SerializeStructVariant = Impossible<Vec<IdiomValueTuple>, Error>;
const EXPECTED: &'static str = "a `Vec<(Idiom, Value)>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdiomValueVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
struct SerializeIdiomValueVec(Vec<IdiomValueTuple>);
impl serde::ser::SerializeSeq for SerializeIdiomValueVec {
type Ok = Vec<IdiomValueTuple>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(IdiomValueTupleSerializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
struct IdiomValueTupleSerializer;
impl ser::Serializer for IdiomValueTupleSerializer {
type Ok = IdiomValueTuple;
type Error = Error;
type SerializeSeq = Impossible<IdiomValueTuple, Error>;
type SerializeTuple = SerializeIdiomValueTuple;
type SerializeTupleStruct = Impossible<IdiomValueTuple, Error>;
type SerializeTupleVariant = Impossible<IdiomValueTuple, Error>;
type SerializeMap = Impossible<IdiomValueTuple, Error>;
type SerializeStruct = Impossible<IdiomValueTuple, Error>;
type SerializeStructVariant = Impossible<IdiomValueTuple, Error>;
const EXPECTED: &'static str = "an `(Idiom, Value)`";
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
Ok(SerializeIdiomValueTuple::default())
}
}
#[derive(Default)]
struct SerializeIdiomValueTuple {
index: usize,
idiom: Option<Idiom>,
value: Option<Value>,
}
impl serde::ser::SerializeTuple for SerializeIdiomValueTuple {
type Ok = IdiomValueTuple;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match self.index {
0 => {
self.idiom = Some(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
}
1 => {
self.value = Some(value.serialize(ser::value::Serializer.wrap())?);
}
index => {
return Err(Error::custom(format!(
"unexpected tuple index `{index}` for `(Idiom, Value)`"
)));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.idiom, self.value) {
(Some(idiom), Some(value)) => Ok((idiom, value)),
_ => Err(Error::custom("`(Idiom, Value)` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_expression() {
let data = Data::EmptyExpression;
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn set_expression() {
let data =
Data::SetExpression(vec![(Default::default(), Default::default(), Default::default())]);
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn unset_expression() {
let data = Data::UnsetExpression(vec![Default::default()]);
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn patch_expression() {
let data = Data::PatchExpression(Default::default());
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn merge_expression() {
let data = Data::MergeExpression(Default::default());
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn replace_expression() {
let data = Data::ReplaceExpression(Default::default());
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn content_expression() {
let data = Data::ContentExpression(Default::default());
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn single_expression() {
let data = Data::SingleExpression(Default::default());
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn values_expression() {
let data = Data::ValuesExpression(vec![vec![(Default::default(), Default::default())]]);
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
#[test]
fn update_expression() {
let data = Data::UpdateExpression(vec![(
Default::default(),
Default::default(),
Default::default(),
)]);
let serialized = data.serialize(Serializer.wrap()).unwrap();
assert_eq!(data, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Data;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Data>;
type Error = Error;
type SerializeSeq = Impossible<Option<Data>, Error>;
type SerializeTuple = Impossible<Option<Data>, Error>;
type SerializeTupleStruct = Impossible<Option<Data>, Error>;
type SerializeTupleVariant = Impossible<Option<Data>, Error>;
type SerializeMap = Impossible<Option<Data>, Error>;
type SerializeStruct = Impossible<Option<Data>, Error>;
type SerializeStructVariant = Impossible<Option<Data>, Error>;
const EXPECTED: &'static str = "an `Option<Data>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Data> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Data::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,58 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use chrono::offset::Utc;
use chrono::DateTime;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
use std::fmt::Display;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = DateTime<Utc>;
type Error = Error;
type SerializeSeq = Impossible<DateTime<Utc>, Error>;
type SerializeTuple = Impossible<DateTime<Utc>, Error>;
type SerializeTupleStruct = Impossible<DateTime<Utc>, Error>;
type SerializeTupleVariant = Impossible<DateTime<Utc>, Error>;
type SerializeMap = Impossible<DateTime<Utc>, Error>;
type SerializeStruct = Impossible<DateTime<Utc>, Error>;
type SerializeStructVariant = Impossible<DateTime<Utc>, Error>;
const EXPECTED: &'static str = "a struct `DateTime<Utc>`";
#[inline]
fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: Display + ?Sized,
{
value.to_string().parse().map_err(Error::custom)
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn now() {
let dt = Utc::now();
let serialized = dt.serialize(Serializer.wrap()).unwrap();
assert_eq!(dt, serialized);
}
}

View file

@ -1,41 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use rust_decimal::Decimal;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Decimal;
type Error = Error;
type SerializeSeq = Impossible<Decimal, Error>;
type SerializeTuple = Impossible<Decimal, Error>;
type SerializeTupleStruct = Impossible<Decimal, Error>;
type SerializeTupleVariant = Impossible<Decimal, Error>;
type SerializeMap = Impossible<Decimal, Error>;
type SerializeStruct = Impossible<Decimal, Error>;
type SerializeStructVariant = Impossible<Decimal, Error>;
const EXPECTED: &'static str = "a struct `Decimal`";
#[inline]
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
value.parse::<Decimal>().map_err(Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn from_i32() {
let decimal = Decimal::from(25);
let serialized = Serialize::serialize(&decimal, Serializer.wrap()).unwrap();
assert_eq!(decimal, serialized);
}
}

View file

@ -1,65 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Dir;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Dir;
type Error = Error;
type SerializeSeq = Impossible<Dir, Error>;
type SerializeTuple = Impossible<Dir, Error>;
type SerializeTupleStruct = Impossible<Dir, Error>;
type SerializeTupleVariant = Impossible<Dir, Error>;
type SerializeMap = Impossible<Dir, Error>;
type SerializeStruct = Impossible<Dir, Error>;
type SerializeStructVariant = Impossible<Dir, Error>;
const EXPECTED: &'static str = "an enum `Dir`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"In" => Ok(Dir::In),
"Out" => Ok(Dir::Out),
"Both" => Ok(Dir::Both),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn r#in() {
let dir = Dir::In;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn out() {
let dir = Dir::Out;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn both() {
let dir = Dir::Both;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
}

View file

@ -1,86 +0,0 @@
use crate::err::Error;
use crate::sql::index::Distance;
use crate::sql::value::serde::ser;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Distance;
type Error = Error;
type SerializeSeq = Impossible<Distance, Error>;
type SerializeTuple = Impossible<Distance, Error>;
type SerializeTupleStruct = Impossible<Distance, Error>;
type SerializeTupleVariant = Impossible<Distance, Error>;
type SerializeMap = Impossible<Distance, Error>;
type SerializeStruct = Impossible<Distance, Error>;
type SerializeStructVariant = Impossible<Distance, Error>;
const EXPECTED: &'static str = "an enum `Distance`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Chebyshev" => Ok(Distance::Chebyshev),
"Cosine" => Ok(Distance::Cosine),
"Euclidean" => Ok(Distance::Euclidean),
"Hamming" => Ok(Distance::Hamming),
"Jaccard" => Ok(Distance::Jaccard),
"Manhattan" => Ok(Distance::Manhattan),
"Pearson" => Ok(Distance::Pearson),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Minkowski" => {
Ok(Distance::Minkowski(value.serialize(ser::number::Serializer.wrap())?))
}
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sql::value::serde::ser::Serializer;
#[test]
fn distance_euclidean() {
for dist in [
Distance::Chebyshev,
Distance::Cosine,
Distance::Euclidean,
Distance::Jaccard,
Distance::Hamming,
Distance::Manhattan,
Distance::Minkowski(7.into()),
Distance::Pearson,
] {
let serialized = dist.serialize(Serializer.wrap()).unwrap();
assert_eq!(dist, serialized, "{}", dist);
}
}
}

View file

@ -1,96 +0,0 @@
pub(super) mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
use std::time::Duration;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Duration;
type Error = Error;
type SerializeSeq = Impossible<Duration, Error>;
type SerializeTuple = Impossible<Duration, Error>;
type SerializeTupleStruct = Impossible<Duration, Error>;
type SerializeTupleVariant = Impossible<Duration, Error>;
type SerializeMap = Impossible<Duration, Error>;
type SerializeStruct = SerializeDuration;
type SerializeStructVariant = Impossible<Duration, Error>;
const EXPECTED: &'static str = "a struct `Duration`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeDuration::default())
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[derive(Default)]
pub(super) struct SerializeDuration {
secs: Option<u64>,
nanos: Option<u32>,
}
impl serde::ser::SerializeStruct for SerializeDuration {
type Ok = Duration;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"secs" => {
self.secs = Some(value.serialize(ser::primitive::u64::Serializer.wrap())?);
}
"nanos" => {
self.nanos = Some(value.serialize(ser::primitive::u32::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected field `Duration::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.secs, self.nanos) {
(Some(secs), Some(nanos)) => Ok(Duration::new(secs, nanos)),
_ => Err(Error::custom("`Duration` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn default() {
let duration = Duration::default();
let serialized = duration.serialize(Serializer.wrap()).unwrap();
assert_eq!(duration, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use serde::ser::Impossible;
use serde::ser::Serialize;
use std::time::Duration;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Duration>;
type Error = Error;
type SerializeSeq = Impossible<Option<Duration>, Error>;
type SerializeTuple = Impossible<Option<Duration>, Error>;
type SerializeTupleStruct = Impossible<Option<Duration>, Error>;
type SerializeTupleVariant = Impossible<Option<Duration>, Error>;
type SerializeMap = Impossible<Option<Duration>, Error>;
type SerializeStruct = Impossible<Option<Duration>, Error>;
type SerializeStructVariant = Impossible<Option<Duration>, Error>;
const EXPECTED: &'static str = "an `Option<Duration>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Duration> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Duration::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,98 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Dir;
use crate::sql::Edges;
use crate::sql::Tables;
use crate::sql::Thing;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Serialize;
#[derive(Default)]
pub(super) struct SerializeEdges {
dir: Option<Dir>,
from: Option<Thing>,
what: Option<Tables>,
}
impl serde::ser::SerializeStruct for SerializeEdges {
type Ok = Edges;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"dir" => {
self.dir = Some(value.serialize(ser::dir::Serializer.wrap())?);
}
"from" => {
self.from = Some(value.serialize(ser::thing::Serializer.wrap())?);
}
"what" => {
self.what = Some(Tables(value.serialize(ser::table::vec::Serializer.wrap())?));
}
key => {
return Err(Error::custom(format!("unexpected field `Edges::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.dir, self.from, self.what) {
(Some(dir), Some(from), Some(what)) => Ok(Edges {
dir,
from,
what,
}),
_ => Err(Error::custom("`Edges` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sql::thing;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Edges;
type Error = Error;
type SerializeSeq = Impossible<Edges, Error>;
type SerializeTuple = Impossible<Edges, Error>;
type SerializeTupleStruct = Impossible<Edges, Error>;
type SerializeTupleVariant = Impossible<Edges, Error>;
type SerializeMap = Impossible<Edges, Error>;
type SerializeStruct = SerializeEdges;
type SerializeStructVariant = Impossible<Edges, Error>;
const EXPECTED: &'static str = "a struct `Edges`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeEdges::default())
}
}
#[test]
fn edges() {
let edges = Edges {
dir: Dir::Both,
from: thing("foo:bar").unwrap(),
what: Tables(Vec::new()),
};
let serialized = edges.serialize(Serializer.wrap()).unwrap();
assert_eq!(edges, serialized);
}
}

View file

@ -0,0 +1,73 @@
use super::Content;
use crate::err::Error;
use crate::sql;
use crate::sql::Object;
use crate::sql::Value;
use serde::de::IntoDeserializer;
use serde::Deserialize;
use serde_content::Data;
use serde_content::Expected;
use serde_content::Unexpected;
use std::collections::BTreeMap;
pub(super) fn to_value(content: Content) -> Result<Value, Error> {
match content {
Content::Enum(v) => match v.name.as_ref() {
sql::expression::TOKEN => {
sql::Expression::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into)
}
sql::subquery::TOKEN => {
sql::Subquery::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into)
}
sql::function::TOKEN => {
sql::Function::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into)
}
sql::constant::TOKEN => {
sql::Constant::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into)
}
sql::mock::TOKEN => sql::Mock::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into),
sql::number::TOKEN => sql::Number::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into),
sql::geometry::TOKEN => {
sql::Geometry::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into)
}
sql::value::TOKEN => sql::Value::deserialize(Content::Enum(v).into_deserializer())
.map(Into::into)
.map_err(Into::into),
_ => match v.data {
Data::Unit => Ok(v.variant.into_owned().into()),
Data::NewType {
value,
} => (v.variant, value).try_into(),
Data::Tuple {
values,
} => (v.variant, Content::Seq(values)).try_into(),
Data::Struct {
fields,
} => {
let mut map = BTreeMap::new();
let value = fields.try_into()?;
map.insert(v.variant.into_owned(), value);
Ok(Value::Object(Object(map)))
}
},
},
content => Err(content.unexpected(Expected::Enum {
name: None,
typ: None,
}))?,
}
}

View file

@ -1 +0,0 @@
pub(super) mod opt;

View file

@ -1,75 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Explain;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Explain>;
type Error = Error;
type SerializeSeq = Impossible<Option<Explain>, Error>;
type SerializeTuple = Impossible<Option<Explain>, Error>;
type SerializeTupleStruct = Impossible<Option<Explain>, Error>;
type SerializeTupleVariant = Impossible<Option<Explain>, Error>;
type SerializeMap = Impossible<Option<Explain>, Error>;
type SerializeStruct = Impossible<Option<Explain>, Error>;
type SerializeStructVariant = Impossible<Option<Explain>, Error>;
const EXPECTED: &'static str = "an `Option<Explain>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(Explain(value.serialize(ser::primitive::bool::Serializer.wrap())?)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Explain> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some_default() {
let option = Some(Explain::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some_full() {
let option = Some(Explain(true));
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,190 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Expression;
use crate::sql::Operator;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Serialize;
pub(super) enum SerializeExpression {
Unary(SerializeUnary),
Binary(SerializeBinary),
}
impl serde::ser::SerializeStructVariant for SerializeExpression {
type Ok = Expression;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match self {
Self::Unary(unary) => unary.serialize_field(key, value),
Self::Binary(binary) => binary.serialize_field(key, value),
}
}
fn end(self) -> Result<Self::Ok, Error> {
match self {
Self::Unary(unary) => unary.end(),
Self::Binary(binary) => binary.end(),
}
}
}
#[derive(Default)]
pub(super) struct SerializeUnary {
o: Option<Operator>,
v: Option<Value>,
}
impl serde::ser::SerializeStructVariant for SerializeUnary {
type Ok = Expression;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"o" => {
self.o = Some(value.serialize(ser::operator::Serializer.wrap())?);
}
"v" => {
self.v = Some(value.serialize(ser::value::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!(
"unexpected field `Expression::Unary{{{key}}}`"
)));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.o, self.v) {
(Some(o), Some(v)) => Ok(Expression::Unary {
o,
v,
}),
_ => Err(Error::custom("`Expression::Unary` missing required field(s)")),
}
}
}
#[derive(Default)]
pub(super) struct SerializeBinary {
l: Option<Value>,
o: Option<Operator>,
r: Option<Value>,
}
impl serde::ser::SerializeStructVariant for SerializeBinary {
type Ok = Expression;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"l" => {
self.l = Some(value.serialize(ser::value::Serializer.wrap())?);
}
"o" => {
self.o = Some(value.serialize(ser::operator::Serializer.wrap())?);
}
"r" => {
self.r = Some(value.serialize(ser::value::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!(
"unexpected field `Expression::Binary{{{key}}}`"
)));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.l, self.o, self.r) {
(Some(l), Some(o), Some(r)) => Ok(Expression::Binary {
l,
o,
r,
}),
_ => Err(Error::custom("`Expression::Binary` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Expression;
type Error = Error;
type SerializeSeq = Impossible<Expression, Error>;
type SerializeTuple = Impossible<Expression, Error>;
type SerializeTupleStruct = Impossible<Expression, Error>;
type SerializeTupleVariant = Impossible<Expression, Error>;
type SerializeMap = Impossible<Expression, Error>;
type SerializeStruct = Impossible<Expression, Error>;
type SerializeStructVariant = SerializeExpression;
const EXPECTED: &'static str = "an enum `Expression`";
#[inline]
fn serialize_struct_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
debug_assert_eq!(name, crate::sql::expression::TOKEN);
match variant {
"Unary" => Ok(SerializeExpression::Unary(Default::default())),
"Binary" => Ok(SerializeExpression::Binary(Default::default())),
_ => Err(Error::custom(format!("unexpected `Expression::{name}`"))),
}
}
}
#[test]
fn default() {
let expression = Expression::default();
let serialized = expression.serialize(Serializer.wrap()).unwrap();
assert_eq!(expression, serialized);
}
#[test]
fn unary() {
let expression = Expression::Unary {
o: Operator::Not,
v: "Bar".into(),
};
let serialized = expression.serialize(Serializer.wrap()).unwrap();
assert_eq!(expression, serialized);
}
#[test]
fn foo_equals_bar() {
let expression = Expression::Binary {
l: "foo".into(),
o: Operator::Equal,
r: "Bar".into(),
};
let serialized = expression.serialize(Serializer.wrap()).unwrap();
assert_eq!(expression, serialized);
}
}

View file

@ -1,84 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::{Fetch, Idiom, Value};
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) mod vec;
struct FetchSerializer;
impl ser::Serializer for FetchSerializer {
type Ok = Fetch;
type Error = Error;
type SerializeSeq = Impossible<Fetch, Error>;
type SerializeTuple = Impossible<Fetch, Error>;
type SerializeTupleStruct = SerializeFetch;
type SerializeTupleVariant = Impossible<Fetch, Error>;
type SerializeMap = Impossible<Fetch, Error>;
type SerializeStruct = Impossible<Fetch, Error>;
type SerializeStructVariant = Impossible<Fetch, Error>;
const EXPECTED: &'static str = "a `Fetch`";
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Error> {
Ok(SerializeFetch::default())
}
}
#[derive(Default)]
struct SerializeFetch {
index: usize,
idiom: Option<Idiom>,
value: Option<Value>,
}
impl serde::ser::SerializeTupleStruct for SerializeFetch {
type Ok = Fetch;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match self.index {
0 => {
self.idiom = Some(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
}
1 => {
self.value = Some(value.serialize(ser::value::Serializer.wrap())?);
}
index => {
return Err(Error::custom(format!("unexpected `Fetch` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.idiom, self.value) {
(Some(idiom), Some(value)) => Ok(Fetch(idiom, value)),
_ => Err(ser::Error::custom("`Fetch` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fetch() {
let fetch = Fetch::default();
let serialized = fetch.serialize(FetchSerializer.wrap()).unwrap();
assert_eq!(fetch, serialized);
}
}

View file

@ -1,82 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::value::serde::ser::fetch::FetchSerializer;
use crate::sql::Fetch;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Fetch>;
type Error = Error;
type SerializeSeq = SerializeFetchVec;
type SerializeTuple = Impossible<Vec<Fetch>, Error>;
type SerializeTupleStruct = Impossible<Vec<Fetch>, Error>;
type SerializeTupleVariant = Impossible<Vec<Fetch>, Error>;
type SerializeMap = Impossible<Vec<Fetch>, Error>;
type SerializeStruct = Impossible<Vec<Fetch>, Error>;
type SerializeStructVariant = Impossible<Vec<Fetch>, Error>;
const EXPECTED: &'static str = "a `Vec<Fetch>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeFetchVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeFetchVec(Vec<Fetch>);
impl serde::ser::SerializeSeq for SerializeFetchVec {
type Ok = Vec<Fetch>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(FetchSerializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Fetch> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Fetch::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Fetch;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Fetch>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeMap = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Fetch>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Fetch>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Fetch>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Fetch>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Fetch::default()]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod opt;

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Fetchs;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Fetchs>;
type Error = Error;
type SerializeSeq = Impossible<Option<Fetchs>, Error>;
type SerializeTuple = Impossible<Option<Fetchs>, Error>;
type SerializeTupleStruct = Impossible<Option<Fetchs>, Error>;
type SerializeTupleVariant = Impossible<Option<Fetchs>, Error>;
type SerializeMap = Impossible<Option<Fetchs>, Error>;
type SerializeStruct = Impossible<Option<Fetchs>, Error>;
type SerializeStructVariant = Impossible<Option<Fetchs>, Error>;
const EXPECTED: &'static str = "an `Option<Fetchs>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(Fetchs(value.serialize(ser::fetch::vec::Serializer.wrap())?)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Fetchs> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Fetchs::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,156 +0,0 @@
pub(super) mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Field;
use crate::sql::Idiom;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Field;
type Error = Error;
type SerializeSeq = Impossible<Field, Error>;
type SerializeTuple = Impossible<Field, Error>;
type SerializeTupleStruct = Impossible<Field, Error>;
type SerializeTupleVariant = Impossible<Field, Error>;
type SerializeMap = Impossible<Field, Error>;
type SerializeStruct = Impossible<Field, Error>;
type SerializeStructVariant = SerializeValueIdiomTuple;
const EXPECTED: &'static str = "an enum `Field`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"All" => Ok(Field::All),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
fn serialize_struct_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
match variant {
"Single" => Ok(SerializeValueIdiomTuple::default()),
variant => Err(Error::custom(format!("unexpected struct variant `{name}::{variant}`"))),
}
}
}
#[derive(Default)]
pub(super) struct SerializeValueIdiomTuple {
value: Option<Value>,
idiom: Option<Option<Idiom>>,
}
impl serde::ser::SerializeStructVariant for SerializeValueIdiomTuple {
type Ok = Field;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match key {
"expr" => {
self.value = Some(value.serialize(ser::value::Serializer.wrap())?);
}
"alias" => {
self.idiom = Some(value.serialize(SerializeOptionIdiom.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected `Field::Single` field `{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.value, self.idiom) {
(Some(expr), Some(alias)) => Ok(Field::Single {
expr,
alias,
}),
_ => Err(Error::custom("`Field::Single` missing required value(s)")),
}
}
}
#[derive(Default)]
struct SerializeOptionIdiom;
impl ser::Serializer for SerializeOptionIdiom {
type Ok = Option<Idiom>;
type Error = Error;
type SerializeSeq = Impossible<Self::Ok, Error>;
type SerializeTuple = Impossible<Self::Ok, Error>;
type SerializeTupleStruct = Impossible<Self::Ok, Error>;
type SerializeTupleVariant = Impossible<Self::Ok, Error>;
type SerializeMap = Impossible<Self::Ok, Error>;
type SerializeStruct = Impossible<Self::Ok, Error>;
type SerializeStructVariant = Impossible<Self::Ok, Error>;
const EXPECTED: &'static str = "an enum `Option<Idiom>`";
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
let idiom = Idiom(value.serialize(ser::part::vec::Serializer.wrap())?);
Ok(Some(idiom))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn all() {
let field = Field::All;
let serialized = field.serialize(Serializer.wrap()).unwrap();
assert_eq!(field, serialized);
}
#[test]
fn alone() {
let field = Field::Single {
expr: Default::default(),
alias: None,
};
let serialized = field.serialize(Serializer.wrap()).unwrap();
assert_eq!(field, serialized);
}
#[test]
fn alias() {
let field = Field::Single {
expr: Default::default(),
alias: Some(Default::default()),
};
let serialized = field.serialize(Serializer.wrap()).unwrap();
assert_eq!(field, serialized);
}
}

View file

@ -1,79 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Field;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Field>;
type Error = Error;
type SerializeSeq = SerializeFieldVec;
type SerializeTuple = Impossible<Vec<Field>, Error>;
type SerializeTupleStruct = Impossible<Vec<Field>, Error>;
type SerializeTupleVariant = Impossible<Vec<Field>, Error>;
type SerializeMap = Impossible<Vec<Field>, Error>;
type SerializeStruct = Impossible<Vec<Field>, Error>;
type SerializeStructVariant = Impossible<Vec<Field>, Error>;
const EXPECTED: &'static str = "a `Vec<Field>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeFieldVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeFieldVec(Vec<Field>);
impl serde::ser::SerializeSeq for SerializeFieldVec {
type Ok = Vec<Field>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(ser::field::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Field> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Field::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,90 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Field;
use crate::sql::Fields;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Fields;
type Error = Error;
type SerializeSeq = Impossible<Fields, Error>;
type SerializeTuple = Impossible<Fields, Error>;
type SerializeTupleStruct = SerializeFields;
type SerializeTupleVariant = Impossible<Fields, Error>;
type SerializeMap = Impossible<Fields, Error>;
type SerializeStruct = Impossible<Fields, Error>;
type SerializeStructVariant = Impossible<Fields, Error>;
const EXPECTED: &'static str = "a struct `Fields`";
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Error> {
Ok(SerializeFields::default())
}
}
#[derive(Default)]
pub(super) struct SerializeFields {
index: usize,
fields: Option<Vec<Field>>,
boolean: Option<bool>,
}
impl serde::ser::SerializeTupleStruct for SerializeFields {
type Ok = Fields;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match self.index {
0 => {
self.fields = Some(value.serialize(ser::field::vec::Serializer.wrap())?);
}
1 => {
self.boolean = Some(value.serialize(ser::primitive::bool::Serializer.wrap())?);
}
index => {
return Err(Error::custom(format!("unexpected `Fields` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match (self.fields, self.boolean) {
(Some(fields), Some(boolean)) => Ok(Fields(fields, boolean)),
_ => Err(Error::custom("`Fields` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let fields = Fields::default();
let serialized = fields.serialize(Serializer.wrap()).unwrap();
assert_eq!(fields, serialized);
}
#[test]
fn all() {
let fields = Fields(vec![Field::All], true);
let serialized = fields.serialize(Serializer.wrap()).unwrap();
assert_eq!(fields, serialized);
}
}

View file

@ -1,154 +0,0 @@
pub(super) mod vec;
use crate::err::Error;
use crate::sql::filter::Filter;
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Filter;
type Error = Error;
type SerializeSeq = Impossible<Filter, Error>;
type SerializeTuple = Impossible<Filter, Error>;
type SerializeTupleStruct = Impossible<Filter, Error>;
type SerializeTupleVariant = SerializeFilter;
type SerializeMap = Impossible<Filter, Error>;
type SerializeStruct = Impossible<Filter, Error>;
type SerializeStructVariant = Impossible<Filter, Error>;
const EXPECTED: &'static str = "an enum `Filter`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Ascii" => Ok(Filter::Ascii),
"Lowercase" => Ok(Filter::Lowercase),
"Uppercase" => Ok(Filter::Uppercase),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Snowball" => Ok(Filter::Snowball(value.serialize(ser::language::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
fn serialize_tuple_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let inner = match variant {
"EdgeNgram" => Inner::EdgeNgram(Default::default(), Default::default()),
"Ngram" => Inner::Ngram(Default::default(), Default::default()),
variant => {
return Err(Error::custom(format!("unexpected tuple variant `{name}::{variant}`")));
}
};
Ok(SerializeFilter {
inner,
index: 0,
})
}
}
pub(super) struct SerializeFilter {
index: usize,
inner: Inner,
}
enum Inner {
EdgeNgram(u16, u16),
Ngram(u16, u16),
}
impl serde::ser::SerializeTupleVariant for SerializeFilter {
type Ok = Filter;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match (self.index, &mut self.inner) {
(0, Inner::EdgeNgram(ref mut var, _) | Inner::Ngram(ref mut var, _)) => {
*var = value.serialize(ser::primitive::u16::Serializer.wrap())?;
}
(1, Inner::EdgeNgram(_, ref mut var) | Inner::Ngram(_, ref mut var)) => {
*var = value.serialize(ser::primitive::u16::Serializer.wrap())?;
}
(index, inner) => {
let variant = match inner {
Inner::EdgeNgram(..) => "EdgeNgram",
Inner::Ngram(..) => "Ngram",
};
return Err(Error::custom(format!(
"unexpected `Filter::{variant}` index `{index}`"
)));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self.inner {
Inner::EdgeNgram(one, two) => Ok(Filter::EdgeNgram(one, two)),
Inner::Ngram(one, two) => Ok(Filter::Ngram(one, two)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sql::language::Language;
#[test]
fn ascii() {
let filter = Filter::Ascii;
let serialized = filter.serialize(Serializer.wrap()).unwrap();
assert_eq!(filter, serialized);
}
#[test]
fn lowercase() {
let filter = Filter::Lowercase;
let serialized = filter.serialize(Serializer.wrap()).unwrap();
assert_eq!(filter, serialized);
}
#[test]
fn snowball() {
let filter = Filter::Snowball(Language::English);
let serialized = filter.serialize(Serializer.wrap()).unwrap();
assert_eq!(filter, serialized);
}
}

View file

@ -1,81 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::filter::Filter;
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Filter>;
type Error = Error;
type SerializeSeq = SerializeFilterVec;
type SerializeTuple = Impossible<Vec<Filter>, Error>;
type SerializeTupleStruct = Impossible<Vec<Filter>, Error>;
type SerializeTupleVariant = Impossible<Vec<Filter>, Error>;
type SerializeMap = Impossible<Vec<Filter>, Error>;
type SerializeStruct = Impossible<Vec<Filter>, Error>;
type SerializeStructVariant = Impossible<Vec<Filter>, Error>;
const EXPECTED: &'static str = "a `Vec<Filter>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeFilterVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeFilterVec(Vec<Filter>);
impl serde::ser::SerializeSeq for SerializeFilterVec {
type Ok = Vec<Filter>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(super::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Filter> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Filter::Ascii];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::filter::Filter;
use crate::sql::value::serde::ser;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Filter>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Filter>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Filter>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Filter>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Filter>>, Error>;
type SerializeMap = Impossible<Option<Vec<Filter>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Filter>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Filter>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Filter>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Filter>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Filter::Ascii]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,148 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Function;
use crate::sql::Script;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Function;
type Error = Error;
type SerializeSeq = Impossible<Function, Error>;
type SerializeTuple = Impossible<Function, Error>;
type SerializeTupleStruct = Impossible<Function, Error>;
type SerializeTupleVariant = SerializeFunction;
type SerializeMap = Impossible<Function, Error>;
type SerializeStruct = Impossible<Function, Error>;
type SerializeStructVariant = Impossible<Function, Error>;
const EXPECTED: &'static str = "an enum `Function`";
fn serialize_tuple_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let inner = match variant {
"Normal" => Inner::Normal(None, None),
"Custom" => Inner::Custom(None, None),
"Script" => Inner::Script(None, None),
"Anonymous" => Inner::Anonymous(None, None),
variant => {
return Err(Error::custom(format!("unexpected tuple variant `{name}::{variant}`")));
}
};
Ok(SerializeFunction {
inner,
index: 0,
})
}
}
pub(super) struct SerializeFunction {
index: usize,
inner: Inner,
}
enum Inner {
Normal(Option<String>, Option<Vec<Value>>),
Custom(Option<String>, Option<Vec<Value>>),
Script(Option<Script>, Option<Vec<Value>>),
Anonymous(Option<Value>, Option<Vec<Value>>),
}
impl serde::ser::SerializeTupleVariant for SerializeFunction {
type Ok = Function;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match (self.index, &mut self.inner) {
(0, Inner::Normal(ref mut var, _) | Inner::Custom(ref mut var, _)) => {
*var = Some(value.serialize(ser::string::Serializer.wrap())?);
}
(0, Inner::Script(ref mut var, _)) => {
*var = Some(Script(value.serialize(ser::string::Serializer.wrap())?));
}
(0, Inner::Anonymous(ref mut var, _)) => {
*var = Some(value.serialize(ser::value::Serializer.wrap())?);
}
(
1,
Inner::Normal(_, ref mut var)
| Inner::Custom(_, ref mut var)
| Inner::Script(_, ref mut var)
| Inner::Anonymous(_, ref mut var),
) => {
*var = Some(value.serialize(ser::value::vec::Serializer.wrap())?);
}
(index, inner) => {
let variant = match inner {
Inner::Normal(..) => "Normal",
Inner::Custom(..) => "Custom",
Inner::Script(..) => "Script",
Inner::Anonymous(..) => "Anonymous",
};
return Err(Error::custom(format!(
"unexpected `Function::{variant}` index `{index}`"
)));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self.inner {
Inner::Normal(Some(one), Some(two)) => Ok(Function::Normal(one, two)),
Inner::Custom(Some(one), Some(two)) => Ok(Function::Custom(one, two)),
Inner::Script(Some(one), Some(two)) => Ok(Function::Script(one, two)),
Inner::Anonymous(Some(one), Some(two)) => Ok(Function::Anonymous(one, two)),
_ => Err(Error::custom("`Function` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn normal() {
let function = Function::Normal(Default::default(), vec![Default::default()]);
let serialized = function.serialize(Serializer.wrap()).unwrap();
assert_eq!(function, serialized);
}
#[test]
fn custom() {
let function = Function::Custom(Default::default(), vec![Default::default()]);
let serialized = function.serialize(Serializer.wrap()).unwrap();
assert_eq!(function, serialized);
}
#[test]
fn script() {
let function = Function::Script(Default::default(), vec![Default::default()]);
let serialized = function.serialize(Serializer.wrap()).unwrap();
assert_eq!(function, serialized);
}
#[test]
fn anonymous() {
let function = Function::Anonymous(Default::default(), vec![Default::default()]);
let serialized = function.serialize(Serializer.wrap()).unwrap();
assert_eq!(function, serialized);
}
}

View file

@ -1,98 +0,0 @@
pub mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::Coord;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Coord<f64>;
type Error = Error;
type SerializeSeq = Impossible<Coord<f64>, Error>;
type SerializeTuple = Impossible<Coord<f64>, Error>;
type SerializeTupleStruct = Impossible<Coord<f64>, Error>;
type SerializeTupleVariant = Impossible<Coord<f64>, Error>;
type SerializeMap = Impossible<Coord<f64>, Error>;
type SerializeStruct = SerializeCoord;
type SerializeStructVariant = Impossible<Coord<f64>, Error>;
const EXPECTED: &'static str = "a struct `Coord<f64>`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeCoord::default())
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[derive(Default)]
pub(super) struct SerializeCoord {
x: Option<f64>,
y: Option<f64>,
}
impl serde::ser::SerializeStruct for SerializeCoord {
type Ok = Coord;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"x" => {
self.x = Some(value.serialize(ser::primitive::f64::Serializer.wrap())?);
}
"y" => {
self.y = Some(value.serialize(ser::primitive::f64::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected field `Coord::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.x, self.y) {
(Some(x), Some(y)) => Ok(Coord {
x,
y,
}),
_ => Err(Error::custom("`Coord` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let coord = Coord::default();
let serialized = coord.serialize(Serializer.wrap()).unwrap();
assert_eq!(coord, serialized);
}
}

View file

@ -1,79 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::Coord;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Coord<f64>>;
type Error = Error;
type SerializeSeq = SerializeCoordVec;
type SerializeTuple = Impossible<Vec<Coord<f64>>, Error>;
type SerializeTupleStruct = Impossible<Vec<Coord<f64>>, Error>;
type SerializeTupleVariant = Impossible<Vec<Coord<f64>>, Error>;
type SerializeMap = Impossible<Vec<Coord<f64>>, Error>;
type SerializeStruct = Impossible<Vec<Coord<f64>>, Error>;
type SerializeStructVariant = Impossible<Vec<Coord<f64>>, Error>;
const EXPECTED: &'static str = "a `Vec<Coord<f64>>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeCoordVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeCoordVec(Vec<Coord<f64>>);
impl serde::ser::SerializeSeq for SerializeCoordVec {
type Ok = Vec<Coord<f64>>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(super::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Coord<f64>> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Coord::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1 +0,0 @@
pub mod vec;

View file

@ -1,80 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::LineString;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<LineString<f64>>;
type Error = Error;
type SerializeSeq = SerializeLineStringVec;
type SerializeTuple = Impossible<Vec<LineString<f64>>, Error>;
type SerializeTupleStruct = Impossible<Vec<LineString<f64>>, Error>;
type SerializeTupleVariant = Impossible<Vec<LineString<f64>>, Error>;
type SerializeMap = Impossible<Vec<LineString<f64>>, Error>;
type SerializeStruct = Impossible<Vec<LineString<f64>>, Error>;
type SerializeStructVariant = Impossible<Vec<LineString<f64>>, Error>;
const EXPECTED: &'static str = "a `Vec<LineString<f64>>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeLineStringVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeLineStringVec(Vec<LineString<f64>>);
impl serde::ser::SerializeSeq for SerializeLineStringVec {
type Ok = Vec<LineString<f64>>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(LineString(value.serialize(ser::geometry::coord::vec::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use geo::Coord;
#[test]
fn empty() {
let vec: Vec<LineString<f64>> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![LineString(vec![Coord::default()])];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,155 +0,0 @@
pub(super) mod coord;
pub(super) mod line_string;
pub(super) mod point;
pub(super) mod polygon;
pub(super) mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Geometry;
use geo::LineString;
use geo::MultiLineString;
use geo::MultiPoint;
use geo::MultiPolygon;
use geo::Point;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Geometry;
type Error = Error;
type SerializeSeq = SerializeGeometryVec;
type SerializeTuple = Impossible<Geometry, Error>;
type SerializeTupleStruct = Impossible<Geometry, Error>;
type SerializeTupleVariant = Impossible<Geometry, Error>;
type SerializeMap = Impossible<Geometry, Error>;
type SerializeStruct = Impossible<Geometry, Error>;
type SerializeStructVariant = Impossible<Geometry, Error>;
const EXPECTED: &'static str = "an enum `Geometry`";
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Point" => Ok(Geometry::Point(Point(
value.serialize(ser::geometry::coord::Serializer.wrap())?,
))),
"Line" => Ok(Geometry::Line(LineString(
value.serialize(ser::geometry::coord::vec::Serializer.wrap())?,
))),
"Polygon" => {
Ok(Geometry::Polygon(value.serialize(ser::geometry::polygon::Serializer.wrap())?))
}
"MultiPoint" => Ok(Geometry::MultiPoint(MultiPoint(
value.serialize(ser::geometry::point::vec::Serializer.wrap())?,
))),
"MultiLine" => Ok(Geometry::MultiLine(MultiLineString(
value.serialize(ser::geometry::line_string::vec::Serializer.wrap())?,
))),
"MultiPolygon" => Ok(Geometry::MultiPolygon(MultiPolygon(
value.serialize(ser::geometry::polygon::vec::Serializer.wrap())?,
))),
"Collection" => {
Ok(Geometry::Collection(value.serialize(ser::geometry::vec::Serializer.wrap())?))
}
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
let serialize_seq = vec::SerializeGeometryVec(Vec::with_capacity(len.unwrap_or_default()));
Ok(SerializeGeometryVec(serialize_seq))
}
}
pub(super) struct SerializeGeometryVec(vec::SerializeGeometryVec);
impl serde::ser::SerializeSeq for SerializeGeometryVec {
type Ok = Geometry;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.serialize_element(value)
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(Geometry::Collection(self.0.end()?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use geo::Coord;
use geo::Polygon;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn point() {
let geometry = Geometry::Point(Default::default());
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn line() {
let geometry = Geometry::Line(LineString(vec![Coord::default()]));
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn polygon() {
let polygon = Polygon::new(LineString(Vec::new()), Vec::new());
let geometry = Geometry::Polygon(polygon);
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn multi_point() {
let geometry = Geometry::MultiPoint(vec![(0., 0.), (1., 2.)].into());
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn multi_line() {
let geometry = Geometry::MultiLine(MultiLineString::new(Vec::new()));
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn multi_polygon() {
let geometry = Geometry::MultiPolygon(MultiPolygon::new(Vec::new()));
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
#[test]
fn collection() {
let geometry = Geometry::Collection(vec![Geometry::Point(Default::default())]);
let serialized = geometry.serialize(Serializer.wrap()).unwrap();
assert_eq!(geometry, serialized);
}
}

View file

@ -1 +0,0 @@
pub mod vec;

View file

@ -1,79 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::Point;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Point<f64>>;
type Error = Error;
type SerializeSeq = SerializePointVec;
type SerializeTuple = Impossible<Vec<Point<f64>>, Error>;
type SerializeTupleStruct = Impossible<Vec<Point<f64>>, Error>;
type SerializeTupleVariant = Impossible<Vec<Point<f64>>, Error>;
type SerializeMap = Impossible<Vec<Point<f64>>, Error>;
type SerializeStruct = Impossible<Vec<Point<f64>>, Error>;
type SerializeStructVariant = Impossible<Vec<Point<f64>>, Error>;
const EXPECTED: &'static str = "a `Vec<Point<f64>>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializePointVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializePointVec(Vec<Point<f64>>);
impl serde::ser::SerializeSeq for SerializePointVec {
type Ok = Vec<Point<f64>>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Point(value.serialize(ser::geometry::coord::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Point<f64>> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Point::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,87 +0,0 @@
pub mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::LineString;
use geo::Polygon;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Polygon<f64>;
type Error = Error;
type SerializeSeq = Impossible<Polygon<f64>, Error>;
type SerializeTuple = Impossible<Polygon<f64>, Error>;
type SerializeTupleStruct = Impossible<Polygon<f64>, Error>;
type SerializeTupleVariant = Impossible<Polygon<f64>, Error>;
type SerializeMap = Impossible<Polygon<f64>, Error>;
type SerializeStruct = SerializePolygon;
type SerializeStructVariant = Impossible<Polygon<f64>, Error>;
const EXPECTED: &'static str = "a struct `Polygon<f64>`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializePolygon::default())
}
}
#[derive(Default)]
pub(super) struct SerializePolygon {
exterior: Option<LineString<f64>>,
interiors: Option<Vec<LineString<f64>>>,
}
impl serde::ser::SerializeStruct for SerializePolygon {
type Ok = Polygon<f64>;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"exterior" => {
self.exterior = Some(LineString(
value.serialize(ser::geometry::coord::vec::Serializer.wrap())?,
));
}
"interiors" => {
self.interiors =
Some(value.serialize(ser::geometry::line_string::vec::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected field `Polygon::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.exterior, self.interiors) {
(Some(exterior), Some(interiors)) => Ok(Polygon::new(exterior, interiors)),
_ => Err(Error::custom("`Polygon` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let polygon = Polygon::new(LineString(Vec::new()), Vec::new());
let serialized = polygon.serialize(Serializer.wrap()).unwrap();
assert_eq!(polygon, serialized);
}
}

View file

@ -1,80 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use geo::Polygon;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Polygon<f64>>;
type Error = Error;
type SerializeSeq = SerializePolygonVec;
type SerializeTuple = Impossible<Vec<Polygon<f64>>, Error>;
type SerializeTupleStruct = Impossible<Vec<Polygon<f64>>, Error>;
type SerializeTupleVariant = Impossible<Vec<Polygon<f64>>, Error>;
type SerializeMap = Impossible<Vec<Polygon<f64>>, Error>;
type SerializeStruct = Impossible<Vec<Polygon<f64>>, Error>;
type SerializeStructVariant = Impossible<Vec<Polygon<f64>>, Error>;
const EXPECTED: &'static str = "a `Vec<Polygon<f64>>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializePolygonVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializePolygonVec(Vec<Polygon<f64>>);
impl serde::ser::SerializeSeq for SerializePolygonVec {
type Ok = Vec<Polygon<f64>>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(super::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
use geo::LineString;
#[test]
fn empty() {
let vec: Vec<Polygon<f64>> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Polygon::new(LineString(Vec::new()), Vec::new())];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,67 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Geometry;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Geometry>;
type Error = Error;
type SerializeSeq = SerializeGeometryVec;
type SerializeTuple = Impossible<Vec<Geometry>, Error>;
type SerializeTupleStruct = Impossible<Vec<Geometry>, Error>;
type SerializeTupleVariant = Impossible<Vec<Geometry>, Error>;
type SerializeMap = Impossible<Vec<Geometry>, Error>;
type SerializeStruct = Impossible<Vec<Geometry>, Error>;
type SerializeStructVariant = Impossible<Vec<Geometry>, Error>;
const EXPECTED: &'static str = "a `Vec<Geometry>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeGeometryVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
#[non_exhaustive]
pub struct SerializeGeometryVec(pub(super) Vec<Geometry>);
impl serde::ser::SerializeSeq for SerializeGeometryVec {
type Ok = Vec<Geometry>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(ser::geometry::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Geometry> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Geometry::Point(Default::default())];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,155 +0,0 @@
use crate::err::Error;
use crate::sql::field::Fields;
use crate::sql::group::Groups;
use crate::sql::limit::Limit;
use crate::sql::order::Orders;
use crate::sql::split::Splits;
use crate::sql::start::Start;
use crate::sql::value::serde::ser;
use crate::sql::Cond;
use crate::sql::Dir;
use crate::sql::Graph;
use crate::sql::Idiom;
use crate::sql::Tables;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Graph;
type Error = Error;
type SerializeSeq = Impossible<Graph, Error>;
type SerializeTuple = Impossible<Graph, Error>;
type SerializeTupleStruct = Impossible<Graph, Error>;
type SerializeTupleVariant = Impossible<Graph, Error>;
type SerializeMap = Impossible<Graph, Error>;
type SerializeStruct = SerializeGraph;
type SerializeStructVariant = Impossible<Graph, Error>;
const EXPECTED: &'static str = "a struct `Graph`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeGraph::default())
}
}
#[derive(Default)]
pub(super) struct SerializeGraph {
dir: Option<Dir>,
expr: Option<Fields>,
what: Option<Tables>,
cond: Option<Cond>,
split: Option<Splits>,
group: Option<Groups>,
order: Option<Orders>,
limit: Option<Limit>,
start: Option<Start>,
alias: Option<Idiom>,
}
impl serde::ser::SerializeStruct for SerializeGraph {
type Ok = Graph;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"dir" => {
self.dir = Some(value.serialize(ser::dir::Serializer.wrap())?);
}
"expr" => {
self.expr = Some(value.serialize(ser::fields::Serializer.wrap())?);
}
"what" => {
self.what = Some(Tables(value.serialize(ser::table::vec::Serializer.wrap())?));
}
"cond" => {
self.cond = value.serialize(ser::cond::opt::Serializer.wrap())?;
}
"split" => {
self.split = value.serialize(ser::split::vec::opt::Serializer.wrap())?.map(Splits);
}
"group" => {
self.group = value.serialize(ser::group::vec::opt::Serializer.wrap())?.map(Groups);
}
"order" => {
self.order = value.serialize(ser::order::vec::opt::Serializer.wrap())?.map(Orders);
}
"limit" => {
self.limit = value.serialize(ser::limit::opt::Serializer.wrap())?;
}
"start" => {
self.start = value.serialize(ser::start::opt::Serializer.wrap())?;
}
"alias" => {
self.alias = value.serialize(ser::part::vec::opt::Serializer.wrap())?.map(Idiom);
}
key => {
return Err(Error::custom(format!("unexpected field `Graph::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.dir, self.expr, self.what) {
(Some(dir), Some(expr), Some(what)) => Ok(Graph {
dir,
expr,
what,
cond: self.cond,
split: self.split,
group: self.group,
order: self.order,
limit: self.limit,
start: self.start,
alias: self.alias,
}),
_ => Err(Error::custom("`Graph` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn default() {
let graph = Graph::default();
let serialized = graph.serialize(Serializer.wrap()).unwrap();
assert_eq!(graph, serialized);
}
#[test]
fn with_cond() {
let graph = Graph {
cond: Some(Default::default()),
..Default::default()
};
let serialized = graph.serialize(Serializer.wrap()).unwrap();
assert_eq!(graph, serialized);
}
#[test]
fn with_alias() {
let graph = Graph {
alias: Some(Default::default()),
..Default::default()
};
let serialized = graph.serialize(Serializer.wrap()).unwrap();
assert_eq!(graph, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod vec;

View file

@ -1,82 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Group;
use crate::sql::Idiom;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Group>;
type Error = Error;
type SerializeSeq = SerializeGroupVec;
type SerializeTuple = Impossible<Vec<Group>, Error>;
type SerializeTupleStruct = Impossible<Vec<Group>, Error>;
type SerializeTupleVariant = Impossible<Vec<Group>, Error>;
type SerializeMap = Impossible<Vec<Group>, Error>;
type SerializeStruct = Impossible<Vec<Group>, Error>;
type SerializeStructVariant = Impossible<Vec<Group>, Error>;
const EXPECTED: &'static str = "a `Vec<Group>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeGroupVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeGroupVec(Vec<Group>);
impl serde::ser::SerializeSeq for SerializeGroupVec {
type Ok = Vec<Group>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Group(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?)));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Group> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Group::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Group;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Group>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Group>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Group>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Group>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Group>>, Error>;
type SerializeMap = Impossible<Option<Vec<Group>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Group>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Group>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Group>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Group>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Group::default()]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,84 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Array;
use crate::sql::Id;
use crate::sql::Object;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Id;
type Error = Error;
type SerializeSeq = Impossible<Id, Error>;
type SerializeTuple = Impossible<Id, Error>;
type SerializeTupleStruct = Impossible<Id, Error>;
type SerializeTupleVariant = Impossible<Id, Error>;
type SerializeMap = Impossible<Id, Error>;
type SerializeStruct = Impossible<Id, Error>;
type SerializeStructVariant = Impossible<Id, Error>;
const EXPECTED: &'static str = "an enum `Id`";
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Number" => Ok(Id::Number(value.serialize(ser::primitive::i64::Serializer.wrap())?)),
"String" => Ok(Id::String(value.serialize(ser::string::Serializer.wrap())?)),
"Array" => Ok(Id::Array(Array(value.serialize(ser::value::vec::Serializer.wrap())?))),
"Object" => {
Ok(Id::Object(Object(value.serialize(ser::value::map::Serializer.wrap())?)))
}
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn number() {
let id = Id::Number(Default::default());
let serialized = id.serialize(Serializer.wrap()).unwrap();
assert_eq!(id, serialized);
}
#[test]
fn string() {
let id = Id::String(Default::default());
let serialized = id.serialize(Serializer.wrap()).unwrap();
assert_eq!(id, serialized);
}
#[test]
fn array() {
let id = Id::Array(Default::default());
let serialized = id.serialize(Serializer.wrap()).unwrap();
assert_eq!(id, serialized);
}
#[test]
fn object() {
let id = Id::Object(Default::default());
let serialized = id.serialize(Serializer.wrap()).unwrap();
assert_eq!(id, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod vec;

View file

@ -1,67 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Ident;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Ident>;
type Error = Error;
type SerializeSeq = SerializeIdentVec;
type SerializeTuple = Impossible<Vec<Ident>, Error>;
type SerializeTupleStruct = Impossible<Vec<Ident>, Error>;
type SerializeTupleVariant = Impossible<Vec<Ident>, Error>;
type SerializeMap = Impossible<Vec<Ident>, Error>;
type SerializeStruct = Impossible<Vec<Ident>, Error>;
type SerializeStructVariant = Impossible<Vec<Ident>, Error>;
const EXPECTED: &'static str = "a `Vec<Ident>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdentVec(Vec::with_capacity(len.unwrap_or_default())))
}
}
#[non_exhaustive]
pub struct SerializeIdentVec(Vec<Ident>);
impl serde::ser::SerializeSeq for SerializeIdentVec {
type Ok = Vec<Ident>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Ident(value.serialize(ser::string::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Ident> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Ident::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod vec;

View file

@ -1,81 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Idiom;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Idiom>;
type Error = Error;
type SerializeSeq = SerializeIdiomVec;
type SerializeTuple = Impossible<Vec<Idiom>, Error>;
type SerializeTupleStruct = Impossible<Vec<Idiom>, Error>;
type SerializeTupleVariant = Impossible<Vec<Idiom>, Error>;
type SerializeMap = Impossible<Vec<Idiom>, Error>;
type SerializeStruct = Impossible<Vec<Idiom>, Error>;
type SerializeStructVariant = Impossible<Vec<Idiom>, Error>;
const EXPECTED: &'static str = "a `Vec<Idiom>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeIdiomVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeIdiomVec(Vec<Idiom>);
impl serde::ser::SerializeSeq for SerializeIdiomVec {
type Ok = Vec<Idiom>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Idiom> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Idiom::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Idiom;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Idiom>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeMap = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Idiom>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Idiom>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Idiom>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Idiom>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Idiom::default()]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,104 +0,0 @@
mod mtreeparams;
mod searchparams;
use crate::err::Error;
use crate::sql::index::Index;
use crate::sql::value::serde::ser;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Index;
type Error = Error;
type SerializeSeq = Impossible<Index, Error>;
type SerializeTuple = Impossible<Index, Error>;
type SerializeTupleStruct = Impossible<Index, Error>;
type SerializeTupleVariant = Impossible<Index, Error>;
type SerializeMap = Impossible<Index, Error>;
type SerializeStruct = Impossible<Index, Error>;
type SerializeStructVariant = Impossible<Index, Error>;
const EXPECTED: &'static str = "an enum `Index`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Idx" => Ok(Index::Idx),
"Uniq" => Ok(Index::Uniq),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Search" => Ok(Index::Search(value.serialize(searchparams::Serializer.wrap())?)),
"MTree" => Ok(Index::MTree(value.serialize(mtreeparams::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sql::index::SearchParams;
use crate::sql::value::serde::ser::Serializer;
use crate::sql::Scoring;
#[test]
fn idx() {
let idx = Index::Idx;
let serialized = idx.serialize(Serializer.wrap()).unwrap();
assert_eq!(idx, serialized);
}
#[test]
fn uniq() {
let idx = Index::Uniq;
let serialized = idx.serialize(Serializer.wrap()).unwrap();
assert_eq!(idx, serialized);
}
#[test]
fn search() {
let idx = Index::Search(SearchParams {
az: Default::default(),
hl: Default::default(),
sc: Scoring::Bm {
k1: Default::default(),
b: Default::default(),
},
doc_ids_order: 1,
doc_lengths_order: 2,
postings_order: 3,
terms_order: 4,
doc_ids_cache: 5,
doc_lengths_cache: 6,
postings_cache: 7,
terms_cache: 8,
});
let serialized = idx.serialize(Serializer.wrap()).unwrap();
assert_eq!(idx, serialized);
}
}

View file

@ -1,116 +0,0 @@
use crate::err::Error;
use crate::sql::index::{Distance, Distance1, MTreeParams, VectorType};
use crate::sql::value::serde::ser;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = MTreeParams;
type Error = Error;
type SerializeSeq = Impossible<MTreeParams, Error>;
type SerializeTuple = Impossible<MTreeParams, Error>;
type SerializeTupleStruct = Impossible<MTreeParams, Error>;
type SerializeTupleVariant = Impossible<MTreeParams, Error>;
type SerializeMap = Impossible<MTreeParams, Error>;
type SerializeStruct = SerializeMTree;
type SerializeStructVariant = Impossible<MTreeParams, Error>;
const EXPECTED: &'static str = "a struct `MTreeParams`";
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeMTree::default())
}
}
#[derive(Default)]
pub(super) struct SerializeMTree {
dimension: u16,
distance: Distance,
vector_type: VectorType,
capacity: u16,
doc_ids_order: u32,
doc_ids_cache: u32,
mtree_cache: u32,
}
impl serde::ser::SerializeStruct for SerializeMTree {
type Ok = MTreeParams;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"dimension" => {
self.dimension = value.serialize(ser::primitive::u16::Serializer.wrap())?;
}
"_distance" => {
self.distance = value.serialize(ser::distance::Serializer.wrap())?;
}
"distance" => {
self.distance = value.serialize(ser::distance::Serializer.wrap())?;
}
"vector_type" => {
self.vector_type = value.serialize(ser::vectortype::Serializer.wrap())?;
}
"capacity" => {
self.capacity = value.serialize(ser::primitive::u16::Serializer.wrap())?;
}
"doc_ids_order" => {
self.doc_ids_order = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"doc_ids_cache" => {
self.doc_ids_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"mtree_cache" => {
self.mtree_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `MTreeParams {{ {key} }}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(MTreeParams {
dimension: self.dimension,
_distance: Distance1::Euclidean,
distance: self.distance,
vector_type: self.vector_type,
capacity: self.capacity,
doc_ids_order: self.doc_ids_order,
doc_ids_cache: self.doc_ids_cache,
mtree_cache: self.mtree_cache,
})
}
}
#[test]
fn mtree_params() {
let params = MTreeParams::new(1, Default::default(), Default::default(), 2, 3, 4, 5);
let serialized = params.serialize(Serializer.wrap()).unwrap();
assert_eq!(params, serialized);
}

View file

@ -1,149 +0,0 @@
use crate::err::Error;
use crate::sql::index::SearchParams;
use crate::sql::value::serde::ser;
use crate::sql::{Ident, Scoring};
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = SearchParams;
type Error = Error;
type SerializeSeq = Impossible<SearchParams, Error>;
type SerializeTuple = Impossible<SearchParams, Error>;
type SerializeTupleStruct = Impossible<SearchParams, Error>;
type SerializeTupleVariant = Impossible<SearchParams, Error>;
type SerializeMap = Impossible<SearchParams, Error>;
type SerializeStruct = SerializeSearch;
type SerializeStructVariant = Impossible<SearchParams, Error>;
const EXPECTED: &'static str = "a struct `SearchParams`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeSearch::default())
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[derive(Default)]
pub(super) struct SerializeSearch {
az: Ident,
hl: bool,
sc: Option<Scoring>,
doc_ids_order: u32,
doc_lengths_order: u32,
postings_order: u32,
terms_order: u32,
doc_ids_cache: u32,
doc_lengths_cache: u32,
postings_cache: u32,
terms_cache: u32,
}
impl serde::ser::SerializeStruct for SerializeSearch {
type Ok = SearchParams;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"az" => {
self.az = Ident(value.serialize(ser::string::Serializer.wrap())?);
}
"hl" => {
self.hl = value.serialize(ser::primitive::bool::Serializer.wrap())?;
}
"sc" => {
self.sc = Some(value.serialize(ser::scoring::Serializer.wrap())?);
}
"doc_ids_order" => {
self.doc_ids_order = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"doc_lengths_order" => {
self.doc_lengths_order = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"postings_order" => {
self.postings_order = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"terms_order" => {
self.terms_order = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"doc_ids_cache" => {
self.doc_ids_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"doc_lengths_cache" => {
self.doc_lengths_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"postings_cache" => {
self.postings_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
"terms_cache" => {
self.terms_cache = value.serialize(ser::primitive::u32::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `SearchParams {{ {key} }}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match self.sc {
Some(sc) => Ok(SearchParams {
az: self.az,
hl: self.hl,
sc,
doc_ids_order: self.doc_ids_order,
doc_lengths_order: self.doc_lengths_order,
postings_order: self.postings_order,
terms_order: self.terms_order,
doc_ids_cache: self.doc_ids_cache,
doc_lengths_cache: self.doc_lengths_cache,
postings_cache: self.postings_cache,
terms_cache: self.terms_cache,
}),
_ => Err(Error::custom("`SearchParams` missing required field(s)")),
}
}
}
#[test]
fn search_params() {
let params = SearchParams {
az: Default::default(),
hl: false,
sc: Scoring::Vs,
doc_ids_order: 1,
doc_lengths_order: 2,
postings_order: 3,
terms_order: 4,
doc_ids_cache: 5,
doc_lengths_cache: 6,
postings_cache: 7,
terms_cache: 8,
};
let serialized = params.serialize(Serializer.wrap()).unwrap();
assert_eq!(params, serialized);
}

View file

@ -1,316 +0,0 @@
pub(super) mod opt;
pub(super) mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Kind;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Kind;
type Error = Error;
type SerializeSeq = Impossible<Kind, Error>;
type SerializeTuple = Impossible<Kind, Error>;
type SerializeTupleStruct = Impossible<Kind, Error>;
type SerializeTupleVariant = SerializeKindTuple;
type SerializeMap = Impossible<Kind, Error>;
type SerializeStruct = Impossible<Kind, Error>;
type SerializeStructVariant = Impossible<Kind, Error>;
const EXPECTED: &'static str = "an enum `Kind`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Any" => Ok(Kind::Any),
"Null" => Ok(Kind::Null),
"Bool" => Ok(Kind::Bool),
"Bytes" => Ok(Kind::Bytes),
"Datetime" => Ok(Kind::Datetime),
"Decimal" => Ok(Kind::Decimal),
"Duration" => Ok(Kind::Duration),
"Float" => Ok(Kind::Float),
"Int" => Ok(Kind::Int),
"Number" => Ok(Kind::Number),
"Object" => Ok(Kind::Object),
"Point" => Ok(Kind::Point),
"String" => Ok(Kind::String),
"Uuid" => Ok(Kind::Uuid),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Record" => Ok(Kind::Record(value.serialize(ser::table::vec::Serializer.wrap())?)),
"Geometry" => Ok(Kind::Geometry(value.serialize(ser::string::vec::Serializer.wrap())?)),
"Option" => Ok(Kind::Option(Box::new(value.serialize(Serializer.wrap())?))),
"Either" => Ok(Kind::Either(value.serialize(vec::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
#[inline]
fn serialize_tuple_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let inner = match variant {
"Set" => Inner::Set(Default::default(), Default::default()),
"Array" => Inner::Array(Default::default(), Default::default()),
"Function" => Inner::Function(Default::default(), Default::default()),
variant => {
return Err(Error::custom(format!("unexpected tuple variant `{name}::{variant}`")));
}
};
Ok(SerializeKindTuple {
inner,
index: 0,
})
}
}
pub(super) struct SerializeKindTuple {
index: usize,
inner: Inner,
}
enum Inner {
Set(Box<Kind>, Option<u64>),
Array(Box<Kind>, Option<u64>),
Function(Option<Vec<Kind>>, Option<Box<Kind>>),
}
impl serde::ser::SerializeTupleVariant for SerializeKindTuple {
type Ok = Kind;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match (self.index, &mut self.inner) {
(0, Inner::Set(ref mut var, _) | Inner::Array(ref mut var, _)) => {
*var = Box::new(value.serialize(Serializer.wrap())?);
}
(1, Inner::Set(_, ref mut var) | Inner::Array(_, ref mut var)) => {
*var = value.serialize(ser::primitive::u64::opt::Serializer.wrap())?;
}
(0, Inner::Function(ref mut var, _)) => {
*var = value.serialize(ser::kind::vec::opt::Serializer.wrap())?;
}
(1, Inner::Function(_, ref mut var)) => {
*var = value.serialize(ser::kind::opt::Serializer.wrap())?.map(Box::new);
}
(index, inner) => {
let variant = match inner {
Inner::Set(..) => "Set",
Inner::Array(..) => "Array",
Inner::Function(..) => "Function",
};
return Err(Error::custom(format!("unexpected `Kind::{variant}` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self.inner {
Inner::Set(one, two) => Ok(Kind::Set(one, two)),
Inner::Array(one, two) => Ok(Kind::Array(one, two)),
Inner::Function(one, two) => Ok(Kind::Function(one, two)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn any() {
let kind = Kind::Any;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn bool() {
let kind = Kind::Bool;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn bytes() {
let kind = Kind::Bytes;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn datetime() {
let kind = Kind::Datetime;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn decimal() {
let kind = Kind::Decimal;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn duration() {
let kind = Kind::Duration;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn float() {
let kind = Kind::Float;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn int() {
let kind = Kind::Int;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn number() {
let kind = Kind::Number;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn object() {
let kind = Kind::Object;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn point() {
let kind = Kind::Point;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn string() {
let kind = Kind::String;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn uuid() {
let kind = Kind::Uuid;
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn function() {
let kind = Kind::Function(Default::default(), Default::default());
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn record() {
let kind = Kind::Record(Default::default());
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
let kind = Kind::Record(vec![Default::default()]);
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn geometry() {
let kind = Kind::Geometry(Default::default());
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
let kind = Kind::Geometry(vec![Default::default()]);
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn option() {
let kind = Kind::Option(Box::default());
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn either() {
let kind = Kind::Either(Default::default());
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
let kind = Kind::Either(vec![Default::default()]);
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn set() {
let kind = Kind::Set(Box::default(), None);
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
let kind = Kind::Set(Box::default(), Some(Default::default()));
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
#[test]
fn array() {
let kind = Kind::Array(Box::default(), None);
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
let kind = Kind::Array(Box::default(), Some(Default::default()));
let serialized = kind.serialize(Serializer.wrap()).unwrap();
assert_eq!(kind, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Kind;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Kind>;
type Error = Error;
type SerializeSeq = Impossible<Option<Kind>, Error>;
type SerializeTuple = Impossible<Option<Kind>, Error>;
type SerializeTupleStruct = Impossible<Option<Kind>, Error>;
type SerializeTupleVariant = Impossible<Option<Kind>, Error>;
type SerializeMap = Impossible<Option<Kind>, Error>;
type SerializeStruct = Impossible<Option<Kind>, Error>;
type SerializeStructVariant = Impossible<Option<Kind>, Error>;
const EXPECTED: &'static str = "an `Option<Kind>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Kind> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Kind::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,81 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Kind;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub mod opt;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Kind>;
type Error = Error;
type SerializeSeq = SerializeKindVec;
type SerializeTuple = Impossible<Vec<Kind>, Error>;
type SerializeTupleStruct = Impossible<Vec<Kind>, Error>;
type SerializeTupleVariant = Impossible<Vec<Kind>, Error>;
type SerializeMap = Impossible<Vec<Kind>, Error>;
type SerializeStruct = Impossible<Vec<Kind>, Error>;
type SerializeStructVariant = Impossible<Vec<Kind>, Error>;
const EXPECTED: &'static str = "a `Vec<Kind>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeKindVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeKindVec(Vec<Kind>);
impl serde::ser::SerializeSeq for SerializeKindVec {
type Ok = Vec<Kind>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(ser::kind::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Kind> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Kind::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Kind;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Kind>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Kind>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Kind>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Kind>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Kind>>, Error>;
type SerializeMap = Impossible<Option<Vec<Kind>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Kind>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Kind>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Kind>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Kind>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Kind::default()]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,65 +0,0 @@
use crate::err::Error;
use crate::sql::language::Language;
use crate::sql::value::serde::ser;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Language;
type Error = Error;
type SerializeSeq = Impossible<Language, Error>;
type SerializeTuple = Impossible<Language, Error>;
type SerializeTupleStruct = Impossible<Language, Error>;
type SerializeTupleVariant = Impossible<Language, Error>;
type SerializeMap = Impossible<Language, Error>;
type SerializeStruct = Impossible<Language, Error>;
type SerializeStructVariant = Impossible<Language, Error>;
const EXPECTED: &'static str = "an enum `Language`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Arabic" => Ok(Language::Arabic),
"Danish" => Ok(Language::Danish),
"Dutch" => Ok(Language::Dutch),
"English" => Ok(Language::English),
"French" => Ok(Language::French),
"German" => Ok(Language::German),
"Greek" => Ok(Language::Greek),
"Hungarian" => Ok(Language::Hungarian),
"Italian" => Ok(Language::Italian),
"Norwegian" => Ok(Language::Norwegian),
"Portuguese" => Ok(Language::Portuguese),
"Romanian" => Ok(Language::Romanian),
"Russian" => Ok(Language::Russian),
"Spanish" => Ok(Language::Spanish),
"Swedish" => Ok(Language::Swedish),
"Tamil" => Ok(Language::Tamil),
"Turkish" => Ok(Language::Turkish),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::ser::Serialize;
#[test]
fn english() {
let perm = Language::English;
let serialized = perm.serialize(Serializer.wrap()).unwrap();
assert_eq!(perm, serialized);
}
}

View file

@ -1 +0,0 @@
pub(super) mod opt;

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Limit;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Limit>;
type Error = Error;
type SerializeSeq = Impossible<Option<Limit>, Error>;
type SerializeTuple = Impossible<Option<Limit>, Error>;
type SerializeTupleStruct = Impossible<Option<Limit>, Error>;
type SerializeTupleVariant = Impossible<Option<Limit>, Error>;
type SerializeMap = Impossible<Option<Limit>, Error>;
type SerializeStruct = Impossible<Option<Limit>, Error>;
type SerializeStructVariant = Impossible<Option<Limit>, Error>;
const EXPECTED: &'static str = "an `Option<Limit>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(Limit(value.serialize(ser::value::Serializer.wrap())?)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Limit> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Limit::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,113 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Mock;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Mock;
type Error = Error;
type SerializeSeq = Impossible<Mock, Error>;
type SerializeTuple = Impossible<Mock, Error>;
type SerializeTupleStruct = Impossible<Mock, Error>;
type SerializeTupleVariant = SerializeMock;
type SerializeMap = Impossible<Mock, Error>;
type SerializeStruct = Impossible<Mock, Error>;
type SerializeStructVariant = Impossible<Mock, Error>;
const EXPECTED: &'static str = "an enum `Mock`";
fn serialize_tuple_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let inner = match variant {
"Count" => Inner::Count(None, None),
"Range" => Inner::Range(None, None, None),
variant => {
return Err(Error::custom(format!("unexpected tuple variant `{name}::{variant}`")));
}
};
Ok(SerializeMock {
inner,
index: 0,
})
}
}
pub(super) struct SerializeMock {
index: usize,
inner: Inner,
}
enum Inner {
Count(Option<String>, Option<u64>),
Range(Option<String>, Option<u64>, Option<u64>),
}
impl serde::ser::SerializeTupleVariant for SerializeMock {
type Ok = Mock;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match (self.index, &mut self.inner) {
(0, Inner::Count(ref mut var, _) | Inner::Range(ref mut var, ..)) => {
*var = Some(value.serialize(ser::string::Serializer.wrap())?);
}
(1, Inner::Count(_, ref mut var) | Inner::Range(_, ref mut var, _)) => {
*var = Some(value.serialize(ser::primitive::u64::Serializer.wrap())?);
}
(2, Inner::Range(.., ref mut var)) => {
*var = Some(value.serialize(ser::primitive::u64::Serializer.wrap())?);
}
(index, inner) => {
let variant = match inner {
Inner::Count(..) => "Count",
Inner::Range(..) => "Range",
};
return Err(Error::custom(format!("unexpected `Mock::{variant}` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self.inner {
Inner::Count(Some(one), Some(two)) => Ok(Mock::Count(one, two)),
Inner::Range(Some(one), Some(two), Some(three)) => Ok(Mock::Range(one, two, three)),
_ => Err(Error::custom("`Mock` missing required value(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn count() {
let model = Mock::Count(Default::default(), Default::default());
let serialized = model.serialize(Serializer.wrap()).unwrap();
assert_eq!(model, serialized);
}
#[test]
fn range() {
let model = Mock::Range(Default::default(), 1, 2);
let serialized = model.serialize(Serializer.wrap()).unwrap();
assert_eq!(model, serialized);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,137 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Number;
use rust_decimal::Decimal;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Number;
type Error = Error;
type SerializeSeq = Impossible<Number, Error>;
type SerializeTuple = Impossible<Number, Error>;
type SerializeTupleStruct = Impossible<Number, Error>;
type SerializeTupleVariant = Impossible<Number, Error>;
type SerializeMap = Impossible<Number, Error>;
type SerializeStruct = Impossible<Number, Error>;
type SerializeStructVariant = Impossible<Number, Error>;
const EXPECTED: &'static str = "an enum `Number`";
#[inline]
fn serialize_i8(self, value: i8) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_i16(self, value: i16) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_i32(self, value: i32) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_i64(self, value: i64) -> Result<Self::Ok, Error> {
Ok(value.into())
}
fn serialize_i128(self, value: i128) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_u8(self, value: u8) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_u16(self, value: u16) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_u32(self, value: u32) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_u64(self, value: u64) -> Result<Self::Ok, Error> {
Ok(value.into())
}
fn serialize_u128(self, value: u128) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_f32(self, value: f32) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_f64(self, value: f64) -> Result<Self::Ok, Error> {
Ok(value.into())
}
#[inline]
fn serialize_str(self, value: &str) -> Result<Self::Ok, Error> {
let decimal = value.parse::<Decimal>().map_err(Error::custom)?;
Ok(decimal.into())
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Int" => Ok(Number::Int(value.serialize(ser::primitive::i64::Serializer.wrap())?)),
"Float" => Ok(Number::Float(value.serialize(ser::primitive::f64::Serializer.wrap())?)),
"Decimal" => Ok(Number::Decimal(value.serialize(ser::decimal::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn int() {
let number = Number::Int(Default::default());
let serialized = number.serialize(Serializer.wrap()).unwrap();
assert_eq!(number, serialized);
}
#[test]
fn float() {
let number = Number::Float(Default::default());
let serialized = number.serialize(Serializer.wrap()).unwrap();
assert_eq!(number, serialized);
}
#[test]
fn decimal() {
let number = Number::Decimal(Default::default());
let serialized = number.serialize(Serializer.wrap()).unwrap();
assert_eq!(number, serialized);
}
}

View file

@ -1,331 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Operator;
use serde::ser::Error as _;
use serde::ser::Impossible;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Operator;
type Error = Error;
type SerializeSeq = Impossible<Operator, Error>;
type SerializeTuple = Impossible<Operator, Error>;
type SerializeTupleStruct = Impossible<Operator, Error>;
type SerializeTupleVariant = Impossible<Operator, Error>;
type SerializeMap = Impossible<Operator, Error>;
type SerializeStruct = Impossible<Operator, Error>;
type SerializeStructVariant = Impossible<Operator, Error>;
const EXPECTED: &'static str = "an enum `Operator`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"Neg" => Ok(Operator::Neg),
"Not" => Ok(Operator::Not),
"Or" => Ok(Operator::Or),
"And" => Ok(Operator::And),
"Tco" => Ok(Operator::Tco),
"Nco" => Ok(Operator::Nco),
"Add" => Ok(Operator::Add),
"Sub" => Ok(Operator::Sub),
"Mul" => Ok(Operator::Mul),
"Div" => Ok(Operator::Div),
"Pow" => Ok(Operator::Pow),
"Inc" => Ok(Operator::Inc),
"Dec" => Ok(Operator::Dec),
"Equal" => Ok(Operator::Equal),
"Exact" => Ok(Operator::Exact),
"NotEqual" => Ok(Operator::NotEqual),
"AllEqual" => Ok(Operator::AllEqual),
"AnyEqual" => Ok(Operator::AnyEqual),
"Like" => Ok(Operator::Like),
"NotLike" => Ok(Operator::NotLike),
"AllLike" => Ok(Operator::AllLike),
"AnyLike" => Ok(Operator::AnyLike),
"LessThan" => Ok(Operator::LessThan),
"LessThanOrEqual" => Ok(Operator::LessThanOrEqual),
"MoreThan" => Ok(Operator::MoreThan),
"MoreThanOrEqual" => Ok(Operator::MoreThanOrEqual),
"Contain" => Ok(Operator::Contain),
"NotContain" => Ok(Operator::NotContain),
"ContainAll" => Ok(Operator::ContainAll),
"ContainAny" => Ok(Operator::ContainAny),
"ContainNone" => Ok(Operator::ContainNone),
"Inside" => Ok(Operator::Inside),
"NotInside" => Ok(Operator::NotInside),
"AllInside" => Ok(Operator::AllInside),
"AnyInside" => Ok(Operator::AnyInside),
"NoneInside" => Ok(Operator::NoneInside),
"Outside" => Ok(Operator::Outside),
"Intersects" => Ok(Operator::Intersects),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn or() {
let dir = Operator::Or;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn and() {
let dir = Operator::And;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn tco() {
let dir = Operator::Tco;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn nco() {
let dir = Operator::Nco;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn add() {
let dir = Operator::Add;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn sub() {
let dir = Operator::Sub;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn mul() {
let dir = Operator::Mul;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn div() {
let dir = Operator::Div;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn pow() {
let dir = Operator::Pow;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn inc() {
let dir = Operator::Inc;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn dec() {
let dir = Operator::Dec;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn equal() {
let dir = Operator::Equal;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn exact() {
let dir = Operator::Exact;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn not_equal() {
let dir = Operator::NotEqual;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn all_equal() {
let dir = Operator::AllEqual;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn any_equal() {
let dir = Operator::AnyEqual;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn like() {
let dir = Operator::Like;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn not_like() {
let dir = Operator::NotLike;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn all_like() {
let dir = Operator::AllLike;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn any_like() {
let dir = Operator::AnyLike;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn less_than() {
let dir = Operator::LessThan;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn less_than_or_equal() {
let dir = Operator::LessThanOrEqual;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn more_than() {
let dir = Operator::MoreThan;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn more_than_or_equal() {
let dir = Operator::MoreThanOrEqual;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn contain() {
let dir = Operator::Contain;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn not_contain() {
let dir = Operator::NotContain;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn contain_all() {
let dir = Operator::ContainAll;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn contain_any() {
let dir = Operator::ContainAny;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn contain_none() {
let dir = Operator::ContainNone;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn inside() {
let dir = Operator::Inside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn not_inside() {
let dir = Operator::NotInside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn all_inside() {
let dir = Operator::AllInside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn any_inside() {
let dir = Operator::AnyInside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn none_inside() {
let dir = Operator::NoneInside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn outside() {
let dir = Operator::Outside;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
#[test]
fn intersects() {
let dir = Operator::Intersects;
let serialized = dir.serialize(Serializer.wrap()).unwrap();
assert_eq!(dir, serialized);
}
}

View file

@ -1,105 +0,0 @@
pub(super) mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Idiom;
use crate::sql::Order;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Order;
type Error = Error;
type SerializeSeq = Impossible<Order, Error>;
type SerializeTuple = Impossible<Order, Error>;
type SerializeTupleStruct = Impossible<Order, Error>;
type SerializeTupleVariant = Impossible<Order, Error>;
type SerializeMap = Impossible<Order, Error>;
type SerializeStruct = SerializeOrder;
type SerializeStructVariant = Impossible<Order, Error>;
const EXPECTED: &'static str = "a struct `Order`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializeOrder::default())
}
}
#[derive(Default)]
pub(super) struct SerializeOrder {
order: Option<Idiom>,
random: Option<bool>,
collate: Option<bool>,
numeric: Option<bool>,
direction: Option<bool>,
}
impl serde::ser::SerializeStruct for SerializeOrder {
type Ok = Order;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"order" => {
self.order = Some(Idiom(value.serialize(ser::part::vec::Serializer.wrap())?));
}
"random" => {
self.random = Some(value.serialize(ser::primitive::bool::Serializer.wrap())?);
}
"collate" => {
self.collate = Some(value.serialize(ser::primitive::bool::Serializer.wrap())?);
}
"numeric" => {
self.numeric = Some(value.serialize(ser::primitive::bool::Serializer.wrap())?);
}
"direction" => {
self.direction = Some(value.serialize(ser::primitive::bool::Serializer.wrap())?);
}
key => {
return Err(Error::custom(format!("unexpected field `Order::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
match (self.order, self.random, self.collate, self.numeric, self.direction) {
(Some(order), Some(random), Some(collate), Some(numeric), Some(direction)) => {
Ok(Order {
order,
random,
collate,
numeric,
direction,
})
}
_ => Err(Error::custom("`Order` missing required field(s)")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
#[test]
fn default() {
let order = Order::default();
let serialized = order.serialize(Serializer.wrap()).unwrap();
assert_eq!(order, serialized);
}
}

View file

@ -1,81 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Order;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Order>;
type Error = Error;
type SerializeSeq = SerializeOrderVec;
type SerializeTuple = Impossible<Vec<Order>, Error>;
type SerializeTupleStruct = Impossible<Vec<Order>, Error>;
type SerializeTupleVariant = Impossible<Vec<Order>, Error>;
type SerializeMap = Impossible<Vec<Order>, Error>;
type SerializeStruct = Impossible<Vec<Order>, Error>;
type SerializeStructVariant = Impossible<Vec<Order>, Error>;
const EXPECTED: &'static str = "a `Vec<Order>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializeOrderVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializeOrderVec(Vec<Order>);
impl serde::ser::SerializeSeq for SerializeOrderVec {
type Ok = Vec<Order>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(super::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Order> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Order::default()];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Order;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Order>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Order>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Order>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Order>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Order>>, Error>;
type SerializeMap = Impossible<Option<Vec<Order>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Order>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Order>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Order>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Order>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Order::default()]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,109 +0,0 @@
pub(super) mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Output;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Output;
type Error = Error;
type SerializeSeq = Impossible<Output, Error>;
type SerializeTuple = Impossible<Output, Error>;
type SerializeTupleStruct = Impossible<Output, Error>;
type SerializeTupleVariant = Impossible<Output, Error>;
type SerializeMap = Impossible<Output, Error>;
type SerializeStruct = Impossible<Output, Error>;
type SerializeStructVariant = Impossible<Output, Error>;
const EXPECTED: &'static str = "an enum `Output`";
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"None" => Ok(Output::None),
"Null" => Ok(Output::Null),
"Diff" => Ok(Output::Diff),
"After" => Ok(Output::After),
"Before" => Ok(Output::Before),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Fields" => Ok(Output::Fields(value.serialize(ser::fields::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn none() {
let output = Output::None;
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
#[test]
fn null() {
let output = Output::Null;
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
#[test]
fn diff() {
let output = Output::Diff;
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
#[test]
fn after() {
let output = Output::After;
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
#[test]
fn before() {
let output = Output::Before;
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
#[test]
fn fields() {
let output = Output::Fields(Default::default());
let serialized = output.serialize(Serializer.wrap()).unwrap();
assert_eq!(output, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Output;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Output>;
type Error = Error;
type SerializeSeq = Impossible<Option<Output>, Error>;
type SerializeTuple = Impossible<Option<Output>, Error>;
type SerializeTupleStruct = Impossible<Option<Output>, Error>;
type SerializeTupleVariant = Impossible<Option<Output>, Error>;
type SerializeMap = Impossible<Option<Output>, Error>;
type SerializeStruct = Impossible<Option<Output>, Error>;
type SerializeStructVariant = Impossible<Option<Output>, Error>;
const EXPECTED: &'static str = "an `Option<Output>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Output> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Output::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,206 +0,0 @@
pub(super) mod vec;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Ident;
use crate::sql::Part;
use crate::sql::Value;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Part;
type Error = Error;
type SerializeSeq = Impossible<Part, Error>;
type SerializeTuple = Impossible<Part, Error>;
type SerializeTupleStruct = Impossible<Part, Error>;
type SerializeTupleVariant = SerializePart;
type SerializeMap = Impossible<Part, Error>;
type SerializeStruct = Impossible<Part, Error>;
type SerializeStructVariant = Impossible<Part, Error>;
const EXPECTED: &'static str = "an enum `Part`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"All" => Ok(Part::All),
"Last" => Ok(Part::Last),
"First" => Ok(Part::First),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Field" => Ok(Part::Field(Ident(value.serialize(ser::string::Serializer.wrap())?))),
"Index" => Ok(Part::Index(value.serialize(ser::number::Serializer.wrap())?)),
"Where" => Ok(Part::Where(value.serialize(ser::value::Serializer.wrap())?)),
"Graph" => Ok(Part::Graph(value.serialize(ser::graph::Serializer.wrap())?)),
"Start" => Ok(Part::Start(value.serialize(ser::value::Serializer.wrap())?)),
"Value" => Ok(Part::Value(value.serialize(ser::value::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
fn serialize_tuple_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let inner = match variant {
"Method" => Inner::Method(Default::default(), Default::default()),
variant => {
return Err(Error::custom(format!("unexpected tuple variant `{name}::{variant}`")));
}
};
Ok(SerializePart {
inner,
index: 0,
})
}
}
pub(super) struct SerializePart {
index: usize,
inner: Inner,
}
enum Inner {
Method(String, Vec<Value>),
}
impl serde::ser::SerializeTupleVariant for SerializePart {
type Ok = Part;
type Error = Error;
fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
match (self.index, &mut self.inner) {
(0, Inner::Method(ref mut var, _)) => {
*var = value.serialize(ser::string::Serializer.wrap())?;
}
(1, Inner::Method(_, ref mut var)) => {
*var = value.serialize(ser::value::vec::Serializer.wrap())?;
}
(index, inner) => {
let variant = match inner {
Inner::Method(..) => "Method",
};
return Err(Error::custom(format!("unexpected `Part::{variant}` index `{index}`")));
}
}
self.index += 1;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
match self.inner {
Inner::Method(one, two) => Ok(Part::Method(one, two)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sql;
use ser::Serializer as _;
use serde::Serialize;
#[test]
fn all() {
let part = Part::All;
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn last() {
let part = Part::Last;
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn first() {
let part = Part::First;
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn field() {
let part = Part::Field(Default::default());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn index() {
let part = Part::Index(Default::default());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn r#where() {
let part = Part::Where(Default::default());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn graph() {
let part = Part::Graph(Default::default());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn start() {
let part = Part::Start(sql::thing("foo:bar").unwrap().into());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn value() {
let part = Part::Value(sql::thing("foo:bar").unwrap().into());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
#[test]
fn method() {
let part = Part::Method(Default::default(), Default::default());
let serialized = part.serialize(Serializer.wrap()).unwrap();
assert_eq!(part, serialized);
}
}

View file

@ -1,81 +0,0 @@
pub mod opt;
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Part;
use ser::Serializer as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Vec<Part>;
type Error = Error;
type SerializeSeq = SerializePartVec;
type SerializeTuple = Impossible<Vec<Part>, Error>;
type SerializeTupleStruct = Impossible<Vec<Part>, Error>;
type SerializeTupleVariant = Impossible<Vec<Part>, Error>;
type SerializeMap = Impossible<Vec<Part>, Error>;
type SerializeStruct = Impossible<Vec<Part>, Error>;
type SerializeStructVariant = Impossible<Vec<Part>, Error>;
const EXPECTED: &'static str = "a `Vec<Part>`";
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
Ok(SerializePartVec(Vec::with_capacity(len.unwrap_or_default())))
}
#[inline]
fn serialize_newtype_struct<T>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
value.serialize(self.wrap())
}
}
#[non_exhaustive]
pub struct SerializePartVec(Vec<Part>);
impl serde::ser::SerializeSeq for SerializePartVec {
type Ok = Vec<Part>;
type Error = Error;
fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize + ?Sized,
{
self.0.push(value.serialize(ser::part::Serializer.wrap())?);
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let vec: Vec<Part> = Vec::new();
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
#[test]
fn vec() {
let vec = vec![Part::All];
let serialized = vec.serialize(Serializer.wrap()).unwrap();
assert_eq!(vec, serialized);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Part;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Vec<Part>>;
type Error = Error;
type SerializeSeq = Impossible<Option<Vec<Part>>, Error>;
type SerializeTuple = Impossible<Option<Vec<Part>>, Error>;
type SerializeTupleStruct = Impossible<Option<Vec<Part>>, Error>;
type SerializeTupleVariant = Impossible<Option<Vec<Part>>, Error>;
type SerializeMap = Impossible<Option<Vec<Part>>, Error>;
type SerializeStruct = Impossible<Option<Vec<Part>>, Error>;
type SerializeStructVariant = Impossible<Option<Vec<Part>>, Error>;
const EXPECTED: &'static str = "an `Option<Vec<Part>>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(super::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Vec<Part>> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(vec![Part::All]);
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

View file

@ -1,83 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Permission;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub(super) struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Permission;
type Error = Error;
type SerializeSeq = Impossible<Permission, Error>;
type SerializeTuple = Impossible<Permission, Error>;
type SerializeTupleStruct = Impossible<Permission, Error>;
type SerializeTupleVariant = Impossible<Permission, Error>;
type SerializeMap = Impossible<Permission, Error>;
type SerializeStruct = Impossible<Permission, Error>;
type SerializeStructVariant = Impossible<Permission, Error>;
const EXPECTED: &'static str = "an enum `Permission`";
#[inline]
fn serialize_unit_variant(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Error> {
match variant {
"None" => Ok(Permission::None),
"Full" => Ok(Permission::Full),
variant => Err(Error::custom(format!("unexpected unit variant `{name}::{variant}`"))),
}
}
#[inline]
fn serialize_newtype_variant<T>(
self,
name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Error>
where
T: ?Sized + Serialize,
{
match variant {
"Specific" => Ok(Permission::Specific(value.serialize(ser::value::Serializer.wrap())?)),
variant => {
Err(Error::custom(format!("unexpected newtype variant `{name}::{variant}`")))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let perm = Permission::None;
let serialized = perm.serialize(Serializer.wrap()).unwrap();
assert_eq!(perm, serialized);
}
#[test]
fn full() {
let perm = Permission::Full;
let serialized = perm.serialize(Serializer.wrap()).unwrap();
assert_eq!(perm, serialized);
}
#[test]
fn specific() {
let perm = Permission::Specific(Default::default());
let serialized = perm.serialize(Serializer.wrap()).unwrap();
assert_eq!(perm, serialized);
}
}

View file

@ -1,96 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Permission;
use crate::sql::Permissions;
use ser::Serializer as _;
use serde::ser::Error as _;
use serde::ser::Impossible;
use serde::ser::Serialize;
pub mod opt;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Permissions;
type Error = Error;
type SerializeSeq = Impossible<Permissions, Error>;
type SerializeTuple = Impossible<Permissions, Error>;
type SerializeTupleStruct = Impossible<Permissions, Error>;
type SerializeTupleVariant = Impossible<Permissions, Error>;
type SerializeMap = Impossible<Permissions, Error>;
type SerializeStruct = SerializePermissions;
type SerializeStructVariant = Impossible<Permissions, Error>;
const EXPECTED: &'static str = "a struct `Permissions`";
#[inline]
fn serialize_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Error> {
Ok(SerializePermissions::default())
}
}
#[derive(Default)]
#[non_exhaustive]
pub struct SerializePermissions {
select: Permission,
create: Permission,
update: Permission,
delete: Permission,
}
impl serde::ser::SerializeStruct for SerializePermissions {
type Ok = Permissions;
type Error = Error;
fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Error>
where
T: ?Sized + Serialize,
{
match key {
"select" => {
self.select = value.serialize(ser::permission::Serializer.wrap())?;
}
"create" => {
self.create = value.serialize(ser::permission::Serializer.wrap())?;
}
"update" => {
self.update = value.serialize(ser::permission::Serializer.wrap())?;
}
"delete" => {
self.delete = value.serialize(ser::permission::Serializer.wrap())?;
}
key => {
return Err(Error::custom(format!("unexpected field `Permissions::{key}`")));
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, Error> {
Ok(Permissions {
select: self.select,
create: self.create,
update: self.update,
delete: self.delete,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default() {
let stmt = Permissions::default();
let value: Permissions = stmt.serialize(Serializer.wrap()).unwrap();
assert_eq!(value, stmt);
}
}

View file

@ -1,56 +0,0 @@
use crate::err::Error;
use crate::sql::value::serde::ser;
use crate::sql::Permissions;
use serde::ser::Impossible;
use serde::ser::Serialize;
#[non_exhaustive]
pub struct Serializer;
impl ser::Serializer for Serializer {
type Ok = Option<Permissions>;
type Error = Error;
type SerializeSeq = Impossible<Option<Permissions>, Error>;
type SerializeTuple = Impossible<Option<Permissions>, Error>;
type SerializeTupleStruct = Impossible<Option<Permissions>, Error>;
type SerializeTupleVariant = Impossible<Option<Permissions>, Error>;
type SerializeMap = Impossible<Option<Permissions>, Error>;
type SerializeStruct = Impossible<Option<Permissions>, Error>;
type SerializeStructVariant = Impossible<Option<Permissions>, Error>;
const EXPECTED: &'static str = "an `Option<Permissions>`";
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
Ok(None)
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: ?Sized + Serialize,
{
Ok(Some(value.serialize(ser::permissions::Serializer.wrap())?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ser::Serializer as _;
#[test]
fn none() {
let option: Option<Permissions> = None;
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
#[test]
fn some() {
let option = Some(Permissions::default());
let serialized = option.serialize(Serializer.wrap()).unwrap();
assert_eq!(option, serialized);
}
}

Some files were not shown because too many files have changed in this diff Show more