我在清除已存在的sql文件中的注释和空行时遇到问题。 该文件有超过10k行,因此不能手动清理它。
我有一个小的python脚本,但我不知道如何处理多行插入内的注释。
f = file( 'file.sql', 'r' )
t = filter( lambda x: not x.startswith('--') \
and not x.isspace()
, f.readlines() )
f.close()
t #<- here the cleaned data should be
应该清理:
-- normal sql comment
这应保持不变:
CREATE FUNCTION func1(a integer) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
-- comment
[...]
END;
$$;
INSERT INTO public.texts (multilinetext) VALUES ('
and more lines here \'
-- part of text
\'
[...]
');
答案 0 :(得分:9)
尝试sqlparse模块。
更新示例:将注释保留在插入值内,并在CREATE FUNCTION块中添加注释。您可以进一步调整以调整行为:
import sqlparse
from sqlparse import tokens
queries = '''
CREATE FUNCTION func1(a integer) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
-- comment
END;
$$;
SELECT -- comment
* FROM -- comment
TABLE foo;
-- comment
INSERT INTO foo VALUES ('a -- foo bar');
INSERT INTO foo
VALUES ('
a
-- foo bar'
);
'''
IGNORE = set(['CREATE FUNCTION',]) # extend this
def _filter(stmt, allow=0):
ddl = [t for t in stmt.tokens if t.ttype in (tokens.DDL, tokens.Keyword)]
start = ' '.join(d.value for d in ddl[:2])
if ddl and start in IGNORE:
allow = 1
for tok in stmt.tokens:
if allow or not isinstance(tok, sqlparse.sql.Comment):
yield tok
for stmt in sqlparse.split(queries):
sql = sqlparse.parse(stmt)[0]
print sqlparse.sql.TokenList([t for t in _filter(sql)])
输出:
CREATE FUNCTION func1(a integer) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
-- comment
END;
$$;
SELECT * FROM TABLE foo;
INSERT INTO foo VALUES ('a -- foo bar');
INSERT INTO foo
VALUES ('
a
-- foo bar'
);
答案 1 :(得分:2)
添加更新的答案:)
import sqlparse
sql_example = """--comment
SELECT * from test;
INSERT INTO test VALUES ('
-- test
a
');
"""
print sqlparse.format(sql_example, strip_comments=True).strip()
输出:
从测试中选择*;
插入测试值(“ -测试 一种 ');
它获得相同的结果,但同时涵盖了所有其他极端情况,并且更加简洁
答案 2 :(得分:1)
这是与您的示例一起使用的samplebias答案的扩展:
import sqlparse
sql_example = """--comment
SELECT * from test;
INSERT INTO test VALUES ('
-- test
a
');
"""
new_sql = []
for statement in sqlparse.parse(sql_example):
new_tockens = [stm for stm in statement.tokens
if not isinstance(stm, sqlparse.sql.Comment)]
new_statement = sqlparse.sql.TokenList(new_tockens)
new_sql.append(new_statement.to_unicode())
print sqlparse.format("\n".join(new_sql))
输出:
SELECT * from test;
INSERT INTO test VALUES ('
-- test
a
');
答案 3 :(得分:0)
可以使用正则表达式来完成。首先,您必须按字符串拆分文件,然后您可以按注释拆分文件。以下Perl程序可以实现:
#! /usr/bin/perl -w
# Read hole file.
my $file = join ('', <>);
# Split by strings including the strings.
my @major_parts = split (/('(?:[^'\\]++|\\.)*+')/, $file);
foreach my $part (@major_parts) {
if ($part =~ /^'/) {
# Print the part if it is a string.
print $part;
}
else {
# Split by comments removing the comments
my @minor_parts = split (/^--.*$/m, $part);
# Print the remaining parts.
print join ('', @minor_parts);
}
}
答案 4 :(得分:0)
# Remove comments i.e. lines beginning with whitespace and '--' (using multi-line flag)
re.sub('^\s*--.*\n?', '', query, flags=re.MULTILINE)
正则表达式字符串解释:
&#34;指定时,模式字符&#39; ^&#39;匹配字符串的开头和每行的开头(紧跟在每个换行符后)&#34;
有关更多详细信息,请参阅Python正则表达式文档: