Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 75903f2

Browse files
authored
gh-108364: Simplify quoting values and identifiers in sqlite3's iterdump() (#108472)
1 parent bc2f9e6 commit 75903f2

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

Lib/sqlite3/dump.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77
# future enhancements, you should normally quote any identifier that
88
# is an English language word, even if you do not have to."
99

10+
def _quote_name(name):
11+
return '"{0}"'.format(name.replace('"', '""'))
12+
13+
14+
def _quote_value(value):
15+
return "'{0}'".format(value.replace("'", "''"))
16+
17+
1018
def _iterdump(connection):
1119
"""
1220
Returns an iterator to the dump of the database in an SQL text format.
@@ -31,11 +39,11 @@ def _iterdump(connection):
3139
sqlite_sequence = []
3240
for table_name, type, sql in schema_res.fetchall():
3341
if table_name == 'sqlite_sequence':
34-
rows = cu.execute('SELECT * FROM "sqlite_sequence";').fetchall()
42+
rows = cu.execute('SELECT * FROM "sqlite_sequence";')
3543
sqlite_sequence = ['DELETE FROM "sqlite_sequence"']
3644
sqlite_sequence += [
37-
f'INSERT INTO "sqlite_sequence" VALUES(\'{row[0]}\',{row[1]})'
38-
for row in rows
45+
f'INSERT INTO "sqlite_sequence" VALUES({_quote_value(table_name)},{seq_value})'
46+
for table_name, seq_value in rows.fetchall()
3947
]
4048
continue
4149
elif table_name == 'sqlite_stat1':
@@ -53,12 +61,15 @@ def _iterdump(connection):
5361
yield('{0};'.format(sql))
5462

5563
# Build the insert statement for each row of the current table
56-
table_name_ident = table_name.replace('"', '""')
57-
res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
64+
table_name_ident = _quote_name(table_name)
65+
res = cu.execute(f'PRAGMA table_info({table_name_ident})')
5866
column_names = [str(table_info[1]) for table_info in res.fetchall()]
59-
q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
67+
q = "SELECT 'INSERT INTO {0} VALUES('{1}')' FROM {0};".format(
6068
table_name_ident,
61-
",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
69+
"','".join(
70+
"||quote({0})||".format(_quote_name(col)) for col in column_names
71+
)
72+
)
6273
query_res = cu.execute(q)
6374
for row in query_res:
6475
yield("{0};".format(row[0]))

0 commit comments

Comments
 (0)