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
//! Parse SQL queries as text to [IndexMap] (`tag` => `query`).
//!
//! Inspired by [github.com/krisajenkins/yesql](https://github.com/krisajenkins/yesql). This is Rust port with additional features.

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quick_error;

use std::borrow::Cow;

pub use indexmap;
use indexmap::IndexMap;
use regex::{Regex, RegexBuilder};

quick_error! {
    /// The error type for parse SQL queries as text
    #[derive(Debug, PartialEq)]
    pub enum ParseError {
        /// Tag with same name already exists.
        TagOverwritten { line: usize, tag: String } {
            display(r#"Tag "{}" overwritten at line: {}"#, tag, line)
        }
        /// Tag for query is not defined.
        QueryWithoutTag{line: usize, query: String} {
            display(r#"Query without tag (line: {}): "{}""#, line, query)
        }
    }
}

#[derive(Debug, PartialEq)]
enum LineType {
    Empty,
    Tag,
    Query,
}

/// Parse SQL queries as text to [IndexMap].
///
/// Text parsed to [IndexMap], where keys are tags and values are queries.
/// [IndexMap] used instead [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html)
/// because with [IndexMap] it's possible execute queries in defined order what can be important on
/// database scheme creation.
///
/// # Example
///
/// Content of file with SQL:
/// ```sql
/// -- name: select
/// SELECT * FROM users;
///
/// -- name: delete
/// DELETE FROM users WHERE id = $1;
/// ```
///
/// in Rust:
/// ```ignore
/// let queries = rsyesql::parse(include_str!("./queries.sql"));
/// println!("{}", queries.get("select").unwrap()); // SELECT * FROM users;
/// println!("{}", queries.get("delete").unwrap()); // DELETE FROM users WHERE id = $1;
/// ```
pub fn parse<S: AsRef<str>>(text: S) -> Result<IndexMap<String, String>, ParseError> {
    let mut queries = IndexMap::new();

    let mut last_type: Option<LineType> = None;
    let mut last_tag: Option<&str> = None;

    for (idx, line) in remove_multi_line_comments(text.as_ref())
        .lines()
        .enumerate()
    {
        if line.is_empty() {
            continue;
        }

        let (ty, value) = parse_line(line);
        match ty {
            LineType::Empty => continue,
            LineType::Tag => {
                if last_type.is_some() && last_type.as_ref().unwrap() == &LineType::Tag {
                    return Err(ParseError::TagOverwritten {
                        line: idx + 1,
                        tag: value.to_owned(),
                    });
                }

                last_tag = Some(value);
            }
            LineType::Query => {
                if last_tag.is_none() {
                    return Err(ParseError::QueryWithoutTag {
                        line: idx + 1,
                        query: value.to_owned(),
                    });
                }

                queries
                    .entry(last_tag.unwrap().to_owned())
                    .and_modify(|x| {
                        *x = format!("{} {}", *x, value);
                    })
                    .or_insert_with(|| value.to_owned());
            }
        };

        last_type = Some(ty);
    }

    Ok(queries)
}

// Inner comments are not allowed.
// Preserve newlines for better error messages.
fn remove_multi_line_comments(text: &str) -> Cow<'_, str> {
    lazy_static! {
        static ref RE: Regex = RegexBuilder::new(r#"(/\*.*?\*/)"#)
            .multi_line(true)
            .dot_matches_new_line(true)
            .build()
            .unwrap();
    }

    RE.replace_all(text, |caps: &regex::Captures| {
        let mut rep = String::with_capacity(caps[1].len());
        for c in caps[1].chars() {
            let nc = match c {
                '\r' => '\r',
                '\n' => '\n',
                _ => ' ',
            };
            rep.push(nc);
        }
        rep
    })
}

// Remove single-line comment and trim string
fn parse_line(mut line: &str) -> (LineType, &str) {
    lazy_static! {
        static ref RE_TAG: Regex = Regex::new(r#"^\s*--\s*name\s*:\s*(.*?)\s*$"#).unwrap();
    }

    match RE_TAG.captures(line) {
        Some(caps) => (LineType::Tag, caps.get(1).unwrap().as_str()),
        None => {
            if let Some(idx) = line.find("--") {
                line = line.get(0..idx).unwrap();
            };

            line = line.trim();
            if line.is_empty() {
                (LineType::Empty, line)
            } else {
                (LineType::Query, line)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accept_str_string() {
        let text = "--name: x\nquery";
        assert!(parse(text).is_ok());
        assert!(parse(text.to_owned()).is_ok());
    }

    #[test]
    fn error_tag_overwritten() {
        let text = "--name: x\n--name: x";
        assert_eq!(
            parse(text).err(),
            Some(ParseError::TagOverwritten {
                line: 2,
                tag: "x".to_owned()
            })
        );
    }

    #[test]
    fn error_query_without_tag() {
        let text = "SELECT 1;";
        assert_eq!(
            parse(text).err(),
            Some(ParseError::QueryWithoutTag {
                line: 1,
                query: "SELECT 1;".to_owned()
            })
        );
    }

    #[test]
    fn parse_text() {
        let text = "-- just comment\n--name: x\nselect 2;";
        let mut queries = IndexMap::new();
        queries.insert("x".to_owned(), "select 2;".to_owned());
        assert_eq!(parse(text).ok(), Some(queries));
    }

    #[test]
    fn remove_zero_comments() {
        let text = "123\nabc";
        let result = "123\nabc";
        assert_eq!(remove_multi_line_comments(text), result);
    }

    #[test]
    fn remove_line_comment() {
        let text = "123/*qqq*/ /*123**/ 321";
        let result = "123                 321";
        assert_eq!(remove_multi_line_comments(text), result);
    }

    #[test]
    fn remove_multi_line_comment() {
        let text = "123/*9\nqqq\nz*/321";
        let result = "123   \n   \n   321";
        assert_eq!(remove_multi_line_comments(text), result);
    }

    #[test]
    fn parse_line_with_comment() {
        let line = "33 -- 123";
        let result = (LineType::Query, "33");
        assert_eq!(parse_line(line), result);
    }

    #[test]
    fn parse_line_invalid_tag() {
        let line = "0 -- name: start";
        let result = (LineType::Query, "0");
        assert_eq!(parse_line(line), result);
    }

    #[test]
    fn parse_line_tag() {
        let line = " --  name:start";
        let result = (LineType::Tag, "start");
        assert_eq!(parse_line(line), result);
    }

    #[test]
    fn parse_line_tag_with_space() {
        let line = "-- name: start end ";
        let result = (LineType::Tag, "start end");
        assert_eq!(parse_line(line), result);
    }
}