Exemple #1
0
    def recordInfo(self, tablename_or_query):
        if not self.isOpen():
            return None

        info = []

        if isinstance(tablename_or_query, str):
            tablename = tablename_or_query

            doc = QDomDocument(tablename)
            stream = self.db_.managerModules().contentCached("%s.mtd" % tablename)
            util = FLUtil()
            if not util.domDocumentSetContent(doc, stream):
                print("FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla") + tablename)

                return self.recordInfo2(tablename)

            docElem = doc.documentElement()
            mtd = self.db_.manager().metadata(docElem, True)
            if not mtd:
                return self.recordInfo2(tablename)
            fL = mtd.fieldList()
            if not fL:
                del mtd
                return self.recordInfo2(tablename)

            for f in mtd.fieldsNames():
                field = mtd.field(f)
                info.append([field.name(), field.type(), not field.allowNull(), field.length(
                ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()])

            del mtd

        return info
    def contentStatic(self, n):

        str_ret = FLStaticLoader.content(n, self.staticBdInfo_)
        if str_ret:
            from pineboolib.fllegacy.FLUtil import FLUtil
            util = FLUtil()
            sha = util.sha1(str_ret)
            if n in self.dictKeyFiles.keys():
                s = self.dictKeyFiles[n]

            if self.dictKeyFiles and s == sha:
                return None
            elif self.dictKeyFiles and n.find(".qs") > -1:
                self.dictKeyFiles[n] = sha

                if n.endswith(".mtd"):
                    from PyQt5.QtXml import QDomDocument
                    doc = QDomDocument(n)
                    if util.domDocumentSetContent(doc, str_ret):
                        mng = self.conn_.manager()
                        docElem = doc.documentElement()
                        mtd = mng.metadata(docElem, True)

                        if not mtd or mtd.isQuery():
                            return str_ret

                        if not mng.existTable(mtd.name()):
                            mng.createTable(mng)
                        elif (self.conn_.canRegenTables()):
                            self.conn_.regenTable(mtd.name(), mtd)

        return str_ret
Exemple #3
0
    def createTable(self, n_or_tmd):
        """
        Crea una tabla en la base de datos.

        @param n_tmd Nombre o metadatos de la tabla que se quiere crear
        @return Un objeto FLTableMetaData con los metadatos de la tabla que se ha creado, o
          0 si no se pudo crear la tabla o ya existía
        """
        util = FLUtil()
        if n_or_tmd is None:
            return False

        if isinstance(n_or_tmd, str):
            tmd = self.metadata(n_or_tmd)
            if not tmd:
                return False

            if self.existsTable(tmd.name()):
                self.listTables_.append(n_or_tmd)
                return tmd
            else:
                qWarning("FLMAnager :: No existe tabla %s" % n_or_tmd)

            return self.createTable(tmd)
        else:
            if n_or_tmd.isQuery() or self.existsTable(n_or_tmd.name(), False):
                return n_or_tmd

            if not self.db_.createTable(n_or_tmd):
                logger.warn("FLManager : %s", util.tr(
                    "No se ha podido crear la tabla ") + n_or_tmd.name())
                return False

            return n_or_tmd
Exemple #4
0
    def setText(self, txt):
        if not self.labelFunction_:
            if QtWidgets.QApplication.multiLangEnabled() and txt:
                self.text_ = txt.decode("utf8")
                if self.text_ == txt:
                    self.text_ = FLUtil.translate(self, "app", txt)
            else:
                self.text_ = txt
        else:
            dni = 0
            argList = QtCore.QSArgumentList()
            argList << txt

            if self.domNodeData_ and not self.domNodeData_.isNull():
                dni = FLDomDocument(self.domNodeData_)
                argList << dni

            v = self.labelFunction_(*argList)
            if v:
                txtFun = str(v)

                if QtWidgets.QApplication.multiLangEnabled() and txtFun:
                    self.text_ = txtFun.decode("utf8")
                    if self.text_ == txtFun:
                        self.text_ = FLUtil.translate(self, "app", txtFun)
                else:
                    self.text_ = txtFun

            if dni:
                del dni
Exemple #5
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None

        if v is None:
            v = ""
        # TODO: psycopg2.mogrify ???

        if type_ == "bool" or type_ == "unlock":
            s = text2bool(v)

        elif type_ == "date":
            s = "'%s'" % util.dateDMAtoAMD(v)

        elif type_ == "time":
            s = "'%s'" % v

        elif type_ == "uint" or type_ == "int" or type_ == "double" or type_ == "serial":
            s = v

        else:
            v = auto_qt_translate_text(v)
            if upper and type_ == "string":
                v = v.upper()

            s = "'%s'" % v
        # print ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
Exemple #6
0
    def createTable(self, n_or_tmd):
        util = FLUtil()
        if n_or_tmd == None:
            return False

        if isinstance(n_or_tmd, str):
            tmd = self.metadata(n_or_tmd)
            if not tmd:
                return False

            if self.existsTable(tmd.name()):
                self.listTables_.append(n_or_tmd)
                return tmd
            else:
                qWarning("FLMAnager :: No existe tabla %s" % n_or_tmd)

            return self.createTable(tmd)
        else:
            if n_or_tmd.isQuery() or self.existsTable(n_or_tmd.name(), False):
                return n_or_tmd

            if not self.db_.createTable(n_or_tmd):
                print(
                    "FLManager :",
                    util.tr("No se ha podido crear la tabla ") +
                    n_or_tmd.name())
                return False

            return n_or_tmd
Exemple #7
0
    def createSystemTable(self, n):
        util = FLUtil()
        if not self.existsTable(n):
            doc = QDomDocument()
            _path = filedir("..", "share", "pineboo", "tables")
            dir = qsatype.Dir(_path)
            _tables = dir.entryList("%s.mtd" % n)

            for f in _tables:
                path = "%s/%s" % (_path, f)
                _file = QtCore.QFile(path)
                _file.open(QtCore.QIODevice.ReadOnly)
                _in = QtCore.QTextStream(_file)
                _data = _in.readAll()
                if not util.domDocumentSetContent(doc, _data):
                    print(
                        "FLManager::createSystemTable :",
                        util.tr(
                            "Error al cargar los metadatos para la tabla %1").
                        arg(n))
                    return False
                else:
                    docElem = doc.documentElement()

                    mtd = self.createTable(self.metadata(docElem, True))
                    return mtd

                f.close()

        return False
Exemple #8
0
    def formatValueLike(self, type_, v, upper):
        res = "IS NULL"

        if type_ == "bool":
            s = str(v[0]).upper()
            if s == str(QApplication.tr("Sí")[0]).upper():
                res = "=1"
            elif str(QApplication.tr("No")[0]).upper():
                res = "=0"

        elif type_ == "date":
            util = FLUtil()
            res = "LIKE '%%" + util.dateDMAtoAMD(str(v)) + "'"

        elif type_ == "time":
            t = v.toTime()
            res = "LIKE '" + t.toString(QtCore.Qt.ISODate) + "%%'"

        else:
            res = str(v)
            if upper:
                res = "%s" % res.upper()

            res = "LIKE '" + res + "%%'"

        return res
Exemple #9
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None

        #if v == None:
        #    v = ""
        # TODO: psycopg2.mogrify ???

        if type_ == "bool" or type_ == "unlock":
            s = text2bool(v)

        elif type_ == "date":
            s = "'%s'" % util.dateDMAtoAMD(v)

        elif type_ == "time":
            s = "'%s'" % v

        elif type_ in ("uint", "int", "double", "serial"):
            if v == None:
                s = 0
            else:
                s = v

        else:
            v = auto_qt_translate_text(v)
            if upper == True and type_ == "string":
                v = v.upper()

            s = "'%s'" % v
        #qWarning ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
Exemple #10
0
    def recordInfo(self, tablename_or_query):
        if not self.isOpen():
            return None

        info = []

        if isinstance(tablename_or_query, str):
            tablename = tablename_or_query

            doc = QDomDocument(tablename)
            stream = self.db_.managerModules().contentCached("%s.mtd" % tablename)
            util = FLUtil()
            if not util.domDocumentSetContent(doc, stream):
                print(
                    "FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla %1").arg(tablename))

                return self.recordInfo2(tablename)

            docElem = doc.documentElement()
            mtd = self.db_.manager().metadata(docElem, True)
            if not mtd:
                return self.recordInfo2(tablename)
            fL = mtd.fieldList()
            if not fL:
                del mtd
                return self.recordInfo2(tablename)

            for f in mtd.fieldsNames():
                field = mtd.field(f)
                info.append([field.name(), field.type(), not field.allowNull(), field.length(
                ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()])

            del mtd

        return info
    def content(n, b, only_path=False):
        global warn_
        b.readSettings()
        util = FLUtil()
        separator = "\\" if util.getOS().find("WIN") > -1 else "/"
        for info in b.dirs_:
            content_path = info.path_ + separator + n
            if info.active_ and os.path.exists(content_path):
                if not warn_:
                    warn_ = FLStaticLoaderWarning()

                timer = QtCore.QTimer()
                settings = FLSettings()
                if not warn_.warns_ and settings.readBoolEntry("ebcomportamiento/SLInterface", True):
                    timer.singleShot(500, warn_.popupWarnings)

                if not warn_.paths_:
                    timer.singleShot(1500, warn_.updateScripts)

                msg = "%s -> ...%s" % (n, info.path_[0:40])

                if not msg in warn_.warns_:
                    warn_.warns_.append(msg)
                    warn_.paths_.append("%s:%s" % (n, info.path_))
                    if settings.readBoolEntry("ebcomportamiento/SLConsola", False):
                        logger.warn("CARGA ESTATICA ACTIVADA:%s -> %s", n, info.path_)

                if only_path:
                    return content_path
                else:
                    from pineboolib.pncontrolsfactory import aqApp
                    return aqApp.db().managerModules().contentFS(info.path_ + separator + n)

        return None
Exemple #12
0
    def recordInfo(self, tablename_or_query):
        if not self.isOpen():
            return None

        info = []

        if isinstance(tablename_or_query, str):
            tablename = tablename_or_query

            doc = QDomDocument(tablename)
            stream = self.db_.managerModules().contentCached("%s.mtd" %
                                                             tablename)
            util = FLUtil()
            if not util.domDocumentSetContent(doc, stream):
                print("FLManager : " +
                      qApp.tr("Error al cargar los metadatos para la tabla %1"
                              ).arg(tablename))

                return self.recordInfo2(tablename)

            docElem = doc.documentElement()
            mtd = self.db_.manager().metadata(docElem, True)
            if not mtd:
                return self.recordInfo2(tablename)
            fL = mtd.fieldList()
            if not fL:
                del mtd
                return self.recordInfo2(tablename)

            for f in mtd.fieldsNames():
                field = mtd.field(f)
                info.append([
                    field.name(),
                    field.type(), not field.allowNull(),
                    field.length(),
                    field.partDecimal(),
                    field.defaultValue(),
                    field.isPrimaryKey()
                ])

            del mtd
            return info

        else:
            for columns in tablename_or_query:
                fName = columns[1]
                fType = columns[2]
                fSize = 0
                fAllowNull = (columns[3] == 0)
                if fType.find("VARCHAR(") > -1:
                    fSize = int(fType[fType.find("(") + 1:len(fType) - 1])

                info.append(
                    [fName,
                     self.decodeSqlType(fType), not fAllowNull, fSize])

            return info
Exemple #13
0
    def storeLargeValue(self, mtd, largeValue):

        if largeValue[0:3] == "RK@" or not mtd:
            return None

        tableName = mtd.name()
        if self.isSystemTable(tableName):
            return None

        tableLarge = None

        if self._prj.singleFLLarge():
            tableLarge = "fllarge"
        else:
            tableLarge = "fllarge_%s" % tableName
            if not self.existsTable(tableLarge):
                mtdLarge = FLTableMetaData(tableLarge, tableLarge)
                fieldLarge = FLFieldMetaData("refkey", "refkey", False, True,
                                             "string", 100)
                mtdLarge.addFieldMD(fieldLarge)
                fieldLarge2 = FLFieldMetaData("sha", "sha", True, False,
                                              "string", 50)
                mtdLarge.addFieldMD(fieldLarge2)
                fieldLarge3 = FLFieldMetaData("contenido", "contenido", True,
                                              False, "stringlist")
                mtdLarge.addFieldMD(fieldLarge3)
                mtdAux = self.createTable(mtdLarge)
                mtd.insertChild(mtdLarge)
                if not mtdAux:
                    return None

        util = FLUtil()
        sha = str(util.sha1(largeValue))
        refKey = "RK@%s@%s" % (tableName, sha)
        q = FLSqlQuery()
        q.setSelect("refkey")
        q.setFrom("fllarge")
        q.setWhere(" refkey = '%s'" % refKey)
        if q.exec_() and q.first():
            if not q.value(0) == sha:
                sql = "UPDATE %s SET contenido = '%s' WHERE refkey ='%s'" % (
                    tableLarge, largeValue, refKey)
                if not util.execSql(sql, "Aux"):
                    print("FLManager::ERROR:StoreLargeValue.Update %s.%s" %
                          (tableLarge, refKey))
                    return None
        else:
            sql = "INSERT INTO %s (contenido,refkey) VALUES ('%s','%s')" % (
                tableLarge, largeValue, refKey)
            if not util.execSql(sql, "Aux"):
                print("FLManager::ERROR:StoreLargeValue.Insert %s.%s" %
                      (tableLarge, refKey))
                return None

        return refKey
Exemple #14
0
    def loadSVGStyle(self):
        fileName = QtCore.QFileDialog.getOpenFileName(
            "", FLUtil.translate(self, "app", "Fichero SVG (*.svg)"), self,
            FLUtil.translate(self, "app", "Cargar estilo SVG"),
            FLUtil.translate(self, "app", "Cargar estilo SVG"))

        if not fileName or fileName == "":
            return

        self.ui_.ledStyle.setText("file:" + fileName)
        self.updateReport()
    def init_(self, aclXml=None):
        """
        Lee el fichero "acl.xml" y establece una nueva lista de control de acceso.

        Si el fichero "acl.xml" no se puede leer, la lista de control de acceso queda vacía y
        no se procesará ningún control de acceso sobre ningún objeto.

        @param  aclXml  Contenido XML con la definición de la lista de control de acceso.
        """

        util = FLUtil()
        if aclXml is None:
            aclXml = self._prj.conn.managerModules().content("acl.xml")

        doc = QDomDocument("ACL")
        if self.accessControlList_:
            self.accessControlList_.clear()
            del self.accessControlList_
            self.accessControlList_ = {}

        if aclXml and not util.domDocumentSetContent(doc, aclXml):
            logger.error("Lista de control de acceso errónea")
            return

        self.accessControlList_ = {}
        # self.accessControlList_.setAutoDelete(True)

        docElem = doc.documentElement()
        no = docElem.firstChild()

        while not no.isNull():
            e = no.toElement()
            if e:
                if e.tagName() == "name":
                    self.name_ = e.text()
                    no = no.nextSibling()
                    continue

                ac = FLAccessControlFactory().create(e.tagName())
                if ac:
                    ac.set(e)
                    logger.debug("****************** %s %s %s", ac.type(),
                                 ac.name(), ac.user(), ac)
                    self.accessControlList_["%s::%s::%s" %
                                            (ac.type(), ac.name(),
                                             ac.user())] = ac
                    no = no.nextSibling()
                    continue

            no = no.nextSibling()
    def exportToPDF(self):
        if self.slotsExportedDisabled_:
            return

        util = FLUtil()
        fileName = QFileDialog.getSaveFileName(
            self, util.translate("app", "Exportar a PDF"), "",
            util.translate("app", "Fichero PDF (*.pdf)"))

        if fileName[0] == '':
            return

        if fileName[0].upper().find(".PDF") == -1:
            fileName = fileName[0] + ".pdf"

        if QtCore.QFile.exists(fileName):

            q = QMessageBox.question(
                self,
                util.translate("app", "Sobreescribir {}").format(fileName),
                util.translate(
                    "app",
                    "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"
                ).format(fileName), util.translate("app", "&Sí"),
                util.translate("app", "&No"), "", 0, 1)
            if q:
                return

        self.slotPrintReportToPdf(fileName)
Exemple #17
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None

        # if v == None:
        #    v = ""
        # TODO: psycopg2.mogrify ???

        if v is None:
            s = "Null"

        elif type_ == "bool" or type_ == "unlock":
            s = text2bool(v)

        elif type_ == "date":
            val = util.dateDMAtoAMD(v)
            if val is None:
                s = "Null"
            else:
                s = "'%s'" % val

        elif type_ == "time":
            s = "'%s'" % v

        elif type_ in ("uint", "int", "double", "serial"):
            s = v

        elif type_ in ("string", "stringlist"):
            if v == "":
                s = "Null"
            else:
                if type_ == "string":
                    v = auto_qt_translate_text(v)
                if upper and type_ == "string":
                    v = v.upper()

                s = "'%s'" % v

        elif type_ == "pixmap":
            if v.find("'") > -1:
                v = self.normalizeValue(v)
            s = "'%s'" % v

        else:
            s = v
        # print ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
Exemple #18
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None

        # if v == None:
        #    v = ""
        # TODO: psycopg2.mogrify ???

        if v is None:
            s = "Null"

        elif type_ == "bool" or type_ == "unlock":
            s = text2bool(v)

        elif type_ == "date":
            val = util.dateDMAtoAMD(v)
            if val is None:
                s = "Null"
            else:
                s = "'%s'" % val

        elif type_ == "time":
            s = "'%s'" % v

        elif type_ in ("uint", "int", "double", "serial"):
            s = v

        elif type_ in ("string", "stringlist"):
            if v == "":
                s = "Null"
            else:
                if type_ == "string":
                    v = auto_qt_translate_text(v)
                if upper and type_ == "string":
                    v = v.upper()

                s = "'%s'" % v

        elif type_ == "pixmap":
            if v.find("'") > -1:
                v = self.normalizeValue(v)
            s = "'%s'" % v

        else:
            s = v
        # print ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
Exemple #19
0
    def loadSVGStyle(self):
        util = FLUtil()
        fileName = QtCore.QFileDialog.getOpenFileName(
            "",
            util.translate(self, "app", "Fichero SVG (*.svg)"),
            self,
            util.translate(self, "app", "Cargar estilo SVG"),
            util.translate(self, "app", "Cargar estilo SVG")
        )

        if not fileName or fileName == "":
            return

        self.ui_["ledStyle"].setText("file:" + fileName)
        self.updateReport()
Exemple #20
0
    def recordInfo(self, tablename_or_query):
        if not self.isOpen():
            return None

        info = []

        if isinstance(tablename_or_query, str):
            tablename = tablename_or_query

            doc = QDomDocument(tablename)
            stream = self.db_.managerModules().contentCached("%s.mtd" % tablename)
            util = FLUtil()
            if not util.domDocumentSetContent(doc, stream):
                print(
                    "FLManager : " + qApp.tr("Error al cargar los metadatos para la tabla %1").arg(tablename))

                return self.recordInfo2(tablename)

            docElem = doc.documentElement()
            mtd = self.db_.manager().metadata(docElem, True)
            if not mtd:
                return self.recordInfo2(tablename)
            fL = mtd.fieldList()
            if not fL:
                del mtd
                return self.recordInfo2(tablename)

            for f in mtd.fieldsNames():
                field = mtd.field(f)
                info.append([field.name(), field.type(), not field.allowNull(), field.length(
                ), field.partDecimal(), field.defaultValue(), field.isPrimaryKey()])

            del mtd
            return info

        else:
            for columns in tablename_or_query:
                fName = columns[1]
                fType = columns[2]
                fSize = 0
                fAllowNull = (columns[3] == 0)
                if fType.find("VARCHAR(") > -1:
                    fSize = int(fType[fType.find("(") + 1: len(fType) - 1])

                info.append([fName, self.decodeSqlType(
                    fType), not fAllowNull, fSize])

            return info
    def init_(self, aclXml=None):
        """
        Lee el fichero "acl.xml" y establece una nueva lista de control de acceso.

        Si el fichero "acl.xml" no se puede leer, la lista de control de acceso queda vacía y
        no se procesará ningún control de acceso sobre ningún objeto.

        @param  aclXml  Contenido XML con la definición de la lista de control de acceso.
        """

        util = FLUtil()
        if aclXml is None:
            aclXml = pineboolib.project.conn.managerModules().content("acl.xml")

        doc = QDomDocument("ACL")
        if self.accessControlList_:
            self.accessControlList_.clear()
            del self.accessControlList_
            self.accessControlList_ = {}

        if aclXml and not util.domDocumentSetContent(doc, aclXml):
            logger.error("Lista de control de acceso errónea")
            return

        self.accessControlList_ = {}
        # self.accessControlList_.setAutoDelete(True)

        docElem = doc.documentElement()
        no = docElem.firstChild()

        while not no.isNull():
            e = no.toElement()
            if e:
                if e.tagName() == "name":
                    self.name_ = e.text()
                    no = no.nextSibling()
                    continue

                ac = FLAccessControlFactory().create(e.tagName())
                if ac:
                    ac.set(e)
                    logger.debug("****************** %s %s %s", ac.type(), ac.name(), ac.user(), ac)
                    self.accessControlList_["%s::%s::%s" %
                                            (ac.type(), ac.name(), ac.user())] = ac
                    no = no.nextSibling()
                    continue

            no = no.nextSibling()
    def database(self, connectionName="default"):
        if not self.d:
            self.d = FLSqlConnectionsPrivate()

        if connectionName == "default":
            if not self.d.defaultDB:
                self.addDatabase(FLSqlDatabase())
            return self.d.defaultDB

        if not self.d.dictDB:
            self.addDatabase(FLSqlDatabase())
            return self.d.defaultDB

        ret = self.d.dictDB.get(connectionName)

        if not ret:
            print(
                FLUtil.translate(
                    "FLSqlConnections::database : No existe la conexión '%s', se devuelve la conexión por defecto 'default'"
                    % connectionName))

            if not self.d.defaultDB:
                self.addDatabase(FLSqlDatabase())
            ret = self.defaultDB

        return ret
Exemple #23
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()
Exemple #24
0
 def saveSnapShot(self, pathFile):
     fi = QtCore.QFile(pathFile)
     if not fi.open(QtCore.QFile.WriteOnly):
         print("FLFormDB : " + FLUtil.translate(
             "sys", "Error I/O al intentar escribir el fichero %s" %
             pathFile))
         return
     self.snapShot().save(fi, "PNG")
Exemple #25
0
    def exportFileCSVData(self):
        if self.slotsExportedDisabled_:
            return

        util = FLUtil()
        fileName = QFileDialog.getSaveFileName(
            self,
            util.translate("app", "Exportar a CSV"),
            "",
            util.translate("app", "Fichero CSV (*.csv *.txt)")
        )

        if not fileName or fileName == "":
            return

        if not fileName.upper().contains(".CSV"):
            fileName = fileName + ".csv"

        q = QtCore.QMessageBox.question(
            self,
            util.translate("app", "Sobreescribir {}").format(fileName),
            util.translate(
                self,
                "app",
                "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"
            ).format(fileName),
            util.translate("app", "&Sí"),
            util.translate("app", "&No"),
            "",
            0,
            1
        )

        if QtCore.QFile.exists(fileName) and q:
            return

        file = QtCore.QFile(fileName)

        if file.open(Qt.IO_WriteOnly):
            stream = QtCore.QTextStream(file)
            stream << self.csvData() << "\n"
            file.close()
        else:
            QtCore.QMessageBox.critical(
                self,
                util.translate("app", "Error abriendo fichero"),
                util.translate(
                    "app",
                    "No se pudo abrir el fichero {} para escribir: {}"
                ).format(
                    fileName,
                    QtWidgets.QApplication.translate(
                        "QFile", file.errorString()
                    )
                )
            )
Exemple #26
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None
        # TODO: psycopg2.mogrify ???
        if type_ == "pixmap" and v.find("'") > -1:
            v = self.normalizeValue(v)

        if type_ == "bool" or type_ == "unlock":
            if isinstance(v, str):
                if v[0].lower() == "t":
                    s = 1
                else:
                    s = 0
            elif isinstance(v, bool):
                if v:
                    s = 1
                else:
                    s = 0

        elif type_ == "date":
            s = "'%s'" % util.dateDMAtoAMD(v)

        elif type_ == "time":
            if v:
                s = "'%s'" % v
            else:
                s = ""

        elif type_ in ("uint", "int", "double", "serial"):
            if v is None:
                s = 0
            else:
                s = v

        else:
            if type_ == "string":
                v = auto_qt_translate_text(v)
            if upper and type_ == "string":
                v = v.upper()
                # v = v.encode("UTF-8")
            s = "'%s'" % v
        # print ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
Exemple #27
0
    def exportToPdf(self):
        if self.slotsExportedDisabled_:
            return

        fileName = QtCore.QFileDialog.getSaveFileName(
            "", FLUtil.translate(self, "app", "Fichero PDF (*.pdf)"), self,
            FLUtil.translate(self, "app", "Exportar a PDF"),
            FLUtil.translate(self, "app", "Exportar a PDF"))

        if not fileName or fileName == "":
            return

        if not fileName.upper().contains(".PDF"):
            fileName = fileName + ".pdf"

        q = QtCore.QMessageBox.question(
            self,
            FLUtil.translate(self, "app", "Sobreescribir {}").format(fileName),
            FLUtil.translate(
                self, "app",
                "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?").
            format(fileName), FLUtil.translate(self, "app", "&Sí"),
            FLUtil.translate(self, "app", "&No"), "", 0, 1)

        if QtCore.QFile.exists(fileName) and q:
            return

        self.slotPrintReportToPDF(fileName)
Exemple #28
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()
Exemple #29
0
    def formatValue(self, type_, v, upper):

        util = FLUtil()

        s = None
        # TODO: psycopg2.mogrify ???
        if type_ == "pixmap" and v.find("'") > -1:
            v = self.normalizeValue(v)

        if type_ == "bool" or type_ == "unlock":
            if isinstance(v, str):
                if v[0].lower() == "t":
                    s = 1
                else:
                    s = 0
            elif isinstance(v, bool):
                if v:
                    s = 1
                else:
                    s = 0

        elif type_ == "date":
            s = "'%s'" % util.dateDMAtoAMD(v)

        elif type_ == "time":
            if v:
                s = "'%s'" % v
            else:
                s = ""

        elif type_ in ("uint", "int", "double", "serial"):
            if v:
                s = 0
            else:
                s = v

        else:
            v = auto_qt_translate_text(v)
            if upper and type_ == "string":
                v = v.upper()
                # v = v.encode("UTF-8")
            s = "'%s'" % v
        # print ("PNSqlDriver(%s).formatValue(%s, %s) = %s" % (self.name_, type_, v, s))
        return s
    def installACL(self, idacl):
        """
        Crea un nuevo fichero "acl.xml" y lo almacena sustituyendo el anterior, en el caso de que exista.

        @param idacl Identificador del registro de la tabla "flacls" a utilizar para crear "acl.xml".
        """

        util = FLUtil()

        doc = QDomDocument("ACL")

        root = doc.createElement("ACL")
        doc.appendChild(root)

        name = doc.createElement("name")
        root.appendChild(name)
        n = doc.createTextNode(idacl)
        name.appendChild(n)

        q = FLSqlQuery()

        q.setTablesList("flacs")
        q.setSelect("idac,tipo,nombre,iduser,idgroup,degroup,permiso")
        q.setFrom("flacs")
        q.setWhere("idacl='%s'" % idacl)
        q.setOrderBy("prioridad DESC, tipo")
        q.setForwarOnly(True)

        if q.exec_():
            step = 0
            progress = util.ProgressDialog(
                util.tr("Instalando control de acceso..."), None, q.size(),
                None, None, True)
            progress.setCaption(util.tr("Instalando ACL"))
            progress.setMinimumDuration(0)
            progress.setProgress(++step)
            while q.next():
                self.makeRule(q, doc)
                progress.setProgress(++step)

            self.database().managerModules().setContent(
                "acl.xml", "sys", doc.toString())
    def exportFileCSVData(self):
        if self.slotsExportedDisabled_:
            return

        util = FLUtil()
        fileName = QFileDialog.getSaveFileName(
            self, util.translate("app", "Exportar a CSV"), "",
            util.translate("app", "Fichero CSV (*.csv *.txt)"))

        if not fileName or fileName == "":
            return

        if not fileName.upper().contains(".CSV"):
            fileName = fileName + ".csv"

        q = QtCore.QMessageBox.question(
            self,
            util.translate("app", "Sobreescribir {}").format(fileName),
            util.translate(
                self, "app",
                "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?").
            format(fileName), util.translate("app", "&Sí"),
            util.translate("app", "&No"), "", 0, 1)

        if QtCore.QFile.exists(fileName) and q:
            return

        file = QtCore.QFile(fileName)

        if file.open(Qt.IO_WriteOnly):
            stream = QtCore.QTextStream(file)
            stream << self.csvData() << "\n"
            file.close()
        else:
            QtCore.QMessageBox.critical(
                self, util.translate("app", "Error abriendo fichero"),
                util.translate(
                    "app",
                    "No se pudo abrir el fichero {} para escribir: {}").format(
                        fileName,
                        QtWidgets.QApplication.translate(
                            "QFile", file.errorString())))
Exemple #32
0
    def createSystemTable(self, n):
        """
        Crea una tabla del sistema.

        Este método lee directamente de disco el fichero con la descripción de una tabla
        del sistema y la crea en la base de datos. Su uso normal es para inicializar
        el sistema con tablas iniciales.

        @param n Nombre de la tabla.
        @return Un objeto FLTableMetaData con los metadatos de la tabla que se ha creado, o
          False si no se pudo crear la tabla o ya existía
        """
        util = FLUtil()
        if not self.existsTable(n):
            doc = QDomDocument()
            _path = filedir("..", "share", "pineboo", "tables")
            dir = qsatype.Dir_Class(_path)
            _tables = dir.entryList("%s.mtd" % n)

            for f in _tables:
                path = "%s/%s" % (_path, f)
                _file = QtCore.QFile(path)
                _file.open(QtCore.QIODevice.ReadOnly)
                _in = QtCore.QTextStream(_file)
                _data = _in.readAll()
                if not util.domDocumentSetContent(doc, _data):
                    logger.warn(
                        "FLManager::createSystemTable: %s",
                        util.tr(
                            "Error al cargar los metadatos para la tabla %1").
                        arg(n))
                    return False
                else:
                    docElem = doc.documentElement()

                    mtd = self.createTable(self.metadata(docElem, True))
                    return mtd

                f.close()

        return False
    def init(self, aclXml=None):

        util = FLUtil()
        if not aclXml:
            self.init(self.database().managerModules().content("acl.xml"))
            return

        doc = QDomDocument("ACL")
        if self.accessControlList_:
            self.accessControlList_.clear()
            del self.accessControlList_
            self.accessControlList_ = {}

        if not util.domDocumentSetContent(doc, aclXml):
            qWarning("FLAccessControlList : " +
                     util.tr("Lista de control de acceso vacia o errónea"))
            return

        self.accessControlList_ = {}
        self.accessControlList_.setAutoDelete(True)

        docElem = doc.documentElement()
        no = docElem.firstChild()

        while no:
            e = no.toElement()
            if e:
                if e.tagName() == "name":
                    self.name_ = e.text()
                    no = no.nextSibling()
                    continue

                ac = FLAccessControlFactory.create(e.tagName())
                if ac:
                    ac.set(e)
                    self.accessControlList_.replace(
                        "%s::%s::%s" % (ac.type(), ac.name(), ac.user()), ac)
                    no = no.nextSibling()
                    continue

            no = no.nextSibling()
    def installACL(self, idacl):
        """
        Crea un nuevo fichero "acl.xml" y lo almacena sustituyendo el anterior, en el caso de que exista.

        @param idacl Identificador del registro de la tabla "flacls" a utilizar para crear "acl.xml".
        """

        util = FLUtil()

        doc = QDomDocument("ACL")

        root = doc.createElement("ACL")
        doc.appendChild(root)

        name = doc.createElement("name")
        root.appendChild(name)
        n = doc.createTextNode(idacl)
        name.appendChild(n)

        q = FLSqlQuery()

        q.setTablesList("flacs")
        q.setSelect("idac,tipo,nombre,iduser,idgroup,degroup,permiso")
        q.setFrom("flacs")
        q.setWhere("idacl='%s'" % idacl)
        q.setOrderBy("prioridad DESC, tipo")
        q.setForwarOnly(True)

        if q.exec_():
            step = 0
            progress = util.ProgressDialog(
                util.tr("Instalando control de acceso..."), None, q.size(), None, None, True)
            progress.setCaption(util.tr("Instalando ACL"))
            progress.setMinimumDuration(0)
            progress.setProgress(++step)
            while q.next():
                self.makeRule(q, doc)
                progress.setProgress(++step)

            self.database().managerModules().setContent("acl.xml", "sys", doc.toString())
Exemple #35
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()
Exemple #36
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()
    def saveSVGStyle(self):
        util = FLUtil()
        if self.report_:
            fileName = QtCore.QFileDialog.getSaveFileName(
                "", util.translate(self, "app", "Fichero SVG (*.svg)"), self,
                util.translate(self, "app", "Guardar en SVG"),
                util.translate(self, "app", "Guardar en SVG"))

            if not fileName or fileName == "":
                return

            if not fileName.upper().contains(".SVG"):
                fileName = fileName + ".svg"

            q = QtCore.QMessageBox.question(
                self,
                util.translate(self, "app",
                               "Sobreescribir {}").format(fileName),
                util.translate(
                    self, "app",
                    "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"
                ).format(fileName), util.translate(self, "app", "&Sí"),
                util.translate(self, "app", "&No"), "", 0, 1)

            if QtCore.QFile.exists(fileName) and q:
                return

            FLStylePainter.setSVGMode(True)
            self.updateReport()
            FLStylePainter.setSVGMode(False)

            fileNames = []

            for i in range(self.report_.pageCount()):
                fname = fileName + str(i)
                fileNames.append(fname)
                page = self.report_.getPageAt(i)
                psize = self.report_.pageDimensions()
                page.setBoundingRect(QtCore.QRect(QtCore.QPoint(0, 0), psize))
                page.save(fname, "svg")

            FLStylePainter.normalizeSVGFile(fileName, fileNames)

            self.updateReport()
Exemple #38
0
    def saveSVGStyle(self):
        util = FLUtil()
        if self.report_:
            fileName = QtCore.QFileDialog.getSaveFileName(
                "",
                util.translate(self, "app", "Fichero SVG (*.svg)"),
                self,
                util.translate(self, "app", "Guardar en SVG"),
                util.translate(self, "app", "Guardar en SVG")
            )

            if not fileName or fileName == "":
                return

            if not fileName.upper().contains(".SVG"):
                fileName = fileName + ".svg"

            q = QtCore.QMessageBox.question(
                self,
                util.translate(
                    self, "app", "Sobreescribir {}").format(fileName),
                util.translate(
                    self,
                    "app",
                    "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"
                ).format(fileName),
                util.translate(self, "app", "&Sí"),
                util.translate(self, "app", "&No"),
                "",
                0,
                1
            )

            if QtCore.QFile.exists(fileName) and q:
                return

            FLStylePainter.setSVGMode(True)
            self.updateReport()
            FLStylePainter.setSVGMode(False)

            fileNames = []

            for i in range(self.report_.pageCount()):
                fname = fileName + str(i)
                fileNames.append(fname)
                page = self.report_.getPageAt(i)
                psize = self.report_.pageDimensions()
                page.setBoundingRect(QtCore.QRect(QtCore.QPoint(0, 0), psize))
                page.save(fname, "svg")

            FLStylePainter.normalizeSVGFile(fileName, fileNames)

            self.updateReport()
Exemple #39
0
    def exec(self, n=QString.null):
        if not self.cursor_:
            return QVariant()

        if self.loop and self.inExec_:
            print(
                FLUtil.translate(
                    "app",
                    "FLFormSearchDB::exec(): Se ha detectado una llamada recursiva"
                ))
            self.QWidget.show()
            if self.initFocusWidget_:
                self.initFocusWidget_.setFocus()
            return QVariant()

        self.inExec_ = True
        self.acceptingRejecting_ = False

        self.QWidget.show()
        if self.initFocusWidget_:
            self.initFocusWidget_.setFocus()

        if self.iface:
            aqApp.call("init", self.QSArgumentList(), self.iface)

        #if (!isClosing_ && !aqApp->project()->interpreter()->hadError()) #FIXME
        #    QTimer::singleShot(0, this, SLOT(emitFormReady())); #FIXME

        self.accepted_ = False
        self.loop = True
        if not self.isClosing_ and not self.acceptingRejecting_:
            QtGui.QApplication.eventLoop().enterLoop()
        self.loop = False

        self.clearWFlags(Qt.WShowModal)
        v = None
        if self.accepted_ and not n.isEmpty():
            v = self.cursor_.valueBuffer(n)
        else:
            v = QVariant()

        self.inExec_ = False
        return v
Exemple #40
0
    def initForm(self):
        if self.cursor_ and self.cursor_.metadata():
            caption = None
            if self.action_:
                self.cursor_.setAction(self.action_)
                caption = self.action_.caption()
                if not self.action_.description().isEmpty():
                    self.QtGui.QWhatsThis.add(self, self.action_.description())
                self.idMDI_ = self.action_.name()

            if caption.isEmpty():
                caption = self.cursor_.metadata().alias()
            self.setCaption(caption)

            self.bindIface()
            self.setCursor(self.cursor_)

        else:
            self.setCaption(FLUtil.translate("sys", "No hay metadatos"))
Exemple #41
0
 def initForm(self):
     if self.cursor_ and self.cursor_.metadata():
         caption = None
         if self.action_:
             self.cursor_.setAction(self.action_)
             caption = self.action_.caption()
             if not self.action_.description().isEmpty():
                 self.QtGui.QWhatsThis.add(self, self.action_.description())
             self.idMDI_ = self.action_.name()
         
         if caption.isEmpty():
             caption = self.cursor_.metadata().alias()
         self.setCaption(caption)
         
         self.bindIface()
         self.setCursor(self.cursor_)
     
     else:
         self.setCaption(FLUtil.translate("sys" ,"No hay metadatos"))
Exemple #42
0
    def slotRenderProgress(self, p):
        util = FLUtil()
        if not self.rptEngine_:
            return

        if not self.progress_:
            self.totalSteps_ = self.rptEngine_.getRenderSteps()
            if self.totalSteps_ <= 0:
                self.totalSteps_ = 1
            self.progress_ = util.createProgressDialog(
                util.translate("app", "Creando informe..."), self.totalSteps_)
            # self.progress_.setMinimunDuration(self.M_PROGRESS_DELAY)
            self.progress_.canceled.connect(self.slotCancelPrinting)

        util.setProgress(p)
        QtWidgets.QApplication.processEvents()
Exemple #43
0
    def renderReport(self, initRow=0, initCol=0, fRec=False, pages=None):
        fr = MReportEngine.RenderReportFlags.FillRecords.value

        pgs = FLReportPages()
        if pages:
            pgs.setPageCollection(pages)

        pgc = super(FLReportEngine, self).renderReport(
            initRow,
            initCol,
            pgs,
            fr if fRec else 0
        )

        pgs.setPageCollection(pgc)
        if not fRec or not self.d_.qry_ or not self.d_.qFieldMtdList_ or not self.d_.qDoubleFieldList_:
            return pgs

        nl = QtXml.QDomNodeList(self.rd.elementsByTagName("Row"))
        for i in range(nl.count()):
            itm = nl.item(i)
            if itm.isNull():
                continue
            nm = itm.attributes()

            for it in self.d_.qDoubleFieldList_:
                ita = nm.namedItem(it)
                if ita.isNull():
                    continue
                sVal = ita.nodeValue()
                if not sVal or sVal == "" or sVal.upper() == "NAN":
                    continue
                dVal = float(sVal)
                if not dVal:
                    dVal = 0
                decimals = self.d_.qFieldMtdList_.find(
                    it.section('.', 1, 1).lower()).partDecimal()
                ita.setNodeValue(FLUtil.formatoMiles(round(dVal, decimals)))
        return pgs
Exemple #44
0
 def exec(self, n = QString.null):
     if not self.cursor_:
         return QVariant()
     
     if self.loop and self.inExec_:
         print(FLUtil.translate("app","FLFormSearchDB::exec(): Se ha detectado una llamada recursiva"))
         self.QWidget.show()
         if self.initFocusWidget_:
             self.initFocusWidget_.setFocus()
         return QVariant()
     
     self.inExec_ = True
     self.acceptingRejecting_ = False
     
     self.QWidget.show()
     if self.initFocusWidget_:
         self.initFocusWidget_.setFocus()
     
     if self.iface:
         aqApp.call("init", self.QSArgumentList(), self.iface)
     
     #if (!isClosing_ && !aqApp->project()->interpreter()->hadError()) #FIXME
     #    QTimer::singleShot(0, this, SLOT(emitFormReady())); #FIXME
     
     self.accepted_ = False
     self.loop = True
     if not self.isClosing_ and not self.acceptingRejecting_:
         QtGui.QApplication.eventLoop().enterLoop()
     self.loop = False
     
     self.clearWFlags(Qt.WShowModal)
     v = None
     if self.accepted_ and not n.isEmpty():
         v = self.cursor_.valueBuffer(n)
     else:
         v = QVariant()
     
     self.inExec_ = False
     return v
Exemple #45
0
    def database(self, connectionName="default"):
        if not self.d:
            self.d = FLSqlConnectionsPrivate()

        if connectionName == "default":
            if not self.d.defaultDB:
                self.addDatabase(FLSqlDatabase())
            return self.d.defaultDB

        if not self.d.dictDB:
            self.addDatabase(FLSqlDatabase())
            return self.d.defaultDB

        ret = self.d.dictDB.get(connectionName)

        if not ret:
            print(FLUtil.translate("FLSqlConnections::database : No existe la conexión '%s', se devuelve la conexión por defecto 'default'" % connectionName))

            if not self.d.defaultDB:
                self.addDatabase(FLSqlDatabase())
            ret = self.defaultDB

        return ret
Exemple #46
0
    def exportToPDF(self):
        if self.slotsExportedDisabled_:
            return

        util = FLUtil()
        fileName = QFileDialog.getSaveFileName(
            self,
            util.translate("app", "Exportar a PDF"),
            "",
            util.translate("app", "Fichero PDF (*.pdf)")
        )

        if fileName[0] == '':
            return

        if fileName[0].upper().find(".PDF") == -1:
            fileName = fileName[0] + ".pdf"

        if QtCore.QFile.exists(fileName):

            q = QMessageBox.question(
                self,
                util.translate("app", "Sobreescribir {}").format(fileName),
                util.translate(
                    "app",
                    "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"
                ).format(fileName),
                util.translate("app", "&Sí"),
                util.translate("app", "&No"),
                "",
                0,
                1
            )
            if q:
                return

        self.slotPrintReportToPdf(fileName)
Exemple #47
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}$")
        if rx in self.tables() is not False:
            listOldBks = rx in self.tables()
        else:
            listOldBks = []

        qry.exec_("select nombre from flfiles where nombre similar to"
                  "'%[[:digit:]][[:digit:]][[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]%:[[:digit:]][[:digit:]]%' or nombre similar to"
                  "'%alteredtable[[:digit:]][[:digit:]][[:digit:]][[:digit:]]%' or (bloqueo='f' and nombre like '%.mtd')")

        util.createProgressDialog(
            util.tr("Borrando backups"), len(listOldBks) + qry.size() + 2)

        while qry.next():
            item = qry.value(0)
            util.setLabelText(util.tr("Borrando registro %1").arg(item))
            qry2.exec_("DELETE FROM flfiles WERE nombre ='%s'" % item)
            if item.find("alteredtable") > -1:
                if self.existsTable(item.replace(".mtd", "")):
                    util.setLabelText(util.tr("Borrando tabla %1").arg(item))
                    qry2.exec_("DROP TABLE %s CASCADE" %
                               item.replace(".mtd", ""))

            steps = steps + 1
            util.setProgress(steps)

        for item in listOldBks:
            if self.existsTable(item):
                util.setLabelText(util.tr("Borrando tabla %s" % item))
                qry2.exec_("DROP TABLE %s CASCADE" % item)

            steps = steps + 1
            util.setProgress(steps)

        util.setLabelText(util.tr("Inicializando cachés"))
        steps = steps + 1
        util.setProgress(steps)
        qry.exec_("DELETE FROM flmetadata")
        qry.exec_("DELETE FROM flvar")
        self.db_.manager().cleanupMetaData()
        # self.db_.driver().commit()
        util.destroyProgressDialog()

        steps = 0
        qry.exec_("select tablename from pg_tables where schemaname='public'")
        util.createProgressDialog(
            util.tr("Comprobando base de datos"), qry.size())
        while qry.next():
            item = qry.value(0)
            util.setLabelText(util.tr("Comprobando tabla %s" % item))

            mustAlter = self.mismatchedTable(item, item)
            if mustAlter:
                conte = self.db_.managerModules().content("%s.mtd" % item)
                if conte:
                    msg = util.tr("La estructura de los metadatos de la tabla '%s' y su "
                                  "estructura interna en la base de datos no coinciden. "
                                  "Intentando regenerarla." % item)

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

            steps = steps + 1
            util.setProgress(steps)

        self.db_.dbAux().driver().transaction()
        steps = 0
        sqlCursor = FLSqlCursor(None, True, self.db_.dbAux())
        sqlQuery = FLSqlQuery(None, self.db_.dbAux())
        if sqlQuery.exec_("select relname from pg_class where ( relkind = 'r' ) "
                          "and ( relname !~ '^Inv' ) " "and ( relname !~ '^pg_' ) and ( relname !~ '^sql_' )"):

            util.setTotalSteps(sqlQuery.size())
            while sqlQuery.next():
                item = sqlQuery.value(0)
                steps = steps + 1
                util.setProgress(steps)
                util.setLabelText(util.tr("Creando índices para %s" % item))
                mtd = self.db_.manager().metadata(item)
                fL = mtd.fieldList()
                if not mtd or not fL:
                    continue
                for it in fL:
                    if not it or not it.type() == "pixmap":
                        continue
                    cur = FLSqlCursor(item, True, self.db_.dbAux())
                    cur.select(it.name() + " not like 'RK@%'")
                    while cur.next():
                        v = cur.value(it.name())
                        if v is None:
                            continue

                        v = self.db_.manager().storeLargeValue(mtd, v)
                        if v:
                            buf = cur.primeUpdate()
                            buf.setValue(it.name(), v)
                            cur.update(False)

                sqlCursor.setName(item, True)

        # self.db_.dbAux().driver().commit()

        steps = 0
        qry.exec_("select tablename from pg_tables where schemaname='public'")
        util.createProgressDialog(
            util.tr("Analizando base de datos"), qry.size())
        while qry.next():
            item = qry.value(0)
            util.setLabelText(util.tr("Analizando tabla %s" % item))
            qry2.exec_("vacuum analyze %s" % item)
            steps = steps + 1
            util.setProgress(steps)

        util.destroyProgressDialog()
