mod generated;
use std::fmt;
use generated::CONDITIONS;
pub use generated::codes;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
Success,
NoData,
Warning,
Informational,
Exception,
}
impl Severity {
pub const fn is_success(self) -> bool {
!matches!(self, Severity::Exception)
}
pub const fn letter(self) -> &'static str {
match self {
Severity::Success => "S",
Severity::NoData => "N",
Severity::Warning => "W",
Severity::Informational => "I",
Severity::Exception => "X",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Condition {
pub code: &'static str,
pub severity: Severity,
pub class: &'static str,
pub subclass: Option<&'static str>,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GqlStatus(u16);
impl GqlStatus {
pub fn from_code(code: &str) -> Option<Self> {
CONDITIONS
.iter()
.position(|c| c.code == code)
.map(|i| GqlStatus(i as u16))
}
pub fn condition(self) -> &'static Condition {
&CONDITIONS[self.0 as usize]
}
pub fn code(self) -> &'static str {
self.condition().code
}
pub fn severity(self) -> Severity {
self.condition().severity
}
pub fn class(self) -> &'static str {
&self.condition().code[..2]
}
pub fn standard_text(self) -> String {
let c = self.condition();
match c.subclass {
Some(sub) => format!("{}, {sub}", c.class),
None => c.class.to_string(),
}
}
pub fn doc_url(self) -> String {
format!("{DOC_BASE}{}", self.code())
}
pub fn retryable(self) -> bool {
self.code() == "40000"
}
}
pub const DOC_BASE: &str = "https://zu.dev/docs/errors/";
impl fmt::Debug for GqlStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "GqlStatus({})", self.code())
}
}
impl fmt::Display for GqlStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.code())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
pub offset: u32,
pub line: u32,
pub column: u32,
}
impl Position {
pub fn of(source: &str, offset: usize) -> Self {
let offset = boundary(source, offset);
let mut line = 1u32;
let mut column = 1u32;
for (ix, ch) in source.char_indices() {
if ix >= offset {
break;
}
if ch == '\n' {
line += 1;
column = 1;
} else {
column += 1;
}
}
Position {
offset: u32::try_from(offset).unwrap_or(u32::MAX),
line,
column,
}
}
}
fn boundary(source: &str, offset: usize) -> usize {
let mut offset = offset.min(source.len());
while !source.is_char_boundary(offset) {
offset -= 1;
}
offset
}
const EXCERPT_LIMIT: usize = 4096;
fn line_at(source: &str, offset: usize) -> Option<&str> {
let offset = boundary(source, offset);
let start = source[..offset].rfind('\n').map_or(0, |ix| ix + 1);
let end = source[offset..]
.find('\n')
.map_or(source.len(), |ix| offset + ix);
let line = source[start..end].trim_end_matches('\r');
(!line.is_empty() && line.len() <= EXCERPT_LIMIT).then_some(line)
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "line {}, column {}", self.line, self.column)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Subject {
Graph(String),
Schema(String),
Label(String),
Property(String),
Variable(String),
Type(String),
Function(String),
}
impl Subject {
pub const fn kind(&self) -> &'static str {
match self {
Subject::Graph(_) => "graph",
Subject::Schema(_) => "schema",
Subject::Label(_) => "label",
Subject::Property(_) => "property",
Subject::Variable(_) => "variable",
Subject::Type(_) => "type",
Subject::Function(_) => "function",
}
}
pub fn name(&self) -> &str {
match self {
Subject::Graph(s)
| Subject::Schema(s)
| Subject::Label(s)
| Subject::Property(s)
| Subject::Variable(s)
| Subject::Type(s)
| Subject::Function(s) => s,
}
}
}
impl fmt::Display for Subject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.kind(), self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticRecord {
pub status: GqlStatus,
pub detail: String,
pub position: Option<Position>,
pub excerpt: Option<String>,
pub subject: Option<Subject>,
pub graph: Option<String>,
pub schema: Option<String>,
}
impl DiagnosticRecord {
pub fn new(status: GqlStatus, detail: impl Into<String>) -> Self {
DiagnosticRecord {
status,
detail: detail.into(),
position: None,
excerpt: None,
subject: None,
graph: None,
schema: None,
}
}
pub fn about(mut self, subject: Subject) -> Self {
self.subject = Some(subject);
self
}
pub fn within(&mut self, graph: &str, schema: &str) {
self.graph.get_or_insert_with(|| graph.to_string());
self.schema.get_or_insert_with(|| schema.to_string());
}
pub fn at(status: GqlStatus, position: Position, detail: impl fmt::Display) -> Self {
DiagnosticRecord {
position: Some(position),
..DiagnosticRecord::new(status, format!("{position}: {detail}"))
}
}
pub fn in_source(
status: GqlStatus,
source: &str,
offset: usize,
detail: impl fmt::Display,
) -> Self {
let position = Position::of(source, offset);
DiagnosticRecord {
excerpt: line_at(source, offset).map(str::to_string),
..DiagnosticRecord::at(status, position, detail)
}
}
pub fn severity(&self) -> Severity {
self.status.severity()
}
pub fn doc_url(&self) -> String {
self.status.doc_url()
}
pub fn retryable(&self) -> bool {
self.status.retryable()
}
}
impl fmt::Display for DiagnosticRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.detail.is_empty() {
write!(f, "{}: {}", self.status.code(), self.status.standard_text())
} else {
write!(f, "{}: {}", self.status.code(), self.detail)
}
}
}
pub fn all() -> &'static [Condition] {
CONDITIONS
}
pub fn subclass_rows() -> impl Iterator<Item = &'static Condition> {
CONDITIONS.iter().filter(|c| c.subclass.is_some())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_table_is_the_standard_table() {
assert_eq!(CONDITIONS.len(), 80, "12 class rows plus 68 subclass rows");
assert_eq!(
subclass_rows().count(),
68,
"68 subclass rows, the conformance denominator"
);
}
#[test]
fn a_statement_that_did_nothing_notable_has_a_code_for_that() {
assert_eq!(codes::C00000.code(), "00000");
assert_eq!(codes::C00000.standard_text(), "successful completion");
assert_eq!(codes::C00000.severity(), Severity::Success);
assert_eq!(
codes::C00001.standard_text(),
"successful completion, omitted result"
);
}
#[test]
fn codes_are_unique_and_sorted() {
let mut seen: Vec<&str> = CONDITIONS.iter().map(|c| c.code).collect();
let n = seen.len();
seen.sort_unstable();
seen.dedup();
assert_eq!(seen.len(), n, "duplicate GQLSTATUS code in the table");
let codes: Vec<&str> = CONDITIONS.iter().map(|c| c.code).collect();
assert_eq!(codes, seen, "table is not in code order");
}
#[test]
fn lookup_round_trips_and_rejects_inventions() {
for c in CONDITIONS {
let status = GqlStatus::from_code(c.code).expect("code in table");
assert_eq!(status.code(), c.code);
}
assert!(GqlStatus::from_code("99999").is_none());
assert!(GqlStatus::from_code("ZU001").is_none());
assert!(GqlStatus::from_code("").is_none());
}
#[test]
fn severity_follows_the_class_letter() {
assert_eq!(codes::C00001.severity(), Severity::Success);
assert_eq!(codes::C01G11.severity(), Severity::Warning);
assert_eq!(codes::C02000.severity(), Severity::NoData);
assert_eq!(codes::C22012.severity(), Severity::Exception);
assert!(codes::C01G11.severity().is_success());
assert!(!codes::C42001.severity().is_success());
}
#[test]
fn standard_text_is_the_standards_words() {
assert_eq!(
codes::C22012.standard_text(),
"data exception, division by zero"
);
assert_eq!(
codes::C42001.standard_text(),
"syntax error or access rule violation, invalid syntax"
);
assert_eq!(codes::CG2000.standard_text(), "graph type violation");
}
#[test]
fn a_record_prefers_our_detail_but_never_loses_the_code() {
let bare = DiagnosticRecord::new(codes::C22012, "");
assert_eq!(bare.to_string(), "22012: data exception, division by zero");
let ours = DiagnosticRecord::new(codes::C42001, "line 1, column 7: expected MATCH");
assert_eq!(ours.to_string(), "42001: line 1, column 7: expected MATCH");
assert_eq!(ours.status.code(), "42001");
}
#[test]
fn a_position_reads_the_same_way_it_did_when_it_was_only_prose() {
let at = Position {
offset: 6,
line: 1,
column: 7,
};
let raised = DiagnosticRecord::at(codes::C42001, at, "expected MATCH");
assert_eq!(
raised.to_string(),
"42001: line 1, column 7: expected MATCH"
);
assert_eq!(raised.position, Some(at));
assert_eq!(at.to_string(), "line 1, column 7");
assert!(DiagnosticRecord::new(codes::C22012, "").position.is_none());
}
#[test]
fn an_offset_lands_on_the_line_and_column_a_reader_would_count() {
let source = "MATCH (n)\nWHERE n.x\nRETURN n";
let at = |offset, line, column| Position {
offset,
line,
column,
};
assert_eq!(Position::of(source, 0), at(0, 1, 1));
assert_eq!(Position::of(source, 6), at(6, 1, 7));
assert_eq!(Position::of(source, 9), at(9, 1, 10));
assert_eq!(Position::of(source, 10), at(10, 2, 1));
assert_eq!(Position::of(source, 20), at(20, 3, 1));
assert_eq!(Position::of(source, 9999), at(28, 3, 9));
}
#[test]
fn a_column_counts_characters_and_not_the_bytes_they_took() {
let source = "RETURN 'héllo wörld'";
let offset = source.find('w').expect("w");
assert_eq!(
Position::of(source, offset),
Position {
offset: 15,
line: 1,
column: 15
}
);
let at = Position::of(source, offset);
assert_eq!(&source[at.offset as usize..], "wörld'");
let inside = source.find('é').expect("e") + 1;
assert_eq!(Position::of(source, inside).offset as usize, inside - 1);
}
#[test]
fn an_excerpt_is_the_line_the_column_counts_into() {
let source = "MATCH (n)\nWHERE n.x = 1\nRETURN n";
let offset = source.find("n.x").expect("n.x");
let record = DiagnosticRecord::in_source(codes::C42001, source, offset, "no such property");
let excerpt = record.excerpt.as_deref().expect("a line to quote");
assert_eq!(excerpt, "WHERE n.x = 1");
let position = record.position.expect("a place");
assert_eq!(position.line, 2);
let caret: String = excerpt
.chars()
.take(position.column as usize - 1)
.map(|_| ' ')
.chain(['^'])
.collect();
assert_eq!(caret, " ^");
assert_eq!(&source[position.offset as usize..][..3], "n.x");
assert_eq!(
record.to_string(),
"42001: line 2, column 7: no such property"
);
}
#[test]
fn a_line_nobody_would_read_is_left_out_rather_than_cut() {
let record = DiagnosticRecord::in_source(codes::C42001, "\n\nRETURN 1", 1, "empty");
assert!(record.excerpt.is_none());
let long = format!("RETURN {}", "1 + ".repeat(2000));
let record = DiagnosticRecord::in_source(codes::C42001, &long, 7, "long");
assert!(long.len() > 4096, "the fixture has to pass the limit");
assert!(record.excerpt.is_none());
assert!(DiagnosticRecord::new(codes::C22012, "").excerpt.is_none());
}
#[test]
fn a_condition_says_where_it_is_written_up_and_whether_to_try_again() {
assert_eq!(codes::C42001.class(), "42");
assert_eq!(
codes::C42001.doc_url(),
"https://zu.dev/docs/errors/42001",
"the code is the page, so a message hands over a link rather than a thing to search for"
);
assert!(codes::C40000.retryable());
assert!(!codes::C40003.retryable());
assert!(!codes::C42001.retryable());
assert!(!codes::C22012.retryable());
}
}