Skip to content

Commit

Permalink
Fix matching on SqlState
Browse files Browse the repository at this point in the history
Closes #756
  • Loading branch information
sfackler committed Apr 24, 2021
1 parent c7a8adf commit 05a0643
Show file tree
Hide file tree
Showing 2 changed files with 852 additions and 289 deletions.
68 changes: 61 additions & 7 deletions codegen/src/sqlstate.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use linked_hash_map::LinkedHashMap;
use phf_codegen;
use std::fs::File;
use std::io::{BufWriter, Write};

Expand All @@ -11,7 +10,9 @@ pub fn build() {
let codes = parse_codes();

make_type(&mut file);
make_code(&codes, &mut file);
make_consts(&codes, &mut file);
make_inner(&codes, &mut file);
make_map(&codes, &mut file);
}

Expand All @@ -38,26 +39,51 @@ fn make_type(file: &mut BufWriter<File>) {
write!(
file,
"// Autogenerated file - DO NOT EDIT
use std::borrow::Cow;
/// A SQLSTATE error code
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SqlState(Cow<'static, str>);
pub struct SqlState(Inner);
impl SqlState {{
/// Creates a `SqlState` from its error code.
pub fn from_code(s: &str) -> SqlState {{
match SQLSTATE_MAP.get(s) {{
Some(state) => state.clone(),
None => SqlState(Cow::Owned(s.to_string())),
None => SqlState(Inner::Other(s.into())),
}}
}}
"
)
.unwrap();
}

fn make_code(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<File>) {
write!(
file,
r#"
/// Returns the error code corresponding to the `SqlState`.
pub fn code(&self) -> &str {{
&self.0
match &self.0 {{"#,
)
.unwrap();

for code in codes.keys() {
write!(
file,
r#"
Inner::E{code} => "{code}","#,
code = code,
)
.unwrap();
}

write!(
file,
r#"
Inner::Other(code) => code,
}}
}}
"
"#
)
.unwrap();
}
Expand All @@ -69,7 +95,7 @@ fn make_consts(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<
file,
r#"
/// {code}
pub const {name}: SqlState = SqlState(Cow::Borrowed("{code}"));
pub const {name}: SqlState = SqlState(Inner::E{code});
"#,
name = name,
code = code,
Expand All @@ -81,6 +107,34 @@ fn make_consts(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<
write!(file, "}}").unwrap();
}

fn make_inner(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<File>) {
write!(
file,
r#"
#[derive(PartialEq, Eq, Clone, Debug)]
enum Inner {{"#,
)
.unwrap();
for code in codes.keys() {
write!(
file,
r#"
E{},"#,
code,
)
.unwrap();
}
write!(
file,
r#"
Other(Box<str>),
}}
"#,
)
.unwrap();
}

fn make_map(codes: &LinkedHashMap<String, Vec<String>>, file: &mut BufWriter<File>) {
let mut builder = phf_codegen::Map::new();
for (code, names) in codes {
Expand Down
Loading

0 comments on commit 05a0643

Please sign in to comment.