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 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 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 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 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 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 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 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 init(self): self.initCount_ = self.initCount_ + 1 tmpTMD = self.createSystemTable("flmetadata") tmpTMD = self.createSystemTable("flseqs") if not self.db_.dbAux(): return q = FLSqlQuery(None, self.db_.dbAux()) q.setForwardOnly(True) tmpTMD = self.createSystemTable("flsettings") if not q.exec_("SELECT * FROM flsettings WHERE flkey = 'sysmodver'"): q.exec_("DROP TABLE flsettings CASCADE") tmpTMD = 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_.insert(q.value(0), q.value(1)) q.exec_("SELECT * FROM flsettings WHERE flkey = 'sysmodver'") if not q.next(): q.exec_("DROP TABLE flmetadata CASCADE") tmpTMD = 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 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 sqlSelect(self, f, s, w, tL=None, size=0, connName="default"): 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(): return q.value(0) if size: return False
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 nextCounter(self, *args, **kwargs): 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 = 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)=%d" % (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 = float(q.value(0)) numero = numero + 1 if type_ == "string": cadena = str(numero) if len(cadena) < _len: relleno = None relleno = cadena.rjust(_len - len(cadena), '0') cadena = str + cadena 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 sqlCreateTable(self, tmd): if not tmd: return None primaryKey = None sql = "CREATE TABLE %s (" % tmd.name() fieldList = tmd.fieldList() unlocks = 0 for field in fieldList: if field.type() == "unlock": unlocks = unlocks + 1 if unlocks > 1: print(u"FLManager : No se ha podido crear la tabla " + tmd.name()) print( 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 + " INTEGER" elif field.type() == "uint": sql = sql + " INTEGER" elif field.type() in ("bool", "unlock"): sql = sql + " BOOLEAN" elif field.type() == "double": sql = sql + " FLOAT" elif field.type() == "time": sql = sql + " VARCHAR(20)" elif field.type() == "date": sql = sql + " VARCHAR(20)" 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 + " CLOB" elif field.type() == "serial": sql = sql + " INTEGER" if not field.isPrimaryKey(): sql = sql + " PRIMARY KEY" longitud = field.length() if longitud > 0: sql = sql + "(%s)" % longitud if field.isPrimaryKey(): if primaryKey is None: sql = sql + " PRIMARY KEY" else: print( 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 + ")" createIndex = "CREATE INDEX %s_pkey ON %s (%s)" % ( tmd.name(), tmd.name(), tmd.primaryKey()) q = FLSqlQuery() q.setForwardOnly(True) q.exec_(createIndex) return sql
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 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 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 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 == 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 nextCounter(self, *args, **kwargs): 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 = 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)=%d" % (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 = float(q.value(0)) numero = numero + 1 if type_ == "string": cadena = str(numero) if len(cadena) < _len: relleno = None relleno = cadena.rjust(_len - len(cadena), '0') cadena = str + cadena 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