Esempio n. 1
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
Esempio n. 2
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