File:  [Repository] / ZSQLExtend / importFMPXML.py
Revision 1.16: download - view: text, annotated - select for diffs - revision graph
Tue Dec 11 16:21:24 2007 UTC (16 years, 5 months ago) by casties
Branches: MAIN
CVS tags: HEAD
importFMPXML now creates a real backup and updates the current table with id_field and backup_table

    1: #!/usr/local/bin/python
    2: #
    3: 
    4: import string
    5: import logging
    6: import sys
    7: import types
    8: import time
    9: 
   10: from xml import sax
   11: from amara import saxtools
   12: 
   13: try:
   14:     import psycopg2 as psycopg
   15:     psyco = 2
   16: except:
   17:     import psycopg
   18:     psyco = 1
   19: 
   20: fm_ns = 'http://www.filemaker.com/fmpxmlresult'
   21: 
   22: version_string = "V0.5 ROC 11.12.2007"
   23: 
   24: def getTextFromNode(nodename):
   25:     """get the cdata content of a node"""
   26:     if nodename is None:
   27:         return ""
   28:     nodelist=nodename.childNodes
   29:     rc = ""
   30:     for node in nodelist:
   31:         if node.nodeType == node.TEXT_NODE:
   32:            rc = rc + node.data
   33:     return rc
   34: 
   35: def sql_quote(v):
   36:     # quote dictionary
   37:     quote_dict = {"\'": "''", "\\": "\\\\"}
   38:     for dkey in quote_dict.keys():
   39:         if string.find(v, dkey) >= 0:
   40:             v=string.join(string.split(v,dkey),quote_dict[dkey])
   41:     return "'%s'"%v
   42: 
   43: def SimpleSearch(curs,query, args=None, ascii=False):
   44:     """execute sql query and return data"""
   45:     #logger.debug("executing: "+query)
   46:     if ascii:
   47:         # encode all in UTF-8
   48:         query = query.encode("UTF-8")
   49:         if args is not None:
   50:             encargs = []
   51:             for a in args:
   52:                 if a is not None:
   53:                     a = a.encode("UTF-8")
   54:                 encargs.append(a)
   55:             
   56:             args = encargs
   57: 
   58:     curs.execute(query, args)
   59:     #logger.debug("sql done")
   60:     try:
   61:         return curs.fetchall()
   62:     except:
   63:         return None
   64: 
   65: 
   66: class TableColumn:
   67:     """simple type for storing sql column name and type"""
   68:     
   69:     def __init__(self, name, type=None):
   70:         #print "new tablecolumn(%s,%s)"%(name, type)
   71:         self.name = name
   72:         self.type = type
   73:         
   74:     def getName(self):
   75:         return self.name
   76:     
   77:     def getType(self):
   78:         if self.type is not None:
   79:             return self.type
   80:         else:
   81:             return "text"
   82: 
   83:     def __str__(self):
   84:         return self.name
   85:     
   86:     
   87: class xml_handler:
   88:     def __init__(self,options):
   89:         """SAX handler to import FileMaker XML file (FMPXMLRESULT format) into the table.
   90:         @param options: dict of options
   91:         @param options.dsn: database connection string
   92:         @param options.table: name of the table the xml shall be imported into
   93:         @param options.filename: xmlfile filename
   94:         @param options.update_fields: (optional) list of fields to update; default is to create all fields
   95:         @param options.id_field: (optional) field which uniquely identifies an entry for updating purposes.
   96:         @param options.sync_mode: (optional) really synchronise, i.e. delete entries not in XML file
   97:         @param options.lc_names: (optional) lower case and clean up field names from XML
   98:         @param options.keep_fields: (optional) don't add fields to SQL database
   99:         @param options.ascii_db: (optional) assume ascii encoding in db
  100:         @param options.replace_table: (optional) delete and re-insert data
  101:         @param options.backup_table: (optional) create backup of old table (breaks indices)
  102:         @param options.use_logger_instance: (optional) use this instance of a logger
  103:         """
  104:         
  105:         # set up logger
  106:         if hasattr(options, 'use_logger_instance'):
  107:             self.logger = options.use_logger_instance
  108:         else:
  109:             self.logger = logging.getLogger('db.import.fmpxml')
  110: 
  111:         
  112:         # set up parser
  113:         self.event = None
  114:         self.top_dispatcher = { 
  115:             (saxtools.START_ELEMENT, fm_ns, u'METADATA'): 
  116:             self.handle_meta_fields,
  117:             (saxtools.START_ELEMENT, fm_ns, u'RESULTSET'): 
  118:             self.handle_data_fields,
  119:             }
  120:         
  121:         # connect database
  122:         self.dbCon = psycopg.connect(options.dsn)
  123:         self.db = self.dbCon.cursor()
  124:         assert self.db, "AIIEE no db cursor for %s!!"%options.dsn
  125:     
  126:         self.table = getattr(options,"table",None)
  127:         self.update_fields = getattr(options,"update_fields",None)
  128:         self.id_field = getattr(options,"id_field",None)
  129:         self.sync_mode = getattr(options,"sync_mode",None)
  130:         self.lc_names = getattr(options,"lc_names",None)
  131:         self.keep_fields = getattr(options,"keep_fields",None)
  132:         self.ascii_db = getattr(options,"ascii_db",None)
  133:         self.replace_table = getattr(options,"replace_table",None)
  134:         self.backup_table = getattr(options,"backup_table",None)
  135: 
  136:         self.logger.debug("dsn: "+repr(getattr(options,"dsn",None)))
  137:         self.logger.debug("table: "+repr(self.table))
  138:         self.logger.debug("update_fields: "+repr(self.update_fields))
  139:         self.logger.debug("id_field: "+repr(self.id_field))
  140:         self.logger.debug("sync_mode: "+repr(self.sync_mode))
  141:         self.logger.debug("lc_names: "+repr(self.lc_names))
  142:         self.logger.debug("keep_fields: "+repr(self.keep_fields))
  143:         self.logger.debug("ascii_db: "+repr(self.ascii_db))
  144:         self.logger.debug("replace_table: "+repr(self.replace_table))
  145:         self.logger.debug("backup_table: "+repr(self.backup_table))
  146:         
  147:         self.dbIDs = {}
  148:         self.rowcnt = 0
  149:         
  150:         if self.id_field is not None:
  151:             # prepare a list of ids for sync mode
  152:             qstr="select %s from %s"%(self.id_field,self.table)
  153:             for id in SimpleSearch(self.db, qstr):
  154:                 # value 0: not updated
  155:                 self.dbIDs[id[0]] = 0;
  156:                 self.rowcnt += 1
  157:                 
  158:             self.logger.info("%d entries in DB to sync"%self.rowcnt)
  159:         
  160:         # names of fields in XML file
  161:         self.xml_field_names = []
  162:         # map XML field names to SQL field names
  163:         self.xml_field_map = {}
  164:         # and vice versa
  165:         self.sql_field_map = {}
  166:         
  167:         return
  168: 
  169:     def handle_meta_fields(self, end_condition):
  170:         dispatcher = {
  171:             (saxtools.START_ELEMENT, fm_ns, u'FIELD'):
  172:             self.handle_meta_field,
  173:             }
  174:         #First round through the generator corresponds to the
  175:         #start element event
  176:         self.logger.info("reading metadata...")
  177:         self.logger.debug("START METADATA")
  178:         yield None
  179:     
  180:         #delegate is a generator that handles all the events "within"
  181:         #this element
  182:         delegate = None
  183:         while not self.event == end_condition:
  184:             delegate = saxtools.tenorsax.event_loop_body(
  185:                 dispatcher, delegate, self.event)
  186:             yield None
  187:         
  188:         #Element closed. Wrap up
  189:         self.logger.debug("END METADATA")
  190:         
  191:         # rename table for backup
  192:         if self.backup_table:
  193:             self.orig_table = self.table
  194:             self.tmp_table = self.table + "_tmp"
  195:             backup_name = "%s_%s"%(self.table,time.strftime('%Y_%m_%d_%H_%M_%S'))
  196:             
  197:             # remove old temp table
  198:             qstr = "DROP TABLE %s"%(self.tmp_table)
  199:             try:
  200:                 self.db.execute(qstr)
  201:             except:
  202:                 pass
  203:             
  204:             self.dbCon.commit()
  205:            
  206:             if self.id_field:
  207:                 # sync mode -- copy backup table, update current table 
  208:                 self.logger.info("copy table %s to %s"%(self.table,backup_name))
  209:                 qstr = "CREATE TABLE %s AS (SELECT * FROM %s)"%(backup_name,self.table)
  210: 
  211:             else:
  212:                 # replace mode -- create empty tmp table, insert into tmp table
  213:                 self.table = self.tmp_table
  214:                 self.logger.info("create empty table %s"%(self.table))
  215:                 qstr = "CREATE TABLE %s AS (SELECT * FROM %s WHERE 1=0)"%(self.table,self.orig_table)
  216:             
  217:             self.db.execute(qstr)
  218:             self.dbCon.commit()
  219:         
  220:         # delete data from table for replace
  221:         if self.replace_table:
  222:             self.logger.info("delete data from table %s"%(self.table))
  223:             qstr = "TRUNCATE TABLE %s"%(self.table)
  224:             self.db.execute(qstr)
  225:             self.dbCon.commit()
  226:            
  227:         # try to match date style with XML
  228:         self.db.execute("set datestyle to 'german'")
  229:         
  230:         # translate id_field (SQL-name) to XML-name
  231:         self.xml_id = self.sql_field_map.get(self.id_field, None)
  232:         
  233:         #self.logger.debug("xml-fieldnames:"+repr(self.xml_field_names))
  234:         # get list of fields and types of db table
  235:         qstr="select attname, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) from pg_attribute, pg_class where attrelid = pg_class.oid and pg_attribute.attnum > 0 and relname = '%s'"
  236:         self.sql_fields={}
  237:         for f in SimpleSearch(self.db, qstr%self.table):
  238:             n = f[0]
  239:             t = f[1]
  240:             #print "SQL fields: %s (%s)"%(n,t)
  241:             self.sql_fields[n] = TableColumn(n,t)
  242:         
  243:         # check fields to update
  244:         if self.update_fields is None:
  245:             if self.keep_fields:
  246:                 # update all existing fields from sql (when they are in the xml file)
  247:                 self.update_fields = {}
  248:                 for f in self.sql_fields.keys():
  249:                     if self.sql_field_map.has_key(f):
  250:                         xf = self.sql_field_map[f]
  251:                         self.update_fields[f] = self.xml_field_map[xf]
  252: 
  253:             else:
  254:                 # update all fields
  255:                 if self.lc_names:
  256:                     # create dict with sql names
  257:                     self.update_fields = {}
  258:                     for f in self.xml_field_map.values():
  259:                         self.update_fields[f.getName()] = f
  260:                         
  261:                 else:
  262:                     self.update_fields = self.xml_field_map
  263:             
  264:         # and translate to list of xml fields
  265:         if self.lc_names:
  266:             self.xml_update_list = [self.sql_field_map[x] for x in self.update_fields]
  267:         else:
  268:             self.xml_update_list = self.update_fields.keys()
  269:         
  270:         if not self.keep_fields:
  271:             # adjust db table to fields in XML and update_fields
  272:             for f in self.xml_field_map.values():
  273:                 self.logger.debug("sync-fieldname: %s"%f.getName())
  274:                 sf = self.sql_fields.get(f.getName(), None)
  275:                 uf = self.update_fields.get(f.getName(), None)
  276:                 if sf is not None:
  277:                     # name in db -- check type
  278:                     if f.getType() != sf.getType():
  279:                         self.logger.debug("field %s has different type (%s vs %s)"%(f,f.getType(),sf.getType()))
  280:                 elif uf is not None:
  281:                     # add field to table
  282:                     qstr="alter table %s add %s %s"%(self.table,uf.getName(),uf.getType())
  283:                     self.logger.info("db add field:"+qstr)
  284:                     
  285:                     if self.ascii_db and type(qstr)==types.UnicodeType:
  286:                         qstr=qstr.encode('utf-8')
  287:                         
  288:                     self.db.execute(qstr)
  289:                     self.dbCon.commit()
  290:                 
  291:         # prepare sql statements for update
  292:         setStr=string.join(["%s = %%s"%self.xml_field_map[f] for f in self.xml_update_list], ', ')
  293:         self.updQuery="UPDATE %s SET %s WHERE %s = %%s"%(self.table,setStr,self.id_field)
  294:         # and insert
  295:         fields=string.join([self.xml_field_map[x].getName() for x in self.xml_update_list], ',')
  296:         values=string.join(['%s' for f in self.xml_update_list], ',')
  297:         self.addQuery="INSERT INTO %s (%s) VALUES (%s)"%(self.table,fields,values)
  298:         self.logger.debug("update-query: "+self.updQuery)
  299:         self.logger.debug("add-query: "+self.addQuery)
  300:         return
  301: 
  302:     def handle_meta_field(self, end_condition):
  303:         name = self.params.get((None, u'NAME'))
  304:         yield None
  305:         #Element closed.  Wrap up
  306:         if self.lc_names:
  307:             # clean name
  308:             sqlname = name.replace(" ","_").lower() 
  309:         else:
  310:             sqlname = name
  311:         self.xml_field_names.append(name)
  312:         # map to sql name and default text type
  313:         self.xml_field_map[name] = TableColumn(sqlname, 'text')
  314:         self.sql_field_map[sqlname] = name
  315:         self.logger.debug("FIELD name: "+name)
  316:         return
  317: 
  318:     def handle_data_fields(self, end_condition):
  319:         dispatcher = {
  320:             (saxtools.START_ELEMENT, fm_ns, u'ROW'):
  321:             self.handle_row,
  322:             }
  323:         #First round through the generator corresponds to the
  324:         #start element event
  325:         self.logger.info("reading data...")
  326:         self.logger.debug("START RESULTSET")
  327:         self.rowcnt = 0
  328:         yield None
  329:     
  330:         #delegate is a generator that handles all the events "within"
  331:         #this element
  332:         delegate = None
  333:         while not self.event == end_condition:
  334:             delegate = saxtools.tenorsax.event_loop_body(
  335:                 dispatcher, delegate, self.event)
  336:             yield None
  337:         
  338:         #Element closed.  Wrap up
  339:         self.logger.debug("END RESULTSET")
  340:         self.dbCon.commit()
  341:         
  342:         if self.sync_mode:
  343:             # delete unmatched entries in db
  344:             self.logger.info("deleting unmatched rows from db")
  345:             delQuery = "DELETE FROM %s WHERE %s = %%s"%(self.table,self.id_field)
  346:             for id in self.dbIDs.keys():
  347:                 # find all not-updated fields
  348:                 if self.dbIDs[id] == 0:
  349:                     self.logger.info(" delete:"+id)
  350:                     SimpleSearch(self.db, delQuery, [id], ascii=self.ascii_db)
  351:                     sys.exit(1)
  352:                     
  353:                 elif self.dbIDs[id] > 1:
  354:                     self.logger.info(" sync: ID %s used more than once?"%id)
  355:             
  356:             self.dbCon.commit()
  357:             
  358:         # reinstate backup tables
  359:         if self.backup_table and not self.id_field:
  360:             backup_name = "%s_%s"%(self.orig_table,time.strftime('%Y_%m_%d_%H_%M_%S'))
  361:             self.logger.info("rename backup table %s to %s"%(self.orig_table,backup_name))
  362:             qstr = "ALTER TABLE %s RENAME TO %s"%(self.orig_table,backup_name)
  363:             self.db.execute(qstr)
  364:             self.logger.info("rename working table %s to %s"%(self.table,self.orig_table))
  365:             qstr = "ALTER TABLE %s RENAME TO %s"%(self.table,self.orig_table)
  366:             self.db.execute(qstr)
  367:             self.dbCon.commit()
  368:         
  369:         return
  370: 
  371:     def handle_row(self, end_condition):
  372:         dispatcher = {
  373:             (saxtools.START_ELEMENT, fm_ns, u'COL'):
  374:             self.handle_col,
  375:             }
  376:         self.logger.debug("START ROW")
  377:         self.xml_data = {}
  378:         self.colIdx = 0
  379:         yield None
  380:     
  381:         #delegate is a generator that handles all the events "within"
  382:         #this element
  383:         delegate = None
  384:         while not self.event == end_condition:
  385:             delegate = saxtools.tenorsax.event_loop_body(
  386:                 dispatcher, delegate, self.event)
  387:             yield None
  388:         
  389:         #Element closed.  Wrap up
  390:         self.logger.debug("END ROW")
  391:         self.rowcnt += 1
  392:         # process collected row data
  393:         update=False
  394:         id_val=''
  395:         # synchronize by id_field
  396:         if self.id_field:
  397:             id_val = self.xml_data[self.xml_id]
  398:             if id_val in self.dbIDs:
  399:                 self.dbIDs[id_val] += 1
  400:                 update=True
  401: 
  402:         # collect all values
  403:         args = []
  404:         for fn in self.xml_update_list:
  405:             f = self.xml_field_map[fn]
  406:             val = self.xml_data[fn]
  407:             type = self.sql_fields[f.getName()].getType()
  408:             if type == "date" and len(val) == 0: 
  409:                 # empty date field
  410:                 val = None
  411:                 
  412:             elif type == "integer" and len(val) == 0: 
  413:                 # empty int field
  414:                 val = None
  415:                 
  416:             args.append(val)
  417:                     
  418:         if update:
  419:             # update existing row (by id_field)
  420:             # last argument is ID match
  421:             args.append(id_val)
  422:             self.logger.debug("update: %s = %s"%(id_val, args))
  423:             SimpleSearch(self.db, self.updQuery, args, ascii=self.ascii_db)
  424: 
  425:         else:
  426:             # create new row
  427:             self.logger.debug("insert: %s"%args)
  428:             SimpleSearch(self.db, self.addQuery, args, ascii=self.ascii_db)
  429: 
  430:         #self.logger.info(" row:"+"%d (%s)"%(self.rowcnt,id_val))
  431:         if (self.rowcnt % 100) == 0:
  432:             self.logger.info(" row:"+"%d (id:%s)"%(self.rowcnt,id_val))
  433:             self.dbCon.commit()
  434:             
  435:         return
  436: 
  437:     def handle_col(self, end_condition):
  438:         dispatcher = {
  439:             (saxtools.START_ELEMENT, fm_ns, u'DATA'):
  440:             self.handle_data_tag,
  441:             }
  442:         #print "START COL"
  443:         yield None
  444:         #delegate is a generator that handles all the events "within"
  445:         #this element
  446:         delegate = None
  447:         while not self.event == end_condition:
  448:             delegate = saxtools.tenorsax.event_loop_body(
  449:                 dispatcher, delegate, self.event)
  450:             yield None
  451:         #Element closed.  Wrap up
  452:         #print "END COL"
  453:         self.colIdx += 1
  454:         return
  455: 
  456:     def handle_data_tag(self, end_condition):
  457:         #print "START DATA"
  458:         content = u''
  459:         yield None
  460:         # gather child elements
  461:         while not self.event == end_condition:
  462:             if self.event[0] == saxtools.CHARACTER_DATA:
  463:                 content += self.params
  464:             yield None
  465:         #Element closed.  Wrap up
  466:         fn = self.xml_field_names[self.colIdx]
  467:         self.xml_data[fn] = content
  468:         return
  469: 
  470: 
  471: def importFMPXML(options):
  472:     """import FileMaker XML file (FMPXMLRESULT format) into the table.     
  473:         @param options: dict of options
  474:         @param options.dsn: database connection string
  475:         @param options.table: name of the table the xml shall be imported into
  476:         @param options.filename: xmlfile filename
  477:         @param options.update_fields: (optional) list of fields to update; default is to create all fields
  478:         @param options.id_field: (optional) field which uniquely identifies an entry for updating purposes.
  479:         @param options.sync_mode: (optional) really synchronise, i.e. delete entries not in XML file
  480:         @param options.lc_names: (optional) lower case and clean up field names from XML
  481:         @param options.keep_fields: (optional) don't add fields to SQL database
  482:         @param options.ascii_db: (optional) assume ascii encoding in db
  483:         @param options.replace_table: (optional) delete and re-insert data
  484:         @param options.backup_table: (optional) create backup of old table
  485:         """
  486:         
  487:     if getattr(options,'update_fields',None):
  488:         uf = {}
  489:         for f in options.update_fields.split(','):
  490:             if f.find(':') > 0:
  491:                 (n,t) = f.split(':')
  492:             else:
  493:                 n = f
  494:                 t = None
  495:             uf[n] = TableColumn(n,t)
  496:             
  497:         options.update_fields = uf
  498:     
  499:     if getattr(options,'id_field',None) and getattr(options,'replace_table',None):
  500:         logging.error("ABORT: sorry, you can't do both sync (id_field) and replace")
  501:         return
  502:         
  503:     parser = sax.make_parser()
  504:     #The "consumer" is our own handler
  505:     consumer = xml_handler(options)
  506:     #Initialize Tenorsax with handler
  507:     handler = saxtools.tenorsax(consumer)
  508:     #Resulting tenorsax instance is the SAX handler 
  509:     parser.setContentHandler(handler)
  510:     parser.setFeature(sax.handler.feature_namespaces, 1)
  511:     parser.parse(options.filename)  
  512:     
  513: 
  514: if __name__ == "__main__":
  515:     from optparse import OptionParser
  516: 
  517:     opars = OptionParser()
  518:     opars.add_option("-f", "--file", 
  519:                      dest="filename",
  520:                      help="FMPXML file name", metavar="FILE")
  521:     opars.add_option("-c", "--dsn", 
  522:                      dest="dsn", 
  523:                      help="database connection string")
  524:     opars.add_option("-t", "--table", 
  525:                      dest="table", 
  526:                      help="database table name")
  527:     opars.add_option("--fields", default=None, 
  528:                      dest="update_fields", 
  529:                      help="list of fields to update (comma separated, sql-names)", metavar="LIST")
  530:     opars.add_option("--id-field", default=None, 
  531:                      dest="id_field", 
  532:                      help="name of id field for synchronisation (only appends data otherwise, sql-name)", metavar="NAME")
  533:     opars.add_option("--sync", "--sync-mode", default=False, action="store_true", 
  534:                      dest="sync_mode", 
  535:                      help="do full sync based on id field (remove unmatched fields from db)")
  536:     opars.add_option("--lc-names", default=False, action="store_true", 
  537:                      dest="lc_names", 
  538:                      help="clean and lower case field names from XML")
  539:     opars.add_option("--keep-fields", default=False, action="store_true", 
  540:                      dest="keep_fields", 
  541:                      help="don't add fields from XML to SQL table")
  542:     opars.add_option("--ascii-db", default=False, action="store_true", 
  543:                      dest="ascii_db", 
  544:                      help="the SQL database stores ASCII instead of unicode")
  545:     opars.add_option("--replace", default=False, action="store_true", 
  546:                      dest="replace_table", 
  547:                      help="replace table i.e. delete and re-insert data")
  548:     opars.add_option("--backup", default=False, action="store_true", 
  549:                      dest="backup_table", 
  550:                      help="create backup of old table")
  551:     opars.add_option("-d", "--debug", default=False, action="store_true", 
  552:                      dest="debug", 
  553:                      help="debug mode (more output)")
  554:     
  555:     (options, args) = opars.parse_args()
  556:     
  557:     if len(sys.argv) < 2 or options.filename is None or options.dsn is None:
  558:         print "importFMPXML "+version_string
  559:         opars.print_help()
  560:         sys.exit(1)
  561:     
  562:     if options.debug:
  563:         loglevel = logging.DEBUG
  564:     else:
  565:         loglevel = logging.INFO
  566:     
  567:     logging.basicConfig(level=loglevel, 
  568:                         format='%(asctime)s %(levelname)s %(message)s',
  569:                         datefmt='%H:%M:%S')
  570: 
  571:     importFMPXML(options)
  572: 
  573: 
  574:     
  575: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>