From fa7def01d00fc7c5c3047b077bc0f1a4cdc1d10a Mon Sep 17 00:00:00 2001 From: Fredy Wijaya Date: Thu, 13 Dec 2018 16:44:29 -0600 Subject: Fix formatting on INSERT (fixes #329) This patch fixes the formatting on INSERT by creating a new instance of sql.Values to group all the values. SQL: insert into foo values (1, 'foo'), (2, 'bar'), (3, 'baz') Before: insert into foo values (1, 'foo'), (2, 'bar'), (3, 'baz') After: insert into foo values (1, 'foo'), (2, 'bar'), (3, 'baz') --- tests/test_format.py | 43 +++++++++++++++++++++++++++++++++++++++++++ tests/test_grouping.py | 11 +++++++---- 2 files changed, 50 insertions(+), 4 deletions(-) (limited to 'tests') diff --git a/tests/test_format.py b/tests/test_format.py index acee9ac..a95b3d1 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -554,6 +554,49 @@ class TestFormatReindent(object): ' nvl(1)', 'from dual']) + def test_insert_values(self): + # issue 329 + f = lambda sql: sqlparse.format(sql, reindent=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2),', + ' (3, 4),', + ' (5, 6)']) + + f = lambda sql: sqlparse.format(sql, reindent=True, + comma_first=True) + s = 'insert into foo values (1, 2)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)']) + + s = 'insert into foo values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + + s = 'insert into foo(a, b) values (1, 2), (3, 4), (5, 6)' + assert f(s) == '\n'.join([ + 'insert into foo(a, b)', + 'values (1, 2)', + ' , (3, 4)', + ' , (5, 6)']) + class TestOutputFormat(object): def test_python(self): diff --git a/tests/test_grouping.py b/tests/test_grouping.py index f26f8b3..c55df7c 100644 --- a/tests/test_grouping.py +++ b/tests/test_grouping.py @@ -49,10 +49,13 @@ def test_grouping_identifiers(): assert str(parsed) == s assert isinstance(parsed.tokens[-1].tokens[3], sql.Identifier) - s = "INSERT INTO `test` VALUES('foo', 'bar');" - parsed = sqlparse.parse(s)[0] - types = [l.ttype for l in parsed.tokens if not l.is_whitespace] - assert types == [T.DML, T.Keyword, None, T.Keyword, None, T.Punctuation] + for s in ["INSERT INTO `test` VALUES('foo', 'bar');", + "INSERT INTO `test` VALUES(1, 2), (3, 4), (5, 6);", + "INSERT INTO `test(a, b)` VALUES(1, 2), (3, 4), (5, 6);"]: + parsed = sqlparse.parse(s)[0] + types = [l.ttype for l in parsed.tokens if not l.is_whitespace] + assert types == [T.DML, T.Keyword, None, None, T.Punctuation] + assert isinstance(parsed.tokens[6], sql.Values) s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" parsed = sqlparse.parse(s)[0] -- cgit v1.2.1