Created
April 13, 2012 02:03
-
-
Save ajmcdaniel/2372930 to your computer and use it in GitHub Desktop.
Snippet to dump and load zipped sqlite3 databases, based on Eli Bendersky's example. Useful for storing sqlite3 databases from memory to disk
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
import zipfile | |
def dump_database(connection, dump_file, sql_file): | |
"""Function to dump sqlite3 database into zipped file | |
see: http://bit.ly/IAUmKc | |
python 2.6+ only | |
connection: sqlite3 database connection | |
dumpfile: the name of the zipfile to store the sql_file info | |
[remember to add a .zip extension] | |
sql_file: The name of the sql file to dump the database info into | |
[remember to add a .sql extension] | |
""" | |
# Open the db and dump all its data into the 'data' buffer | |
sql_dump = ''.join([data.encode('ISO-8859-1') for data in connection.iterdump()]) | |
# Create a zip file and write add the dump into it as a new file | |
zf = zipfile.ZipFile(dump_file, mode='w', compression=zipfile.ZIP_DEFLATED) | |
zf.writestr(sql_file, sql_dump ) | |
zf.close() | |
def load_database(zip_file, sql_file): | |
"""Returns a list of sql statements used to recreate a dumped database""" | |
zf = zipfile.ZipFile(zip_file) | |
try: | |
data = zf.read(sql_file) | |
# break sql into readable statements and re-create creation statements | |
# return data # uncomment for return of raw sql data | |
return data.split(';') | |
except KeyError: | |
print '%s not found in zip file' % (sql_file,) | |
if __name__ == '__main__': | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment