def setFromObject(self, obj):
       tm = obj 
       if not tm:
           return
       
       if self.acosPerms_:
           self.acosPerms_.clear()
           self.acosPerms_ = None
       
       self.acosPerms_ = QtCore.QDict(31)
       self.acosPerms_.setAutoDelete(True)
       
       fL = FLTableMetaData(tm.fieldList())
       if not fL:
           return
       
       field = FLFieldMetaData()
       permW = QtCore.Qchar()
       permR = QtCore.Qchar()
       it = QtCore.QDictIterator(fL)
       
       while not it.current() == 0:
           field = it.current()
           ++it
           permR = '-'
           permW = '-'
           if field.visible():
               permR = 'r'
           if field.editable():
               permW = 'w'
           self.acosPerms_.replace(field.name(), QtCore.QString(permR + permW))
 
   
          
           
예제 #2
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
예제 #3
0
    def metadataField(self, field, v=True, ed=True):
        """
        Crea un objeto FLFieldMetaData a partir de un elemento XML.

        Dado un elemento XML, que contiene la descripción de un
        campo de una tabla construye y agrega a una lista de descripciones
        de campos el objeto FLFieldMetaData correspondiente, que contiene
        dicha definición del campo. Tambien lo agrega a una lista de claves
        compuesta, si el campo construido pertenece a una clave compuesta.
        NO SE HACEN CHEQUEOS DE ERRORES SINTÁCTICOS EN EL XML.

        @param field Elemento XML con la descripción del campo
        @param v Valor utilizado por defecto para la propiedad visible
        @param ed Valor utilizado por defecto para la propiedad editable
        @return Objeto FLFieldMetaData que contiene la descripción del campo
        """
        if not field:
            return None

        util = FLUtil()

        ck = False
        n = None
        a = None
        ol = False
        rX = None
        assocBy = None
        assocWith = None
        so = None

        aN = True
        iPK = True
        c = False
        iNX = False
        uNI = False
        coun = False
        oT = False
        vG = True
        fullCalc = False
        trimm = False

        t = -1
        length = 0
        pI = 4
        pD = 0

        dV = None

        no = field.firstChild()

        while not no.isNull():
            e = no.toElement()
            if not e.isNull():
                if e.tagName() in ("relation", "associated"):
                    no = no.nextSibling()
                    continue

                if e.tagName() == "name":
                    n = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "alias":
                    a = auto_qt_translate_text(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "null":
                    aN = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "pk":
                    iPK = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "type":
                    if e.text() == "int":
                        t = "int"
                    elif e.text() == "uint":
                        t = "uint"
                    elif e.text() == "bool":
                        t = "bool"
                    elif e.text() == "double":
                        t = "double"
                    elif e.text() == "time":
                        t = "time"
                    elif e.text() == "date":
                        t = "date"
                    elif e.text() == "pixmap":
                        t = "pixmap"
                    elif e.text() == "bytearray":
                        t = "bytearray"
                    elif e.text() == "string":
                        t = "string"
                    elif e.text() == "stringlist":
                        t = "stringlist"
                    elif e.text() == "unlock":
                        t = "unlock"
                    elif e.text() == "serial":
                        t = "serial"
                    no = no.nextSibling()
                    continue

                if e.tagName() == "length":
                    length = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "regexp":
                    rX = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "default":
                    if e.text().find("QT_TRANSLATE_NOOP") > -1:
                        dV = auto_qt_translate_text(e.text())
                    else:
                        dV = e.text()

                    no = no.nextSibling()
                    continue

                if e.tagName() == "outtransaction":
                    oT = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "counter":
                    coun = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "calculated":
                    c = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "fullycalculated":
                    fullCalc = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "trimmed":
                    trimm = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "visible":
                    v = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "visiblegrid":
                    vG = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "editable":
                    ed = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "partI":
                    pI = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "partD":
                    pD = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "index":
                    iNX = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "unique":
                    uNI = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "ck":
                    ck = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "optionslist":
                    ol = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "searchoptions":
                    so = e.text()
                    no = no.nextSibling()
                    continue

            no = no.nextSibling()

        f = FLFieldMetaData(n, util.translate("Metadata",
                                              a), aN, iPK, t, length, c, v, ed,
                            pI, pD, iNX, uNI, coun, dV, oT, rX, vG, True, ck)
        f.setFullyCalculated(fullCalc)
        f.setTrimed(trimm)

        if ol:
            f.setOptionsList(ol)
        if so is not None:
            f.setSearchOptions(so)

        no = field.firstChild()

        while not no.isNull():
            e = no.toElement()
            if not e.isNull():
                if e.tagName() == "relation":
                    f.addRelationMD(self.metadataRelation(e))
                    no = no.nextSibling()
                    continue

                if e.tagName() == "associated":
                    noas = e.firstChild()
                    while not noas.isNull():
                        eas = noas.toElement()
                        if not eas.isNull():
                            if eas.tagName() == "with":
                                assocWith = eas.text()
                                noas = noas.nextSibling()
                                continue

                            if eas.tagName() == "by":
                                assocBy = eas.text()
                                noas = noas.nextSibling()
                                continue

                        noas = noas.nextSibling()

                    no = no.nextSibling()
                    continue

            no = no.nextSibling()

        if assocWith and assocBy:
            f.setAssociatedField(assocWith, assocBy)

        return f
예제 #4
0
    def metadata(self, n, quick=False):
        """
        Para obtener definicion de una tabla de la base de datos, a partir de un fichero XML.

        El nombre de la tabla corresponde con el nombre del fichero mas la extensión ".mtd"
        que contiene en XML la descripción de la tablas. Este método escanea el fichero
        y construye/devuelve el objeto FLTableMetaData correspondiente, además
        realiza una copia de estos metadatos en una tabla de la misma base de datos
        para poder determinar cuando ha sido modificados y así, si es necesario, reconstruir
        la tabla para que se adapte a la nuevos metadatos. NO SE HACEN
        CHEQUEOS DE ERRORES SINTÁCTICOS EN EL XML.

        IMPORTANTE :Para que estos métodos funcionen correctamente, es estrictamente
            necesario haber creado la base de datos en PostgreSQL con codificación
            UNICODE; "createdb -E UNICODE abanq".

        @param n Nombre de la tabla de la base de datos de la que obtener los metadatos
        @param quick Si TRUE no realiza chequeos, usar con cuidado
        @return Un objeto FLTableMetaData con los metadatos de la tabla solicitada
        """

        util = FLUtil()

        if not n:
            return None

        if isinstance(n, str):

            if not n or not self.db_.dbAux():
                return None

            ret = False
            acl = False
            key = n
            stream = None

            isSysTable = (n[0:3] == "sys" or self.isSystemTable(n))
            if not isSysTable:
                stream = self.db_.managerModules().contentCached("%s.mtd" %
                                                                 key)

                if not stream:
                    qWarning(
                        "FLManager : Error al cargar los metadatos para la tabla %s"
                        % n)

                    return None

            #    if not key:
            #        key = n

            if not isSysTable:
                for fi in self.cacheMetaData_:
                    if fi.name() == key:
                        ret = fi
                        break
            else:
                for fi in self.cacheMetaDataSys_:
                    if fi.name() == key:
                        ret = fi
                        break

            if not ret:
                if isSysTable:
                    stream = self.db_.managerModules().contentCached("%s.mtd" %
                                                                     n)

                    if not stream:
                        qWarning("FLManager : " + util.tr(
                            "Error al cargar los metadatos para la tabla %s" %
                            n))

                        return None

                doc = QDomDocument(n)
                if not util.domDocumentSetContent(doc, stream):
                    qWarning("FLManager : " + util.tr(
                        "Error al cargar los metadatos para la tabla %s" % n))
                    return None

                docElem = doc.documentElement()
                ret = self.metadata(docElem, quick)
                if not ret:
                    return None

                if not isSysTable and not ret.isQuery():
                    self.cacheMetaData_.append(ret)
                elif isSysTable:
                    self.cacheMetaDataSys_.append(ret)

            else:
                acl = self._prj.acl()

            if ret.fieldsNamesUnlock():
                ret = FLTableMetaData(ret)

            if acl:
                acl.process(ret)

            if not quick and not isSysTable and self._prj.consoleShown(
            ) and not ret.isQuery() and self.db_.mismatchedTable(n, ret):
                msg = util.translate(
                    "application",
                    "La estructura de los metadatos de la tabla '%1' y su estructura interna en la base de datos no coinciden.\n"
                    "Debe regenerar la base de datos.").replace("%1", n)
                logger.warn(msg)
                # throwMsgWarning(self.db_, msg)

            return ret

        else:
            # QDomDoc
            name = None
            q = None
            a = None
            ftsfun = None
            v = True
            ed = True
            cw = False
            dl = False

            no = n.firstChild()
            while not no.isNull():
                e = no.toElement()
                if not e.isNull():
                    if e.tagName() == "field":
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "name":
                        name = e.text()
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "query":
                        q = e.text()
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "alias":
                        a = auto_qt_translate_text(e.text())
                        a = util.translate("Metadata", a)
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "visible":
                        v = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "editable":
                        ed = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "concurWarn":
                        cw = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "detectLocks":
                        dl = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "FTSFunction":
                        ftsfun = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                no = no.nextSibling()
            tmd = FLTableMetaData(name, a, q)
            cK = None
            assocs = []
            tmd.setFTSFunction(ftsfun)
            tmd.setConcurWarn(cw)
            tmd.setDetectLocks(dl)
            no = n.firstChild()

            while not no.isNull():
                e = no.toElement()
                if not e.isNull():
                    if e.tagName() == "field":
                        f = self.metadataField(e, v, ed)
                        if not tmd:
                            tmd = FLTableMetaData(name, a, q)
                        tmd.addFieldMD(f)
                        if f.isCompoundKey():
                            if not cK:
                                cK = FLCompoundKey()
                            cK.addFieldMD(f)

                        if f.associatedFieldName():
                            assocs.append(f.associatedFieldName())
                            assocs.append(f.associatedFieldFilterTo())
                            assocs.append(f.name())

                        no = no.nextSibling()
                        continue

                no = no.nextSibling()

            tmd.setCompoundKey(cK)
            aWith = None
            aBy = None

            for it in assocs:
                if not aWith:
                    aWith = it
                    continue
                if not aBy:
                    aBy = it
                    continue
                if not tmd.field(it):
                    continue
                tmd.field(it).setAssociatedField(tmd.field(aWith), aBy)

            if q and not quick:
                qry = self.query(q, tmd)

                if qry:
                    fL = qry.fieldList()
                    table = None
                    field = None
                    fields = tmd.fieldsNames()
                    # .split(",")
                    fieldsEmpty = (not fields)

                    for it in fL:
                        pos = it.find(".")
                        if pos > -1:
                            table = it[:pos]
                            field = it[pos + 1:]
                        else:
                            field = it

                        # if not (not fieldsEmpty and table == name and fields.find(field.lower())) != fields.end():
                        # print("Tabla %s nombre %s campo %s buscando en %s" % (table, name, field, fields))
                        # if not fieldsEmpty and table == name and (field.lower() in fields): Asi esta en Eneboo, pero incluye campos repetidos
                        if not fieldsEmpty and (field.lower() in fields):
                            continue

                        mtdAux = self.metadata(table, True)
                        if mtdAux:
                            fmtdAux = mtdAux.field(field)
                            if mtdAux:
                                isForeignKey = False
                                if fmtdAux.isPrimaryKey(
                                ) and not table == name:
                                    fmtdAux = FLFieldMetaData(fmtdAux)
                                    fmtdAux.setIsPrimaryKey(False)
                                    fmtdAux.setEditable(False)

                                # newRef = (not isForeignKey)
                                fmtdAuxName = fmtdAux.name().lower()
                                if fmtdAuxName.find(".") == -1:
                                    # fieldsAux = tmd.fieldsNames().split(",")
                                    fieldsAux = tmd.fieldsNames()
                                    # if not fieldsAux.find(fmtdAuxName) == fieldsAux.end():
                                    if fmtdAuxName not in fieldsAux:
                                        if not isForeignKey:
                                            FLFieldMetaData(fmtdAux)

                                        # fmtdAux.setName("%s.%s" % (table, field))

                                # if newRef:
                                #    fmtdAux.ref()

                                tmd.addFieldMD(fmtdAux)

                    del qry

            acl = self._prj.acl()
            if acl:
                acl.process(tmd)

            return tmd
예제 #5
0
    def storeLargeValue(self, mtd, largeValue):
        """
        Utilizado para almacenar valores grandes de campos en tablas separadas indexadas
        por claves SHA del contenido del valor.

        Se utiliza para optimizar consultas que incluyen campos con valores grandes,
        como por ejemplo imágenes, para manejar en las consulta SQL la referencia al valor
        que es de tamaño constante en vez del valor en sí. Esto disminuye el tráfico al
        reducir considerablemente el tamaño de los registros obtenidos.

        Las consultas pueden utilizar una referencia y obtener su valor sólo cuando se
        necesita mediante FLManager::fetchLargeValue().


        @param mtd Metadatos de la tabla que contiene el campo
        @param largeValue Valor de gran tamaño del campo
        @return Clave de referencia al valor
        """

        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"):
                    logger.warn(
                        "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"):
                logger.warn("FLManager::ERROR:StoreLargeValue.Insert %s.%s",
                            tableLarge, refKey)
                return None

        return refKey
예제 #6
0
def getTableObj(tree, root):
    table = SchemaTableStruct()
    table.xmltree = tree
    table.xmlroot = root
    query_name = one(table.xmlroot.xpath("query/text()"), None)
    name = table.xmlroot.xpath("name/text()")[0]
    table.tablename = name
    if query_name:
        table.name = query_name
        table.query_table = name
    else:
        table.name = name
        table.query_table = None
    table.fields = []
    table.pk = []
    table.fields_idx = {}
    for xmlfield in table.xmlroot.xpath("field"):
        try:
            field = SchemaFieldStruct()
            field.name = None
            field.alias = None
            field.allowNull = False
            field.pk = False
            field.mtd_type = None
            field.length_ = 0
            field.calculated = False
            field.visible = True
            field.editable = True
            field.pI = 4
            field.pD = 0
            field.iNX = False
            field.uNI = False
            field.coun = False
            field.defValue = None
            field.oT = False
            field.rX = None
            field.vG = True
            field.gene = False
            field.iCK = False
            fks = {}
            for fieldprop in xmlfield:
                if fieldprop.text: fks[fieldprop.tag] = fieldprop.text
                #else: fks[fieldprop.tag] = fieldprop
                #print("Field Prop: %r:%r" % (fieldprop.tag,fieldprop.text))

            field.name = fks.get("name")
            field.alias = fks.get("alias")
            build_field_type(field, xmlfield, fks)
            field.length_ = fks.get("length", 0)
            field.allowNull = text2bool(fks.get("null", "true"))
            field.pk = text2bool(fks.get("pk", "false"))
            field.editable = text2bool(fks.get("editable", "true"))
            field.visible = text2bool(fks.get("visible", "true"))
            field.iCK = text2bool(fks.get("ck", "false"))
            field.defValue = fks.get("default")
            field.optionsList = fks.get("optionslist")
            field.vG = text2bool(fks.get("visiblegrid", "true"))
            field.rX = ""
            field.pI = fks.get("partI", 4)
            field.pD = fks.get("partD", 0)
            field.calculated = text2bool(fks.get("counter", "false"))

            # TODO: la lectura insistente con xpath parece ralentizar el parseo de las MTD

            if field.pk: table.pk.append(field.name)
            if field.name in table.fields_idx:
                raise ValueError("La tabla %s tiene el campo %s repetido" %
                                 (table.name, field.name))
            field.number = len(table.fields)
            table.fields_idx[field.name] = field.number
            fieldMD = FLFieldMetaData(field.name, field.alias, field.allowNull,
                                      field.pk, field.mtd_type, field.length_,
                                      field.calculated, field.visible,
                                      field.editable, field.pI, field.pD,
                                      field.iNX, field.uNI, field.coun,
                                      field.defValue, field.oT, field.rX,
                                      field.vG, field.gene, field.iCK)
            relations = xmlfield.xpath("relation")
            for xmlRelation in relations:
                rks = {}
                for rel in xmlRelation:
                    if rel.text: rks[rel.tag] = rel.text

                tableNameR = rks.get("table")
                fieldRelation = rks.get("field")
                cardR = rks.get("card")
                delC = text2bool(rks.get("delC", "false"))
                updC = text2bool(rks.get("updC", "false"))
                checkIn = rks.get("checkIn")
                relation = FLRelationMetaData(tableNameR, fieldRelation, cardR,
                                              delC, updC, checkIn)
                fieldMD.addRelationMD(relation)

            associateds = xmlfield.xpath("associated")
            for xmlAssoc in associateds:
                aks = {}
                for assoc in xmlAssoc:
                    if assoc.text: aks[assoc.tag] = assoc.text
                aWith = aks.get("with")
                aBy = aks.get("by")

                fieldMD.setAssociatedField(aWith, aBy)

            if field.optionsList:
                fieldMD.setOptionsList(field.optionsList)

            table.fields.append(fieldMD)

            #table.fields.append(fieldMD)

            #fieldMD.addRelationMD(relation)
            #print(relationTableNameList_)
            """
            fieldMD = FLFieldMetaData(field.name, field.alias, field.allowNull, field.pk, field.mtd_type, field.length_, field.calculated, field.visible, field.editable, field.pI, field.pD, field.iNX, field.uNI, field.coun, field.defValue, field.oT, field.rX, field.vG, field.gene, field.iCK)

            i = 0
            l = len(relationTableNameList_)
            l1 = len(relationFieldRelationList_)
            l2 = len(relationCardList_)
            while i < l:
                print("%s.%s->%s de %s ojo (%s,%s) " % (table.name, field.name, i, l, l1, l2))
                #print("%s.%s --(%s)--> %s.%s" % (table.name, field.name, relationCardList_[i],relationTableNameList_[i], relationFieldRelationList_[i]))
                if relationDelCList_[i] == "false":
                    delC = False
                else:
                    delC = True
                
                if relationupdCList_[i] == "false":
                    updC = False
                else:
                    updC = True
                
                if relationCIList_[i] == "false":
                    cI = False
                else:
                    cI = True
                
                relation = FLRelationMetaData(relationTableNameList_[i],relationFieldRelationList_[i], relationCardList_[i], delC, updC ,cI)
                fieldMD.addRelationMD(relation)
                i = i + 1
            
            
            
            
            
            
            
            table.fields.append(fieldMD)
            """
        except Exception as e:
            print("ERROR: procesando tabla %r:" % table.name, e)
            print(traceback.format_exc())
    return table
예제 #7
0
    def initCursor(self):
        # si no existe crea la tabla
        if not self._cursor: return False
        if not self._cursor._model: return False

        self._tMD = 0

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

        if not self._tMD:
            return

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

            return

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

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

                return

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

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

            return

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

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

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

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

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

        if ownTMD and tMD and not tMD.inCache():
            tMD = None
예제 #8
0
def getTableObj(tree, root):
    table = Struct()
    table.xmltree = tree
    table.xmlroot = root
    query_name = one(table.xmlroot.xpath("query/text()"), None)
    name = table.xmlroot.xpath("name/text()")[0]
    if query_name:
        table.name = query_name
        table.query_table = name
    else:
        table.name = name
    table.fields = []
    table.pk = []
    table.fields_idx = {}
    for xmlfield in table.xmlroot.xpath("field"):
        try:
            field = Struct()
            field.name = None
            field.alias = None
            field.allowNull = False
            field.pk = False
            field.mtd_type = None
            field.length_ = 0
            field.calculated = False
            field.visible = True
            field.editable = True
            field.pI = 4
            field.pD = 0
            field.iNX = False
            field.uNI = False
            field.coun = False
            field.defValue = None
            field.oT = False
            field.rX = None
            field.vG = True
            field.gene = False
            field.iCK = False

            field.name = xmlfield.xpath("name/text()")[0]
            field.alias = one(xmlfield.xpath("alias/text()"))
            build_field_type(field, xmlfield)
            field.length_ = one(xmlfield.xpath("length/text()"), 0)
            field.allowNull = text2bool(one(xmlfield.xpath("null/text()"), "true"))
            field.pk = text2bool(one(xmlfield.xpath("pk/text()"), "false"))
            field.editable = text2bool(one(xmlfield.xpath("editable/text()"), "true"))
            field.visible = text2bool(one(xmlfield.xpath("visible/text()"), "true"))
            field.iCK = text2bool(one(xmlfield.xpath("ck/text()"), "false"))
            field.defValue = one(xmlfield.xpath("default/text()"), None)
            field.optionsList = one(xmlfield.xpath("optionslist/text()"), None)
            field.vG = text2bool(one(xmlfield.xpath("visiblegrid/text()"), "true"))
            field.rX = QString()
            field.pI = one(xmlfield.xpath("partI/text()"), 4)
            field.pD = one(xmlfield.xpath("partD/text()"), 0)
            field.calculated = text2bool(one(xmlfield.xpath("counter/text()"), "false"))

            if field.pk:
                table.pk.append(field.name)
            if field.name in table.fields_idx:
                raise ValueError("La tabla %s tiene el campo %s repetido" % (table.name, field.name))
            field.number = len(table.fields)
            table.fields_idx[field.name] = field.number
            fieldMD = FLFieldMetaData(
                field.name,
                field.alias,
                field.allowNull,
                field.pk,
                field.mtd_type,
                field.length_,
                field.calculated,
                field.visible,
                field.editable,
                field.pI,
                field.pD,
                field.iNX,
                field.uNI,
                field.coun,
                field.defValue,
                field.oT,
                field.rX,
                field.vG,
                field.gene,
                field.iCK,
            )
            relations = xmlfield.xpath("relation")
            for xmlRelation in relations:
                tableNameR = one(xmlRelation.xpath("table/text()"))
                fieldRelation = one(xmlRelation.xpath("field/text()"))
                cardR = one(xmlRelation.xpath("card/text()"))
                delC = text2bool(one(xmlRelation.xpath("delC/text()"), "false"))
                updC = text2bool(one(xmlRelation.xpath("updC/text()"), "false"))
                checkIn = one(xmlRelation.xpath("checkIn/text()"), "true")
                relation = FLRelationMetaData(tableNameR, fieldRelation, cardR, delC, updC, checkIn)
                fieldMD.addRelationMD(relation)

            associateds = xmlfield.xpath("associated")
            for xmlAssoc in associateds:
                aWith = one(xmlRelation.xpath("with/text()"))
                aBy = one(xmlRelation.xpath("by/text()"))

                fieldMD.setAssociatedField(aWith, aBy)

            if field.optionsList:
                fieldMD.setOptionsList(field.optionsList)

            table.fields.append(fieldMD)

            # table.fields.append(fieldMD)

            # fieldMD.addRelationMD(relation)
            # print(relationTableNameList_)
            """
            fieldMD = FLFieldMetaData(field.name, field.alias, field.allowNull, field.pk, field.mtd_type, field.length_, field.calculated, field.visible, field.editable, field.pI, field.pD, field.iNX, field.uNI, field.coun, field.defValue, field.oT, field.rX, field.vG, field.gene, field.iCK)

            i = 0
            l = len(relationTableNameList_)
            l1 = len(relationFieldRelationList_)
            l2 = len(relationCardList_)
            while i < l:
                print("%s.%s->%s de %s ojo (%s,%s) " % (table.name, field.name, i, l, l1, l2))
                #print("%s.%s --(%s)--> %s.%s" % (table.name, field.name, relationCardList_[i],relationTableNameList_[i], relationFieldRelationList_[i]))
                if relationDelCList_[i] == "false":
                    delC = False
                else:
                    delC = True
                
                if relationupdCList_[i] == "false":
                    updC = False
                else:
                    updC = True
                
                if relationCIList_[i] == "false":
                    cI = False
                else:
                    cI = True
                
                relation = FLRelationMetaData(relationTableNameList_[i],relationFieldRelationList_[i], relationCardList_[i], delC, updC ,cI)
                fieldMD.addRelationMD(relation)
                i = i + 1
            
            
            
            
            
            
            
            table.fields.append(fieldMD)
            """
        except Exception as e:
            print("ERROR: procesando tabla %r:" % table.name, e)
            print(traceback.format_exc())
    return table
예제 #9
0
    def metadataField(self, field, v=True, ed=True):
        if not field:
            return None

        util = FLUtil()

        ck = False
        n = None
        a = None
        ol = False
        rX = None
        assocBy = None
        assocWith = None
        so = None

        aN = True
        iPK = True
        c = False
        iNX = False
        uNI = False
        coun = False
        oT = False
        vG = True
        fullCalc = False
        trimm = False

        t = -1
        l = 0
        pI = 4
        pD = 0

        dV = None

        no = field.firstChild()

        while not no.isNull():
            e = no.toElement()
            if not e.isNull():
                if e.tagName() in ("relation", "associated"):
                    no = no.nextSibling()
                    continue

                if e.tagName() == "name":
                    n = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "alias":
                    a = auto_qt_translate_text(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "null":
                    aN = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "pk":
                    iPK = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "type":
                    if e.text() == "int":
                        t = "int"
                    elif e.text() == "uint":
                        t = "uint"
                    elif e.text() == "bool":
                        t = "bool"
                    elif e.text() == "double":
                        t = "double"
                    elif e.text() == "time":
                        t = "time"
                    elif e.text() == "date":
                        t = "date"
                    elif e.text() == "pixmap":
                        t = "pixmap"
                    elif e.text() == "bytearray":
                        t = "bytearray"
                    elif e.text() == "string":
                        t = "string"
                    elif e.text() == "stringlist":
                        t = "stringlist"
                    elif e.text() == "unlock":
                        t = "unlock"
                    elif e.text() == "serial":
                        t = "serial"
                    no = no.nextSibling()
                    continue

                if e.tagName() == "length":
                    l = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "regexp":
                    rX = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "default":
                    if e.text().find("QT_TRANSLATE_NOOP") > -1:
                        dV = auto_qt_translate_text(e.text())
                    else:
                        dV = e.text()

                    no = no.nextSibling()
                    continue

                if e.tagName() == "outtransaction":
                    oT = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "counter":
                    coun = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "calculated":
                    c = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "fullycalculated":
                    fullCalc = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "trimmed":
                    trimm = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "visible":
                    v = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "visiblegrid":
                    vG = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "editable":
                    ed = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "partI":
                    pI = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "partD":
                    pD = int(e.text())
                    no = no.nextSibling()
                    continue

                if e.tagName() == "index":
                    iNX = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "unique":
                    uNI = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "ck":
                    ck = (e.text() == "true")
                    no = no.nextSibling()
                    continue

                if e.tagName() == "optionslist":
                    ol = e.text()
                    no = no.nextSibling()
                    continue

                if e.tagName() == "searchoptions":
                    so = e.text()
                    no = no.nextSibling()
                    continue

            no = no.nextSibling()

        f = FLFieldMetaData(n, util.translate("Metadata",
                                              a), aN, iPK, t, l, c, v, ed, pI,
                            pD, iNX, uNI, coun, dV, oT, rX, vG, True, ck)
        f.setFullyCalculated(fullCalc)
        f.setTrimed(trimm)

        if ol:
            f.setOptionsList(ol)
        if not so == None:
            f.setSearchOptions(so)

        no = field.firstChild()

        while not no.isNull():
            e = no.toElement()
            if not e.isNull():
                if e.tagName() == "relation":
                    f.addRelationMD(self.metadataRelation(e))
                    no = no.nextSibling()
                    continue

                if e.tagName() == "associated":
                    noas = e.firstChild()
                    while not noas.isNull():
                        eas = noas.toElement()
                        if not eas.isNull():
                            if eas.tagName() == "with":
                                assocWith = eas.text()
                                noas = noas.nextSibling()
                                continue

                            if eas.tagName() == "by":
                                assocBy = eas.text()
                                noas = noas.nextSibling()
                                continue

                        noas = noas.nextSibling()

                    no = no.nextSibling()
                    continue

            no = no.nextSibling()

        if assocWith and assocBy:
            f.setAssociatedField(assocWith, assocBy)

        return f
예제 #10
0
    def metadata(self, n, quick=False):

        util = FLUtil()

        if not n:
            return None

        if isinstance(n, str):

            if not n or not self.db_.dbAux():
                return None

            ret = False
            acl = False
            key = n
            stream = None

            isSysTable = (n[0:3] == "sys" or self.isSystemTable(n))
            if not isSysTable:
                stream = self.db_.managerModules().contentCached("%s.mtd" %
                                                                 key)

                if not stream:
                    qWarning(
                        "FLManager : Error al cargar los metadatos para la tabla %s"
                        % n)

                    return None

            #    if not key:
            #        key = n

            if not isSysTable:
                for fi in self.cacheMetaData_:
                    if fi.name() == key:
                        ret = fi
                        break
            else:
                for fi in self.cacheMetaDataSys_:
                    if fi.name() == key:
                        ret = fi
                        break

            if not ret:
                if isSysTable:
                    stream = self.db_.managerModules().contentCached("%s.mtd" %
                                                                     n)

                    if not stream:
                        qWarning("FLManager : " + util.tr(
                            "Error al cargar los metadatos para la tabla %s" %
                            n))

                        return None

                doc = QDomDocument(n)
                if not util.domDocumentSetContent(doc, stream):
                    qWarning("FLManager : " + util.tr(
                        "Error al cargar los metadatos para la tabla %s" % n))
                    return None

                docElem = doc.documentElement()
                ret = self.metadata(docElem, quick)
                if not ret:
                    return None

                if not isSysTable and not ret.isQuery():
                    self.cacheMetaData_.append(ret)
                elif isSysTable:
                    self.cacheMetaDataSys_.append(ret)

            else:
                acl = self._prj.acl()

            if ret.fieldsNamesUnlock():
                ret = FLTableMetaData(ret)

            if acl:
                acl.process(ret)

            if not quick and not isSysTable and self._prj.consoleShown(
            ) and not ret.isQuery() and self.db_.mismatchedTable(n, ret):
                msg = util.tr(
                    "La estructura de los metadatos de la tabla '%1' y su "
                    "estructura interna en la base de datos no coinciden. "
                    "Debe regenerar la base de datos.").arg(n)

                throwMsgWarning(self.db_, msg)

            return ret

        else:
            #QDomDoc
            name = None
            q = None
            a = None
            ftsfun = None
            v = True
            ed = True
            cw = False
            dl = False

            no = n.firstChild()
            while not no.isNull():
                e = no.toElement()
                if not e.isNull():
                    if e.tagName() == "field":
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "name":
                        name = e.text()
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "query":
                        q = e.text()
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "alias":
                        a = auto_qt_translate_text(e.text())
                        a = util.translate("Metadata", a)
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "visible":
                        v = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "editable":
                        ed = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "concurWarn":
                        cw = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "detectLocks":
                        dl = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                    if e.tagName() == "FTSFunction":
                        ftsfun = (e.text() == "true")
                        no = no.nextSibling()
                        continue

                no = no.nextSibling()
            tmd = FLTableMetaData(name, a, q)
            cK = None
            assocs = []
            tmd.setFTSFunction(ftsfun)
            tmd.setConcurWarn(cw)
            tmd.setDetectLocks(dl)
            no = n.firstChild()

            while not no.isNull():
                e = no.toElement()
                if not e.isNull():
                    if e.tagName() == "field":
                        f = self.metadataField(e, v, ed)
                        if not tmd:
                            tmd = FLTableMetaData(name, a, q)
                        tmd.addFieldMD(f)
                        if f.isCompoundKey():
                            if not cK:
                                cK = FLCompoundKey()
                            cK.addFieldMD(f)

                        if f.associatedFieldName():
                            assocs.append(f.associatedFieldName())
                            assocs.append(f.associatedFieldFilterTo())
                            assocs.append(f.name())

                        no = no.nextSibling()
                        continue

                no = no.nextSibling()

            tmd.setCompoundKey(cK)
            aWith = None
            aBy = None

            for it in assocs:
                if not aWith:
                    aWith = it
                    continue
                if not aBy:
                    aBy = it
                    continue
                tmd.field(it).setAssociatedField(tmd.field(aWith), aBy)

            if q and not quick:
                qry = self.query(q, tmd)

                if qry:
                    fL = qry.fieldList()
                    table = None
                    field = None
                    fields = tmd.fieldsNames().split(",")
                    fieldsEmpty = (not fields)

                    for it in fL:
                        pos = it.find(".")
                        if pos > -1:
                            table = it[:pos]
                            field = it[:pos]
                        else:
                            field = it

                        if not (not fieldsEmpty and table == name and
                                fields.find(field.lower())) == fields.end():
                            continue

                        mtdAux = self.metadata(table, True)
                        if mtdAux:
                            fmtdAux = mtdAux.field(field)
                            if mtdAux:
                                isForeignKey = False
                                if fmtdAux.isPrimaryKey(
                                ) and not table == name:
                                    fmtdAux = FLFieldMetaData(fmtdAux)
                                    fmtdAux.setIsprimaryKey(False)
                                    fmtdAux.setEditable(False)

                                newRef = (not isForeignKey)
                                fmtdAuxName = fmtdAux.name().lower()
                                if fmtdAuxName.find(".") == -1:
                                    fieldsAux = tmd.fieldsNames().split(",")
                                    if not fieldsAux.find(
                                            fmtdAuxName) == fieldsAux.end():
                                        if not isForeignKey:
                                            fmdtAux = FLFieldMetaData(fmtdAux)

                                        fmtdAux.setName("%s.%s" %
                                                        (tambe, field))
                                        newRef = False

                                if newRef:
                                    fmtdAux.ref()

                                tmd.addFieldMD(fmtdAux)

                    qry.deleteLater()

            acl = self._prj.acl()
            if acl:
                acl.process(tmd)

            return tmd