I've got a qgis project with a lot of layers. In the past they were established as postgis-polygon-layers/-tables.
I updated my postgres/postgis-database recently.
Now the updated database stores the tables as MultiPolygon tables but QGIS does not recognize the modified type with the old connections. The change is only recognized if the tables are imported new into the project. It's the same with using qlr's with "Polygon"-connection-details.
I'd like to use the MultiPolygon-format to have less trouble cutting polygons into pieces.... So it would be nice to change the data-source-connection from Polygon to MultiPolygon.
As there are more than a hundered layers with relations to other layers in the project it would be a huge effort to replace the "old" Polygon layers with "new" MultiPolygon-layers and establish all the relataions, symbology ... manually
Is it possible to change the connection-details in a efficient, secure way (like python script / editing the qgs-file (replace all "Polygon" text with "MultiPolygon")) ?
I tried to change every layer-child of the layertree with the following code, but the connection is not changed.
If you run the code a second time the code does not enter the if-clause - so I thing some changes are applied but not enough.
What do I have to do to apply my changes in the layer-tree ?
from PyQt5.QtCore import *
from qgis.gui import QgsMessageBar
def editConnectionDeeperInstance(laTrGr):
pos = 0
for child in laTrGr.children():
if isinstance(child, QgsLayerTreeGroup):
editConnectionDeeperInstance(child)
elif isinstance(child, QgsLayerTreeLayer) and child.layer():
l=child.layer()
provider = l.dataProvider()
if provider.name() == 'postgres':
uri = provider.dataSourceUri()
for t in tablesToEdit:
if re.search(t,uri) and re.search("type=Polygon",uri):
print('changed:',child.name(),'-', t)
new_uri=x = re.sub("type=Polygon", "type=MultiPolygon", uri)
# print(new_uri)
provider.setDataSourceUri(new_uri)
provider.reloadData()
tablesToEdit=["""public"."table1""","""public"."table2""" ]
laTrRo = QgsProject.instance().layerTreeRoot()
editConnectionDeeperInstance(laTrRo)