Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        parent = None
        name = None
        action = None

        if isinstance(args[0], str):
            # @param actionName Nombre de la acción asociada al formulario

            if len(args) == 2:
                parent = args[1]

            name = args[0]

            self.setAction(name)
            action = self.action
            if action is None:
                return

            table = action.table
            if not table:
                return

            self.cursor_ = FLSqlCursor(table, True, "default", None, None,
                                       self)
            self.accepted_ = False

        elif isinstance(args[0], FLSqlCursor):
            # @param cursor Objeto FLSqlCursor para asignar a este formulario
            # @param actionName Nombre de la acción asociada al formulario

            if len(args) == 3:
                parent = args[2]
                name = args[1]

            self.cursor_ = args[0]
            action = self.cursor_._action

        elif len(args) == 2:
            action = args[0]
            parent = args[1]
            name = action.name()
            self.cursor_ = FLSqlCursor(action.table(), True, "default", None,
                                       None, self)

        if not parent:
            parent = QtWidgets.QApplication.activeModalWidget()

        super(FLFormSearchDB, self).__init__(parent, action, load=True)
        self.setFocusPolicy(QtCore.Qt.NoFocus)

        if not name:
            print("FLFormSearchDB : Nombre de acción vacío")
            return

        if not action:
            print("FLFormSearchDB : No existe la acción", name)
            return

        self.eventloop = QtCore.QEventLoop()
Ejemplo n.º 2
0
    def sqlInsert(self, t, fL, vL, connName="default"):
        """
        Realiza la inserción de un registro en una tabla mediante un objeto FLSqlCursor

        @param t Nombre de la tabla
        @param fL Lista separada con comas de los nombres de los campos
        @param vL Lista separada con comas de los valores correspondientes
        @param connName Nombre de la conexion
        @return Verdadero en caso de realizar la inserción con éxito, falso en cualquier otro caso
        """
        from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor

        fL = fL.split(",")
        vL = vL.split(",")

        if not len(fL) == len(vL):
            return False

        c = FLSqlCursor(t, True, connName)
        c.setModeAccess(FLSqlCursor.Insert)
        c.refreshBuffer()

        i = 0
        for f in fL:
            if vL[i] is None:
                c.bufferSetNull(f)
            else:
                c.setValueBuffer(f, vL[i])

            i = i + 1

        return c.commitBuffer()
Ejemplo n.º 3
0
    def sqlUpdate(self, t, fL, vL, w, connName="default"):
        """
        Realiza la modificación de uno o más registros en una tabla mediante un objeto FLSqlCursor

        @param t Nombre de la tabla
        @param fL Lista separada con comas de los nombres de los campos
        @param vL Lista separada con comas de los valores correspondientes
        @param w Sentencia where para identificar los registros a editar.
        @param connName Nombre de la conexion
        @return Verdadero en caso de realizar la inserción con éxito, falso en cualquier otro caso
        """
        from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor
        c = FLSqlCursor(t, True, connName)
        c.setForwardOnly(True)

        # if not c.select(w):
        #     return False
        c.select(w)

        while c.next():
            c.setModeAccess(FLSqlCursor.Edit)
            c.refreshBuffer()

            if isinstance(fL, list):
                i = 0
                for f in fL:
                    c.setValueBuffer(f, vL[i])
                    i = i + 1
            else:
                c.setValueBuffer(fL, vL)

            if not c.commitBuffer():
                return False

        return True
Ejemplo n.º 4
0
    def initCursor(self):
        filtro = None
        self._cursorLoaded = True
        if not self._foreignField:
            return
        if not self._fieldRelation:
            return
        if not self._tableName:
            return

        if self._loaded:

            tipo = self._cursor.model().fieldType(self._fieldRelation)
            foranea = self._parent.parentWidget().cursor().valueBuffer(
                self._foreignField)
            if foranea is None:
                #print("FLTable(%s): campo foraneo \"%s.%s\" no encontrado." % (self._tableName,self._parent.parentWidget()._cursor.table(), self._foreignField))
                return
            if tipo is "uint":
                self._foreignFilter = "%s = %s" % (
                    self._fieldRelation,
                    self._parent.parentWidget().cursor().valueBuffer(
                        self._foreignField))
            else:
                self._foreignFilter = "%s = '%s'" % (
                    self._fieldRelation,
                    self._parent.parentWidget().cursor().valueBuffer(
                        self._foreignField))

            #print("Filtro:%s" % filtro)
            self._cursor.setMainFilter(self._foreignFilter)
            self._cursor.refresh()
        else:
            self._cursor = FLSqlCursor(self._tableName)
Ejemplo n.º 5
0
    def sqlUpdate(self, t, fL, vL, w, connName="default"):
        from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor
        c = FLSqlCursor(t, True, connName)
        c.setForwardOnly(True)

        # if not c.select(w):
        #     return False
        c.select(w)

        while c.next():
            c.setModeAccess(FLSqlCursor.Edit)
            c.refreshBuffer()
            
            if isinstance(fL, list):
                i = 0
                for f in fL:
                    c.setValueBuffer(f, vL[i])
                    i = i + 1
            else:
                c.setValueBuffer(fL, vL)
                
            if not c.commitBuffer():
                return False

        return True
Ejemplo n.º 6
0
    def insert(table_or_cursor, fields, values, where="", conn=None):

        if isinstance(table_or_cursor, str):
            cur = FLSqlCursor(table_or_cursor, conn)
        else:
            cur = table_or_cursor

        if cur is None:
            return False

        if not cur.metadata():
            return False

        fieldsCount = len(fields)

        cur.setModeAccess(cur.Insert)
        cur.refreshBuffer()

        for i in range(0, fieldsCount - 1):
            cur.setValueBuffer(fields[i], values[i])

        msgCheck = cur.msgCheckIntegrity()
        if msgCheck != "":
            ok = False
            raise Exception(msgCheck)

        ok = False
        actCheck = cur.activatedCheckIntegrity()
        cur.setActivatedCheckIntegrity(False)
        ok = cur.commitBuffer()
        cur.setActivatedCheckIntegrity(actCheck)

        return ok
Ejemplo n.º 7
0
    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'"):

            if pineboolib.project.conn.driver().cascadeSupport():
                q.exec_("DROP TABLE flsettings CASCADE")
            else:
                q.exec_("DROP TABLE flsettings")

            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():

            if pineboolib.project.conn.driver().cascadeSupport():
                q.exec_("DROP TABLE flmetadata CASCADE")
            else:
                q.exec_("DROP TABLE flmetadata")

            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_ = []
Ejemplo n.º 8
0
    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))
Ejemplo n.º 9
0
    def run(self):
        value = 0
        cursor = FLSqlCursor("paises")

        try:
            cursor.setModeAccess(cursor.Insert)
            cursor.refreshBuffer()
        except Exception:
            print(traceback.format_exc())
        else:
            value = value + 10

        try:
            cursor.setValueBuffer("codpais", "TEST")
            cursor.setValueBuffer("nombre", "test name")
            cursor.setValueBuffer("codiso", "TS")
        except Exception:
            print(traceback.format_exc())
        else:
            value = value + 10

        try:
            cursor.commitBuffer()
        except Exception:
            print(traceback.format_exc())
        else:
            value = value + 10

        try:
            val1 = cursor.valueBuffer("codpais")
        except Exception:
            print(traceback.format_exc())
        else:
            if val1 == "TEST":
                value = value + 10

        try:
            cursor.select("codpais = 'TEST'")
            while cursor.next():
                cursor.setModeAccess(cursor.Del)
                cursor.refreshBuffer()
                cursor.commitBuffer()
        except Exception:
            print(traceback.format_exc())
        else:
            value = value + 10

        return value
