コード例 #1
0
ファイル: test_provider_virtual.py プロジェクト: medspx/QGIS
    def test_joined_layers_conversion(self):
        v1 = QgsVectorLayer("Point?field=id:integer&field=b_id:integer&field=c_id:integer&field=name:string", "A", "memory")
        self.assertEqual(v1.isValid(), True)
        v2 = QgsVectorLayer("Point?field=id:integer&field=bname:string&field=bfield:integer", "B", "memory")
        self.assertEqual(v2.isValid(), True)
        v3 = QgsVectorLayer("Point?field=id:integer&field=cname:string", "C", "memory")
        self.assertEqual(v3.isValid(), True)
        QgsProject.instance().addMapLayers([v1, v2, v3])
        joinInfo = QgsVectorJoinInfo()
        joinInfo.targetFieldName = "b_id"
        joinInfo.joinLayerId = v2.id()
        joinInfo.joinFieldName = "id"
        #joinInfo.prefix = "B_";
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 6)

        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))

        # with a field subset
        v1.removeJoin(v2.id())
        joinInfo.setJoinFieldNamesSubset(["bname"])
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 5)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))
        joinInfo.setJoinFieldNamesSubset(None)

        # add a table prefix to the join
        v1.removeJoin(v2.id())
        joinInfo.prefix = "BB_"
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 6)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS BB_bname, j1.bfield AS BB_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))
        joinInfo.prefix = ""
        v1.removeJoin(v2.id())
        v1.addJoin(joinInfo)

        # add another join
        joinInfo2 = QgsVectorJoinInfo()
        joinInfo2.targetFieldName = "c_id"
        joinInfo2.joinLayerId = v3.id()
        joinInfo2.joinFieldName = "id"
        v1.addJoin(joinInfo2)
        self.assertEqual(len(v1.fields()), 7)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), ('SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield, j2.cname AS C_cname FROM {} AS t ' +
                                      'LEFT JOIN {} AS j1 ON t."b_id"=j1."id" ' +
                                      'LEFT JOIN {} AS j2 ON t."c_id"=j2."id"').format(v1.id(), v2.id(), v3.id()))

        QgsProject.instance().removeMapLayers([v1.id(), v2.id(), v3.id()])
コード例 #2
0
    def test_joined_layers_conversion(self):
        v1 = QgsVectorLayer("Point?field=id:integer&field=b_id:integer&field=c_id:integer&field=name:string", "A", "memory")
        self.assertEqual(v1.isValid(), True)
        v2 = QgsVectorLayer("Point?field=id:integer&field=bname:string&field=bfield:integer", "B", "memory")
        self.assertEqual(v2.isValid(), True)
        v3 = QgsVectorLayer("Point?field=id:integer&field=cname:string", "C", "memory")
        self.assertEqual(v3.isValid(), True)
        QgsMapLayerRegistry.instance().addMapLayers([v1, v2, v3])
        joinInfo = QgsVectorJoinInfo()
        joinInfo.targetFieldName = "b_id"
        joinInfo.joinLayerId = v2.id()
        joinInfo.joinFieldName = "id"
        #joinInfo.prefix = "B_";
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 6)

        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))

        # with a field subset
        v1.removeJoin(v2.id())
        joinInfo.setJoinFieldNamesSubset(["bname"])
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 5)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))
        joinInfo.setJoinFieldNamesSubset(None)

        # add a table prefix to the join
        v1.removeJoin(v2.id())
        joinInfo.prefix = "BB_"
        v1.addJoin(joinInfo)
        self.assertEqual(len(v1.fields()), 6)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), 'SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS BB_bname, j1.bfield AS BB_bfield FROM {} AS t LEFT JOIN {} AS j1 ON t."b_id"=j1."id"'.format(v1.id(), v2.id()))
        joinInfo.prefix = ""
        v1.removeJoin(v2.id())
        v1.addJoin(joinInfo)

        # add another join
        joinInfo2 = QgsVectorJoinInfo()
        joinInfo2.targetFieldName = "c_id"
        joinInfo2.joinLayerId = v3.id()
        joinInfo2.joinFieldName = "id"
        v1.addJoin(joinInfo2)
        self.assertEqual(len(v1.fields()), 7)
        df = QgsVirtualLayerDefinitionUtils.fromJoinedLayer(v1)
        self.assertEqual(df.query(), ('SELECT t.rowid AS uid, t.id, t.b_id, t.c_id, t.name, j1.bname AS B_bname, j1.bfield AS B_bfield, j2.cname AS C_cname FROM {} AS t ' +
                                      'LEFT JOIN {} AS j1 ON t."b_id"=j1."id" ' +
                                      'LEFT JOIN {} AS j2 ON t."c_id"=j2."id"').format(v1.id(), v2.id(), v3.id()))

        QgsMapLayerRegistry.instance().removeMapLayers([v1.id(), v2.id(), v3.id()])
コード例 #3
0
    def addCsv(self):
        """Crea una capa a partir de un archivo CSV, y une la información que
           contiene esta, con la tabla de atributos de la capa de secciones,
           la cual tendrá que existir, para que se pueda realizar esta operación.
        """
        try:
            shp = QgsMapLayerRegistry.instance().mapLayersByName(
                "secciones")[0]
        except IndexError:
            self.errorDialog(
                u'No se encontró la capa de secciones.',
                u'Asegurate de agregarla con la opción de Cargar fondos.')
            return

        sheet = None
        field_names = [field.name() for field in shp.pendingFields()]
        csvDialog = CSVDialog(field_names)
        result = csvDialog.exec_()
        if result and csvDialog.getLayer():
            # print csvDialog.getSelectedColumns()

            sheet = csvDialog.getLayer()
            QgsMapLayerRegistry.instance().addMapLayer(sheet)

            #Columnas del archivo CSV
            columns = csvDialog.getSelectedColumns()
            #Filtra las columnas existentes, para evitar información duplicada
            field_names = [field.name() for field in shp.pendingFields()]

            columns = [
                col for col in columns if 'csv' + col not in field_names
            ]

            if columns == []:
                #No hay columnas nuevas para unir
                return

            shpField = csvDialog.getJoinFieldTarget()
            csvField = csvDialog.getJoinField()
            joinObject = QgsVectorJoinInfo()
            joinObject.joinLayerId = sheet.id()
            joinObject.joinFieldName = csvField
            joinObject.targetFieldName = shpField

            joinObject.setJoinFieldNamesSubset(columns)
            joinObject.memoryCache = True
            shp.addJoin(joinObject)
コード例 #4
0
    def pos(self, layer, csv_cols, csv_field, shp_cols, shp_field):
        """Este método se encarga de realizar la unión entre el archivo CSV que se cargo, y la tabla de atributos de self.shp.

        :param layer: Capa del archivo CSV.
        :type layer: QgsVectorLayer

        :param csv_cols: Lista con las columnas de la capa CSV que se van a unir.
        :type csv_cols: Lista str

        :param csv_field: Campo de la capa CSV que se va a usar como columna de unión.
        :type csv_field: str

        :param shp_cols: Lista de columnas de la tabla de atributos de self.shp que se van a unir.
        :type shp_cols: Lista str

        :param shp_field: Campo de la capa self.shp que se va a usar como columna de unión.
        :type shp_field: str
        """
        sheet = layer
        manager.add_layers([sheet])

        #Columnas del archivo CSV
        columns = csv_cols
        #Columnas del archivo shp
        field_names = shp_cols

        #Filtra las columnas existentes, para evitar información duplicada
        columns = [col for col in columns if 'csv_' + col not in field_names]
        # print columns
        if columns == []:
            #No hay columnas nuevas para unir
            return

        joinObject = QgsVectorJoinInfo()
        joinObject.joinLayerId = sheet.id()
        joinObject.joinFieldName = csv_field
        joinObject.targetFieldName = shp_field

        joinObject.setJoinFieldNamesSubset(columns)
        joinObject.memoryCache = True
        self.shp.addJoin(joinObject)
コード例 #5
0
    def execute_layers_join(layer, layer_field, column_header, fk_layer, fk_field):
        """
        Joins two layers with specified field.
        :param layer: The destination layer of the merge.
        :type layer: QgsVectorLayer
        :param layer_field: The source layer of the merge.
        :type layer_field: String
        :param fk_layer: The foreign key layer object.
        :type fk_layer: QgsVectorLayer
        :param fk_field: The foreign key layer field name.
        :type fk_field: String
        :return:
        :rtype:
        """
        join = QgsVectorJoinInfo()
        join.joinLayerId = fk_layer.id()
        join.joinFieldName = 'id'

        join.setJoinFieldNamesSubset([fk_field])
        join.targetFieldName = layer_field
        join.memoryCache = True
        join.prefix = u'{} '.format(column_header)
        layer.addJoin(join)
コード例 #6
0
ファイル: spatial_unit_manager.py プロジェクト: gltn/stdm
    def execute_layers_join(layer, layer_field, column_header, fk_layer, fk_field):
        """
        Joins two layers with specified field.
        :param layer: The destination layer of the merge.
        :type layer: QgsVectorLayer
        :param layer_field: The source layer of the merge.
        :type layer_field: String
        :param fk_layer: The foreign key layer object.
        :type fk_layer: QgsVectorLayer
        :param fk_field: The foreign key layer field name.
        :type fk_field: String
        :return:
        :rtype:
        """
        join = QgsVectorJoinInfo()
        join.joinLayerId = fk_layer.id()
        join.joinFieldName = 'id'

        join.setJoinFieldNamesSubset([fk_field])
        join.targetFieldName = layer_field
        join.memoryCache = True
        join.prefix = u'{} '.format(column_header)
        layer.addJoin(join)