如何从原始sql文件中清除注释

问题描述 投票:10回答:5

我有清除注释和已存在的SQL文件中的空行的问题。该文件有超过10k行,因此不能手动清理它。

我有一个小的python脚本,但我不知道如何处理多行插入内的注释。

Code:

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

How it should work:

这应该清理:

-- 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 
\'
[...]

');
python sql postgresql text-parsing
5个回答
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'
);

2
投票

添加更新的答案:)

import sqlparse

sql_example = """--comment
SELECT * from test;
INSERT INTO test VALUES ('
-- test
a
');
 """
print sqlparse.format(sql_example, strip_comments=True).strip()

输出:

SELECT * from test;

插入测试值(' - 测试');

它实现了相同的结果,但也涵盖了所有其他角落情况,更简洁


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
');

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);
    }
}

0
投票
# Remove comments i.e. lines beginning with whitespace and '--' (using multi-line flag)
re.sub('^\s*--.*\n?', '', query, flags=re.MULTILINE)

正则表达式字符串解释:

  • ^线的开始
  • \ s空白
  • \ s *零个或多个空格字符
  • - 两个连字符(静态字符串模式)
  • 。*零个或多个任何字符(即行的其余部分)
  • \ n换行符
  • ?字符串的结尾
  • flags = re.M是多行修饰符

“当指定时,模式字符'^'在字符串的开头和每行的开头(紧接每个换行符后)匹配”

有关详细信息,请参阅Python正则表达式文档:

https://docs.python.org/3/library/re.html

© www.soinside.com 2019 - 2024. All rights reserved.