Skip to content

Commit 2063c92

Browse files
committed
reduce code copy-pastes
1 parent 6ac8f07 commit 2063c92

File tree

3 files changed

+138
-275
lines changed

3 files changed

+138
-275
lines changed

src/ops/shared/postgres.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
use crate::prelude::*;
22

3+
use crate::ops::sdk::*;
34
use crate::settings::DatabaseConnectionSpec;
45
use sqlx::PgPool;
6+
use sqlx::postgres::types::PgRange;
7+
use std::ops::Bound;
58

69
pub async fn get_db_pool(
710
db_ref: Option<&spec::AuthEntryReference<DatabaseConnectionSpec>>,
@@ -18,3 +21,54 @@ pub async fn get_db_pool(
1821
};
1922
Ok(db_pool)
2023
}
24+
25+
pub fn key_value_fields_iter<'a>(
26+
key_fields_schema: &[FieldSchema],
27+
key_value: &'a KeyValue,
28+
) -> Result<&'a [KeyValue]> {
29+
let slice = if key_fields_schema.len() == 1 {
30+
std::slice::from_ref(key_value)
31+
} else {
32+
match key_value {
33+
KeyValue::Struct(fields) => fields,
34+
_ => bail!("expect struct key value"),
35+
}
36+
};
37+
Ok(slice)
38+
}
39+
40+
pub fn bind_key_field<'arg>(
41+
builder: &mut sqlx::QueryBuilder<'arg, sqlx::Postgres>,
42+
key_value: &'arg KeyValue,
43+
) -> Result<()> {
44+
match key_value {
45+
KeyValue::Bytes(v) => {
46+
builder.push_bind(&**v);
47+
}
48+
KeyValue::Str(v) => {
49+
builder.push_bind(&**v);
50+
}
51+
KeyValue::Bool(v) => {
52+
builder.push_bind(v);
53+
}
54+
KeyValue::Int64(v) => {
55+
builder.push_bind(v);
56+
}
57+
KeyValue::Range(v) => {
58+
builder.push_bind(PgRange {
59+
start: Bound::Included(v.start as i64),
60+
end: Bound::Excluded(v.end as i64),
61+
});
62+
}
63+
KeyValue::Uuid(v) => {
64+
builder.push_bind(v);
65+
}
66+
KeyValue::Date(v) => {
67+
builder.push_bind(v);
68+
}
69+
KeyValue::Struct(fields) => {
70+
builder.push_bind(sqlx::types::Json(fields));
71+
}
72+
}
73+
Ok(())
74+
}

0 commit comments

Comments
 (0)