Exemple #48
0
 def saveSnapShot(self, pathFile):
     fi = QtCore.QFile(pathFile)
     if not fi.open(QtCore.QFile.WriteOnly):
         print("FLFormDB : " + FLUtil.translate("sys", "Error I/O al intentar escribir el fichero %s" % pathFile))
         return
     self.snapShot().save(fi, "PNG")
Exemple #49
0
    def load(self):

        self.ui_ = pineboolib.project.conn.managerModules().createUI(
            filedir('plugins/mainform/pineboo/mainform.ui'), None, self)

        self.w_ = self
        frameGm = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

        self.areasTab = QTabWidget()
        self.areasTab.setTabPosition(QTabWidget.West)
        self.formTab = QTabWidget()
        try:
            self.areasTab.removeItem = self.areasTab.removeTab
            self.areasTab.addItem = self.areasTab.addTab
        except Exception:
            pass

        self.dockAreasTab = QDockWidget()
        self.dockAreasTab.setWindowTitle("Módulos")
        #self.dockAreas = QtWidgets.QDockWidget()
        self.dockFavoritos = QDockWidget()
        self.dockFavoritos.setWindowTitle("Favoritos")

        self.dockForm = QDockWidget()

        self.dockConsole = None

        self.dockAreasTab.setWidget(self.areasTab)
        self.dockAreasTab.setMaximumWidth(400)
        self.dockFavoritos.setMaximumWidth(400)
        self.dockFavoritos.setMaximumHeight(500)
        # self.dockAreasTab.setMinimumWidth(400)
        # self.dockAreasTab.setMaximumHeight(500)

        self.dockForm.setWidget(self.formTab)

        self.addDockWidget(Qt.RightDockWidgetArea, self.dockForm)
        # self.dockForm.setMaximumWidth(950)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockFavoritos)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockAreasTab)
        # self.dockAreasTab.show()
        # self.dockForm.show()

        # self.areasTab.removeItem(0) #Borramos tab de ejemplo.

        self.formTab.setTabsClosable(True)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.formTab.tabCloseRequested[int].connect(self.closeFormTab)
        self.formTab.removeTab(0)
        #app_icon = QtGui.QIcon('share/icons/pineboo-logo-16.png')
        # app_icon.addFile(filedir('share/icons/pineboo-logo-16.png'),
        #                 QtCore.QSize(16, 16))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-24.png'),
        #                 QtCore.QSize(24, 24))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-32.png'),
        #                 QtCore.QSize(32, 32))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-48.png'),
        #                 QtCore.QSize(48, 48))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-64.png'),
        #                 QtCore.QSize(64, 64))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-128.png'),
        #                 QtCore.QSize(128, 128))
        # app_icon.addFile(filedir('share/icons/pineboo-logo-256.png'),
        #                 QtCore.QSize(256, 256))
        # self.setWindowIcon(app_icon)
        self.setWindowIcon(QtGui.QIcon('share/icons/pineboo-logo-16.png'))
        self.actionAcercaQt.triggered.connect(pineboolib.project.aboutQt)
        self.actionAcercaPineboo.triggered.connect(pineboolib.project.aboutPineboo)
        self.actionFavoritos.triggered.connect(self.changeStateDockFavoritos)
        self.dockFavoritos.visibilityChanged.connect(self.changeStateActionFavoritos)
        self.actionModulos.triggered.connect(self.changeStateDockAreas)
        self.dockAreasTab.visibilityChanged.connect(self.changeStateActionAreas)
        self.actionTipografia.triggered.connect(pineboolib.project.chooseFont)
        self.menuPineboo.addSeparator()
        # self.actionEstilo.triggered.connect(pineboolib.main.styleDialog)
        # pineboolib.pnapplication.initStyle(self.configMenu)
        self.setWindowTitle("Pineboo")

        logger.info("Módulos y pestañas ...")
        for k, area in sorted(pineboolib.project.areas.items()):
            self.loadArea(area)
        for k, module in sorted(pineboolib.project.modules.items()):
            self.loadModule(module)

        # Cargando Area desarrollo si procede ...
        sett_ = FLSettings()
        if (sett_.readBoolEntry("application/isDebuggerMode", False)):
            areaDevelop = Struct(idarea="dvl", descripcion="Desarrollo")
            self.loadArea(areaDevelop)

            self.loadDevelop()

        self.restoreOpenedTabs()

        self.loadState()
        # Cargamos nombre de vertical
        util = FLUtil()
        verticalName = util.sqlSelect("flsettings", "valor", "flkey='verticalName'")
        cbPosInfo = util.sqlSelect("flsettings", "valor", "flkey='PosInfo'")

        statusText = ""

        if verticalName != None:
            statusText = verticalName

        if cbPosInfo == 'True':
            from pineboolib.pncontrolsfactory import SysType
            sys_ = SysType()
            statusText += "\t\t\t" + sys_.nameUser() + "@" + sys_.nameBD()

        self.statusBar().showMessage(statusText)