Ejemplo n.º 10
0
    def sqlInsert(self, t, fL, vL, connName="default"):

        if not fL.len == vL:
            return False

        c = FLSqlCursor(t, True, connName)
        c.setModeAccess(FLSqlCursor.Insert)
        c.refreshBuffer()

        for f, v in (fL, vL):
            if v == "NULL":
                c.bufferSetNull(f)
            else:
                c.setValueBuffer(f, v)

        return c.commitBuffer()
Ejemplo n.º 11
0
    def sqlDelete(self, t, w, connName="default"):
        from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor
        c = FLSqlCursor(t, True, connName)
        c.setForwardOnly(True)

        # if not c.select(w):
        #     return False
        c.select(w)

        while c.next():
            c.setModeAccess(FLSqlCursor.DEL)
            c.refreshBuffer()
            if not c.commitBuffer():
                return False

        return True
Ejemplo n.º 12
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_ = []
Ejemplo n.º 13
0
    def inicialize2(self, *args, **kwargs):
        actionName = str(args[0][0])
        parent = args[0][1]
        f = args[1]

        if parent:
            self.parent_ = parent
        else:
            self.parent_ = QtGui.QWidget(pineboolib.project.mainWidget(),
                                         actionName, f)

        self.layout = None
        self.mainWidget_ = None
        self.layoutButtons = None
        self.pushButtonCancel = None
        self.showed = False
        self.iface = None
        self.oldCursorCtxt = None
        self.isClosing_ = False
        self.initFocusWidget_ = None
        self.oldFormObj = None
        self.accepted_ = False

        self.setFocusPolicy(QtGui.QWidget.NoFocus)

        if actionName.isEmpty():
            self.action_ = None
            print(FLUtil.translate("sys", "FLFormDB : Nombre de acción vacío"))
            return
        else:
            self.action_ = FLSqlConnections.database().manager().action(
                actionName)

        if not self.action_:
            print(
                FLUtil.translate(
                    "sys", "FLFormDB : No existe la acción %s" % actionName))
            return

        self.cursor_ = FLSqlCursor(self.action_.table(), True, "default", 0, 0,
                                   self)
        self.name_ = self.action_.name()

        self.initForm()
Ejemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        parent = None
        name = None
        action = None

        if isinstance(args[0], str):
            #@param actionName Nombre de la acción asociada al formulario

            if len(args) == 2:
                parent = args[1]

            name = args[0]

            self.cursor_ = FLSqlCursor(name, True, "default", None, None, self)
            action = self.cursor_.action()
            self.accepted_ = False

        elif isinstance(args[0], FLSqlCursor):
            #@param cursor Objeto FLSqlCursor para asignar a este formulario
            #@param actionName Nombre de la acción asociada al formulario

            if len(args) > 2:
                action = args[1]
                name = action.name

            if len(args) == 3:
                parent = args[2]

            self.cursor_ = args[0]

        super(FLFormSearchDB, self).__init__(parent, action)
        self.setFocusPolicy(QtCore.Qt.NoFocus)

        if not name:
            print("FLFormSearchDB : Nombre de acción vacío")
            return

        if not action:
            print("FLFormSearchDB : No existe la acción", name)
            return

        self.initForm()
Ejemplo n.º 15
0
    def runTransaction(self, f, oParam):

        curT = FLSqlCursor("flfiles")
        curT.transaction(False)
        # gui = self.interactiveGUI()
        # if gui:
        #   AQS.Application_setOverrideCursor(AQS.WaitCursor);

        errorMsg = None
        try:
            valor = f(oParam)
            errorMsg = getattr(oParam, "errorMsg", None)
            if valor:
                curT.commit()
            else:
                curT.rollback()
                # if gui:
                #   AQS.Application_restoreOverrideCursor();
                if errorMsg is None:
                    self.warnMsgBox(
                        self.translate(u"Error al ejecutar la función"))
                else:
                    self.warnMsgBox(errorMsg)
                return False

        except Exception:
            curT.rollback()
            # if gui:
            #   AQS.Application_restoreOverrideCursor();
            if errorMsg is None:
                self.warnMsgBox(
                    self.translate(u"Error al ejecutar la función"))
            else:
                self.warnMsgBox(errorMsg)
            return False

        # if gui:
        #   AQS.Application_restoreOverrideCursor();
        return valor
