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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
//! PostgreSQL search index writer implementation.
use chrono::{DateTime, Utc};
use crate::error::{BackendError, StorageResult};
use crate::search::{converters::IndexValue, extractor::ExtractedValue};
fn internal_error(message: String) -> crate::error::StorageError {
crate::error::StorageError::Backend(BackendError::Internal {
backend_name: "postgres".to_string(),
message,
source: None,
})
}
/// PostgreSQL implementation of SearchIndexWriter.
pub struct PostgresSearchIndexWriter;
impl PostgresSearchIndexWriter {
/// Writes a single search index entry to PostgreSQL.
///
/// Accepts any type that can be dereferenced to a `tokio_postgres::Client`,
/// including `deadpool_postgres::Client` and `&deadpool_postgres::Client`.
pub async fn write_entry(
client: &deadpool_postgres::Client,
tenant_id: &str,
resource_type: &str,
resource_id: &str,
extracted: &ExtractedValue,
) -> StorageResult<()> {
match &extracted.value {
IndexValue::String(s) => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_string, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
&Some(s.as_str()),
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!("Failed to insert string search index entry: {}", e))
})?;
}
IndexValue::Token {
system,
code,
display,
identifier_type_system,
identifier_type_code,
} => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_token_system, value_token_code, value_token_display,
composite_group, value_identifier_type_system, value_identifier_type_code
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
&system.as_deref(),
&code.as_str(),
&display.as_deref(),
&extracted.composite_group.map(|g| g as i32),
&identifier_type_system.as_deref(),
&identifier_type_code.as_deref(),
],
)
.await
.map_err(|e| {
internal_error(format!("Failed to insert token search index entry: {}", e))
})?;
}
IndexValue::Date { value, precision } => {
let precision_str = precision.to_string();
let normalized = normalize_date_for_pg(value);
let timestamp: DateTime<Utc> = DateTime::parse_from_rfc3339(&normalized)
.map(|dt| dt.with_timezone(&Utc))
.or_else(|_| normalized.parse::<DateTime<Utc>>())
.unwrap_or_else(|_| Utc::now());
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_date, value_date_precision, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
×tamp,
&precision_str.as_str(),
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!("Failed to insert date search index entry: {}", e))
})?;
}
IndexValue::Number(n) => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_number, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
n,
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!("Failed to insert number search index entry: {}", e))
})?;
}
IndexValue::Quantity {
value,
unit,
system,
code: _,
} => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_quantity_value, value_quantity_unit, value_quantity_system, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
value,
&unit.as_deref(),
&system.as_deref(),
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!(
"Failed to insert quantity search index entry: {}",
e
))
})?;
}
IndexValue::Reference {
reference,
resource_type: _,
resource_id: _,
} => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_reference, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
&reference.as_str(),
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!(
"Failed to insert reference search index entry: {}",
e
))
})?;
}
IndexValue::Uri(uri) => {
client
.execute(
"INSERT INTO search_index (
tenant_id, resource_type, resource_id, param_name, param_url,
value_uri, composite_group
) VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[
&tenant_id,
&resource_type,
&resource_id,
&extracted.param_name.as_str(),
&extracted.param_url.as_str(),
&uri.as_str(),
&extracted.composite_group.map(|g| g as i32),
],
)
.await
.map_err(|e| {
internal_error(format!("Failed to insert URI search index entry: {}", e))
})?;
}
}
Ok(())
}
}
/// Normalize a date string for PostgreSQL TIMESTAMPTZ.
///
/// Converts partial dates to full timestamps:
/// - "2024" -> "2024-01-01T00:00:00+00:00"
/// - "2024-01" -> "2024-01-01T00:00:00+00:00"
/// - "2024-01-15" -> "2024-01-15T00:00:00+00:00"
/// - "2024-01-15T10:30:00" -> "2024-01-15T10:30:00+00:00"
fn normalize_date_for_pg(value: &str) -> String {
if value.contains('T') {
// Already has time component - ensure timezone
if value.contains('+') || value.contains('Z') || value.ends_with("-00:00") {
value.to_string()
} else {
format!("{}+00:00", value)
}
} else if value.len() == 10 {
// YYYY-MM-DD
format!("{}T00:00:00+00:00", value)
} else if value.len() == 7 {
// YYYY-MM
format!("{}-01T00:00:00+00:00", value)
} else if value.len() == 4 {
// YYYY
format!("{}-01-01T00:00:00+00:00", value)
} else {
// Best effort
value.to_string()
}
}