Exemple #50
0
    def run(self):
        # TODO: Refactorizar esta función en otras más sencillas
        # Preparar temporal
        if self.deleteCache and not not os.path.exists(
                self.dir("cache/%s" % self.dbname)):
            self.logger.debug("DEVELOP: DeleteCache Activado\nBorrando %s",
                              self.dir("cache/%s" % self.dbname))
            for root, dirs, files in os.walk(self.dir("cache/%s" %
                                                      self.dbname),
                                             topdown=False):
                for name in files:
                    os.remove(os.path.join(root, name))
                for name in dirs:
                    os.rmdir(os.path.join(root, name))
            # borrando de share
            # for root, dirs, files in os.walk(self.dir("../share/pineboo"), topdown=False):
            #    for name in files:
            #        if name.endswith("qs.py") or name.endswith("qs.py.debug") or name.endswith("qs.xml"):
            #            os.remove(os.path.join(root, name))

        if not os.path.exists(self.dir("cache")):
            os.makedirs(self.dir("cache"))

        # Conectar:

        if not self.conn:
            self.conn = PNConnection(self.dbname, self.dbserver.host,
                                     self.dbserver.port, self.dbauth.username,
                                     self.dbauth.password, self.dbserver.type)
        if self.conn.conn is False:
            return False

        # Se verifica que existen estas tablas
        for table in ("flareas", "flmodules", "flfiles", "flgroups", "fllarge",
                      "flserial", "flusers", "flvar"):
            self.conn.manager().createSystemTable(table)

        util = FLUtil()
        util.writeSettingEntry(u"DBA/lastDB", self.dbname)
        self.cur = self.conn.cursor()
        self.areas = {}
        self.cur.execute(
            """ SELECT idarea, descripcion FROM flareas WHERE 1 = 1""")
        for idarea, descripcion in self.cur:
            self.areas[idarea] = Struct(idarea=idarea, descripcion=descripcion)

        self.areas["sys"] = Struct(idarea="sys", descripcion="Area de Sistema")

        # Obtener modulos activos
        self.cur.execute(
            """ SELECT idarea, idmodulo, descripcion, icono FROM flmodules WHERE bloqueo = %s """
            % self.conn.driver().formatValue("bool", "True", False))
        self.modules = {}
        for idarea, idmodulo, descripcion, icono in self.cur:
            icono = clearXPM(icono)
            self.modules[idmodulo] = Module(self, idarea, idmodulo,
                                            descripcion, icono)

        file_object = open(filedir("..", "share", "pineboo", "sys.xpm"), "r")
        icono = file_object.read()
        file_object.close()
        icono = clearXPM(icono)

        self.modules["sys"] = Module(self, "sys", "sys", "Administración",
                                     icono)

        # Descargar proyecto . . .

        self.cur.execute(
            """ SELECT idmodulo, nombre, sha FROM flfiles ORDER BY idmodulo, nombre """
        )
        size_ = len(self.cur.fetchall())
        self.cur.execute(
            """ SELECT idmodulo, nombre, sha FROM flfiles ORDER BY idmodulo, nombre """
        )
        f1 = open(self.dir("project.txt"), "w")
        self.files = {}
        if self._DGI.useDesktop() and self._DGI.localDesktop():
            tiempo_ini = time.time()
        if not os.path.exists(self.dir("cache")):
            raise AssertionError
        # if self.parseProject:
        if self._DGI.useDesktop() and self._DGI.localDesktop():
            util.createProgressDialog("Pineboo", size_)
        p = 0
        for idmodulo, nombre, sha in self.cur:
            p = p + 1
            if self._DGI.useDesktop() and self._DGI.localDesktop():
                util.setProgress(p)
                util.setLabelText("Convirtiendo %s." % nombre)
            if idmodulo not in self.modules:
                continue  # I
            fileobj = File(self, idmodulo, nombre, sha)
            if nombre in self.files:
                self.logger.warn(
                    "run: file %s already loaded, overwritting..." % nombre)
            self.files[nombre] = fileobj
            self.modules[idmodulo].add_project_file(fileobj)
            f1.write(fileobj.filekey + "\n")
            if os.path.exists(self.dir("cache", fileobj.filekey)):
                continue
            fileobjdir = os.path.dirname(self.dir("cache", fileobj.filekey))
            if not os.path.exists(fileobjdir):
                os.makedirs(fileobjdir)

            cur2 = self.conn.cursor()
            sql = "SELECT contenido FROM flfiles WHERE idmodulo = %s AND nombre = %s AND sha = %s" % (
                self.conn.driver().formatValue("string", idmodulo, False),
                self.conn.driver().formatValue("string", nombre, False),
                self.conn.driver().formatValue("string", sha, False))
            cur2.execute(sql)
            for (contenido, ) in cur2:
                f2 = open(self.dir("cache", fileobj.filekey), "wb")
                # La cadena decode->encode corrige el bug de guardado de
                # AbanQ/Eneboo
                txt = ""
                try:
                    # txt = contenido.decode("UTF-8").encode("ISO-8859-15")
                    txt = contenido.encode("ISO-8859-15")
                except Exception:
                    self.logger.exception("Error al decodificar %s %s",
                                          idmodulo, nombre)
                    # txt = contenido.decode("UTF-8","replace").encode("ISO-8859-15","replace")
                    txt = contenido.encode("ISO-8859-15", "replace")

                f2.write(txt)

            if self.parseProject and nombre.endswith(".qs"):
                self.parseScript(self.dir("cache", fileobj.filekey))

        if self._DGI.useDesktop() and self._DGI.localDesktop():
            tiempo_fin = time.time()
            self.logger.info(
                "Descarga del proyecto completo a disco duro: %.3fs",
                (tiempo_fin - tiempo_ini))

        # Cargar el núcleo común del proyecto
        idmodulo = 'sys'
        for root, dirs, files in os.walk(filedir("..", "share", "pineboo")):
            for nombre in files:
                if root.find("modulos") == -1:
                    fileobj = File(self, idmodulo, nombre, basedir=root)
                    self.files[nombre] = fileobj
                    self.modules[idmodulo].add_project_file(fileobj)
                    if self.parseProject and nombre.endswith(".qs"):
                        self.parseScript(self.dir(root, nombre))

        if self._DGI.useDesktop() and self._DGI.localDesktop():
            try:
                util.destroyProgressDialog()
            except Exception as e:
                self.logger.error(e)

        self.loadTranslations()
        self.readState()
        self.acl_ = FLAccessControlLists()
        self.acl_.init_()