Ejemplo n.º 16
0
    def init1(self, actionName, parent=None):
        self.setFocusPolicy(QtGui.QWidget.NoFocus)
        if actionName.isEmpty():
            self.action_ = False
            print(
                FLUtil.translate("app",
                                 "FLFormSearchDB : Nombre de acción vacío"))
            return
        else:
            self.action_ = FLSqlConnections.database().manager().action(
                actionName)
        if not self.action_:
            print(
                FLUtil.translate(
                    "app",
                    "FLFormSearchDB : No existe la acción %s" % actionName))
            return

        self.cursor_ = FLSqlCursor(self.action_.table(), True, "default", 0, 0,
                                   self)
        self.name_ = self.action_.name()

        self.initForm()
Ejemplo n.º 17
0
    def sqlDelete(self, t, w, connName="default"):
        """
        Borra uno o más registros en una tabla mediante un objeto FLSqlCursor

        @param t Nombre de la tabla
        @param w Sentencia where para identificar los registros a borrar.
        @param connName Nombre de la conexion
        @return Verdadero en caso de realizar la inserción con éxito, falso en cualquier otro caso
        """
        from pineboolib.fllegacy.FLSqlCursor import FLSqlCursor
        c = FLSqlCursor(t, True, connName)
        c.setForwardOnly(True)

        # if not c.select(w):
        #     return False
        c.select(w)

        while c.next():
            c.setModeAccess(FLSqlCursor.Del)
            c.refreshBuffer()
            if not c.commitBuffer():
                return False

        return True
Ejemplo n.º 18
0
    def __init__(self, parent=None, action_or_cursor=None, *args):
        print("FLTableDB:", parent, action_or_cursor, args)
        # TODO: Falta el lineeditsearch y el combo, que los QS lo piden
        super(FLTableDB, self).__init__(parent, *args)
        # TODO: LA inicialización final hay que hacerla más tarde, en el primer
        # show(), porque sino obligas a tenerlo todo preparado en el constructor.
        self._tableView = QtGui.QTableView()
        self._lineEdit = QtGui.QLineEdit()
        _label1 = QtGui.QLabel()
        _label2 = QtGui.QLabel()
        self._comboBox_1 = QtGui.QComboBox()
        self._comboBox_2 = QtGui.QComboBox()
        _label1.setText("Buscar")
        _label2.setText("en")
        self._vlayout = QtGui.QVBoxLayout()
        _hlayout = QtGui.QHBoxLayout()
        self._tableView._v_header = self._tableView.verticalHeader()
        self._tableView._v_header.setDefaultSectionSize(18)
        self._tableView._h_header = self._tableView.horizontalHeader()
        self._tableView._h_header.setDefaultSectionSize(70)
        _hlayout.addWidget(_label1)
        _hlayout.addWidget(self._lineEdit)
        _hlayout.addWidget(_label2)
        _hlayout.addWidget(self._comboBox_1)
        _hlayout.addWidget(self._comboBox_2)
        self._vlayout.addLayout(_hlayout)
        self._vlayout.addWidget(self._tableView)
        self.setLayout(self._vlayout)
        self._parent = parent
        while True:
            parent_cursor = getattr(self._parent, "_cursor", None)
            if parent_cursor: break
            new_parent = self._parent.parentWidget()
            if new_parent is None: break
            self._parent = new_parent
            print(self._parent)

        self._tableView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self._tableView.setSelectionMode(
            QtGui.QAbstractItemView.SingleSelection)
        self._tableView.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self._tableView.setAlternatingRowColors(True)

        if action_or_cursor is None and parent_cursor:
            action_or_cursor = parent_cursor
        if isinstance(action_or_cursor, FLSqlCursor):
            self._cursor = action_or_cursor
        elif isinstance(action_or_cursor, str):
            self._cursor = FLSqlCursor(action_or_cursor)
        else:
            self._cursor = None
        if self._cursor:
            self._tableView._h_header.setResizeMode(
                QtGui.QHeaderView.ResizeToContents)
            self._tableView.setModel(self._cursor._model)
            self._tableView.setSelectionModel(self._cursor.selection())
        self.tableRecords = self  # control de tabla interno

        #Carga de comboBoxs y connects .- posiblemente a mejorar
        if self._cursor:
            for column in range(self._cursor._model.columnCount()):
                self._comboBox_1.addItem(
                    self._cursor._model.headerData(column,
                                                   QtCore.Qt.Horizontal,
                                                   QtCore.Qt.DisplayRole))
                self._comboBox_2.addItem(
                    self._cursor._model.headerData(column,
                                                   QtCore.Qt.Horizontal,
                                                   QtCore.Qt.DisplayRole))
        self._comboBox_1.addItem("*")
        self._comboBox_2.addItem("*")
        self._comboBox_1.setCurrentIndex(0)
        self._comboBox_2.setCurrentIndex(1)
        self._comboBox_1.currentIndexChanged.connect(self.comboBox_putFirstCol)
        self._comboBox_2.currentIndexChanged.connect(
            self.comboBox_putSecondCol)

        self.sort = []
        self.timer_1 = QtCore.QTimer(self)
        self.timer_1.singleShot(100, self.loaded)
Ejemplo n.º 19
0
    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}$")
        listOldBks = rx in self.tables("")
        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 %1").arg(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_.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 %1").arg(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 '%1' y su "
                        "estructura interna en la base de datos no coinciden. "
                        "Intentando regenerarla.").arg(item)

                    print(msg)
                    self.alterTable2(conte, conte, None, True)

            steps = steps + 1
            util.setProgress(steps)

        self.db_.dbAux().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 %1").arg(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("%s not like 'RK@%'" % it.name())
                    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().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 %1").arg(item))
            qry2.exec_("vacuum analyze %s" % item)
            steps = steps + 1
            util.setProgress(steps)

        util.destroyProgressDialog()
Ejemplo n.º 20
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
Ejemplo n.º 21
0
    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
Ejemplo n.º 22
0
    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
Ejemplo n.º 23
0
    def initCursor(self):
        if not self.topWidget or not self.cursor_:
            return

        if not self.cursor_.metadata():
            return

        
        tMD = self.cursor_.metadata()
        if not self.sortField_:
            if tMD:
                self.sortField_ = tMD.field(tMD.primaryKey())


        ownTMD = None
        if self.tableName_:
            if DEBUG: print("**FLTableDB::name: %r tableName: %r" % (self.objectName(), self.tableName_))

            if not self.cursor_.db().manager().existsTable(self.tableName_):
                ownTMD = True
                tMD = self.cursor_.db().manager().createTable(self.tableName_)
            else:
                ownTMD = True
                tMD = self.cursor_.db().manager().metadata(self.tableName_)

            if not tMD or isinstance(tMD,bool):
                return

            if not self.foreignField_ or not self.fieldRelation_:
                if not self.cursor_.metadata():
                    if ownTMD and tMD and not tMD.inCache():
                        del tMD
                    return

                if not self.cursor_.metadata().name() == self.tableName_:
                    ctxt = self.cursor_.context()
                    self.cursor_ = FLSqlCursor(self.tableName_, True, self.cursor_.db().connectionName(), None, None , self)


                    if self.cursor_:
                        self.cursor_.setContext(ctxt)
                        self.cursorAux = None

                    if ownTMD and tMD and not tMD.inCache():
                        del tMD

                    return

            else:
                cursorTopWidget = self.topWidget.cursor()
                if cursorTopWidget and not cursorTopWidget.metadata().name() == self.tableName_:
                    self.cursor_ = cursorTopWidget

        if not self.tableName_ or not self.foreignField_ or not self.fieldRelation_ or self.cursorAux:
            if ownTMD and tMD and not tMD.inCache():
                del tMD

            return

        self.cursorAux = self.cursor_
        curName = self.cursor_.metadata().name()
        rMD =  self.cursor_.metadata().relation(self.foreignField_, self.fieldRelation_, self.tableName_)
        testM1 = tMD.relation(self.fieldRelation_, self.foreignField_, curName)
        checkIntegrity = False
        if not rMD:
            if testM1:
                if testM1.cardinality() == FLRelationMetaData.RELATION_M1:
                    checkIntegrity = True
            fMD = self.cursor_.metadata().field(self.foreignField_)
            if fMD:
                tmdAux = self.cursor_.db().manager().metadata(self.tableName_)
                if not tmdAux or tmdAux.isQuery():
                    checkIntegrity = False
                if tmdAux and not tmdAux.inCache():
                    del tmdAux

                rMD = FLRelationMetaData(self.tableName_, self.fieldRelation_, FLRelationMetaData.RELATION_1M, False, False, checkIntegrity)
                fMD.addRelationMD(rMD)
                #print("FLTableDB : La relación entre la tabla del formulario %s y esta tabla %s de este campo no existe, pero sin embargo se han indicado los campos de relación( %s, %s )" % ( curName, self.tableName_, self.fieldRelation_, self.foreignField_))
                #print("FLTableDB : Creando automáticamente %s.%s --1M--> %s.%s" % (curName, self.foreignField_, self.tableName_, self.fieldRelation_))
            else:
                #print("FLTableDB : El campo ( %s ) indicado en la propiedad foreignField no se encuentra en la tabla ( %s )" % (self.foreignField_, curName))
                pass

        rMD = testM1
        if not rMD:
            fMD = tMD.field(self.fieldRelation_)
            if fMD:
                rMD = FLRelationMetaData(curName, self.foreignField_, FLRelationMetaData.RELATION_1M, False, False, False)
                fMD.addRelationMD(rMD)
                if DEBUG: print("FLTableDB : Creando automáticamente %s.%s --1M--> %s.%s" % (self.tableName_, self.fieldRelation_, curName, self.foreignField_))

            else:
                if DEBUG: print("FLTableDB : El campo ( %s ) indicado en la propiedad fieldRelation no se encuentra en la tabla ( %s )" % (self.fieldRelation_, self.tableName_))

        self.cursor_ = FLSqlCursor(self.tableName_, True, self.cursor_.db().connectionName(), self.cursorAux, rMD, self)
        if not self.cursor_:
            self.cursor_ = self.cursorAux
            self.cursorAux = None

        else:

            self.cursor_.setContext(self.cursorAux.context())
            if self.showed:
                try:
                    self.cursorAux.newBuffer.disconnect(self.refresh)
                except:
                    pass

            self.cursorAux.newBuffer.connect(self.refresh)

        if self.cursorAux and isinstance(self.topWidget, FLFormSearchDB):
            self.topWidget.setCaption(self.cursor_.metadata().alias())
            self.topWidget_.setCursor(self.cursor_)

        if ownTMD or tMD and not tMD.inCache():
            del tMD
Ejemplo n.º 24
0
    def initCursor(self):
        # si no existe crea la tabla
        if not self._cursor: return False
        if not self._cursor._model: return False

        self._tMD = 0

        if not self._sortField: self._tMD = self._cursor._model.name()
        if self._tMD:
            self.sortField_ = self._tMD.value(self._cursor._currentregister,
                                              self._tMD.primaryKey())
        ownTMD = False
        if not self._tableName:
            #if not cursor_->db()->manager()->existsTable(tableName_)) {
            ownTMD = True
            #tMD = cursor_->db()->manager()->createTable(tableName_);
        else:
            ownTMD = True
            self._tMD = self._cursor._model._table.name

        if not self._tMD:
            return

        if not self._foreignField or not self._fieldRelation:
            if not self._cursor._model:
                if ownTMD and self._tMD and not self._tMD.inCache():
                    self._tMD = None

            return

            if not self._cursor._model.name() == self._tableName:
                ctxt = self._cursor.context()
                self._cursor = FLSqlCursor(self._tableName)
                if self._cursor:
                    self._cursor.setContext(ctxt)
                    cursorAux = 0

                if ownTMD and self._tMD and not self._tMD.inCache():
                    self._tMD = None

                return

        else:
            cursorTopWidget = self.topWidget._cursor(
            )  # ::qt_cast<FLFormDB *>(topWidget)->cursor()
            if cursorTopWidget and not cursorTopWidget._model.name(
            ) == self._tableName:
                self._cursor = cursorTopWidget

        if not self._tableName or not self._foreignField or not self._fieldRelation or cursorAux:
            if ownTMD and self._tMD and not self._tMD.inCache():
                tMD = None

            return

        cursorAux = self._cursor
        curName = self._cursor._model.name()
        rMD = self._cursor._model.relation(self._foreignField,
                                           self._fieldRelation,
                                           self._tableName)
        testM1 = self._tMD.relation(self._fieldRelation, self._foreignField,
                                    curName)
        checkIntegrity = bool(False)

        if not rMD:
            if testM1:
                checkIntegrity = (
                    testM1.cardinality() == FLRelationMetaData.RELATION_M1)
            fMD = FLTableMetaData(self._cursor._model.field(
                self._foreignField))
            if (fMD):
                tmdAux = self._cursor._model(self._tableName)
                if not tmdAux or tmdAux.isQuery():
                    checkIntegrity = False
                if tmdAux and not tmdAux.inCache():  # mirar inCache()
                    tmdAux = None
                rMD = FLRelationMetaData(self._tableName, self._fieldRelation,
                                         FLRelationMetaData.RELATION_1M, False,
                                         False, checkIntegrity)
                fMD.addRelationMD(rMD)
                print(
                    "FLTableDB : La relación entre la tabla del formulario %r y esta tabla %r de este campo no existe, pero sin embargo se han indicado los campos de relación( %r, %r )"
                    % (curName, self._tableName, self._fieldRelation,
                       self._foreignField))
                print(
                    "FLTableDB : Creando automáticamente %r.%r --1M--> %r.%r" %
                    (curName, self._foreignField, self._tableName,
                     self._fieldRelation))

            else:
                print(
                    "FLTableDB : El campo ( %r ) indicado en la propiedad foreignField no se encuentra en la tabla ( %r )"
                    % (self._foreignField, curName))
        rMD = testM1
        if not rMD:
            fMD = FLFieldMetaData(tMD.field(self._fieldRelation))
            if (fMD):
                rMD = FLRelationMetaData(curName, self._foreignField,
                                         FLRelationMetaData.RELATION_1M, False,
                                         False, False)
                fMD.addRelationMD(rMD)
                print(
                    "FLTableDB : Creando automáticamente %r.%r --1M--> %r.%r" %
                    (self._tableName, self._fieldRelation, curName,
                     self._foreignField))
            else:
                print(
                    "FLTableDB : El campo ( %r ) indicado en la propiedad fieldRelation no se encuentra en la tabla ( %r )"
                    % (self._fieldRelation, self._tableName))

        self._cursor = FLSqlCursor(self._tableName, True,
                                   self._cursor.db().connectionName(),
                                   cursorAux, rMD, self)
        if not self._cursor:
            self._cursor = cursorAux
            cursorAux = 0
        else:
            self._cursor.setContext(cursorAux.context())
        if self.showed:
            self.disconnect(cursorAux, QtCore.SIGNAL('newBuffer()'),
                            self.refresh())
            self.connect(cursorAux, QtCore.SIGNAL('newBuffer()'),
                         self.refresh())

        if cursorAux and self.topWidget.isA("FLFormSearchDB"):
            self.topWidget.setCaption(self._cursor._model.alias())
            self.topWidget.setCursor(
                self._cursor
            )  #::qt_cast<FLFormSearchDB *>(topWidget)->setCursor(cursor_);

        if ownTMD and tMD and not tMD.inCache():
            tMD = None