-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathsearch.rs
439 lines (409 loc) · 13.5 KB
/
search.rs
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#![allow(clippy::manual_unwrap_or_default)]
use darling::{ast, util, Error, FromDeriveInput, FromField};
use darling::{FromMeta, Result};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::DeriveInput;
#[derive(FromDeriveInput)]
#[darling(
attributes(search),
forward_attrs(allow, doc, cfg),
supports(struct_named)
)]
struct SearchParams {
table: String,
migration: Option<Migration>,
#[darling(default)]
joins: String,
#[darling(multiple, rename = "column")]
columns: Vec<SearchColumn>,
// Magic fields
data: ast::Data<util::Ignored, SearchField>,
}
#[derive(Debug, FromMeta)]
struct Migration {
src_table: String,
src_primary_key: Option<String>,
#[darling(default)]
query_joins: String,
prepend_sql: Option<SubMigration>,
append_sql: Option<SubMigration>,
}
#[derive(Debug, FromMeta)]
struct SubMigration {
#[darling(default)]
up: String,
#[darling(default)]
down: String,
}
#[derive(Debug, FromMeta)]
struct SearchColumn {
name: String,
data_type: String,
sql: Option<String>, // some search objects may not have a migration
index: Option<bool>,
#[darling(default)]
textual_search: bool,
}
#[derive(Debug, FromField)]
#[darling(attributes(search), forward_attrs(allow, doc, cfg))]
struct SearchField {
// Magic fields
// Get the ident of the field. For fields in tuple or newtype structs or
// enum bodies, this can be `None`.
ident: Option<syn::Ident>,
// This magic field name pulls the type from the input.
ty: syn::Type,
// Actual custom options
sql: String,
#[darling(default)]
rename: Option<String>,
}
#[derive(PartialEq)]
enum ColumnType {
Integer,
Float,
String,
TextualSearchString,
Boolean,
Null,
Sequence(Box<ColumnType>),
}
impl SearchField {
fn type_string(&self) -> String {
self.ty
.clone()
.into_token_stream()
.into_iter()
.last()
.unwrap()
.to_string()
}
fn ident_string(&self) -> Option<String> {
self.rename
.clone()
.or_else(|| self.ident.clone().map(|id| id.to_string()))
}
}
impl ColumnType {
fn from_sql_type(sql_type: &str) -> Option<Self> {
match sql_type.to_lowercase().trim() {
"bigint" | "int8" | "bigserial" | "serial8" | "integer" | "int" | "int4"
| "smallint" | "int2" | "smallserial" | "serial2" | "serial" | "serial4" => {
Some(ColumnType::Integer)
}
"float" | "double" | "double precision" | "float8" | "numeric" | "decimal" | "real"
| "float4" => Some(ColumnType::Float),
"text" | "string" | "str" | "character varying" | "varchar" | "character" | "char" => {
Some(ColumnType::String)
}
"boolean" | "bool" => Some(ColumnType::Boolean),
"null" => Some(ColumnType::Null),
// handles VARCHAR(240), NUMERIC(4, 2), etc.
prefix if prefix.contains('(') => {
let (prefix, _) = prefix.split_once('(').unwrap();
ColumnType::from_sql_type(prefix)
}
array if array.ends_with(']') => {
let elt = array.split_once('[').unwrap().0;
Some(ColumnType::Sequence(Box::new(ColumnType::from_sql_type(
elt,
)?)))
}
_ => None,
}
}
fn to_type_spec(&self) -> TokenStream {
match self {
ColumnType::Integer => {
quote! { editoast_search::TypeSpec::Type(editoast_search::AstType::Integer) }
}
ColumnType::Float => {
quote! { editoast_search::TypeSpec::Type(editoast_search::AstType::Float) }
}
ColumnType::String | ColumnType::TextualSearchString => {
quote! { editoast_search::TypeSpec::Type(editoast_search::AstType::String) }
}
ColumnType::Boolean => {
quote! { editoast_search::TypeSpec::Type(editoast_search::AstType::Boolean) }
}
ColumnType::Null => {
quote! { editoast_search::TypeSpec::Type(editoast_search::AstType::Null) }
}
ColumnType::Sequence(ct) => {
let ts = ct.to_type_spec();
quote! { editoast_search::TypeSpec::Sequence(Box::new(#ts)) }
}
}
}
fn index(&self) -> TokenStream {
match self {
ColumnType::TextualSearchString => quote! { editoast_search::Index::GinTrgm },
_ => quote! { editoast_search::Index::Default },
}
}
}
pub fn expand_search(input: &DeriveInput) -> Result<TokenStream> {
let params = SearchParams::from_derive_input(input)?;
let has_migration = params.migration.is_some();
let struct_name = &input.ident;
let table = params.table;
let joins = match params.joins {
ref joins if !joins.is_empty() => quote! { Some(#joins.to_owned()) },
_ => quote! { None },
};
let mut criterias = Punctuated::<TokenStream, Comma>::new();
for SearchColumn {
name,
data_type,
sql,
index,
textual_search,
} in params.columns.iter()
{
let mut st = ColumnType::from_sql_type(data_type).ok_or_else(|| {
Error::custom(format!(
"cannot translate SQL type '{data_type}' into a search engine-compatible type specifier"
))
})?;
let ts = st.to_type_spec();
let migration = if has_migration {
let search_type = if *textual_search {
if st != ColumnType::String {
return Err(Error::custom(format!(
"cannot perform textual search on non-text column '{}'",
name
)));
}
st = ColumnType::TextualSearchString;
quote! { editoast_search::SearchType::Textual }
} else {
quote! { editoast_search::SearchType::None }
};
let Some(sql) = sql else {
return Err(Error::custom(format!(
"missing SQL query for search criteria '{}'",
name
)));
};
let index = if index.unwrap_or(true) {
let index = st.index();
quote! { Some(#index) }
} else {
quote! { None }
};
quote! {
Some(editoast_search::CriteriaMigration {
sql_type: #data_type.to_owned(),
sql: #sql.to_owned(),
index: #index,
search_type: #search_type,
})
}
} else {
quote! { None }
};
criterias.push(quote! {
editoast_search::Criteria {
name: #name.to_owned(),
data_type: #ts,
migration: #migration,
}
});
}
let mut properties = Punctuated::<TokenStream, Comma>::new();
for prop in params
.data
.take_struct()
.expect("search derive macro only works on named structs")
.into_iter()
{
let name = prop
.ident_string()
.expect("search derive macro only works on named structs");
let ts = match ColumnType::from_sql_type(&prop.type_string()).map(|t| t.to_type_spec()) {
Some(ts) => quote! { Some(#ts) },
None => quote! { None },
};
let sql = prop.sql;
properties.push(quote! { editoast_search::Property {
name: #name.to_owned(),
sql: #sql.to_owned(),
data_type: #ts,
} });
}
let migration = if let Some(Migration {
src_table,
src_primary_key,
query_joins,
prepend_sql,
append_sql,
}) = params.migration
{
let src_primary_key = src_primary_key.unwrap_or_else(|| "id".to_owned());
let prepend = match prepend_sql {
Some(SubMigration { up, down }) => quote! { Some((#up.to_owned(), #down.to_owned())) },
None => quote! { None },
};
let append = match append_sql {
Some(SubMigration { up, down }) => quote! { Some((#up.to_owned(), #down.to_owned())) },
None => quote! { None },
};
quote! {
Some(editoast_search::Migration {
src_table: #src_table.to_owned(),
src_primary_key: #src_primary_key.to_owned(),
query_joins: #query_joins.to_owned(),
prepend_sql: #prepend,
append_sql: #append,
})
}
} else {
quote! { None }
};
Ok(quote! {
impl editoast_search::SearchObject for #struct_name {
fn search_config() -> editoast_search::SearchConfig {
editoast_search::SearchConfig {
table: #table.to_owned(),
joins: #joins,
criterias: vec![#criterias],
properties: vec![#properties],
migration: #migration,
}
}
}
})
}
#[derive(FromDeriveInput)]
#[darling(
attributes(search_config_store),
forward_attrs(allow, doc, cfg),
supports(struct_unit)
)]
struct SearchStoreParams {
#[darling(default, multiple, rename = "object")]
objects: Vec<SearchStoreObject>,
}
#[derive(FromMeta)]
struct SearchStoreObject {
name: String,
config: syn::Path,
}
pub fn expand_store(input: &DeriveInput) -> Result<TokenStream> {
let name = &input.ident;
let SearchStoreParams { objects } = SearchStoreParams::from_derive_input(input)?;
if objects.is_empty() {
return Err(Error::custom(
"no search objects configured — this is likely a mistake",
));
}
let (object_name, ident): (Vec<_>, Vec<_>) = objects
.iter()
.map(|SearchStoreObject { name, config }| (name, config))
.unzip();
Ok(quote! {
impl editoast_search::SearchConfigStore for #name {
fn find<S: AsRef<str>>(object_name: S) -> Option<editoast_search::SearchConfig> {
match object_name.as_ref() {
#(#object_name => Some(< #ident as editoast_search::SearchObject > :: search_config())),* ,
_ => None
}
}
fn all() -> Vec<(&'static str, editoast_search::SearchConfig)> {
vec![#(
(
#object_name,
< #ident as editoast_search::SearchObject > :: search_config()
)
),*]
}
}
#[derive(Serialize, ToSchema)]
#[serde(untagged)]
#[allow(unused, clippy::enum_variant_names)]
/// A search result item that depends on the query's `object`
pub(super) enum SearchResultItem {
#(#ident(#ident)),*
}
impl SearchResultItem {
editoast_common::schemas! {
#(#ident),*,
SearchResultItem,
}
}
})
}
#[cfg(test)]
mod tests {
use darling::FromDeriveInput;
use pretty_assertions::assert_eq;
use crate::search::SearchParams;
use super::SearchField;
fn track() -> syn::DeriveInput {
syn::parse_quote! {
#[search(
table = "search_track",
column(name = "infra_id", data_type = "INT"),
column(name = "line_code", data_type = "INT"),
column(name = "line_name", data_type = "TEXT")
)]
pub struct Track {
#[search(sql = "search_track.infra_id")]
infra_id: i64,
#[search(sql = "search_track.unprocessed_line_name")]
line_name: std::string::String,
#[search(sql = "search_track.line_code", rename = "code")]
line_code: i64,
}
}
}
impl SearchField {
fn to_tuple(&self) -> (String, String, String) {
(
self.ident_string().unwrap(),
self.type_string(),
self.sql.to_owned(),
)
}
}
#[test]
fn test_construction() {
let params = SearchParams::from_derive_input(&track()).unwrap();
assert_eq!(¶ms.table, "search_track");
assert!(¶ms.joins.is_empty());
assert_eq!(
params.columns.iter().map(|c| &c.name).collect::<Vec<_>>(),
vec!["infra_id", "line_code", "line_name"]
);
assert_eq!(
params
.columns
.iter()
.map(|c| &c.data_type)
.collect::<Vec<_>>(),
vec!["INT", "INT", "TEXT"]
);
let tuples = params
.data
.take_struct()
.unwrap()
.fields
.into_iter()
.map(|p| p.to_tuple())
.collect::<Vec<_>>();
assert_eq!(
tuples
.iter()
.map(|t| (t.0.as_ref(), t.1.as_ref(), t.2.as_ref()))
.collect::<Vec<_>>(),
vec![
("infra_id", "i64", "search_track.infra_id"),
("line_name", "String", "search_track.unprocessed_line_name"),
("code", "i64", "search_track.line_code")
]
);
}
}