Created
September 19, 2014 23:46
-
-
Save jtprince/50904bfa5f38e45e9131 to your computer and use it in GitHub Desktop.
delete all tables in an sqlite database that match a regular expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import sqlite3 | |
import argparse | |
import re | |
parser = argparse.ArgumentParser(description='deletes tables matching some regular expression') | |
parser.add_argument('database', help='the database file') | |
parser.add_argument('regexp', help='the regexp you are matching') | |
parser.add_argument('--dry', action='store_true', help='just list the matching tables') | |
args = parser.parse_args() | |
conn = sqlite3.connect(args.database) | |
c = conn.cursor() | |
c.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;") | |
reply = c.fetchall() | |
table_names = map(lambda tup: tup[0], reply) | |
matching_tables = filter(lambda name: re.search(args.regexp, name), table_names) | |
if args.dry: | |
print("\n".join(matching_tables)) | |
else: | |
for name in matching_tables: | |
c.execute("DROP TABLE %s" % name) | |
conn.commit() | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment