I’m using pyparsing to add a semicolon (“;”) after “CREATE TABLE”. If I have this input:
CREATE TABLE A ( B VARCHAR(255) )
the program would give the next output:
CREATE TABLE A ( B VARCHAR(255) );
Trouble arises when there are comments around, like this:
CREATE TABLE A ( B VARCHAR(255) )
--Comment
Where the program is giving:
CREATE TABLE A ( B VARCHAR(255) )
--Comment
;
Here is the code:
import pyparsing as par
alphanumsword = par.Word(par.alphanums + "_")
element = "(" + alphanumsword + ")" | alphanumsword
row = par.OneOrMore(element)
rows = row + par.OneOrMore("," + row) | row
semicolon = par.Literal(";")
comment1 = par.Literal("--") + par.restOfLine + par.LineEnd()
createtable = par.CaselessLiteral("create") + par.CaselessLiteral("table")
+ alphanumsword + "(" + rows + ")" + ~semicolon
createtable.ignore(comment1)
createtable.ignore(par.cStyleComment)
text = \
"""
CREATE TABLE PERSON
(
/* Comment */
/*
Comment
*/
ID VARCHAR(255),
NAME VARCHAR(255), -- Comment
--- Comment
ADDRESS VARCHAR(255) NULL, -- Comment
CONSTRAINT PK_PERSON PRIMARY KEY (ID)
)
-- Comment
CREATE TABLE A ( B VARCHAR(255) )
"""
text_list = list(text)
offset = 0
for t,s,e in createtable.scanString(text):
print "(", t, ",", s, ",", e, ")"
print "||", text[s:e], "||"
text_list.insert(e + offset, ';')
offset += 1
print "".join(text_list)
Use
~( semicolon | comment1 )instead of~( semicolon ).output: