22from constants import DATA_FOLDER
33import csv
44import db .datastore as db
5+ import errno
56import os
67import re
78import shutil
89import sqlite3 as lite
910import tarfile
1011import time
1112
12- TABLES = {
13+ _TABLES = {
1314 'hashmap' : ['hash' , 'filepath' ],
1415 'profile' : ['id' , 'serializedUserInfo' ],
1516 'listings' : ['id' , 'serializedListings' ],
2627}
2728
2829def _getDatabase ():
30+ """Retrieves the OpenBazaar database file."""
2931 Database = db .Database ()
3032 return Database .DATABASE
3133
34+ def silentRemove (filename ):
35+ """Silently removes a file if it exists."""
36+ try :
37+ os .remove (filename )
38+ except OSError as e :
39+ if e .errno != errno .ENOENT : # ENOENT: no such file or directory
40+ raise
41+
3242def _exportDatabaseToCsv (tablesAndColumns ):
3343 """Reads the database for all given tables and stores them as CSV files."""
3444 dbFile = _getDatabase ()
@@ -48,36 +58,40 @@ def _exportDatabaseToCsv(tablesAndColumns):
4858 writer .writerows (data )
4959 return result
5060
51- def backup ( tableList = None , output = None ):
52- """Archives given tables and files in a single tar archive."""
61+ def backupFiles ( output = None ):
62+ """Archives OpenBazaar files in a single tar archive."""
5363 os .chdir (DATA_FOLDER )
5464
55- if tableList :
56- # Parse table list
57- tableList = tableList .replace (' ' , '' ).split (',' )
58- tablesAndColumns = []
59- for table in tableList :
60- if table in TABLES :
61- tablesAndColumns .append ((table , TABLES [table ]))
62- else :
63- return 'ERROR, Table not found: {0}' .format (table )
64-
65- # Remove existing database files and re-make them
66- if os .path .exists ('backup' ):
67- shutil .rmtree ('backup' )
68- os .makedirs ('backup' )
69- _exportDatabaseToCsv (tablesAndColumns )
70-
7165 # Archive files
7266 files = os .listdir (DATA_FOLDER )
7367 if not output :
7468 output = 'backup_{0}.tar.gz' .format (time .strftime ('%Y-%m-%d' ))
69+ silentRemove (output )
7570 with tarfile .open (output , 'w:gz' ) as tar :
7671 for f in files :
7772 tar .add (f )
7873 tar .close ()
7974 return 'Success'
8075
76+ def exportDatabase (tableList , removePrevious = False ):
77+ """Exports given tables to the OpenBazaar folder."""
78+ # Parse table list
79+ tableList = tableList .replace (' ' , '' ).split (',' )
80+ tablesAndColumns = []
81+ for table in tableList :
82+ if table in _TABLES :
83+ tablesAndColumns .append ((table , _TABLES [table ]))
84+ else :
85+ return 'ERROR, Table not found: {0}' .format (table )
86+
87+ # Remove existing database files and re-make them
88+ if removePrevious and os .path .exists ('backup' ):
89+ shutil .rmtree ('backup' )
90+ if not os .path .exists ('backup' ):
91+ os .makedirs ('backup' )
92+ _exportDatabaseToCsv (tablesAndColumns )
93+ return 'Success'
94+
8195def _importCsvToTable (fileName , deleteDataFirst = False ):
8296 """Imports given CSV file to the database."""
8397 tableName = re .search ('table_(\w+).csv' , fileName ).group (1 )
@@ -101,27 +115,30 @@ def _importCsvToTable(fileName, deleteDataFirst=False):
101115 cursor .execute (insertsql , row )
102116
103117
104- def restore (input , deleteTableDataFirst = False ):
105- """Restores files and tables of given archive."""
118+ def restoreFiles (input , removePreviousDatabaseFiles = False ):
119+ """Restores files of given archive to OpenBazaar folder ."""
106120 if not input :
107121 return 'Input path is needed'
108122 os .chdir (DATA_FOLDER )
109123
110124 # Remove existing database files if any
111- if os .path .exists ('backup' ):
125+ if removePreviousDatabaseFiles and os .path .exists ('backup' ):
112126 shutil .rmtree ('backup' )
113127
114128 # Unarchive files
115129 with tarfile .open (input , 'r:gz' ) as tar :
116130 tar .extractall ()
117131
132+ return 'Success'
133+
134+ if __name__ == '__main__' :
135+ print 'Backup tool works as a library.'
136+
137+ def importDatabase (deletePreviousData = False ):
138+ """Imports table files from the OpenBazaar folder."""
118139 # Restore database files to the database
119140 if os .path .exists ('backup' ):
120141 files = ['backup/{0}' .format (f ) for f in os .listdir ('backup' )]
121142 for f in files :
122- _importCsvToTable (f , deleteTableDataFirst )
123-
143+ _importCsvToTable (f , deletePreviousData )
124144 return 'Success'
125-
126- if __name__ == '__main__' :
127- print 'Backup tool works as a library.'
0 commit comments