1use oqx::Consumer;
27use oqx::ast::{Expr, Follow, FollowDestination, OpNode, Query, SelectItem, Subquery, Where};
28use oqx::{Plan, QueryPlanner, Value, partition_pushable, residual_query};
29use rusqlite::Connection;
30use rusqlite::types::Value as SqlValue;
31
32use crate::context::{Target, fetch_rows, tag_rows};
33use crate::translate::{RESERVED_DOC_BASENAMES, TranslateCtx, translate_predicate};
34
35fn aliases(t: Target) -> (&'static str, &'static str) {
37 match t {
38 Target::Docs => ("d", "d"),
39 Target::Blocks => ("b", "d"),
40 Target::Nodes => ("n", "d"),
41 Target::Edges => ("e", "d"),
42 }
43}
44
45pub(crate) fn from_clause(t: Target) -> &'static str {
46 match t {
47 Target::Docs => "docs d",
48 Target::Blocks => "blocks b JOIN docs d ON d.doc_id = b.doc_id",
49 Target::Nodes => "nodes n JOIN docs d ON d.doc_id = n.doc_id",
50 Target::Edges => "edges e JOIN docs d ON d.doc_id = e.src_doc",
51 }
52}
53
54pub(crate) fn columns(t: Target) -> &'static str {
57 match t {
58 Target::Docs => "d.*",
59 Target::Blocks => "b.*, d.path AS __path",
60 Target::Nodes => "n.*, d.path AS __path",
61 Target::Edges => "e.*, d.path AS __path",
62 }
63}
64
65pub(crate) fn order_clause(t: Target) -> &'static str {
67 match t {
68 Target::Docs => "d.path, d.doc_id",
69 Target::Blocks => "d.path, b.block_id",
70 Target::Nodes => "d.path, n.node_id",
71 Target::Edges => "d.path, e.edge_id",
72 }
73}
74
75pub(crate) fn guards(t: Target) -> &'static str {
77 match t {
78 Target::Docs => "d.repo_id = ? AND d.deleted_commit IS NULL",
79 Target::Blocks => "b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL",
80 Target::Nodes => "n.repo_id = ? AND d.deleted_commit IS NULL",
81 Target::Edges => "e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL",
82 }
83}
84
85pub(crate) fn from_by_doc(t: Target) -> &'static str {
91 match t {
92 Target::Docs => from_clause(t),
93 Target::Blocks => "docs d CROSS JOIN blocks b ON b.doc_id = d.doc_id",
94 Target::Nodes => "docs d CROSS JOIN nodes n ON n.doc_id = d.doc_id",
95 Target::Edges => "docs d CROSS JOIN edges e ON e.src_doc = d.doc_id",
96 }
97}
98
99pub(crate) fn guards_by_doc(t: Target) -> &'static str {
104 match t {
105 Target::Docs => guards(t),
106 Target::Blocks => {
107 "d.repo_id = ? AND +b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL"
108 }
109 Target::Nodes => "d.repo_id = ? AND +n.repo_id = ? AND d.deleted_commit IS NULL",
110 Target::Edges => {
111 "d.repo_id = ? AND +e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL"
112 }
113 }
114}
115
116pub(crate) fn root_target(source: &Expr) -> Option<Target> {
121 match source {
122 Expr::Ident { name, .. } => Target::parse(name),
123 _ => None,
124 }
125}
126
127fn is_target_relation_of(target: Target, name: &str) -> bool {
130 matches!(
131 (target, name),
132 (Target::Docs, "nodes" | "blocks") | (Target::Blocks, "nodes") | (Target::Nodes, "blocks")
133 )
134}
135
136fn reach_through(head: &str) -> Option<Target> {
138 match head {
139 "doc" => Some(Target::Docs),
140 "block" => Some(Target::Blocks),
141 "section" => Some(Target::Nodes),
142 _ => None,
143 }
144}
145
146fn residual_may_raise(w: &Where, target: Target) -> bool {
168 where_may_raise(w, target, true)
169}
170
171fn where_may_raise(w: &Where, target: Target, root: bool) -> bool {
172 match w {
173 Where::And { parts, .. } | Where::Or { parts, .. } => {
174 parts.iter().any(|p| where_may_raise(p, target, root))
175 }
176 Where::Not { expr, .. } => where_may_raise(expr, target, root),
177 Where::Scalar { expr, .. } => expr_may_raise(expr, target, root),
178 Where::Op(op) => op_may_raise(op, target, root),
179 }
180}
181
182fn op_may_raise(op: &OpNode, target: Target, root: bool) -> bool {
183 op.op == Consumer::Single
184 || expr_may_raise(&op.receiver, target, root)
185 || subquery_may_raise(&op.sub, target)
186}
187
188fn subquery_may_raise(sub: &Subquery, target: Target) -> bool {
189 let inner = |e: &Expr| expr_may_raise(e, target, false);
190 sub.from.iter().any(inner)
191 || sub
192 .r#where
193 .as_ref()
194 .is_some_and(|w| where_may_raise(w, target, false))
195 || sub.select.iter().any(|item| match item {
196 SelectItem::Field { expr, lift, .. } => *lift > 0 || inner(expr),
197 SelectItem::Collect { op, .. } => op_may_raise(op, target, false),
198 })
199 || sub.order_by.iter().flatten().any(|o| inner(&o.expr))
200 || sub
201 .follow
202 .as_ref()
203 .is_some_and(|f| follow_may_raise(f, target))
204 || sub.limit.as_ref().is_some_and(inner)
205 || sub.offset.as_ref().is_some_and(inner)
206}
207
208fn follow_may_raise(f: &Follow, target: Target) -> bool {
209 let inner = |e: &Expr| expr_may_raise(e, target, false);
210 f.destinations.iter().any(|d| match d {
211 FollowDestination::Relation(e) => inner(e),
212 FollowDestination::Block(op) => op_may_raise(op, target, false),
213 }) || f.r#where.as_ref().is_some_and(inner)
214 || f.frontier.as_ref().is_some_and(inner)
215 || f.by.as_ref().is_some_and(inner)
216}
217
218fn is_reserved(name: &str) -> bool {
219 RESERVED_DOC_BASENAMES.contains(&name)
220}
221
222fn expr_may_raise(e: &Expr, target: Target, root: bool) -> bool {
223 let again = |e: &Expr| expr_may_raise(e, target, root);
224 match e {
225 Expr::Lit { .. } | Expr::Binding { .. } => false,
226 Expr::Ident { name, .. } if Target::parse(name).is_some() => {
230 !root || !is_target_relation_of(target, name)
231 }
232 Expr::Ident { name, .. } => root && target == Target::Docs && is_reserved(name),
233 Expr::Outer { .. } | Expr::Call { .. } => true,
234 Expr::Member { recv, name, .. } => {
238 (is_reserved(name) && matches!(&**recv, Expr::Ident { name, .. } if name == "doc"))
239 || (Target::parse(name).is_some()
240 && !matches!(&**recv, Expr::Ident { name: head, .. }
241 if reach_through(head).is_some_and(|t| is_target_relation_of(t, name))))
242 || again(recv)
243 }
244 Expr::Unary { expr, .. } => again(expr),
245 Expr::Required { .. } => true,
248 Expr::Op(op) => op_may_raise(op, target, root),
249 Expr::Binary { left, right, .. }
250 | Expr::Logical { left, right, .. }
251 | Expr::In { left, right, .. } => again(left) || again(right),
252 Expr::Range { lo, hi, .. } => {
253 lo.as_deref().is_some_and(again) || hi.as_deref().is_some_and(again)
254 }
255 }
256}
257
258#[derive(Clone, Debug, PartialEq)]
261pub struct Compiled {
262 pub target: Target,
263 pub sql: String,
264 pub params: Vec<SqlValue>,
265 pub residual: Query,
266}
267
268#[must_use]
272pub fn compile(query: &Query, params: &[Value], repo_id: &str) -> Option<Compiled> {
273 if query.follow.is_some() || !query.from.is_empty() {
274 return None;
275 }
276 let target = root_target(&query.source)?;
277 let (self_alias, doc_alias) = aliases(target);
278 let ctx = TranslateCtx {
279 target,
280 self_alias,
281 doc_alias,
282 params,
283 };
284 let (pushed, residual) = partition_pushable(query.r#where.as_ref(), |e| {
285 translate_predicate(e, &ctx).is_some()
286 });
287 if pushed.is_empty() {
288 return None;
289 }
290 if residual
293 .as_ref()
294 .is_some_and(|w| residual_may_raise(w, target))
295 {
296 return None;
297 }
298 let mut where_sql = guards(target).to_owned();
299 let mut sql_params = vec![SqlValue::Text(repo_id.to_owned())];
300 for e in &pushed {
301 let frag = translate_predicate(e, &ctx).expect("accepted by partition_pushable");
302 where_sql.push_str(" AND (");
303 where_sql.push_str(&frag.sql);
304 where_sql.push(')');
305 sql_params.extend(frag.params);
306 }
307 let sql = format!(
308 "SELECT {} FROM {} WHERE {where_sql} ORDER BY {}",
309 columns(target),
310 from_clause(target),
311 order_clause(target)
312 );
313 Some(Compiled {
314 target,
315 sql,
316 params: sql_params,
317 residual: residual_query(query, residual),
318 })
319}
320
321pub struct SqlitePlanner<'a> {
323 conn: &'a Connection,
324 repo_id: String,
325}
326
327impl<'a> SqlitePlanner<'a> {
328 #[must_use]
329 pub fn new(conn: &'a Connection, repo_id: &str) -> Self {
330 Self {
331 conn,
332 repo_id: repo_id.to_owned(),
333 }
334 }
335
336 pub fn try_plan(&self, query: &Query, params: &[Value]) -> rusqlite::Result<Option<Plan>> {
341 let Some(compiled) = compile(query, params, &self.repo_id) else {
342 return Ok(None);
343 };
344 let rows = fetch_rows(self.conn, &compiled.sql, &compiled.params)?;
345 Ok(Some(Plan::new(
346 tag_rows(rows, compiled.target),
347 compiled.residual,
348 )))
349 }
350}
351
352impl QueryPlanner for SqlitePlanner<'_> {
353 fn plan(&self, query: &Query, params: &[Value]) -> Option<Plan> {
356 self.try_plan(query, params).ok().flatten()
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363 use oqx::ROWS_ROOT;
364 use oqx::ast::Where;
365
366 fn parse(src: &str) -> Query {
367 oqx::parse_string(src).expect("parses")
368 }
369
370 fn text(s: &str) -> SqlValue {
371 SqlValue::Text(s.to_owned())
372 }
373
374 #[test]
375 fn a_pushable_scan_compiles_to_one_statement_in_root_order() {
376 let c =
377 compile(&parse("from docs where $path == \"index.md\""), &[], "r_1").expect("planned");
378 assert_eq!(c.target, Target::Docs);
379 assert_eq!(
380 c.sql,
381 "SELECT d.* FROM docs d WHERE d.repo_id = ? AND d.deleted_commit IS NULL AND ((('/' || d.path) IS ?)) ORDER BY d.path, d.doc_id"
382 );
383 assert_eq!(c.params, vec![text("r_1"), text("index.md")]);
384 assert_eq!(
385 c.residual.source,
386 Expr::Ident {
387 name: ROWS_ROOT.to_owned(),
388 span: oqx::Span::EMPTY,
389 }
390 );
391 assert_eq!(c.residual.r#where, None);
392 }
393
394 #[test]
395 fn every_target_has_its_join_columns_guards_and_order() {
396 let b = compile(
397 &parse("from blocks where $path.startsWith(\"lab/\")"),
398 &[],
399 "r",
400 )
401 .unwrap();
402 assert_eq!(
403 b.sql,
404 "SELECT b.*, d.path AS __path FROM blocks b JOIN docs d ON d.doc_id = b.doc_id \
405 WHERE b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL \
406 AND ((substr(('/' || d.path), 1, length(?)) = ?)) ORDER BY d.path, b.block_id"
407 );
408 assert_eq!(b.params, vec![text("r"), text("lab/"), text("lab/")]);
409 let n = compile(
410 &parse("nodes count { where kind == \"md:task\" }"),
411 &[],
412 "r",
413 )
414 .unwrap();
415 assert_eq!(n.target, Target::Nodes);
416 assert!(n.sql.starts_with(
417 "SELECT n.*, d.path AS __path FROM nodes n JOIN docs d ON d.doc_id = n.doc_id WHERE n.repo_id = ? AND d.deleted_commit IS NULL AND ((n.kind IS ?))"
418 ));
419 assert!(n.sql.ends_with("ORDER BY d.path, n.node_id"));
420 let e = compile(
421 &parse("from edges where predicate == \"references\""),
422 &[],
423 "r",
424 )
425 .unwrap();
426 assert!(e.sql.starts_with(
427 "SELECT e.*, d.path AS __path FROM edges e JOIN docs d ON d.doc_id = e.src_doc WHERE e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL AND ((e.predicate IS ?))"
428 ));
429 assert!(e.sql.ends_with("ORDER BY d.path, e.edge_id"));
430 }
431
432 #[test]
433 fn mixed_conjunctions_push_the_translatable_parts_and_keep_the_rest() {
434 let q = parse(
435 "from docs where $path.startsWith(\"processes/\") && nodes exists { where kind == \"md:task\" } && layer == \"canon\"",
436 );
437 let c = compile(&q, &[], "r").expect("planned");
438 assert!(
439 c.sql
440 .contains("(substr(('/' || d.path), 1, length(?)) = ?)"),
441 "{}",
442 c.sql
443 );
444 assert!(c.sql.contains("p.key = 'layer'"), "{}", c.sql);
445 assert_eq!(
447 c.params,
448 vec![
449 text("r"),
450 text("processes/"),
451 text("processes/"),
452 text("canon")
453 ]
454 );
455 assert!(
457 matches!(c.residual.r#where, Some(Where::Op(_))),
458 "{:?}",
459 c.residual.r#where
460 );
461 assert!(c.residual.from.is_empty());
462 assert_eq!(c.residual.select, q.select);
463 assert_eq!(c.residual.consumer, q.consumer);
464 }
465
466 #[test]
467 fn declined_shapes_return_none() {
468 assert!(compile(&parse("from docs"), &[], "r").is_none());
470 assert!(compile(&parse("from docs where era in 800..1680"), &[], "r").is_none());
471 assert!(compile(&parse("from docs where !verified"), &[], "r").is_none());
472 assert!(
473 compile(
474 &parse("from docs where $path == \"a\" || $path == \"b\""),
475 &[],
476 "r"
477 )
478 .is_none()
479 );
480 assert!(
481 compile(
482 &parse("from docs where nodes exists { where kind == \"md:task\" }"),
483 &[],
484 "r"
485 )
486 .is_none()
487 );
488 assert!(
490 compile(
491 &parse("from docs where $path == \"a.md\" follow distinct doc.out"),
492 &[],
493 "r"
494 )
495 .is_none()
496 );
497 assert!(
500 compile(
501 &parse("from docs where $path == \"a.md\" follow doc.out, doc.in"),
502 &[],
503 "r"
504 )
505 .is_none()
506 );
507 assert!(
508 compile(
509 &parse(
510 "from docs where $path == \"a.md\" follow ^docs collect { where after.contains(^$path) }"
511 ),
512 &[],
513 "r"
514 )
515 .is_none()
516 );
517 assert!(compile(&parse("from things where $path == \"a.md\""), &[], "r").is_none());
519 assert!(compile(&parse("from nope where $path == \"a.md\""), &[], "r").is_none());
520 assert!(compile(&parse("from docs.nodes where kind == \"x\""), &[], "r").is_none());
521 let mut q = parse("from docs where $path == \"a.md\"");
523 q.from.push(Expr::Ident {
524 name: "nodes".to_owned(),
525 span: oqx::Span::EMPTY,
526 });
527 assert!(compile(&q, &[], "r").is_none());
528 }
529
530 #[test]
533 fn a_residual_that_could_raise_declines_the_whole_query() {
534 let declined = |src: &str| {
535 assert!(
536 compile(&parse(src), &[], "r").is_none(),
537 "should decline: {src}"
538 );
539 };
540 let planned = |src: &str| {
541 assert!(
542 compile(&parse(src), &[], "r").is_some(),
543 "should plan: {src}"
544 );
545 };
546 declined("from docs where path == \"x\" && $path == \"nope.md\"");
548 declined("from docs where $path == \"nope.md\" && !body");
549 declined("from blocks where $path == \"x\" && doc.path == \"y\"");
551 declined("from blocks where $path == \"x\" && nodes exists { where doc.path == \"y\" }");
552 declined("from docs where $path.matches(\"[\") && $path == \"nope.md\"");
554 declined("from docs where nope(\"x\") && $path == \"nope.md\"");
555 declined("from docs where $path == \"x\" && size(tags) > 1");
556 declined("from docs where $path == \"x\" && nodes exists { where name.lower() == \"a\" }");
557 declined(
558 "from docs where $path == \"x\" && nodes count { where kind == \"a\" order by size(name) } > 1",
559 );
560 declined("from docs where $path == \"x\" && ^slug == \"y\"");
562 declined("from docs where $path == \"x\" && nodes exists { where name == ^title }");
563 declined("from docs where $path == \"x\" && nodes collect { ^first_task: name }");
564 declined(
566 "from docs where $path == \"x\" && blocks exists { select t: nodes single { where kind == \"md:task\" } }",
567 );
568 planned("from docs where $path.startsWith(\"lab/\") && $path == \"x\"");
570 planned("from docs where $path == \"x\" && era in 800..1680");
572 planned("from docs where $path == \"x\" && !verified");
573 planned("from docs where $path == \"x\" && (layer == \"a\" || layer == \"b\")");
574 planned("from docs where $path == \"x\" && verified == true");
575 planned("from docs where $path == \"x\" && nodes exists { where kind == \"md:task\" }");
576 planned(
577 "from docs where $path == \"x\" && nodes count { where kind == \"md:task\" limit 5 } > 1",
578 );
579 planned("from blocks where $path == \"x\" && !path");
582 planned("from docs where $path == \"x\" && nodes exists { where path == \"y\" }");
583 planned("from docs where $path == \"x\" && frontmatter.path == \"y\"");
584 }
585
586 #[test]
587 fn a_top_level_not_or_or_is_the_whole_residual_and_declines() {
588 assert!(compile(&parse("from docs where !($path == \"a\")"), &[], "r").is_none());
591 assert!(
592 compile(
593 &parse("from docs where ($path == \"a\" || $path == \"b\") && layer == \"canon\""),
594 &[],
595 "r"
596 )
597 .is_some()
598 );
599 }
600}