Exemple #51
0
 def singleFLLarge(self):
     return FLUtil().sqlSelect("flsettings", "valor",
                               "flkey='FLLargeMode'") == "False"
Exemple #52
0
 def metadata(self, n, quick):
     if quick is None: quick = False
     
     ret = self.metadataDev(n, quick)
     if not quick and ret and not ret.isQuery() and self.db_.mismatchedTable(n, ret):
         msg = FLUtil.translate("sys","La estructura de los metadatos de la tabla '%s' y su estructura interna en la base de datos no coinciden. Debe regenerar la base de datos." % n)
         print(msg)
     
     if n.isEmpty() or not self.db_.dbAux():
         return False
     
     ret = False
     acl = False
     key = n
     stream = QString
     isSysTable = False
     if n[0:2] is "sys" or self.isSystemTable(n):
         isSysTable = True
         
     if not isSysTable:
         stream = self.db_.managerModules().contentCached(n + ".mtd", key)
         
         if stream.isEmpty():
             print("FLManager : " + FLUtil.translate("sys","Error al cargar los metadatos para la tabla %s" % n))
             return False
         
         if key.isEmpty():
             key = n
         
     if self.cacheMetaData_ and not isSysTable:
         ret = self.cacheMetaData_.find(key)
     else if self.cacheMetaDataSys_ and isSysTable:
         ret = self.cacheMetaDataSys_.find(key)
     
     if not ret:
         if isSysTable:
             stream = self.db_.managerModules().contentCached(n + ".mtd")
             if stream.isEmpty():
                 print("FLManager : " + FLUtil.translate("sys","Error al cargar los metadatos para la tabla %s" % n))
                 return False
     
     
         ret = metadata(stream)
         if not ret:
             return False
     
         if self.cacheMetaData_ and not isSysTable and not ret.isQuery():
             ret.setInCache()
             self.cacheMetaData_.insert(key, ret)
         else if self.cacheMetaDataSys_ and isSysTable:
             ret.setInCache()
             self.cacheMetaDataSys_.insert(key.ret)
     
     else:
         acl = aqApp.acl()
         
         if not ret.fieldsNamesUnlock().isEmpty():
             ret = FLTableMetaData(ret)
         
         if acl:
             acl.process(ret)
         
         if not quick and not isSysTable and aqApp.consoleShow() and not ret.isQuery() and self.db_.mismatchedTable(n, ret):
             msg = FLUtil.translate("sys","La estructura de los metadatos de la tabla '%s' y su estructura interna en la base de datos no coinciden. Debe regenerar la base de datos." % n)
             print(msg)
     
     return ret            
Exemple #53
0
    def doCommit(self, cur, notify=True):
        #if not cur or not aqApp or not qApp: #FIXMME
        if not cur:

            return False

        if not notify:
            self.emit(cur.autocommit())

        if self.transaction_ > 0:
            if not cur.d.transactionsOpened_ == []:
                trans = cur.d.transactionsOpened_.pop()
                if not trans == self.transaction_:
                    print(
                        FLUtil.translate(
                            "app",
                            "FLSqlDatabase : El cursor va a terminar la transacción %s pero la última que inició es la %s"
                            % (self.transaction_, trans)))

            else:
                print(
                    FLUtil.translate(
                        "app",
                        "FLSqlDatabase : El cursor va a terminar la transacción %s pero no ha iniciado ninguna"
                        % self.transaction_))

            self.transaction_ = self.transaction_ - 1
        else:
            return True

        if self.transaction_ == 0 and self.canTransaction():
            #aqApp->statusHelpMsg(qApp->tr("Terminando transacción...")); #FIXME
            if self.db_.commit():
                self.lastActiveCursor_ = None
                if not self.canSavePoint():
                    if self.currentSavePoint_:
                        del self.currentSavePoint_
                        self.currentSavePoint_ = None
                    self.stackSavePoints_.clear()
                    self.queueSavePoints_.clear()

                if notify:
                    cur.d.modeAccess_ = FLSqlCursor.BROWSE

                #aqApp.emitTransactionEnd(cur)
                cur.d.md5Tuples_ = self.db_.md5TuplesStateTable(cur.d.curName_)
                return True
            else:
                print(
                    FLUtil.translate(
                        "app",
                        "FLSqlDatabase::doCommit : Fallo al intentar terminar transacción"
                    ))
                return False
        else:
            #aqApp->statusHelpMsg(qApp->tr("Liberando punto de salvaguarda %1...").arg(transaction_));
            if (self.transaction_ == 1 and self.canTransaction()) or (
                    self.transaction_ == 0 and not self.canTransaction()):
                if not self.canSavePoint():
                    if self.currentSavePoint_:
                        del self.currentSavePoint_
                        self.currentSavePoint_ = None
                    self.stackSavePoints_.clear()
                    self.queueSavePoints_.clear()
                else:
                    self.releaseSavePoint(self.transaction_)
                if notify:
                    cur.d.modeAccess_ = FLSqlCursor.BROWSE
                return True

            if not self.canSavePoint():
                for tempSavePoint in self.queueSavePoints_:
                    tempSavePoint.setId(self.transaction_ - 1)

                if self.currentSavePoint_:
                    self.queueSavePoints_.append(self.currentSavePoint_)
                    self.currentSavePoint_ = None
                    if not self.stackSavePoints_ == []:
                        self.currentSavePoint_ = self.stackSavePoints_.pop()

                else:
                    self.releaseSavePoint(self.transaction_)
                if notify:
                    cur.d.modeAccess_ = FLSqlCursor.BROWSE
                return True
Exemple #54
0
 def doRollback(self, cur):
     #if not cur or not self.db_ or not aqApp or not qApp: #FIXME
     if not cur:
         return False
     
     cancel = False
     if self.interactiveGUI() and (cur.d.modeAccess() == FLSqlCursor.INSERT or cur.d.modeAccess_ == FLSqlCursor.EDIT) and cur.isModifiedBuffer() and cur.d.askForCancelChanges_:
         res = QtGui.QMessageBox.information(self,FLUtil.translate("app","Cancelar cambios"),FLUtil.translate("app","Todos los cambios efectuados se cancelarán.¿Está seguro?"),
                                        QtGui.QMessageBox.Yes, QtGui.QMessageBox.No | QtGui.QMessageBox.Default | QtGui.QMessageBox.Escape)
         if res == QtGui.QMessageBox.No:
             return False
         cancel = True
     
     if self.transaction_ > 0:
         if not cur.d.transactionsOpened_ == []:
             trans = cur.d.transactionsOpened_.pop()
             if not trans == self.transaction_:
                 print(FLUtil.translate("app","FLSqlDatabase : El cursor va a deshacer la transacción %s pero la última que inició es la %s" % (self.transaction_, trans)))
         else:
             print(FLUtil.translate("app","FLSqlDatabase : El cursor va a deshacer la transacción %1 pero no ha iniciado ninguna" % self.transaction_))
         self.transaction_ = self.transaction_ -1
     else:
         return True
         
     
     if self.transaction_ == 0 and self.canTransaction():
         #aqApp->statusHelpMsg(qApp->tr("Deshaciendo transacción...")); #FIXME
         if self.db_.rollback():
             self.lastActiveCursor_ = None
         
             if not self.canSavePoint():
                 if self.currentSavePoint_:
                     del self.currentSavePoint_
                     self.currentSavePoint_ = None
             
                 self.stackSavePoints_.clear()
                 self.queueSavePoints_.clear()
         
             cur.d.modeAccess_ = FLSqlCursor.BROWSE 
             if cancel:
                 cur.select()
         
             #aqApp->emitTransactionRollback(cur);
             return True
     
         else:
             print(FLUtil.translate("app","FLSqlDatabase::doRollback : Fallo al intentar deshacer transacción"))
             return False
     
     else:
         #aqApp->statusHelpMsg(qApp->tr("Restaurando punto de salvaguarda %1...").arg(transaction_));
         if not self.canSavePoint():
             for tempSavePoint in self.queueSavePoints_:
                 tempId = tempSavePoint.id()
                 if tempId > self.transaction_ or self.transaction_ == 0:
                     tempSavePoint.undo()
                     del tempSavePoint
                 else:
                     self.queueSavePoints_
                 
             if self.currentSavePoint_:
                 self.currentSavePoint_.undo()
                 del self.currentSavePoint_
                 self.currentSavePoint_ = None
                 if not self.stackSavePoints_ == []:
                     self.currentSavePoint_ = self.stackSavePoints_.pop()
             
             if self.transaction_ == 0:
                 if self.currentSavePoint_:
                     del self.currentSavePoint_
                     self.currentSavePoint_ = None
                 self.stackSavePoints_.clear()
                 self.queueSavePoints_.clear()
         else:
             self.rollbackSavePoint(self.transaction_)
         cur.d.modeAccess_ = FLSqlCursor.BROWSE
         return True
Exemple #55
0
    def Mr_Proper(self):
        util = FLUtil()
        self.db_.dbAux().transaction()
        rx = QRegExp("^.*[\\d][\\d][\\d][\\d].[\\d][\\d].*[\\d][\\d]$")
        rx2 = QRegExp("^.*alteredtable[\\d][\\d][\\d][\\d].*$")
        qry = FLSqlQuery(None, self.db_.dbAux())
        qry2 = FLSqlQuery(None, self.db_.dbAux())
        steps = 0
        item = ""

        rx3 = QRegExp("^.*\\d{6,9}$")
        listOldBks = rx3 in self.tables("")

        qry.exec_("select nombre from flfiles")
        util.createProgressDialog(
            util.tr("Borrando backups"), len(listOldBks) + qry.size() + 5)
        while qry.next():
            item = qry.value(0)
            if item.find(rx) > -1 or item.find(rx2) > -1:
                util.setLabelText(util.tr("Borrando regisro %1").arg(item))
                qry2.exec_("delete from flfiles where nombre = '%s'" % item)
                if item.find("alteredtable") > -1:
                    if item.replace(".mtd", "") in self.tables(""):
                        util.setLabelText(
                            util.tr("Borrando tabla %1").arg(item))
                        qry2.exec_("drop table %s" %
                                   (item.replace(".mtd", "")))

            steps = steps + 1
            util.setProgress(steps)

        for item in listOldBks:
            if item in self.tables(""):
                util.setLabelText(util.tr("Borrando tabla %1").arg(item))
                qry2.exec_("drop table %s" % item)

            steps = steps + 1
            util.setProgress(steps)

        util.setLabelText(util.tr("Inicializando cachés"))
        steps = steps + 1
        util.setProgress(steps)

        qry.exec_("delete from flmetadata")
        qry.exec_("delete from flvar")
        self.db_.manager().cleanupMetaData()
        self.db_.dbAux().commit()

        util.setLabelText(util.tr("Vacunando base de datos"))
        steps = steps + 1
        util.setProgress(steps)
        qry2.exec_("vacuum")
        steps = steps + 1
        util.setProgress(steps)
        util.destryProgressDialog()
