1use datafusion::error::Result;
14use ursa_viz::model::Layout;
15
16use super::plan_err;
17
18#[derive(Debug, Clone, Default, PartialEq)]
20pub struct Style {
21 pub nodes: Option<String>,
23 pub size: Option<Name>,
24 pub color: Option<Name>,
25 pub shape: Option<As>,
28 pub on: Option<Name>,
30 pub layout: Option<Layout>,
32 pub positions: Option<String>,
35 pub group: Option<Name>,
38}
39
40#[derive(Debug, Clone, PartialEq)]
42pub enum As {
43 Edges {
45 src: Name,
46 dst: Name,
47 weight: Option<Name>,
48 },
49 Nodes { id: Name },
51 Path { nodes: Name, edges: Option<Name> },
54 Hops {
56 seed: Name,
57 id: Name,
58 distance: Name,
59 },
60}
61
62impl As {
63 pub fn shown(&self) -> String {
65 let join = |names: &[Option<&Name>]| {
66 names
67 .iter()
68 .flatten()
69 .map(|n| n.shown.as_str())
70 .collect::<Vec<_>>()
71 .join(", ")
72 };
73 match self {
74 As::Edges { src, dst, weight } => {
75 format!(
76 "AS edges({})",
77 join(&[Some(src), Some(dst), weight.as_ref()])
78 )
79 }
80 As::Nodes { id } => format!("AS nodes({})", id.shown),
81 As::Path { nodes, edges } => {
82 format!("AS path({})", join(&[Some(nodes), edges.as_ref()]))
83 }
84 As::Hops { seed, id, distance } => {
85 format!("AS hops({})", join(&[Some(seed), Some(id), Some(distance)]))
86 }
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq)]
94pub struct Name {
95 pub ident: String,
96 pub shown: String,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq)]
100enum Tok {
101 Word,
102 Quoted,
103 Str,
104 Open,
105 Close,
106 Other,
107}
108
109fn tokens(text: &str) -> Vec<(Tok, usize, usize)> {
112 let b = text.as_bytes();
113 let mut out = Vec::new();
114 let mut i = 0;
115 while i < b.len() {
116 let c = b[i];
117 let start = i;
118 if c.is_ascii_whitespace() {
119 i += 1;
120 continue;
121 }
122 if c == b'-' && b.get(i + 1) == Some(&b'-') {
123 while i < b.len() && b[i] != b'\n' {
124 i += 1;
125 }
126 continue;
127 }
128 if c == b'/' && b.get(i + 1) == Some(&b'*') {
129 i += 2;
130 while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
131 i += 1;
132 }
133 i = (i + 2).min(b.len());
134 continue;
135 }
136 let kind = if c == b'\'' || c == b'"' {
137 i += 1;
139 loop {
140 if i >= b.len() {
141 break;
142 }
143 if b[i] == c {
144 if b.get(i + 1) == Some(&c) {
145 i += 2;
146 continue;
147 }
148 i += 1;
149 break;
150 }
151 i += 1;
152 }
153 if c == b'"' {
154 Tok::Quoted
155 } else {
156 Tok::Str
157 }
158 } else if c == b'(' {
159 i += 1;
160 Tok::Open
161 } else if c == b')' {
162 i += 1;
163 Tok::Close
164 } else if c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80 {
165 while i < b.len()
166 && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$' || b[i] >= 0x80)
167 {
168 i += 1;
169 }
170 Tok::Word
171 } else {
172 i += 1;
173 Tok::Other
174 };
175 out.push((kind, start, i));
176 }
177 out
178}
179
180pub const USAGE: &str = ".graph [SOURCE] [ON graph] [AS edges(src, dst [, weight]) | nodes(id) | \
182 path(nodes [, edges]) | hops(seed, id, distance)] [NODES (SELECT id, … \
183 FROM …)] [SIZE BY x] [COLOR BY y] [GROUP BY z] [LAYOUT \
184 force|rings|layers] [POSITIONS (SELECT id, x, y FROM …)]";
185
186const STATEMENTS: [&str; 22] = [
189 "SELECT",
190 "FROM",
191 "WITH",
192 "VALUES",
193 "TABLE",
194 "SHOW",
195 "DESCRIBE",
196 "DESC",
197 "EXPLAIN",
198 "SUMMARIZE",
199 "PIVOT",
200 "UNPIVOT",
201 "CREATE",
202 "DROP",
203 "INSERT",
204 "UPDATE",
205 "DELETE",
206 "COPY",
207 "SET",
208 "CALL",
209 "ALTER",
210 "MATCH",
211];
212
213const FORMS: &str =
215 "AS edges(src, dst [, weight]), AS nodes(id), AS path(nodes [, edges]) or AS hops(seed, id, \
216 distance)";
217
218fn name_of(text: &str, tok: Option<&(Tok, usize, usize)>) -> Option<Name> {
221 match tok {
222 Some(&(Tok::Word, s, e)) => Some(Name {
223 ident: text[s..e].to_lowercase(),
224 shown: text[s..e].to_string(),
225 }),
226 Some(&(Tok::Quoted, s, e)) if e - s > 2 && text[s..e].ends_with('"') => Some(Name {
227 ident: text[s + 1..e - 1].replace("\"\"", "\""),
228 shown: text[s..e].to_string(),
229 }),
230 _ => None,
231 }
232}
233
234fn layout_of(word: &str) -> Option<Layout> {
236 match word {
237 "FORCE" => Some(Layout::Force),
238 "RINGS" => Some(Layout::Rings),
239 "LAYERS" => Some(Layout::Layers),
240 _ => None,
241 }
242}
243
244pub fn parse(text: &str) -> Result<(String, Style)> {
269 let text = text.trim().trim_end_matches(';').trim_end();
270 let toks = tokens(text);
271 let word = |i: usize| -> Option<String> {
272 toks.get(i)
273 .filter(|t| t.0 == Tok::Word)
274 .map(|t| text[t.1..t.2].to_ascii_uppercase())
275 };
276 let kind = |i: usize| toks.get(i).map(|t| t.0);
277 fn starts(
280 i: usize,
281 word: &dyn Fn(usize) -> Option<String>,
282 kind: &dyn Fn(usize) -> Option<Tok>,
283 n: usize,
284 ) -> bool {
285 match word(i).as_deref() {
286 Some("SIZE" | "COLOR" | "COLOUR" | "GROUP") => word(i + 1).as_deref() == Some("BY"),
287 Some("NODES" | "POSITIONS") => kind(i + 1) == Some(Tok::Open),
288 Some("AS") => {
289 i == 0
290 || (matches!(
291 word(i + 1).as_deref(),
292 Some(
294 "EDGES" | "NODES" | "PATH" | "HOPS" | "EDGE" | "NODE" | "PATHS" | "HOP"
295 )
296 ) && kind(i + 2) == Some(Tok::Open))
297 }
298 Some("LAYOUT") => i == 0 || word(i + 1).as_deref().and_then(layout_of).is_some(),
299 Some("ON") => {
300 i == 0
301 || (matches!(kind(i + 1), Some(Tok::Word | Tok::Quoted))
302 && (i + 2 >= n || starts(i + 2, word, kind, n)))
303 }
304 _ => false,
305 }
306 }
307 let is_clause = |i: usize| starts(i, &word, &kind, toks.len());
308 let whole = |i: usize| -> bool {
311 let mut depth = 0i32;
312 for (j, t) in toks[..i].iter().enumerate() {
313 match t.0 {
314 Tok::Open => depth += 1,
315 Tok::Close => {
316 depth -= 1;
317 if depth == 0 {
318 return j + 1 == i;
319 }
320 }
321 _ => {}
322 }
323 }
324 false
325 };
326 let mut depth = 0i32;
327 let named = !is_clause(0)
330 && match (toks.first(), kind(1)) {
331 (Some((Tok::Quoted, _, _)), Some(Tok::Word)) => true,
332 (Some((Tok::Word, _, _)), Some(Tok::Word)) => {
333 !STATEMENTS.contains(&word(0).unwrap_or_default().as_str())
334 }
335 _ => false,
336 };
337 let mut first = named.then_some(1);
338 let mut joins = 0u32;
340 for (i, t) in toks.iter().enumerate() {
341 if first.is_some() {
342 break;
343 }
344 match t.0 {
345 Tok::Open => depth += 1,
346 Tok::Close => depth -= 1,
347 Tok::Word if depth == 0 => {
348 let w = word(i).unwrap_or_default();
349 match w.as_str() {
350 "JOIN"
351 if !matches!(
352 i.checked_sub(1).and_then(&word).as_deref(),
353 Some("CROSS" | "NATURAL")
354 ) =>
355 {
356 joins += 1
357 }
358 "ON" | "USING" if joins > 0 => joins -= 1,
359 "GROUP"
362 if i > 0
363 && word(i + 1).as_deref() == Some("BY")
364 && !(kind(0) == Some(Tok::Open) && whole(i)) => {}
365 _ if is_clause(i) => {
366 first = Some(i);
367 break;
368 }
369 _ => {}
370 }
371 }
372 _ => {}
373 }
374 }
375 let Some(mut i) = first else {
376 return Ok((text.to_string(), Style::default()));
377 };
378 let source = text[..toks[i].1].trim().to_string();
379 let mut style = Style::default();
380 let closing = |open: usize| -> Option<usize> {
382 let mut depth = 0;
383 for (j, t) in toks.iter().enumerate().skip(open) {
384 match t.0 {
385 Tok::Open => depth += 1,
386 Tok::Close => {
387 depth -= 1;
388 if depth == 0 {
389 return Some(j);
390 }
391 }
392 _ => {}
393 }
394 }
395 None
396 };
397 while i < toks.len() {
398 let t = toks[i];
399 let shown = &text[t.1..t.2];
400 let keyword = word(i).unwrap_or_default();
401 match keyword.as_str() {
402 "NODES" if kind(i + 1) == Some(Tok::Open) => {
403 if style.nodes.is_some() {
404 return plan_err(format!("NODES is given twice; give it once: {USAGE}"));
405 }
406 let open = toks[i + 1];
407 let Some(close) = closing(i + 1) else {
408 return plan_err("NODES ( is not closed: NODES (SELECT id, … FROM …)");
409 };
410 let query = text[open.2..toks[close].1].trim();
411 if query.is_empty() {
412 return plan_err("NODES () is empty: NODES (SELECT id, … FROM …)");
413 }
414 style.nodes = Some(query.to_string());
415 i = close + 1;
416 }
417 "POSITIONS" if kind(i + 1) == Some(Tok::Open) => {
418 const FORM: &str = "POSITIONS (SELECT id, x, y FROM …)";
419 if style.positions.is_some() {
420 return plan_err(format!("POSITIONS is given twice; give it once: {USAGE}"));
421 }
422 let open = toks[i + 1];
423 let Some(close) = closing(i + 1) else {
424 return plan_err(format!("POSITIONS ( is not closed: {FORM}"));
425 };
426 let query = text[open.2..toks[close].1].trim();
427 if query.is_empty() {
428 return plan_err(format!(
429 "POSITIONS () is empty; give the query that places the nodes: {FORM}"
430 ));
431 }
432 style.positions = Some(query.to_string());
433 i = close + 1;
434 }
435 "POSITIONS" => {
436 return plan_err(
437 "POSITIONS needs the query that places the nodes, in parentheses: POSITIONS \
438 (SELECT id, x, y FROM …), as POSITIONS (SELECT * FROM 'pos.parquet')",
439 );
440 }
441 "SIZE" | "COLOR" | "COLOUR" if word(i + 1).as_deref() == Some("BY") => {
442 let clause = if keyword == "SIZE" {
443 "SIZE BY"
444 } else {
445 "COLOR BY"
446 };
447 let Some(name) = name_of(text, toks.get(i + 2)) else {
448 let what = if keyword == "SIZE" {
449 "a numeric column or an algorithm, as SIZE BY pagerank"
450 } else {
451 "a column of categories or an algorithm, as COLOR BY louvain"
452 };
453 return plan_err(format!("{clause} needs {what}"));
454 };
455 let slot = if keyword == "SIZE" {
456 &mut style.size
457 } else {
458 &mut style.color
459 };
460 if slot.is_some() {
461 return plan_err(format!("{clause} is given twice; give it once: {USAGE}"));
462 }
463 *slot = Some(name);
464 i += 3;
465 }
466 "GROUP" if word(i + 1).as_deref() == Some("BY") => {
467 let Some(name) = name_of(text, toks.get(i + 2)) else {
468 return plan_err(
469 "GROUP BY needs a column of categories or an algorithm, as GROUP BY \
470 louvain",
471 );
472 };
473 if style.group.is_some() {
474 return plan_err(format!("GROUP BY is given twice; give it once: {USAGE}"));
475 }
476 style.group = Some(name);
477 i += 3;
478 }
479 "AS" => {
480 if style.shape.is_some() {
481 return plan_err(format!(
482 "AS is given twice; a result is drawn one way, so give one of {FORMS}"
483 ));
484 }
485 let Some(form) = word(i + 1) else {
486 return plan_err(format!(
487 "AS needs what the result's rows are and the columns to read: {FORMS}"
488 ));
489 };
490 let form_shown = &text[toks[i + 1].1..toks[i + 1].2];
491 let usage = match form.as_str() {
492 "EDGES" => "AS edges(src, dst [, weight])",
493 "NODES" => "AS nodes(id)",
494 "PATH" => "AS path(nodes [, edges])",
495 "HOPS" => "AS hops(seed, id, distance)",
496 "EDGE" => {
498 return plan_err(format!(
499 "AS {form_shown} is not a form; write AS edges(src, dst [, weight]). \
500 The forms are {FORMS}"
501 ))
502 }
503 "NODE" => {
504 return plan_err(format!(
505 "AS {form_shown} is not a form; write AS nodes(id). The forms are \
506 {FORMS}"
507 ))
508 }
509 "PATHS" => {
510 return plan_err(format!(
511 "AS {form_shown} is not a form; write AS path(nodes [, edges]). The \
512 forms are {FORMS}"
513 ))
514 }
515 "HOP" | "RINGS" => {
516 return plan_err(format!(
517 "AS {form_shown} is not a form; write AS hops(seed, id, distance). \
518 The forms are {FORMS}"
519 ))
520 }
521 _ => {
522 return plan_err(format!(
523 "AS {form_shown} is not a form; write one of {FORMS}"
524 ))
525 }
526 };
527 if kind(i + 2) != Some(Tok::Open) {
528 return plan_err(format!(
529 "AS {form_shown} needs its columns in parentheses: {usage}"
530 ));
531 }
532 let Some(close) = closing(i + 2) else {
533 return plan_err(format!("AS {form_shown}( is not closed: {usage}"));
534 };
535 let mut names = Vec::new();
537 let mut j = i + 3;
538 while j < close {
539 let Some(name) = name_of(text, toks.get(j)) else {
540 return plan_err(format!(
541 "AS {form_shown}(…) takes the result's column names, with commas \
542 between them, and '{}' is not one: {usage}",
543 &text[toks[j].1..toks[j].2]
544 ));
545 };
546 names.push(name);
547 j += 1;
548 if j < close {
549 let comma = toks[j].0 == Tok::Other && &text[toks[j].1..toks[j].2] == ",";
550 if !comma || j + 1 == close {
551 return plan_err(format!(
552 "AS {form_shown}(…) takes the result's column names, with \
553 commas between them: {usage}"
554 ));
555 }
556 j += 1;
557 }
558 }
559 let given = names.len();
560 let mut names = names.into_iter();
561 let mut next = || names.next().expect("counted");
562 let wrong = |takes: &str| -> Result<(String, Style)> {
563 plan_err(format!(
564 "AS {form_shown}(…) takes {takes}, and was given {given}: {usage}"
565 ))
566 };
567 style.shape = Some(match (form.as_str(), given) {
568 ("EDGES", 2 | 3) => As::Edges {
569 src: next(),
570 dst: next(),
571 weight: names.next(),
572 },
573 ("EDGES", _) => {
574 return wrong("the columns of an edge's two ends, and then its weight's")
575 }
576 ("NODES", 1) => As::Nodes { id: next() },
577 ("NODES", _) => return wrong("one column, the node's id"),
578 ("PATH", 1 | 2) => As::Path {
579 nodes: next(),
580 edges: names.next(),
581 },
582 ("PATH", _) => {
583 return wrong(
584 "the column of each path's nodes, and then the column of its edges",
585 )
586 }
587 ("HOPS", 3) => As::Hops {
588 seed: next(),
589 id: next(),
590 distance: next(),
591 },
592 _ => {
593 return wrong("three columns: the seed, the node reached and its distance")
594 }
595 });
596 i = close + 1;
597 }
598 "ON" => {
599 if style.on.is_some() {
600 return plan_err(format!(
601 "ON is given twice; a result's ids belong to one graph, so give it once: \
602 {USAGE}"
603 ));
604 }
605 let Some(name) = name_of(text, toks.get(i + 1)) else {
606 return plan_err(
607 "ON needs the name of the property graph the result's ids belong to, as \
608 ON karate; .graphs lists the graphs",
609 );
610 };
611 style.on = Some(name);
612 i += 2;
613 }
614 "LAYOUT" => {
615 if style.layout.is_some() {
616 return plan_err(format!("LAYOUT is given twice; give it once: {USAGE}"));
617 }
618 let Some(layout) = word(i + 1).as_deref().and_then(layout_of) else {
619 let given = match toks.get(i + 1) {
620 Some(t) => format!(", and '{}' is none of them", &text[t.1..t.2]),
621 None => String::new(),
622 };
623 return plan_err(format!(
624 "LAYOUT needs force, rings or layers{given}: LAYOUT force lets the edges \
625 pull the nodes into place, LAYOUT rings puts a hop result's nodes on \
626 circles by distance, and LAYOUT layers puts them in rows"
627 ));
628 };
629 style.layout = Some(layout);
630 i += 2;
631 }
632 _ => {
633 return plan_err(format!(
634 "unexpected '{shown}' after the graph's source; the clauses are ON graph, \
635 AS …, NODES (…), SIZE BY x, COLOR BY y, GROUP BY z, LAYOUT l and POSITIONS (…): \
636 {USAGE}"
637 ));
638 }
639 }
640 }
641 Ok((source, style))
642}
643
644pub fn identifier(text: &str) -> Option<String> {
647 let text = text.trim();
648 if let Some(quoted) = text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
649 if quoted.is_empty() || quoted.replace("\"\"", "").contains('"') {
650 return None;
651 }
652 return Some(quoted.replace("\"\"", "\""));
653 }
654 let mut chars = text.chars();
655 let first = chars.next()?;
656 if !(first.is_alphabetic() || first == '_')
657 || !chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
658 {
659 return None;
660 }
661 Some(text.to_lowercase())
662}