Part of lp.services.database.sort_sql View In Hierarchy
Parse an SQL dump into logical lines.
>>> p = Parser() >>> p.feed("UPDATE foo SET bar='baz';\n") >>> p.feed("\n") >>> p.feed("INSERT INTO foo (id, x) VALUES (1, 23);\n") >>> p.feed("INSERT INTO foo (id, x) VALUES (2, 34);\n") >>> for line in p.lines: ... print repr(line) (None, "UPDATE foo SET bar='baz';") (None, '') (1, 'INSERT INTO foo (id, x) VALUES (1, 23);') (2, 'INSERT INTO foo (id, x) VALUES (2, 34);')
Method | __init__ | Undocumented |
Method | parse_quoted_string | Parse strings enclosed in single quote marks. |
Method | is_complete_insert_statement | Check whether a string looks like a complete SQL INSERT |
Method | parse_line | Parse a single line of SQL. |
Method | feed | Give the parser some text to parse. |
Parse strings enclosed in single quote marks.
This takes a string of the form "'foo' ..." and returns a pair containing the first quoted string and the rest of the string. The escape sequence "''" is recognised in the middle of a quoted string as representing a single quote, but is not unescaped.
ValueError is raised if there is no quoted string at the beginning of the string.
>>> p = Parser() >>> p.parse_quoted_string("'foo'") ("'foo'", '') >>> p.parse_quoted_string("'foo' bar") ("'foo'", ' bar') >>> p.parse_quoted_string("'foo '' bar'") ("'foo '' bar'", '') >>> p.parse_quoted_string("foo 'bar'") Traceback (most recent call last): ... ValueError: Couldn't parse quoted string
Parse a single line of SQL.
>>> p = Parser()
Something that's not an INSERT.
>>> p.parse_line('''UPDATE foo SET bar = 42;\n''') (None, 'UPDATE foo SET bar = 42;\n')
A simple INSERT.
>>> p.parse_line('''INSERT INTO foo (id, x) VALUES (2, 'foo');\n''') (2, "INSERT INTO foo (id, x) VALUES (2, 'foo');\n")
Something trickier: multiple lines, and a ');' in the middle.
>>> p.parse_line('''INSERT INTO foo (id, x) VALUES (3, 'b', ... 'b ... b); ... b'); ... ''') (3, "INSERT INTO foo (id, x) VALUES (3, 'b',\n'b\nb);\nb');\n")