def recordInfo(self, tablename_or_query): if not self.isOpen(): return None info = [] if isinstance(tablename_or_query, str): tablename = tablename_or_query doc = QDomDocument(tablename) stream = self.db_.managerModules().contentCached("%s.mtd" % tablename) util = FLUtil() if not util.domDocumentSetContent(doc, stream): print("FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla") + tablename) return self.recordInfo2(tablename) docElem = doc.documentElement() mtd = self.db_.manager().metadata(docElem, True) if not mtd: return self.recordInfo2(tablename) fL = mtd.fieldList() if not fL: del mtd return self.recordInfo2(tablename) for f in mtd.fieldsNames(): field = mtd.field(f) info.append([field.name(), field.type(), not field.allowNull(), field.length( ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()]) del mtd return info
def recordInfo(self, tablename_or_query): if not self.isOpen(): return None info = [] if isinstance(tablename_or_query, str): tablename = tablename_or_query doc = QDomDocument(tablename) stream = self.db_.managerModules().contentCached("%s.mtd" % tablename) util = FLUtil() if not util.domDocumentSetContent(doc, stream): print( "FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla %1").arg(tablename)) return self.recordInfo2(tablename) docElem = doc.documentElement() mtd = self.db_.manager().metadata(docElem, True) if not mtd: return self.recordInfo2(tablename) fL = mtd.fieldList() if not fL: del mtd return self.recordInfo2(tablename) for f in mtd.fieldsNames(): field = mtd.field(f) info.append([field.name(), field.type(), not field.allowNull(), field.length( ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()]) del mtd return info
def createSystemTable(self, n): util = FLUtil() if not self.existsTable(n): doc = QDomDocument() _path = filedir("..", "share", "pineboo", "tables") dir = qsatype.Dir(_path) _tables = dir.entryList("%s.mtd" % n) for f in _tables: path = "%s/%s" % (_path, f) _file = QtCore.QFile(path) _file.open(QtCore.QIODevice.ReadOnly) _in = QtCore.QTextStream(_file) _data = _in.readAll() if not util.domDocumentSetContent(doc, _data): print( "FLManager::createSystemTable :", util.tr( "Error al cargar los metadatos para la tabla %1"). arg(n)) return False else: docElem = doc.documentElement() mtd = self.createTable(self.metadata(docElem, True)) return mtd f.close() return False
def recordInfo(self, tablename_or_query): if not self.isOpen(): return None info = [] if isinstance(tablename_or_query, str): tablename = tablename_or_query doc = QDomDocument(tablename) stream = self.db_.managerModules().contentCached("%s.mtd" % tablename) util = FLUtil() if not util.domDocumentSetContent(doc, stream): print("FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla %1" ).arg(tablename)) return self.recordInfo2(tablename) docElem = doc.documentElement() mtd = self.db_.manager().metadata(docElem, True) if not mtd: return self.recordInfo2(tablename) fL = mtd.fieldList() if not fL: del mtd return self.recordInfo2(tablename) for f in mtd.fieldsNames(): field = mtd.field(f) info.append([ field.name(), field.type(), not field.allowNull(), field.length(), field.partDecimal(), field.defaultValue(), field.isPrimaryKey() ]) del mtd return info else: for columns in tablename_or_query: fName = columns[1] fType = columns[2] fSize = 0 fAllowNull = (columns[3] == 0) if fType.find("VARCHAR(") > -1: fSize = int(fType[fType.find("(") + 1:len(fType) - 1]) info.append( [fName, self.decodeSqlType(fType), not fAllowNull, fSize]) return info
def recordInfo(self, tablename_or_query): if not self.isOpen(): return None info = [] if isinstance(tablename_or_query, str): tablename = tablename_or_query doc = QDomDocument(tablename) stream = self.db_.managerModules().contentCached("%s.mtd" % tablename) util = FLUtil() if not util.domDocumentSetContent(doc, stream): print( "FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla %1").arg(tablename)) return self.recordInfo2(tablename) docElem = doc.documentElement() mtd = self.db_.manager().metadata(docElem, True) if not mtd: return self.recordInfo2(tablename) fL = mtd.fieldList() if not fL: del mtd return self.recordInfo2(tablename) for f in mtd.fieldsNames(): field = mtd.field(f) info.append([field.name(), field.type(), not field.allowNull(), field.length( ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()]) del mtd return info else: for columns in tablename_or_query: fName = columns[1] fType = columns[2] fSize = 0 fAllowNull = (columns[3] == 0) if fType.find("VARCHAR(") > -1: fSize = int(fType[fType.find("(") + 1: len(fType) - 1]) info.append([fName, self.decodeSqlType( fType), not fAllowNull, fSize]) return info
def init(self, aclXml=None): util = FLUtil() if not aclXml: self.init(self.database().managerModules().content("acl.xml")) return doc = QDomDocument("ACL") if self.accessControlList_: self.accessControlList_.clear() del self.accessControlList_ self.accessControlList_ = {} if not util.domDocumentSetContent(doc, aclXml): qWarning("FLAccessControlList : " + util.tr("Lista de control de acceso vacia o errónea")) return self.accessControlList_ = {} self.accessControlList_.setAutoDelete(True) docElem = doc.documentElement() no = docElem.firstChild() while no: e = no.toElement() if e: if e.tagName() == "name": self.name_ = e.text() no = no.nextSibling() continue ac = FLAccessControlFactory.create(e.tagName()) if ac: ac.set(e) self.accessControlList_.replace( "%s::%s::%s" % (ac.type(), ac.name(), ac.user()), ac) no = no.nextSibling() continue no = no.nextSibling()
def installACL(self, idacl): util = FLUtil() doc = QDomDocument("ACL") root = doc.createElement("ACL") doc.appendChild(root) name = doc.createElement("name") root.appendChild(name) n = doc.createTextNode(idacl) name.appendChild(n) q = FLSqlQuery() q.setTablesList("flacs") q.setSelect("idac,tipo,nombre,iduser,idgroup,degroup,permiso") q.setFrom("flacs") q.setWhere("idacl='%s'" % idacl) q.setOrderBy("prioridad DESC, tipo") q.setForwarOnly(True) if q.exec_(): step = 0 progress = util.ProgressDialog( util.tr("Instalando control de acceso..."), None, q.size(), None, None, True) progress.setCaption(util.tr("Instalando ACL")) progress.setMinimumDuration(0) progress.setProgress(++step) while q.next(): self.makeRule(q, doc) progress.setProgress(++step) self.database().managerModules().setContent( "acl.xml", "sys", doc.toString())
def alterTable(self, mtd1, mtd2, key): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.docDocumentSetContect(doc, mtd1): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if not util.docDocumentSetContect(doc, mtd2): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + qApp.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + qApp.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + qApp.tr( "La tabla %1 antigua de donde importar los registros no existe." ).arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime( ).currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() q = FLSqlQuery("", self.db_.dbAux()) if not q.exec_("CREATE TABLE %s AS SELECT * FROM %s;" % (renameOld, oldMTD.name())) or not q.exec_( "DROP TABLE %s;" % oldMTD.name()): print("FLManager::alterTable : " + qApp.tr("No se ha podido renombrar la tabla antigua.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux()) newCursor.setMode(newCursor.Insert) oldCursor.select() totalSteps = oldCursor.size() progress = QProgressDialog( qApp.tr("Reestructurando registros para %1...").arg( newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps) progress.setLabelText(qApp.tr("Tabla modificada")) step = 0 newBuffer = None # sequence = "" fieldList = newMTD.fieldList() newField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los nuevos metadatos no tienen campos.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False v = None ok = True while oldCursor.next(): v = None newBuffer = newCursor.primeInsert() for it in fieldList: oldField = oldMTD.field(newField.name()) if not oldField or not oldCursor.field(oldField.name()): if not oldField: oldField = newField v = newField.defaultValue() else: v = oldCursor.value(newField.name()) if (not oldField.allowNull() or not newField.allowNull()) and (v is None): defVal = newField.defaultValue() if defVal is not None: v = defVal if not newBuffer.field( newField.name()).type() == newField.type(): print("FLManager::alterTable : " + qApp.tr( "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo." ).arg(newField.name())) if not oldField.allowNull( ) or not newField.allowNull() and v is not None: if oldField.type() in ("int", "serial", "uint", "bool", "unlock"): v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime().currentTime() elif oldField.type() == "date": v = QDate().currentDate() else: v = "NULL"[0:newField.length()] newBuffer.setValue(newField.name(), v) if not newCursor.insert(): ok = False break step = step + 1 progress.setProgress(step) progress.setProgress(totalSteps) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False return True
def alterTable2(self, mtd1, mtd2, key, force=False): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.docDocumentSetContect(doc, mtd1): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if not util.docDocumentSetContect(doc, mtd2): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + qApp.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + qApp.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + qApp.tr( "La tabla %1 antigua de donde importar los registros no existe.").arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False renameOld = "%salteredtable%s" % ( oldMTD.name()[0:5], QDateTime().currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() q = FLSqlQuery("", self.db_.dbAux()) constraintName = "%s_pkey" % oldMTD.name() if self.constraintExists(constraintName) and not q.exec_("ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): print("FLManager : " + qApp.tr("En método alterTable, no se ha podido borrar el índice %1_pkey de la tabla antigua.").arg(oldMTD.name())) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldsNamesOld = [] for it in fieldList: if newMTD.field(it.name()): fieldsNamesOld.append(it.name()) if it.isUnique(): constraintName = "%s_%s_key" % (oldMTD.name(), it.name()) if self.constraintExists(constraintName) and not q.exec_("ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): print("FLManager : " + qApp.tr("En método alterTable, no se ha podido borrar el índice %1_%2_key de la tabla antigua.") .arg(oldMTD.name(), oldField.name())) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not q.exec_("ALTER TABLE %s RENAME TO %s" % (oldMTD.name(), renameOld)): print("FLManager::alterTable : " + qApp.tr("No se ha podido renombrar la tabla antigua.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False v = None ok = False if not force and not fieldsNamesOld: self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return self.alterTable2(mtd1, mtd2, key, True) oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux()) newCursor.setMode(newCursor.Insert) oldCursor.select() totalSteps = oldCursor.size() progress = QProgressDialog(qApp.tr("Reestructurando registros para %1...").arg( newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps) progress.setLabelText(qApp.tr("Tabla modificada")) step = 0 newBuffer = None newField = None listRecords = [] newBufferInfo = self.recordInfo2(newMTD.name()) oldFieldsList = {} newFieldsList = {} defValues = {} v = None for newField in fieldList: oldField = oldMTD.field(newField.name()) defValues[str(step)] = None if not oldField or not oldCursor.field(oldField.name()): if not oldField: oldField = newField if not newField.type() == "serial": v = newField.defaultValue() defValues[str(step)] = v newFieldsList[str(step)] = newField oldFieldsList[str(step)] = oldField step = step + 1 step = 0 ok = True while oldCursor.next(): newBuffer = newBufferInfo for reg in defValues.keys(): newField = newFieldsList[reg] oldField = oldFieldsList[reg] if defValues[reg]: v = defValues[reg] else: v = oldCursor.value(newField.name()) if (not oldField.allowNull or not newField.allowNull()) and not v and not newField.type() == "serial": defVal = newField.defaultValue() if defVal is not None: v = defVal if v is not None and not newBuffer.field(newField.name()).type() == newField.type(): print("FLManager::alterTable : " + qApp.tr( "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo.").arg(newField.name())) if v is not None and newField.type() == "string" and newField.length() > 0: v = str(v)[0:newField.length()] if (not oldField.allowNull() or not newField.allowNull()) and v is None: if oldField.type() == "serial": v = int(self.nextSerialVal( newMTD.name(), newField.name())) elif oldField.type() in ("int", "uint", "bool", "unlock"): v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime().currentTime() elif oldField.type() == "date": v = QDate().currentDate() else: v = "NULL"[0:newField.length()] newBuffer.setValue(newField.name(), v) listRecords.append(newBuffer) if not self.insertMulti(newMTD.name(), listRecords): ok = False listRecords.clear() break listRecords.clear() if len(listRecords) > 0: if not self.insertMulti(newMTD.name(), listRecords): ok = False listRecords.clear() progress.setProgress(totalSteps) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False if force and ok: q.exec_("DROP TABLE %s CASCADE" % renameOld) return True
def alterTable(self, mtd1, mtd2, key): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.docDocumentSetContect(doc, mtd1): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if not util.docDocumentSetContect(doc, mtd2): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + qApp.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + qApp.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + qApp.tr( "La tabla %1 antigua de donde importar los registros no existe.").arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False renameOld = "%salteredtable%s" % ( oldMTD.name()[0:5], QDateTime().currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() q = FLSqlQuery("", self.db_.dbAux()) if not q.exec_("CREATE TABLE %s AS SELECT * FROM %s;" % (renameOld, oldMTD.name())) or not q.exec_("DROP TABLE %s;" % oldMTD.name()): print("FLManager::alterTable : " + qApp.tr("No se ha podido renombrar la tabla antigua.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux()) newCursor.setMode(newCursor.Insert) oldCursor.select() totalSteps = oldCursor.size() progress = QProgressDialog(qApp.tr("Reestructurando registros para %1...").arg( newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps) progress.setLabelText(qApp.tr("Tabla modificada")) step = 0 newBuffer = None # sequence = "" fieldList = newMTD.fieldList() newField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los nuevos metadatos no tienen campos.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False v = None ok = True while oldCursor.next(): v = None newBuffer = newCursor.primeInsert() for it in fieldList: oldField = oldMTD.field(newField.name()) if not oldField or not oldCursor.field(oldField.name()): if not oldField: oldField = newField v = newField.defaultValue() else: v = oldCursor.value(newField.name()) if (not oldField.allowNull() or not newField.allowNull()) and (v is None): defVal = newField.defaultValue() if defVal is not None: v = defVal if not newBuffer.field(newField.name()).type() == newField.type(): print("FLManager::alterTable : " + qApp.tr("Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo.") .arg(newField.name())) if not oldField.allowNull() or not newField.allowNull() and v is not None: if oldField.type() in ("int", "serial", "uint", "bool", "unlock"): v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime().currentTime() elif oldField.type() == "date": v = QDate().currentDate() else: v = "NULL"[0:newField.length()] newBuffer.setValue(newField.name(), v) if not newCursor.insert(): ok = False break step = step + 1 progress.setProgress(step) progress.setProgress(totalSteps) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False return True
def alterTable2(self, mtd1, mtd2, key, force=False): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.docDocumentSetContect(doc, mtd1): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if not util.docDocumentSetContect(doc, mtd2): print("FLManager::alterTable : " + qApp.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + qApp.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + qApp.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + qApp.tr( "La tabla %1 antigua de donde importar los registros no existe." ).arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + qApp.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime( ).currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() q = FLSqlQuery("", self.db_.dbAux()) constraintName = "%s_pkey" % oldMTD.name() if self.constraintExists(constraintName) and not q.exec_( "ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): print("FLManager : " + qApp.tr( "En método alterTable, no se ha podido borrar el índice %1_pkey de la tabla antigua." ).arg(oldMTD.name())) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldsNamesOld = [] for it in fieldList: if newMTD.field(it.name()): fieldsNamesOld.append(it.name()) if it.isUnique(): constraintName = "%s_%s_key" % (oldMTD.name(), it.name()) if self.constraintExists(constraintName) and not q.exec_( "ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): print("FLManager : " + qApp.tr( "En método alterTable, no se ha podido borrar el índice %1_%2_key de la tabla antigua." ).arg(oldMTD.name(), oldField.name())) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not q.exec_("ALTER TABLE %s RENAME TO %s" % (oldMTD.name(), renameOld)): print("FLManager::alterTable : " + qApp.tr("No se ha podido renombrar la tabla antigua.")) self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False v = None ok = False if not force and not fieldsNamesOld: self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return self.alterTable2(mtd1, mtd2, key, True) oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) newCursor = FLSqlCursor(newMTD.name(), True, self.db_.dbAux()) newCursor.setMode(newCursor.Insert) oldCursor.select() totalSteps = oldCursor.size() progress = QProgressDialog( qApp.tr("Reestructurando registros para %1...").arg( newMTD.alias()), qApp.tr("Cancelar"), 0, totalSteps) progress.setLabelText(qApp.tr("Tabla modificada")) step = 0 newBuffer = None newField = None listRecords = [] newBufferInfo = self.recordInfo2(newMTD.name()) oldFieldsList = {} newFieldsList = {} defValues = {} v = None for newField in fieldList: oldField = oldMTD.field(newField.name()) defValues[str(step)] = None if not oldField or not oldCursor.field(oldField.name()): if not oldField: oldField = newField if not newField.type() == "serial": v = newField.defaultValue() defValues[str(step)] = v newFieldsList[str(step)] = newField oldFieldsList[str(step)] = oldField step = step + 1 step = 0 ok = True while oldCursor.next(): newBuffer = newBufferInfo for reg in defValues.keys(): newField = newFieldsList[reg] oldField = oldFieldsList[reg] if defValues[reg]: v = defValues[reg] else: v = oldCursor.value(newField.name()) if (not oldField.allowNull or not newField.allowNull() ) and not v and not newField.type() == "serial": defVal = newField.defaultValue() if defVal is not None: v = defVal if v is not None and not newBuffer.field( newField.name()).type() == newField.type(): print("FLManager::alterTable : " + qApp.tr( "Los tipos del campo %1 no son compatibles. Se introducirá un valor nulo." ).arg(newField.name())) if v is not None and newField.type( ) == "string" and newField.length() > 0: v = str(v)[0:newField.length()] if (not oldField.allowNull() or not newField.allowNull()) and v is None: if oldField.type() == "serial": v = int( self.nextSerialVal(newMTD.name(), newField.name())) elif oldField.type() in ("int", "uint", "bool", "unlock"): v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime().currentTime() elif oldField.type() == "date": v = QDate().currentDate() else: v = "NULL"[0:newField.length()] newBuffer.setValue(newField.name(), v) listRecords.append(newBuffer) if not self.insertMulti(newMTD.name(), listRecords): ok = False listRecords.clear() break listRecords.clear() if len(listRecords) > 0: if not self.insertMulti(newMTD.name(), listRecords): ok = False listRecords.clear() progress.setProgress(totalSteps) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False if force and ok: q.exec_("DROP TABLE %s CASCADE" % renameOld) return True
def alterTable2(self, mtd1, mtd2, key, force=False): util = FLUtil() oldMTD = None newMTD = None doc = QDomDocument("doc") docElem = None if not util.domDocumentSetContent(doc, mtd1): print("FLManager::alterTable : " + util.tr("Error al cargar los metadatos.")) else: docElem = doc.documentElement() oldMTD = self.db_.manager().metadata(docElem, True) if oldMTD and oldMTD.isQuery(): return True if oldMTD and self.hasCheckColumn(oldMTD): return False if not util.domDocumentSetContent(doc, mtd2): print("FLManager::alterTable : " + util.tr("Error al cargar los metadatos.")) return False else: docElem = doc.documentElement() newMTD = self.db_.manager().metadata(docElem, True) if not oldMTD: oldMTD = newMTD if not oldMTD.name() == newMTD.name(): print("FLManager::alterTable : " + util.tr("Los nombres de las tablas nueva y vieja difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False oldPK = oldMTD.primaryKey() newPK = newMTD.primaryKey() if not oldPK == newPK: print("FLManager::alterTable : " + util.tr("Los nombres de las claves primarias difieren.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not force and self.db_.manager().checkMetaData(oldMTD, newMTD): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return True if not self.db_.manager().existsTable(oldMTD.name()): print("FLManager::alterTable : " + util.tr("La tabla %1 antigua de donde importar los registros no existe.").arg(oldMTD.name())) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldList = oldMTD.fieldList() oldField = None if not fieldList: print("FLManager::alterTable : " + util.tr("Los antiguos metadatos no tienen campos.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False fieldsNamesOld = [] if not force: for it in fieldList: if newMTD.field(it.name()) is not None: fieldsNamesOld.append(it.name()) renameOld = "%salteredtable%s" % (oldMTD.name()[0:5], QDateTime().currentDateTime().toString("ddhhssz")) if not self.db_.dbAux(): if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False #self.db_.dbAux().transaction() fieldList = newMTD.fieldList() if not fieldList: qWarning("FLManager::alterTable : " + util.tr("Los nuevos metadatos no tienen campos")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False q = FLSqlQuery(None, "dbAux") if not q.exec_("ALTER TABLE %s RENAME TO %s" % (oldMTD.name(), renameOld)): qWarning("FLManager::alterTable : " + util.tr("No se ha podido renombrar la tabla antigua.")) if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False self.db_.dbAux().transaction() if not force and key and len(key) == 40: c = FLSqlCursor("flfiles", True, self.db_.dbAux()) c.setForwardOnly(True) c.setFilter("nombre = '%s.mtd'" % renameOld) c.select() if not c.next(): buffer = c.primeInsert() buffer.setValue("nombre", "%s.mtd" % renameOld) buffer.setValue("contenido", mtd1) buffer.setValue("sha", key) c.insert() ok = False if not force and fieldsNamesOld: sel = fieldsNamesOld.join(",") in_sql = "INSERT INTO %s(%s) SELECT %s FROM %s" % (newMTD.name(), sel, self, renameOld) qWarning(in_sql) ok = q.exec_(in_sql) if not ok: self.db_.dbAux().rollback() if oldMTD and not oldMTD == newMTD: del oldMTD if newMTD: del newMTD return False return self.alterTable2(mtd1, mtd2, key, True) if not ok: oldCursor = FLSqlCursor(renameOld, True, "dbAux") oldCursor.setModeAccess(oldCursor.Browse) oldCursor.setForwardOnly(True) oldCursor.select() totalSteps = oldCursor.size() util.createProgressDialog(util.tr("Reestructurando registros para %s..." % newMTD.alias()), totalSteps) util.setLabelText(util.tr("Tabla modificada")) step = 0 newBuffer = None newField = None listRecords = [] newBufferInfo = self.recordInfo2(newMTD.name()) vector_fields = {} defValues = {} v = None for it2 in fieldList: oldField = oldMTD.field(it2.name()) if oldField is None or oldCursor.field(oldField.name()) is None: if oldField is None: oldField = it2 if it2.type() != FLFieldMetaData.Serial: v = it2.defaultValue() step += 1 defValues[str(step)] = v step += 1 vector_fields[str(step)] = it2 step += 1 vector_fields[str(step)] = oldField step2 = 0 ok = True while oldCursor.next(): newBuffer = newBufferInfo i = 0 while i < len(vector_fields): if str(i) in defValues.keys(): v = defValues[str(i)] i += 1 newField = vector_fields[str(i)] i += 1 oldField = vector_fields[str(i)] else: i += 1 newField = vector_fields[str(i)] i += 1 oldField = vector_fields[str(i)] v = oldCursor.value(newField.name()) if (not oldField.allowNull() or not newField.allowNull()) and (v is None) and newField.type != FLFieldMetaData.Serial: defVal = newField.defaultValue() if defVal is not None: v = defVal if v is not None and newField.type() == "string" and newField.length() > 0: v = v[:newField.length()] if (not oldField.allowNull() or not newField.allowNull()) and v is None: if oldField.type() == FLFieldMetadata.Serial: v = int(self.nextSerialVal(newMTD.name(), newField.name())) elif oldField.type() in ["int", "uint", "bool", "unlock"]: v = 0 elif oldField.type() == "double": v = 0.0 elif oldField.type() == "time": v = QTime.currentTime() elif oldField.type() == "date": v = QDate.currentDate() else: v = str("NULL")[:newField.length()] newBuffer.setValue(newField.name(), v) listRecords.append(newBuffer) if len(listRecords) > 0: if not self.insertMulti(newMTD.name(), listRecords): ok = False listRecords.clear() util.setProgress(totalSteps) util.destroyProgressDialog() if ok: self.db_.dbAux().commit() if force: q.exec_("DROP TABLE %s CASCADE" % renameOld) else: self.db_.dbAux().rollback() q.exec_("DROP TABLE %s CASCADE" % oldMTD.name()) q.exec_("ALTER TABLE %s RENAME TO %s" % (renameOld, oldMTD.name())) if oldMTD and oldMTD != newMTD: del oldMTD if newMTD: del newMTD return False if oldMTD and oldMTD != newMTD: del oldMTD if newMTD: del newMTD return True
def metadata(self, n, quick=False): util = FLUtil() if not n: return None if isinstance(n, str): if not n or not self.db_.dbAux(): return None ret = False acl = False key = n stream = None isSysTable = (n[0:3] == "sys" or self.isSystemTable(n)) if not isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % key) if not stream: qWarning( "FLManager : Error al cargar los metadatos para la tabla %s" % n) return None # if not key: # key = n if not isSysTable: for fi in self.cacheMetaData_: if fi.name() == key: ret = fi break else: for fi in self.cacheMetaDataSys_: if fi.name() == key: ret = fi break if not ret: if isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % n) if not stream: qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None doc = QDomDocument(n) if not util.domDocumentSetContent(doc, stream): qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None docElem = doc.documentElement() ret = self.metadata(docElem, quick) if not ret: return None if not isSysTable and not ret.isQuery(): self.cacheMetaData_.append(ret) elif isSysTable: self.cacheMetaDataSys_.append(ret) else: acl = self._prj.acl() if ret.fieldsNamesUnlock(): ret = FLTableMetaData(ret) if acl: acl.process(ret) if not quick and not isSysTable and self._prj.consoleShown( ) and not ret.isQuery() and self.db_.mismatchedTable(n, ret): msg = util.tr( "La estructura de los metadatos de la tabla '%1' y su " "estructura interna en la base de datos no coinciden. " "Debe regenerar la base de datos.").arg(n) throwMsgWarning(self.db_, msg) return ret else: #QDomDoc name = None q = None a = None ftsfun = None v = True ed = True cw = False dl = False no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": no = no.nextSibling() continue if e.tagName() == "name": name = e.text() no = no.nextSibling() continue if e.tagName() == "query": q = e.text() no = no.nextSibling() continue if e.tagName() == "alias": a = auto_qt_translate_text(e.text()) a = util.translate("Metadata", a) no = no.nextSibling() continue if e.tagName() == "visible": v = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "editable": ed = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "concurWarn": cw = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "detectLocks": dl = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "FTSFunction": ftsfun = (e.text() == "true") no = no.nextSibling() continue no = no.nextSibling() tmd = FLTableMetaData(name, a, q) cK = None assocs = [] tmd.setFTSFunction(ftsfun) tmd.setConcurWarn(cw) tmd.setDetectLocks(dl) no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": f = self.metadataField(e, v, ed) if not tmd: tmd = FLTableMetaData(name, a, q) tmd.addFieldMD(f) if f.isCompoundKey(): if not cK: cK = FLCompoundKey() cK.addFieldMD(f) if f.associatedFieldName(): assocs.append(f.associatedFieldName()) assocs.append(f.associatedFieldFilterTo()) assocs.append(f.name()) no = no.nextSibling() continue no = no.nextSibling() tmd.setCompoundKey(cK) aWith = None aBy = None for it in assocs: if not aWith: aWith = it continue if not aBy: aBy = it continue tmd.field(it).setAssociatedField(tmd.field(aWith), aBy) if q and not quick: qry = self.query(q, tmd) if qry: fL = qry.fieldList() table = None field = None fields = tmd.fieldsNames().split(",") fieldsEmpty = (not fields) for it in fL: pos = it.find(".") if pos > -1: table = it[:pos] field = it[:pos] else: field = it if not (not fieldsEmpty and table == name and fields.find(field.lower())) == fields.end(): continue mtdAux = self.metadata(table, True) if mtdAux: fmtdAux = mtdAux.field(field) if mtdAux: isForeignKey = False if fmtdAux.isPrimaryKey( ) and not table == name: fmtdAux = FLFieldMetaData(fmtdAux) fmtdAux.setIsprimaryKey(False) fmtdAux.setEditable(False) newRef = (not isForeignKey) fmtdAuxName = fmtdAux.name().lower() if fmtdAuxName.find(".") == -1: fieldsAux = tmd.fieldsNames().split(",") if not fieldsAux.find( fmtdAuxName) == fieldsAux.end(): if not isForeignKey: fmdtAux = FLFieldMetaData(fmtdAux) fmtdAux.setName("%s.%s" % (tambe, field)) newRef = False if newRef: fmtdAux.ref() tmd.addFieldMD(fmtdAux) qry.deleteLater() acl = self._prj.acl() if acl: acl.process(tmd) return tmd