Exemple #56
0
 def doCommit(self, cur,notify = True):
     #if not cur or not aqApp or not qApp: #FIXMME
     if not cur:
     
         return False
     
     if not notify:
         self.emit(cur.autocommit())
     
     if self.transaction_ > 0:
         if not cur.d.transactionsOpened_ == []:
             trans = cur.d.transactionsOpened_.pop()
             if not trans == self.transaction_:
                 print(FLUtil.translate("app","FLSqlDatabase : El cursor va a terminar la transacción %s pero la última que inició es la %s" % (self.transaction_, trans)))
         
         else:
             print(FLUtil.translate("app","FLSqlDatabase : El cursor va a terminar la transacción %s pero no ha iniciado ninguna" % self.transaction_))
         
         self.transaction_ = self.transaction_ -1
     else:
         return True
     
     if self.transaction_ == 0 and self.canTransaction():
         #aqApp->statusHelpMsg(qApp->tr("Terminando transacción...")); #FIXME
         if self.db_.commit():
             self.lastActiveCursor_ = None
             if not self.canSavePoint():
                 if self.currentSavePoint_:
                     del self.currentSavePoint_
                     self.currentSavePoint_ = None
                 self.stackSavePoints_.clear()
                 self.queueSavePoints_.clear()
             
             if notify:
                 cur.d.modeAccess_ = FLSqlCursor.BROWSE 
             
             #aqApp.emitTransactionEnd(cur)
             cur.d.md5Tuples_ = self.db_.md5TuplesStateTable(cur.d.curName_)
             return True
         else:
             print(FLUtil.translate("app","FLSqlDatabase::doCommit : Fallo al intentar terminar transacción"))
             return False
     else:
         #aqApp->statusHelpMsg(qApp->tr("Liberando punto de salvaguarda %1...").arg(transaction_)); 
         if (self.transaction_ == 1 and self.canTransaction()) or (self.transaction_ == 0 and not self.canTransaction()):
             if not self.canSavePoint():
                 if self.currentSavePoint_:
                     del self.currentSavePoint_
                     self.currentSavePoint_ = None
                 self.stackSavePoints_.clear()
                 self.queueSavePoints_.clear()
             else:
                 self.releaseSavePoint(self.transaction_)
             if notify:
                 cur.d.modeAccess_ = FLSqlCursor.BROWSE
             return True
         
         if not self.canSavePoint():
             for tempSavePoint in self.queueSavePoints_:
                 tempSavePoint.setId(self.transaction_ - 1)
             
             if self.currentSavePoint_:
                 self.queueSavePoints_.append(self.currentSavePoint_)
                 self.currentSavePoint_ = None
                 if not self.stackSavePoints_ == []:
                     self.currentSavePoint_ = self.stackSavePoints_.pop()
             
             else:
                 self.releaseSavePoint(self.transaction_)
             if notify:
                 cur.d.modeAccess_ = FLSqlCursor.BROWSE
             return True
Exemple #57
0
 def setFromObject(self, object):
     print("FLAccessControlMainWindow::setFromObject %s" %   FLUtil.translate(self,"app","No implementado todavía."))
Exemple #58
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
Exemple #59
0
 def osName(self):
     from pineboolib.fllegacy.FLUtil import FLUtil
     util = FLUtil()
     return util.getOS()
Exemple #60
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