File:  [Repository] / ZSQLExtend / importFMPXML.py
Revision 1.23: download - view: text, annotated - select for diffs - revision graph
Wed Feb 13 19:48:50 2008 UTC (16 years, 3 months ago) by casties
Branches: MAIN
CVS tags: HEAD
added option --read-before-update to minimize updates of unchanged data at the cost of additional reads
fixed deletion of unmatched rows (hopefully)

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

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