Skip to content

Instantly share code, notes, and snippets.

@jtprince
Created September 19, 2014 23:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtprince/50904bfa5f38e45e9131 to your computer and use it in GitHub Desktop.
Save jtprince/50904bfa5f38e45e9131 to your computer and use it in GitHub Desktop.
delete all tables in an sqlite database that match a regular expression
#!/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