gh-91602: Add iterdump() support for filtering database objects (#114501)

Add optional 'filter' parameter to iterdump() that allows a "LIKE"
pattern for filtering database objects to dump.

Co-authored-by: Erlend E. Aasland <erlend@python.org>
This commit is contained in:
Mariusz Felisiak 2024-02-06 12:34:56 +01:00 committed by GitHub
parent 4bf41879d0
commit 1a10437a14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 176 additions and 17 deletions

View file

@ -15,7 +15,7 @@ def _quote_value(value):
return "'{0}'".format(value.replace("'", "''"))
def _iterdump(connection):
def _iterdump(connection, *, filter=None):
"""
Returns an iterator to the dump of the database in an SQL text format.
@ -32,15 +32,23 @@ def _iterdump(connection):
yield('PRAGMA foreign_keys=OFF;')
yield('BEGIN TRANSACTION;')
if filter:
# Return database objects which match the filter pattern.
filter_name_clause = 'AND "name" LIKE ?'
params = [filter]
else:
filter_name_clause = ""
params = []
# sqlite_master table contains the SQL CREATE statements for the database.
q = """
q = f"""
SELECT "name", "type", "sql"
FROM "sqlite_master"
WHERE "sql" NOT NULL AND
"type" == 'table'
{filter_name_clause}
ORDER BY "name"
"""
schema_res = cu.execute(q)
schema_res = cu.execute(q, params)
sqlite_sequence = []
for table_name, type, sql in schema_res.fetchall():
if table_name == 'sqlite_sequence':
@ -82,13 +90,14 @@ def _iterdump(connection):
yield("{0};".format(row[0]))
# Now when the type is 'index', 'trigger', or 'view'
q = """
q = f"""
SELECT "name", "type", "sql"
FROM "sqlite_master"
WHERE "sql" NOT NULL AND
"type" IN ('index', 'trigger', 'view')
{filter_name_clause}
"""
schema_res = cu.execute(q)
schema_res = cu.execute(q, params)
for name, type, sql in schema_res.fetchall():
yield('{0};'.format(sql))