-
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathbinding.rs
More file actions
225 lines (206 loc) · 6.97 KB
/
binding.rs
File metadata and controls
225 lines (206 loc) · 6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use super::helpers::{
escape_identifier, extract_base_type, is_raw_sql_function, is_wkt_geometry,
json_array_to_pg_literal, try_parse_pg_array,
};
use tokio_postgres::types::ToSql;
pub(super) type PgParam = Box<dyn ToSql + Send + Sync>;
pub(super) struct BoundValue {
pub sql: String,
pub param: Option<PgParam>,
}
pub(super) struct PgValueOptions<'a> {
pub column_type: Option<&'a str>,
pub max_blob_size: u64,
pub allow_default: bool,
}
/// Build a parameterized "<pk_col> = $N" predicate plus the boxed parameter for the
/// given JSON pk_val. Numeric values are cast through bigint/double precision so the
/// bind succeeds against int2/int4/int8/real columns; UUID strings are bound as the
/// `Uuid` type so PostgreSQL receives the matching OID.
pub(super) fn build_pk_predicate(
pk_col: &str,
pk_val: serde_json::Value,
placeholder_idx: usize,
) -> Result<(String, PgParam), String> {
let col = format!("\"{}\"", escape_identifier(pk_col));
match pk_val {
serde_json::Value::Number(n) => {
let bound = bind_pg_number(&n, placeholder_idx)?;
let param = bound
.param
.ok_or_else(|| "Internal PostgreSQL numeric binding error".to_string())?;
Ok((format!("{} = {}", col, bound.sql), param))
}
serde_json::Value::String(s) => {
if let Ok(uuid) = s.parse::<uuid::Uuid>() {
Ok((format!("{} = ${}", col, placeholder_idx), Box::new(uuid)))
} else {
Ok((format!("{} = ${}", col, placeholder_idx), Box::new(s)))
}
}
_ => Err("Unsupported PK type".into()),
}
}
pub(super) fn bind_pg_value(
value: serde_json::Value,
placeholder_idx: usize,
options: PgValueOptions<'_>,
) -> Result<BoundValue, String> {
match value {
serde_json::Value::Number(n) => bind_pg_number(&n, placeholder_idx),
serde_json::Value::String(s) => bind_pg_string(&s, placeholder_idx, options),
serde_json::Value::Bool(b) => Ok(BoundValue {
sql: format!("${}", placeholder_idx),
param: Some(Box::new(b)),
}),
serde_json::Value::Null => Ok(BoundValue {
sql: "NULL".to_string(),
param: None,
}),
serde_json::Value::Array(arr) => Ok(BoundValue {
sql: json_array_to_pg_literal(&arr)?,
param: None,
}),
_ => Err("Unsupported Value type".into()),
}
}
/// SQL fragment + boxed parameter for a JSON Number bound to PostgreSQL.
///
/// tokio-postgres binds Rust `i64` as INT8 and `f64` as FLOAT8, and rejects the
/// bind when the column is INT2/INT4/REAL with "error serializing parameter X".
/// Wrapping the placeholder in `CAST($N AS bigint)` / `CAST($N AS double precision)`
/// lets PostgreSQL convert to the actual column width via its assignment / implicit
/// comparison casts.
pub(super) fn bind_pg_number(
n: &serde_json::Number,
placeholder_idx: usize,
) -> Result<BoundValue, String> {
if let Some(v) = n.as_i64() {
Ok(BoundValue {
sql: format!("CAST(${} AS bigint)", placeholder_idx),
param: Some(Box::new(v)),
})
} else if let Some(v) = n.as_f64() {
Ok(BoundValue {
sql: format!("CAST(${} AS double precision)", placeholder_idx),
param: Some(Box::new(v)),
})
} else {
Err(format!("Unsupported numeric value: {}", n))
}
}
pub(super) fn bind_pg_numeric_string(
s: &str,
column_type: &str,
placeholder_idx: usize,
) -> Option<Result<BoundValue, String>> {
let trimmed = s.trim();
let normalized = extract_base_type(column_type).to_lowercase();
if matches!(
normalized.as_str(),
"smallint" | "integer" | "bigint" | "int2" | "int4" | "int8" | "serial" | "bigserial"
) {
return Some(trimmed.parse::<i64>().map_or_else(
|e| {
Err(format!(
"Cannot convert value {:?} to PostgreSQL numeric column type {}: {}",
s, column_type, e
))
},
|v| {
Ok(BoundValue {
sql: format!("CAST(${} AS bigint)", placeholder_idx),
param: Some(Box::new(v) as PgParam),
})
},
));
}
if matches!(normalized.as_str(), "numeric" | "decimal") {
return Some(trimmed.parse::<rust_decimal::Decimal>().map_or_else(
|e| {
Err(format!(
"Cannot convert value {:?} to PostgreSQL numeric column type {}: {}",
s, column_type, e
))
},
|v| {
Ok(BoundValue {
sql: format!("CAST(${} AS numeric)", placeholder_idx),
param: Some(Box::new(v) as PgParam),
})
},
));
}
if matches!(
normalized.as_str(),
"real" | "double precision" | "float4" | "float8"
) {
return Some(trimmed.parse::<f64>().map_or_else(
|e| {
Err(format!(
"Cannot convert value {:?} to PostgreSQL numeric column type {}: {}",
s, column_type, e
))
},
|v| {
Ok(BoundValue {
sql: format!("CAST(${} AS double precision)", placeholder_idx),
param: Some(Box::new(v) as PgParam),
})
},
));
}
None
}
fn bind_pg_string(
s: &str,
placeholder_idx: usize,
options: PgValueOptions<'_>,
) -> Result<BoundValue, String> {
if options.allow_default && s == "__USE_DEFAULT__" {
return Ok(BoundValue {
sql: "DEFAULT".to_string(),
param: None,
});
}
if let Some(bytes) = crate::drivers::common::decode_blob_wire_format(s, options.max_blob_size) {
return Ok(BoundValue {
sql: format!("${}", placeholder_idx),
param: Some(Box::new(bytes)),
});
}
if let Some(binding) = options
.column_type
.and_then(|data_type| bind_pg_numeric_string(s, data_type, placeholder_idx))
{
return binding;
}
if is_raw_sql_function(s) {
return Ok(BoundValue {
sql: s.to_string(),
param: None,
});
}
if is_wkt_geometry(s) {
return Ok(BoundValue {
sql: format!("ST_GeomFromText(${})", placeholder_idx),
param: Some(Box::new(s.to_string())),
});
}
if s.parse::<uuid::Uuid>().is_ok() {
return Ok(BoundValue {
sql: format!("CAST(${} AS uuid)", placeholder_idx),
param: Some(Box::new(s.to_string())),
});
}
if let Some(pg_arr) = try_parse_pg_array(s) {
return Ok(BoundValue {
sql: pg_arr?,
param: None,
});
}
Ok(BoundValue {
sql: format!("${}", placeholder_idx),
param: Some(Box::new(s.to_string())),
})
}