def cleanupMetaData(self): """ Limpieza la tabla flmetadata, actualiza el cotenido xml con el de los fichero .mtd actualmente cargados """ # util = FLUtil() if not self.existsTable("flfiles") or not self.existsTable( "flmetadata"): return q = FLSqlQuery(None, self.db_.dbAux()) c = FLSqlCursor("flmetadata", True, self.db_.dbAux()) buffer = None table = "" # q.setForwardOnly(True) # c.setForwardOnly(True) if not self.dictKeyMetaData_: self.dictKeyMetaData_ = {} else: self.dictKeyMetaData_.clear() self.loadTables() self.db_.managerModules().loadKeyFiles() self.db_.managerModules().loadAllIdModules() self.db_.managerModules().loadIdAreas() q.exec_("SELECT tabla, xml FROM flmetadata") while q.next(): self.dictKeyMetaData_[str(q.value(0))] = str(q.value(1)) q.exec_( "SELECT nombre, sha FROM flfiles WHERE nombre LIKE '%.mtd'") while q.next(): table = str(q.value(0)) table = table.replace(".mtd", "") if not self.existsTable(table): self.createTable(table) tmd = self.metadata(table) if not tmd: qWarning("FLManager::cleanupMetaDAta " + QApplication.tr( "No se ha podido crear los metadatatos para la tabla %1" ).arg(table)) c.select("tabla='%s'" % table) if c.next(): buffer = c.primeUpdate() buffer.setValue("xml", str(q.value(1))) c.update() self.dictKeyMetaData_[table] = str(q.value(1))
def loadIdAreas(self): if not self._prj.conn.dbAux(): return self.listIdAreas_ = [] q = FLSqlQuery(None, self._prj.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT idarea from flareas WHERE idarea <> 'sys'") while q.next(): self.listIdAreas_.append(str(q.value(0))) self.listIdAreas_.append("sys")
def loadKeyFiles(self): self.dictKeyFiles = {} self.dictModFiles = {} q = FLSqlQuery(None, pineboolib.project.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT nombre, sha, idmodulo FROM flfiles") name = None while q.next(): name = str(q.value(0)) self.dictKeyFiles[name] = str(q.value(1)) self.dictModFiles[name.upper()] = str(q.value(2))
def loadKeyFiles(self): self.dictKeyFiles = {} self.dictModFiles = {} q = FLSqlQuery(None, self._prj.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT nombre, sha, idmodulo FROM flfiles") name = None while q.next(): name = str(q.value(0)) self.dictKeyFiles[name] = str(q.value(1)) self.dictModFiles[name.upper()] = str(q.value(2))
def shaOfFile(self, n): if pineboolib.project.conn.dbAux() and not n[:3] == "sys" and not pineboolib.project.conn.manager().isSystemTable(n): formatVal = pineboolib.project.conn.manager( ).formatAssignValue("nombre", "string", n, True) q = FLSqlQuery(None, pineboolib.project.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT sha FROM flfiles WHERE %s" % formatVal) if q.next(): return str(q.value(0)) return None else: return None
def loadIdAreas(self): if not pineboolib.project.conn.dbAux(): return self.listIdAreas_ = [] q = FLSqlQuery(None, pineboolib.project.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT idarea from flareas WHERE idarea <> 'sys'") while q.next(): self.listIdAreas_.append(str(q.value(0))) if not "sys" in self.listIdAreas_: self.listIdAreas_.append("sys")
def shaOfFile(self, n): if self._prj.conn.dbAux( ) and not n[:3] == "sys" and not self._prj.conn.manager( ).isSystemTable(n): formatVal = self._prj.conn.manager().formatAssignValue( "nombre", "string", n, True) q = FLSqlQuery(None, self._prj.conn.dbAux()) # q.setForwardOnly(True) q.exec_("SELECT sha FROM flfiles WHERE %s" % formatVal) if q.next(): return str(q.value(0)) return None else: return None
def fetchLargeValue(self, refKey): """ Obtiene el valor de gran tamaño segun su clave de referencia. @param refKey Clave de referencia. Esta clave se suele obtener mediante FLManager::storeLargeValue @return Valor de gran tamaño almacenado """ if refKey is None: return None if not refKey[0:3] == "RK@": return None q = FLSqlQuery() q.setSelect("contenido") q.setFrom("fllarge") q.setWhere(" refkey = '%s'" % refKey) if q.exec_() and q.first(): v = q.value(0) del q # print(v) if v.find("{"): v = v[v.find("{") + 3:] v = v[:v.find("};") + 1] # v = v.replace("\t", "") v = v.replace("\n", "") # v = v.replace("\",", ",") # v = v.replace(",\"", ",") v = v.replace("\t", " ") # v = v.replace("\n\"", "") # v = v.split(",") v = v.split('","') # print(v) return v
def sqlSelect(self, f, s, w, tL=None, size=0, connName="default"): """ Ejecuta una query de tipo select, devolviendo los resultados del primer registro encontrado @param f: Sentencia from de la query @param s: Sentencia select de la query, que será el nombre del campo a devolver @param w: Sentencia where de la query @param tL: Sentencia tableslist de la query. Necesario cuando en la sentencia from se incluya más de una tabla @param size: Número de líneas encontradas. (-1 si hay error) @param connName Nombre de la conexion @return Valor resultante de la query o falso si no encuentra nada. """ if w is None or w == "": return False q = FLSqlQuery(None, connName) if tL: q.setTablesList(tL) else: q.setTablesList(f) q.setSelect(s) q.setFrom(f) q.setWhere(w) # q.setForwardOnly(True) if not q.exec_(): return False if q.next(): valor = q.value(0) if isinstance(valor, datetime.date): valor = str(valor) return valor return False
def makeRuleGroup(self, q, d, idgroup): """ Crea varios nodos DOM correspondientes a un registro de la tabla "flacs" y para un grupo de usuarios determinado. La función de este método es crear una regla para cada uno de los usuarios miembros del grupo, utilizando FLAccessControlLists::makeRuleUser. @param q Consulta sobre la tabla "flacs" posicionada en el registro a utilizar para construir las reglas. @param d Documento DOM/XML en el que insertarán los nodos que describe las reglas de control de acceso. @param idgroup Identificador del grupo de usuarios. """ if not idgroup or not q or not d: return qU = FLSqlQuery() qU.setTablesList("flusers") qU.setSelect("iduser") qU.setFrom("flusers") qU.setWhere("'idgroup='%s'" % idgroup) qU.setForwardOnly(True) if qU.exec_(): while qU.next(): self.makeRuleUser(q, d, str(qU.value(0)))
def makeRuleUser(self, q, d, iduser): if not iduser or not q or not d: return ac = FLAccesccControlFactory.create(str(q.value(1))) if ac: ac.setName(str(q.value(2))) ac.setUser(iduser) ac.setPerm(str(q.value(6))) qAcos = FLSqlQuery() qAcos.setTablesList("flacos") qAcos.setSelect("nombre,permiso") qAcos.setFrom("flacos") qAcos.setWhere("idac ='%s'" % q.value(0)) qAcos.setForwardOnly() acos = None if qAcos.exec_(): while qAcos.next(): acos << str(qAcos.value(0)) acos << str(qAcos.value(1)) ac.setAcos(acos) ac.get(d) del ac
def existsTable(self, n, cache=True): #if not self.db_: # return False #if n == None: # return False #if cache and self.listTables_: # for name in self.listTables_: # if name == n: # return True # return False #else: # return self.db_.existsTable(n) #if cache: # modId = self.db_.managerModules().idModuleOfFile(n +".mtd") # res = os.path.exists(filedir("../tempdata/cache/%s/%s/file.mtd/%s" %(self.db_.db_name, modId, n))) # if res == False: # res == os.path.exists(filedir("../share/pineboo/tables/%s.mtd" %(n))) # return res #else: q = FLSqlQuery() sql_query = "SELECT * FROM %s WHERE 1 = 1" % n q.setTablesList(n) q.setSelect("*") q.setFrom(n) q.setWhere("1 = 1 LIMIT 1") return q.exec_()
def fetchLargeValue(self, refKey): if refKey == None: return None if not refKey[0:3] == "RK@": return None q = FLSqlQuery() q.setSelect("contenido") q.setFrom("fllarge") q.setWhere(" refkey = '%s'" % refKey) if q.exec_() and q.first(): v = q.value(0) del q #print(v) if v.find("{"): v = v[v.find("{") + 3:] v = v[:v.find("};") + 1] #v = v.replace("\t", "") v = v.replace("\n", "") #v = v.replace("\",", ",") #v = v.replace(",\"", ",") v = v.replace("\t", " ") #v = v.replace("\n\"", "") #v = v.split(",") v = v.split('","') #print(v) return v
def fetchLargeValue(self, refKey): """ Obtiene el valor de gran tamaño segun su clave de referencia. @param refKey Clave de referencia. Esta clave se suele obtener mediante FLManager::storeLargeValue @return Valor de gran tamaño almacenado """ if refKey is None: return None if not refKey[0:3] == "RK@": return None if self._prj.singleFLLarge(): tableName = "fllarge" else: tableName = "fllarge_" + refKey.split("@")[1] if not self.existsTable(tableName): return None q = FLSqlQuery() q.setSelect("contenido") q.setFrom(tableName) q.setWhere(" refkey = '%s'" % refKey) if q.exec_() and q.first(): v = q.value(0) del q # print(v) v = clearXPM(v) # print(v) return v
def validateForm(self): if not self.cursor_: return True mtd = self.cursor_.metadata() if not mtd: return True if self.cursor_.modeAccess() == FLSqlCursor.Edit and mtd.concurWarn(): colFields = [] colFields = self.cursor_.concurrencyFields() if colFields: pKN = mtd.primaryKey() pKWhere = self.cursor_.db().manager().formatAssignValue( mtd.field(pKN), self.cursor_.valueBuffer(pKN)) q = FLSqlQuery(None, self.cursor_.db().connectionName()) q.setTablesList(mtd.name()) q.setSelect(colFields) q.setFrom(mtd.name()) q.setWhere(pKWhere) q.setForwardOnly(True) if q.exec_() and q.next(): i = 0 for field in colFields: # msg = "El campo '%s' con valor '%s' ha sido modificado\npor otro usuario con el valor '%s'" % ( # mtd.fieldNameToAlias(field), self.cursor_.valueBuffer(field), q.value(i)) res = QtWidgets.QMessageBox.warning( QtWidgets.QApplication.focusWidget(), "Aviso de concurrencia", "\n\n ¿ Desea realmente modificar este campo ?\n\n" "Sí : Ignora el cambio del otro usuario y utiliza el valor que acaba de introducir\n" "No : Respeta el cambio del otro usuario e ignora el valor que ha introducido\n" "Cancelar : Cancela el guardado del registro y vuelve a la edición del registro\n\n", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Default, QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Escape) if res == QtWidgets.QMessageBox.Cancel: return False if res == QtWidgets.QMessageBox.No: self.cursor_.setValueBuffer(field, q.value(i)) if self.iface and self.cursor_.modeAccess( ) == FLSqlCursor.Insert or self.cursor_.modeAccess( ) == FLSqlCursor.Edit: if self.iface: try: v = self.iface.validateForm() except Exception: pass if v and not isinstance(v, bool): return False return True
def init(self): """ Acciones de inicialización. """ self.initCount_ = self.initCount_ + 1 self.createSystemTable("flmetadata") self.createSystemTable("flseqs") if not self.db_.dbAux(): return q = FLSqlQuery(None, self.db_.dbAux()) # q.setForwardOnly(True) self.createSystemTable("flsettings") if not q.exec_("SELECT * FROM flsettings WHERE flkey = 'sysmodver'"): q.exec_("DROP TABLE flsettings CASCADE") self.createSystemTable("flsettings") if not self.dictKeyMetaData_: self.dictKeyMetaData_ = {} # self.dictKeyMetaData_.setAutoDelete(True) else: self.dictKeyMetaData_.clear() q.exec_("SELECT tabla,xml FROM flmetadata") while q.next(): self.dictKeyMetaData_[q.value(0)] = q.value(1) q.exec_("SELECT * FROM flsettings WHERE flkey = 'sysmodver'") if not q.next(): q.exec_("DROP TABLE flmetadata CASCADE") self.createSystemTable("flmetadata") c = FLSqlCursor("flmetadata", True, self.db_.dbAux()) for key, value in self.dictKeyMetaData_: buffer = c.primeInsert() buffer.setValue("tabla", key) buffer.setValue("xml", value) c.insert() if not self.cacheMetaData_: self.cacheMetaData_ = [] if not self.cacheAction_: self.cacheAction_ = [] if not self.cacheMetaDataSys_: self.cacheMetaDataSys_ = []
def loadAllIdModules(self): if not pineboolib.project.conn.dbAux(): return self.listAllIdModules_ = [] self.listAllIdModules_.append("sys") self.dictInfoMods = {} q = FLSqlQuery(None, pineboolib.project.conn.dbAux()) q.setTablesList("flmodules,flareas") q.setSelect("idmodulo,flmodules.idarea,flmodules.descripcion,version,icono,flareas.descripcion") q.setFrom("flmodules left join flareas on flmodules.idarea = flareas.idarea") q.setWhere("1 = 1") q.setForwardOnly(True) q.exec_() # q.exec_("SELECT idmodulo,flmodules.idarea,flmodules.descripcion,version,icono,flareas.descripcion " # "FROM flmodules left join flareas on flmodules.idarea = flareas.idarea") sysModuleFound = False while q.next(): infoMod = FLInfoMod() infoMod.idModulo = str(q.value(0)) infoMod.idArea = str(q.value(1)) infoMod.descripcion = str(q.value(2)) infoMod.version = str(q.value(3)) infoMod.icono = str(q.value(4)) infoMod.areaDescripcion = str(q.value(5)) self.dictInfoMods[infoMod.idModulo.upper()] = infoMod if not infoMod.idModulo == "sys": self.listAllIdModules_.append(infoMod.idModulo) else: sysModuleFound = True if not sysModuleFound: infoMod = FLInfoMod() infoMod.idModulo = "sys" infoMod.idArea = "sys" infoMod.descripcion = "Administracion" infoMod.version = "0.0" infoMod.icono = self.contentFS( "%s/%s" % (filedir("../share/pineboo"), "/sys.xpm")) infoMod.areaDescripcion = "Sistema" self.dictInfoMods[infoMod.idModulo.upper()] = infoMod
def storeLargeValue(self, mtd, largeValue): if largeValue[0:3] == "RK@" or not mtd: return None tableName = mtd.name() if self.isSystemTable(tableName): return None tableLarge = None if self._prj.singleFLLarge(): tableLarge = "fllarge" else: tableLarge = "fllarge_%s" % tableName if not self.existsTable(tableLarge): mtdLarge = FLTableMetaData(tableLarge, tableLarge) fieldLarge = FLFieldMetaData("refkey", "refkey", False, True, "string", 100) mtdLarge.addFieldMD(fieldLarge) fieldLarge2 = FLFieldMetaData("sha", "sha", True, False, "string", 50) mtdLarge.addFieldMD(fieldLarge2) fieldLarge3 = FLFieldMetaData("contenido", "contenido", True, False, "stringlist") mtdLarge.addFieldMD(fieldLarge3) mtdAux = self.createTable(mtdLarge) mtd.insertChild(mtdLarge) if not mtdAux: return None util = FLUtil() sha = str(util.sha1(largeValue)) refKey = "RK@%s@%s" % (tableName, sha) q = FLSqlQuery() q.setSelect("refkey") q.setFrom("fllarge") q.setWhere(" refkey = '%s'" % refKey) if q.exec_() and q.first(): if not q.value(0) == sha: sql = "UPDATE %s SET contenido = '%s' WHERE refkey ='%s'" % ( tableLarge, largeValue, refKey) if not util.execSql(sql, "Aux"): print("FLManager::ERROR:StoreLargeValue.Update %s.%s" % (tableLarge, refKey)) return None else: sql = "INSERT INTO %s (contenido,refkey) VALUES ('%s','%s')" % ( tableLarge, largeValue, refKey) if not util.execSql(sql, "Aux"): print("FLManager::ERROR:StoreLargeValue.Insert %s.%s" % (tableLarge, refKey)) return None return refKey
def loadAllIdModules(self): if not self._prj.conn.dbAux(): return self.listAllIdModules_ = [] self.listAllIdModules_.append("sys") self.dictInfoMods = {} q = FLSqlQuery(None, self._prj.conn.dbAux()) # q.setForwardOnly(True) q.exec_( "SELECT idmodulo,flmodules.idarea,flmodules.descripcion,version,icono,flareas.descripcion " "FROM flmodules left join flareas on flmodules.idarea = flareas.idarea" ) sysModuleFound = False while q.next(): infoMod = FLInfoMod() infoMod.idModulo = str(q.value(0)) infoMod.idArea = str(q.value(1)) infoMod.descripcion = str(q.value(2)) infoMod.version = str(q.value(3)) infoMod.icono = str(q.value(4)) infoMod.areaDescripcion = str(q.value(5)) self.dictInfoMods[infoMod.idModulo.upper()] = infoMod if not infoMod.idModulo == "sys": self.listAllIdModules_.append(infoMod.idModulo) else: sysModuleFound = True if not sysModuleFound: infoMod = FLInfoMod() infoMod.idModulo = "sys" infoMod.idArea = "sys" infoMod.descripcion = "Administracion" infoMod.version = "0.0" infoMod.icono = self.contentFS( "%s/%s" % (filedir("../share/pineboo"), "/sys.xpm")) infoMod.areaDescripcion = "Sistema" self.dictInfoMods[infoMod.idModulo.upper()] = infoMod
def existsTable(self, name): if not self.isOpen(): return False t = FLSqlQuery() t.setForwardOnly(True) ok = t.exec_("SELECT * FROM %s WHERE 1 = 1 LIMIT 1" % name) if ok: ok = t.next() del t return ok
def nextSerialVal(self, table, field): q = FLSqlQuery() q.setSelect("max(%s)" % field) q.setFrom(table) q.setWhere("1 = 1") if not q.exec_(): # FIXME: exec es palabra reservada print("not exec sequence") return None if q.first(): return int(q.value(0)) + 1 else: return None
def nextSerialVal(self, table, field): q = FLSqlQuery() q.setSelect(u"nextval('" + table + "_" + field + "_seq')") q.setFrom("") q.setWhere("") if not q.exec_(): qWarning("not exec sequence") return None if q.first(): return q.value(0) else: return None
def nextSerialVal(self, table, field): q = FLSqlQuery() q.setSelect("max(%s)" % field) q.setFrom(table) q.setWhere("1 = 1") if not q.exec_(): # FIXME: exec es palabra reservada self.logger.warn("not exec sequence") return None if q.first() and q.value(0) is not None: return int(q.value(0)) + 1 else: return None
def tables(self, typeName=None): tl = [] if not self.isOpen(): return tl t = FLSqlQuery() t.setForwardOnly(True) if not typeName or typeName == "Tables": t.exec_( "select relname from pg_class where ( relkind = 'r' ) AND ( relname !~ '^Inv' ) AND relname !~ '^pg_' ) " ) while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "Views": t.exec_( "select relname from pg_class where ( relkind = 'v' ) AND ( relname !~ '^Inv' ) AND relname !~ '^pg_' ) " ) while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "SystemTables": t.exec_( "select relname from pg_class where ( relkind = 'r' ) AND relname like 'pg_%' ) " ) while t.next(): tl.append(str(t.value(0))) del t return tl
def tables(self, typeName=None): tl = [] if not self.isOpen(): return tl t = FLSqlQuery() t.setForwardOnly(True) if not typeName or typeName == "Tables": t.exec_( "select relname from pg_class where ( relkind = 'r' ) AND ( relname !~ '^Inv' ) AND ( relname !~ '^pg_' ) ") while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "Views": t.exec_( "select relname from pg_class where ( relkind = 'v' ) AND ( relname !~ '^Inv' ) AND ( relname !~ '^pg_' ) ") while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "SystemTables": t.exec_( "select relname from pg_class where ( relkind = 'r' ) AND ( relname like 'pg_%' ) ") while t.next(): tl.append(str(t.value(0))) del t return tl
def tables(self, typeName=None): tl = [] if not self.isOpen(): return tl t = FLSqlQuery() t.setForwardOnly(True) if typeName == "Tables" and typeName == "Views": t.exec_( "SELECT name FROM sqlite_master WHERE type='table' OR type='view'" ) elif not typeName or typeName == "Tables": t.exec_("SELECT name FROM sqlite_master WHERE type='table'") elif not typeName or typeName == "Views": t.exec_("SELECT name FROM sqlite_master WHERE type='view'") while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "SystemTables": tl.append("sqlite_master") del t return tl
def fetchLargeValue(self, refKey): if not refKey[0:3] == "RK@": return None q = FLSqlQuery() q.setSelect("contenido") q.setFrom("fllarge") q.setWhere(" refkey = '%s'" % refKey) if q.exec_() and q.first(): v = q.value(0) del q return v return None
def createTable(self, *tmd): if self.driverName_ is None or not self.tmd or not self.dbAux_: return False dr = self.dbAux_.driver() sql = dr.createTable(tmd) if sql is None: return False q = FLSqlQuery() if q.exec_(sql): print("FLManager: SQL - %s" % sql)
def existsTable(self, name): if not self.isOpen(): return False t = FLSqlQuery() t.setForwardOnly(True) ok = t.exec_( "select relname from pg_class where relname = '%s'" % name) if ok: ok = t.next() del t return ok
def existsTable(self, name): if not self.isOpen(): return False t = FLSqlQuery() t.setForwardOnly(True) ok = t.exec_("select relname from pg_class where relname = '%s'" % name) if ok: ok = t.next() del t return ok
def parseKey(name=None): ret = None value = None if name is None: ret = None else: q = FLSqlQuery() # q.setForwardOnly(True) q.exec_("SELECT contenido FROM fllarge WHERE refkey='%s'" % name) if q.next(): value = clearXPM(q.value(0)) imgFile = filedir("../tempdata") imgFile += "/%s.png" % name if not os.path.exists(imgFile) and value: pix = QPixmap(value) if not pix.save(imgFile): self.logger.warn("rml:refkey2cache No se ha podido guardar la imagen %s" % imgFile) ret = None ret = imgFile return ret
def existsTable(self, n, cache = True): if cache: modId = self.db_.managerModules().idModuleOfFile(n +".mtd") return os.path.exists(filedir("../tempdata/cache/%s/file.mtd/%s" %(modId, n))) q = FLSqlQuery() sql_query = "SELECT * FROM %s WHERE 1 = 1" % n q.setTablesList(n) q.setSelect("*") q.setFrom(n) q.setWhere("1 = 1 LIMIT 1") return q.exec_()
def existsTable(self, n, cache=True): if cache: modId = self.db_.managerModules().idModuleOfFile(n + ".mtd") return os.path.exists( filedir("../tempdata/cache/%s/file.mtd/%s" % (modId, n))) q = FLSqlQuery() sql_query = "SELECT * FROM %s WHERE 1 = 1" % n q.setTablesList(n) q.setSelect("*") q.setFrom(n) q.setWhere("1 = 1 LIMIT 1") return q.exec_()
def makeRuleGroup(self, q, d, idgroup): if not idgroup or not q or not d: return qU = FLSqlQuery() qU.setTablesList("flusers") qU.setSelect("iduser") qU.setFrom("flusers") qU.setWhere("'idgroup='%s'" % idgroup) qU.setForwardOnly(True) if qU.exec_(): while qU.next(): self.makeRuleUser(q, d, str(qU.value(0)))
def quickSqlSelect(self, f, s, w, connName="default"): """ Versión rápida de sqlSelect. Ejecuta directamente la consulta sin realizar comprobaciones. Usar con precaución. """ if not w: sql = "select " + s + " from " + f else: sql = "select " + s + " from " + f + " where " + w q = FLSqlQuery(None, connName) if not q.exec_(sql): return False return q.value(0) if q.first() else False
def readDBSettingEntry(self, key): """ Lee el valor de un setting en la tabla flsettings @param key. Clave identificadora del setting @return Valor del setting """ q = FLSqlQuery() q.setSelect("valor") q.setFrom("flsettings") q.setWhere("flkey = '%s'" % key) q.setTablesList("flsettings") if q.exec_() and q.first(): return q.value(0) return None
def validateForm(self): if not self.cursor_: return True mtd = self.cursor_.metadata() if not mtd: return True if self.cursor_.modeAccess() == FLSqlCursor.Edit and mtd.concurWarn(): colFields = [] colFields = self.cursor_.concurrencyFields() if colFields: pKN = mtd.primaryKey() pKWhere = self.cursor_.db().manager().formatAssignValue(mtd.field(pKN), self.cursor_.valueBuffer(pKN)) q = FLSqlQuery(None, self.cursor_.db().connectionName()) q.setTablesList(mtd.name()) q.setSelect(colFields) q.setFrom(mtd.name()) q.setWhere(pKWhere) q.setForwardOnly(True) if q.exec_() and q.next(): i = 0 for field in colFields: msg = "El campo '%s' con valor '%s' ha sido modificado\npor otro usuario con el valor '%s'" % (mtd.fieldNameToAlias(field), self.cursor_.valueBuffer(field), q.value(i)) res = QtGui.QMessageBox.warning(QtGui.qApp.focusWidget(), "Aviso de concurrencia", "\n\n ¿ Desea realmente modificar este campo ?\n\nSí : Ignora el cambio del otro usuario y utiliza el valor que acaba de introducir\nNo : Respeta el cambio del otro usuario e ignora el valor que ha introducido\nCancelar : Cancela el guardado del registro y vuelve a la edición del registro\n\n", QtGui.QMessageBox.Yes | QtGui.QMessageBox.Default, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Escape) if res == QtGui.QMessageBox.Cancel: return False if res == QtGui.QMessageBox.No: self.cursor_.setValueBuffer(field, q.value(i)) if self.iface and self.cursor_.modeAccess() == FLSqlCursor.Insert or self.cursor_.modeAccess() == FLSqlCursor.Edit: if self.iface: try: v = self.iface.validateForm() except Exception: pass if v and not isinstance(v, bool): return False return True
def installACL(self, idacl): """ Crea un nuevo fichero "acl.xml" y lo almacena sustituyendo el anterior, en el caso de que exista. @param idacl Identificador del registro de la tabla "flacls" a utilizar para crear "acl.xml". """ 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 releaseSavePoint(self, n): if not self.canSavePoint(): return False if not self.isOpen(): print("PSQLDriver::releaseSavePoint: Database not open") return False cmd = ("release savepoint sv_%s" % n) q = FLSqlQuery() q.setSelect(cmd) q.setFrom("") q.setWhere("") if not q.exec_(): self.setLastError("No se pudo release a punto de salvaguarda", "release savepoint sv_%s" % n) return False return True
def installACL(self, idacl): """ Crea un nuevo fichero "acl.xml" y lo almacena sustituyendo el anterior, en el caso de que exista. @param idacl Identificador del registro de la tabla "flacls" a utilizar para crear "acl.xml". """ 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 makeRuleUser(self, q, d, iduser): """ Crea un nodo DOM correspondiente a un registro de la tabla "flacs" y para un usuario determinado. @param q Consulta sobre la tabla "flacs" posicionada en el registro a utilizar para construir la regla. @param d Documento DOM/XML en el que insertará el nodo que describe la regla de control de acceso. @param iduser Identificador del usuario utilizado en la regla de control de acceso. """ if not iduser or not q or not d: return ac = FLAccessControlFactory.create(str(q.value(1))) if ac: ac.setName(str(q.value(2))) ac.setUser(iduser) ac.setPerm(str(q.value(6))) qAcos = FLSqlQuery() qAcos.setTablesList("flacos") qAcos.setSelect("nombre,permiso") qAcos.setFrom("flacos") qAcos.setWhere("idac ='%s'" % q.value(0)) qAcos.setForwardOnly() acos = None if qAcos.exec_(): while qAcos.next(): acos << str(qAcos.value(0)) acos << str(qAcos.value(1)) ac.setAcos(acos) ac.get(d) del ac
def tables(self, typeName=None): tl = [] if not self.isOpen(): return tl t = FLSqlQuery() t.setForwardOnly(True) if typeName == "Tables" and typeName == "Views": t.exec_( "SELECT name FROM sqlite_master WHERE type='table' OR type='view'") elif not typeName or typeName == "Tables": t.exec_("SELECT name FROM sqlite_master WHERE type='table'") elif not typeName or typeName == "Views": t.exec_("SELECT name FROM sqlite_master WHERE type='view'") while t.next(): tl.append(str(t.value(0))) if not typeName or typeName == "SystemTables": tl.append("sqlite_master") del t return tl
def sqlCreateTable(self, tmd): # util = FLUtil() if not tmd: return None primaryKey = None sql = "CREATE TABLE %s (" % tmd.name() seq = None fieldList = tmd.fieldList() unlocks = 0 for field in fieldList: if field.type() == "unlock": unlocks = unlocks + 1 if unlocks > 1: qWarning(u"FLManager : No se ha podido crear la tabla " + tmd.name()) qWarning( u"FLManager : Hay mas de un campo tipo unlock. Solo puede haber uno.") return None i = 1 for field in fieldList: sql = sql + field.name() if field.type() == "int": sql = sql + " INT2" elif field.type() == "uint": sql = sql + " INT4" elif field.type() in ("bool", "unlock"): sql = sql + " BOOLEAN" elif field.type() == "double": sql = sql + " FLOAT8" elif field.type() == "time": sql = sql + " TIME" elif field.type() == "date": sql = sql + " DATE" elif field.type() == "pixmap": sql = sql + " TEXT" elif field.type() == "string": sql = sql + " VARCHAR" elif field.type() == "stringlist": sql = sql + " TEXT" elif field.type() == "bytearray": sql = sql + " BYTEA" elif field.type() == "serial": seq = "%s_%s_seq" % (tmd.name(), field.name()) q = FLSqlQuery() q.setForwardOnly(True) q.exec_("SELECT relname FROM pg_class WHERE relname='%s'" % seq) if not q.next(): q.exec_("CREATE SEQUENCE %s" % seq) sql = sql + " INT4 DEFAULT NEXTVAL('%s')" % seq del q longitud = field.length() if longitud > 0: sql = sql + "(%s)" % longitud if field.isPrimaryKey(): if primaryKey is None: sql = sql + " PRIMARY KEY" else: qWarning(QApplication.tr("FLManager : Tabla-> ") + tmd.name() + QApplication.tr(" . Se ha intentado poner una segunda clave primaria para el campo ") + field.name() + QApplication.tr(" , pero el campo ") + primaryKey + QApplication.tr(" ya es clave primaria. Sólo puede existir una clave primaria en FLTableMetaData," " use FLCompoundKey para crear claves compuestas.")) return None else: if field.isUnique(): sql = sql + " UNIQUE" if not field.allowNull(): sql = sql + " NOT NULL" else: sql = sql + " NULL" if not i == len(fieldList): sql = sql + "," i = i + 1 sql = sql + ")" return sql
def constraintExists(self, name): sql = "SELECT constraint_name FROM information_schema.table_constraints where constraint_name='%s'" % name q = FLSqlQuery(None, self.db_.dbAux()) return (q.exec_(sql) and q.size() > 0)
def alterTable3(self, newMTD): if self.hasCheckColumn(newMTD): return False oldMTD = newMTD fieldList = oldMTD.fieldList() renameOld = "%salteredtable%s" % ( oldMTD.name()[0:5], QDateTime().currentDateTime().toString("ddhhssz")) self.db_.dbAux().transaction() q = FLSqlQuery(None, self.db_.dbAux()) constraintName = "%s_key" % oldMTD.name() if self.constraintExists(constraintName) and not q.exec_("ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): self.db_.dbAux().rollback() return False for oldField in fieldList: if oldField.isCheck(): return False if oldField.isUnique(): constraintName = "%s_%s_key" % (oldMTD.name(), oldField.name()) if self.constraintExists(constraintName) and not q.exec_("ALTER TABLE %s DROP CONSTRAINT %s" % (oldMTD.name(), constraintName)): self.db_.dbAux().rollback() return False if not q.exec_("ALTER TABLE %s RENAME TO %s" % (oldMTD.name(), renameOld)): self.db_.dbAux().rollback() return False if not self.db_.manager().createTable(newMTD): self.db_.dbAux().rollback() return False oldCursor = FLSqlCursor(renameOld, True, self.db_.dbAux()) oldCursor.setModeAccess(oldCursor.Browse) oldCursor.select() fieldList = newMTD.fieldList() if not fieldList: self.db_.dbAux().rollback() return False 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 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() if ok: self.db_.dbAux().commit() else: self.db_.dbAux().rollback() return False force = False # FIXME 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.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 nextCounter(self, *args, **kwargs): """ Este metodo devuelve el siguiente valor de un campo tipo contador de una tabla. Este metodo es muy util cuando se insertan registros en los que la referencia es secuencial y no nos acordamos de cual fue el ultimo numero usado. El valor devuelto es un QVariant del tipo de campo es el que se busca la ultima referencia. Lo más aconsejable es que el tipo del campo sea 'String' porque así se le puede dar formato y ser usado para generar un código de barras. De todas formas la función soporta tanto que el campo sea de tipo 'String' como de tipo 'double'. @param name Nombre del campo @param cursor_ Cursor a la tabla donde se encuentra el campo. @return Qvariant con el numero siguiente. @author Andrés Otón Urbano. """ """ dpinelo: Este método es una extensión de nextCounter pero permitiendo la introducción de una primera secuencia de caracteres. Es útil cuando queremos mantener diversos contadores dentro de una misma tabla. Ejemplo, Tabla Grupo de clientes: Agregamos un campo prefijo, que será una letra: A, B, C, D. Queremos que la numeración de los clientes sea del tipo A00001, o B000023. Con esta función, podremos seguir usando los métodos counter cuando agregamos esa letra. Este metodo devuelve el siguiente valor de un campo tipo contador de una tabla para una serie determinada. Este metodo es muy util cuando se insertan registros en los que la referencia es secuencial según una secuencia y no nos acordamos de cual fue el último numero usado. El valor devuelto es un QVariant del tipo de campo es el que se busca la ultima referencia. Lo más aconsejable es que el tipo del campo sea 'String' porque así se le puede dar formato y ser usado para generar un código de barras. De todas formas la función soporta tanto que el campo sea de tipo 'String' como de tipo 'double'. @param serie serie que diferencia los contadores @param name Nombre del campo @param cursor_ Cursor a la tabla donde se encuentra el campo. @return Qvariant con el numero siguiente. @author Andrés Otón Urbano. """ if len(args) == 2: name = args[0] cursor_ = args[1] if not cursor_: return None tMD = cursor_.metadata() if not tMD: return None field = tMD.field(name) if not field: return None type_ = field.type() if not type_ == "string" and not not type_ == "double": return None _len = int(field.length()) cadena = None q = FLSqlQuery(None, cursor_.db().connectionName()) q.setForwardOnly(True) q.setTablesList(tMD.name()) q.setSelect(name) q.setFrom(tMD.name()) q.setWhere("LENGTH(%s)=%s" % (name, _len)) q.setOrderBy(name + " DESC") if not q.exec_(): return None maxRange = 10 ** _len numero = maxRange while numero >= maxRange: if not q.next(): numero = 1 break numero = int(q.value(0)) numero = numero + 1 if type_ == "string": cadena = str(numero) if len(cadena) < _len: relleno = None relleno = cadena.rjust(_len, '0') cadena = relleno return cadena if type_ == "double": return numero return None else: serie = args[0] name = args[1] cursor_ = args[2] if not cursor_: return None tMD = cursor_.metadata() if not tMD: return None field = tMD.field(name) if not field: return None type_ = field.type() if not type_ == "string" and not type_ == "double": return None _len = field.length() - len(serie) cadena = None where = "length(%s)=%d AND substring(%s FROM 1 for %d) = '%s'" % ( name, field.length(), name, len(serie), serie) select = "substring(%s FROM %d) as %s" % ( name, len(serie) + 1, name) q = FLSqlQuery(None, cursor_.db().connectionName()) q.setForwardOnly(True) q.setTablesList(tMD.name()) q.setSelect(select) q.setFrom(tMD.name()) q.setWhere(where) q.setOrderBy(name + " DESC") if not q.exec_(): return None maxRange = 10 ** _len numero = maxRange while numero >= maxRange: if not q.next(): numero = 1 break numero = float(q.value(0)) numero = numero + 1 if type_ == "string" or type_ == "double": cadena = numero if len(cadena) < _len: relleno = cadena.rjust(_len - len(cadena), '0') cadena = relleno + cadena # res = serie + cadena return cadena return None
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 Mr_Proper(self): util = FLUtil() self.db_.dbAux().transaction() rx = QRegExp("^.*[\\d][\\d][\\d][\\d].[\\d][\\d].*[\\d][\\d]$") rx2 = QRegExp("^.*alteredtable[\\d][\\d][\\d][\\d].*$") qry = FLSqlQuery(None, self.db_.dbAux()) qry2 = FLSqlQuery(None, self.db_.dbAux()) steps = 0 item = "" rx3 = QRegExp("^.*\\d{6,9}$") listOldBks = rx3 in self.tables("") qry.exec_("select nombre from flfiles") util.createProgressDialog( util.tr("Borrando backups"), len(listOldBks) + qry.size() + 5) while qry.next(): item = qry.value(0) if item.find(rx) > -1 or item.find(rx2) > -1: util.setLabelText(util.tr("Borrando regisro %1").arg(item)) qry2.exec_("delete from flfiles where nombre = '%s'" % item) if item.find("alteredtable") > -1: if item.replace(".mtd", "") in self.tables(""): util.setLabelText( util.tr("Borrando tabla %1").arg(item)) qry2.exec_("drop table %s" % (item.replace(".mtd", ""))) steps = steps + 1 util.setProgress(steps) for item in listOldBks: if item in self.tables(""): util.setLabelText(util.tr("Borrando tabla %1").arg(item)) qry2.exec_("drop table %s" % item) steps = steps + 1 util.setProgress(steps) util.setLabelText(util.tr("Inicializando cachés")) steps = steps + 1 util.setProgress(steps) qry.exec_("delete from flmetadata") qry.exec_("delete from flvar") self.db_.manager().cleanupMetaData() self.db_.dbAux().commit() util.setLabelText(util.tr("Vacunando base de datos")) steps = steps + 1 util.setProgress(steps) qry2.exec_("vacuum") steps = steps + 1 util.setProgress(steps) util.destryProgressDialog()
def Mr_Proper(self): util = FLUtil() self.db_.dbAux().transaction() qry = FLSqlQuery(None, self.db_.dbAux()) qry2 = FLSqlQuery(None, self.db_.dbAux()) steps = 0 rx = QRegExp("^.*\\d{6,9}$") if rx in self.tables() is not False: listOldBks = rx in self.tables() else: listOldBks = [] qry.exec_("select nombre from flfiles where nombre similar to" "'%[[:digit:]][[:digit:]][[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]%:[[:digit:]][[:digit:]]%' or nombre similar to" "'%alteredtable[[:digit:]][[:digit:]][[:digit:]][[:digit:]]%' or (bloqueo='f' and nombre like '%.mtd')") util.createProgressDialog( util.tr("Borrando backups"), len(listOldBks) + qry.size() + 2) while qry.next(): item = qry.value(0) util.setLabelText(util.tr("Borrando registro %1").arg(item)) qry2.exec_("DELETE FROM flfiles WERE nombre ='%s'" % item) if item.find("alteredtable") > -1: if self.existsTable(item.replace(".mtd", "")): util.setLabelText(util.tr("Borrando tabla %1").arg(item)) qry2.exec_("DROP TABLE %s CASCADE" % item.replace(".mtd", "")) steps = steps + 1 util.setProgress(steps) for item in listOldBks: if self.existsTable(item): util.setLabelText(util.tr("Borrando tabla %s" % item)) qry2.exec_("DROP TABLE %s CASCADE" % item) steps = steps + 1 util.setProgress(steps) util.setLabelText(util.tr("Inicializando cachés")) steps = steps + 1 util.setProgress(steps) qry.exec_("DELETE FROM flmetadata") qry.exec_("DELETE FROM flvar") self.db_.manager().cleanupMetaData() # self.db_.driver().commit() util.destroyProgressDialog() steps = 0 qry.exec_("select tablename from pg_tables where schemaname='public'") util.createProgressDialog( util.tr("Comprobando base de datos"), qry.size()) while qry.next(): item = qry.value(0) util.setLabelText(util.tr("Comprobando tabla %s" % item)) mustAlter = self.mismatchedTable(item, item) if mustAlter: conte = self.db_.managerModules().content("%s.mtd" % item) if conte: msg = util.tr("La estructura de los metadatos de la tabla '%s' y su " "estructura interna en la base de datos no coinciden. " "Intentando regenerarla." % item) print(msg) self.alterTable2(conte, conte, None, True) steps = steps + 1 util.setProgress(steps) self.db_.dbAux().driver().transaction() steps = 0 sqlCursor = FLSqlCursor(None, True, self.db_.dbAux()) sqlQuery = FLSqlQuery(None, self.db_.dbAux()) if sqlQuery.exec_("select relname from pg_class where ( relkind = 'r' ) " "and ( relname !~ '^Inv' ) " "and ( relname !~ '^pg_' ) and ( relname !~ '^sql_' )"): util.setTotalSteps(sqlQuery.size()) while sqlQuery.next(): item = sqlQuery.value(0) steps = steps + 1 util.setProgress(steps) util.setLabelText(util.tr("Creando índices para %s" % item)) mtd = self.db_.manager().metadata(item) fL = mtd.fieldList() if not mtd or not fL: continue for it in fL: if not it or not it.type() == "pixmap": continue cur = FLSqlCursor(item, True, self.db_.dbAux()) cur.select(it.name() + " not like 'RK@%'") while cur.next(): v = cur.value(it.name()) if v is None: continue v = self.db_.manager().storeLargeValue(mtd, v) if v: buf = cur.primeUpdate() buf.setValue(it.name(), v) cur.update(False) sqlCursor.setName(item, True) # self.db_.dbAux().driver().commit() steps = 0 qry.exec_("select tablename from pg_tables where schemaname='public'") util.createProgressDialog( util.tr("Analizando base de datos"), qry.size()) while qry.next(): item = qry.value(0) util.setLabelText(util.tr("Analizando tabla %s" % item)) qry2.exec_("vacuum analyze %s" % item) steps = steps + 1 util.setProgress(steps) util.destroyProgressDialog()