archives.html


001| '''Archives Database.
001| 
001| commands:
001|     test            - Test function (development)
001| 
001| Developer@Sonnack.com
001| November 2018
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path, listdir, rename, remove as fdelete
006| from time import time, localtime, strftime
007| from datetime import timedelta
008| from logger import logger, info, debug, trace
009| from tables import dbBaseTable, dbFilepathsTable, dbFilenamesTable, dbLinksTable, dbSystemTable
010| from sql_lib import SqlLib
011| from misc import FileHash, do_rename_archive
012| ####################################################################################################
013| Log = logger('ARC')
014| 
015| BasePath = r'C:\CJS\prj\Python\ws\arcs'
016| 
017| QMs = lambda cols: ','.join('?'*len(cols))
018| FDate = lambda t: strftime('%m/%d/%Y %H:%M:%S', localtime(t))
019| 
020| TAB = '\t'
021| 
022| 
023| ##================================================================================================##
024| def builder_traveler (filepath):
025|     '''Recurse filetree and build database of files and paths.'''
026|     Log.trace('Dir: %s' % filepath)
027|     if not path.isdir(filepath):
028|         raise RuntimeError('Invalid filepath: "%s"' % filepath)
029| 
030|     try:
031|         # Insert filepath into the table (and get the PID)...
032|         ptab = dbFilepathsTable()
033|         pid = ptab.find_or_insert(filepath)
034|     except:
035|         Log.error('Directory Problem!!')
036|         Log.error(e)
037|         return
038| 
039|     # Process the files in this directory...
040|     folders = []
041|     filenames = listdir(filepath)
042|     for filename in filenames:
043|         fn = path.join(filepath, filename)
044|         # Process any files found...
045|         if path.isfile(fn):
046|             try:
047|                 # Insert filepath into the table...
048|                 fobj = FileHash(filename, filepath)
049|                 ftab = dbFilenamesTable()
050|                 fid = ftab.find_or_insert(fobj)
051|                 # insert link record into table...
052|                 xtab = dbLinksTable()
053|                 xtab.insert_new_link(fid, pid)
054|             except Exception as e:
055|                 Log.error(e)
056|             continue
057|         # Add any sub-directories to the folders list...
058|         if path.isdir(fn):
059|             folders.append(fn)
060|             continue
061|         Log.warn('Unexpected directory entry: "%s"' % filename)
062| 
063|     # Recurse on any directories found here...
064|     for folder in folders:
065|         builder_traveler(folder)
066| 
067| ##================================================================================================##
068| def do_build_database (*args):
069|     Log.info('buildDB:: #args=%d' % len(args))
070| 
071|     # Create the database...
072|     do_create_tables()
073| 
074|     # Load the record ID counters...
075|     systab = dbSystemTable()
076|     systab.load_ids()
077| 
078|     # Travel the filesystem and build database...
079|     for pathname in args:
080|         builder_traveler(pathname)
081| 
082|     # Save the record ID counters...
083|     systab.save_ids()
084|     systab.list_to_file()
085| 
086|     # List (just) the directories...
087|     dbFilepathsTable().list_to_file()
088|     #dbFilenamesTable().list_to_file()
089|     #dbLinksTable().list_to_file()
090|     return 'Done!'
091| 
092| ##================================================================================================##
093| def do_create_tables ():
094|     fn = path.join(dbBaseTable.dataPath, dbBaseTable.dbName)
095|     if path.exists(fn) and path.isfile(fn):
096|         fdelete(fn)
097|     dbSystemTable().create_table()
098|     dbLinksTable().create_table()
099|     dbFilepathsTable().create_table()
100|     dbFilenamesTable().create_table()
101|     return 'Done!'
102| ##================================================================================================##
103| def do_destroy_tables ():
104|     dbFilepathsTable().destroy_table()
105|     dbFilenamesTable().destroy_table()
106|     dbLinksTable().destroy_table()
107|     dbSystemTable().destroy_table()
108|     return 'Done!'
109| ##================================================================================================##
110| def do_list_tables ():
111|     dbSystemTable().list_to_file()
112|     dbFilenamesTable().list_to_file()
113|     dbFilepathsTable().list_to_file()
114|     dbLinksTable().list_to_file()
115|     return 'Done!'
116| 
117| ##================================================================================================##
118| def do_query (*args):
119|     Log.info('query:: #args=%d' % len(args))
120|     qname = args[0] if 0 < len(args) else '_'
121|     fname = args[1] if 1 < len(args) else 'query.out'
122|     # Query database...
123|     lib = SqlLib[qname]
124|     sql,fmt = lib[0:2]
125|     tbl = dbFilepathsTable() # dbFilepathsTable, dbFilenamesTable, dbLinksTable
126|     rs = tbl.db_query(sql)
127|     # Save query result to file...
128|     fn = path.join(BasePath, fname)
129|     fp = open(fn, mode='w', encoding='utf-8')
130|     try:
131|         for r in rs:
132|             s = (fmt % r) if fmt else str(r)
133|             print(s, file=fp)
134|     except:
135|         raise
136|     finally:
137|         fp.close()
138|     return 'Done!'
139| ##================================================================================================##
140| def do_test (*args):
141|     Log.info('test:: #args=%d' % len(args))
142|     arg1 = args[0] if 0 < len(args) else 'test.out'
143|     arg2 = args[1] if 1 < len(args) else ''
144|     #
145|     return 'Done!'
146| ####################################################################################################
147| def dispatch (cmd, *args):
148|     Log.info('command: %s' % cmd)
149|     Log.info('arguments: %d' % len(args))
150| 
151|     if cmd == 'build': return do_build_database(*args)
152|     if cmd == 'rename': return do_rename_archive()
153| 
154|     if cmd == 'make': return do_create_tables()
155|     if cmd == 'kill': return do_destroy_tables()
156|     if cmd == 'list': return do_list_tables()
157| 
158|     if cmd == 'query': return do_query(*args)
159|     if cmd == 'test': return do_test(*args)
160|     return 'Nothing to do!'
161| ####################################################################################################
162| if __name__ == '__main__':
163|     print('autorun: %s' % argv[0])
164|     Log.start(path.join(BasePath,'archives.log'))
165|     Log.level(trace())
166|     cmd = argv[1] if 1 < len(argv) else 'query'
167|     etc = argv[2:] if 2 < len(argv) else []
168|     try:
169|         t0 = time()
170|         obj = dispatch(cmd, *etc)
171|         te = timedelta(seconds=time()-t0)
172|         print(obj)
173|         Log.info(obj)
174|         Log.info('Elapsed Time: %s' % te)
175|     except:
176|         etype, evalue, tb = exc_info()
177|         ts = extract_tb(tb)
178|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
179|         for t in ts[-3:]:
180|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
181|             Log.error(' %s' % t[3])
182|         raise
183|     finally:
184|         Log.end()
185| ####################################################################################################
186| '''eof'''
187|