Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow postgresraster layers as gdal processing tools input #57958

Merged
merged 5 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions python/plugins/processing/algs/gdal/GdalUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,29 @@ def gdal_connection_details_from_layer(layer: QgsMapLayer) -> GdalConnectionDeta
open_options=parts.get('openOptions', None),
credential_options=parts.get('credentialOptions', None)
)
elif provider == 'postgresraster':
nyalldawson marked this conversation as resolved.
Show resolved Hide resolved
gdal_source = ''
uri = layer.dataProvider().uri()
gdal_source = f"PG: {uri.connectionInfo()}"
schema = uri.schema()
if schema:
gdal_source += f" schema='{schema}'"
table = uri.table()
gdal_source += f" table='{table}'"
column = uri.param('column') or uri.geometryColumn()
if column:
gdal_source += f" column='{column}'"
is_tiled = any([layer.dataProvider().xSize() != layer.dataProvider().xBlockSize(),
layer.dataProvider().ySize() != layer.dataProvider().yBlockSize()])
gdal_source += f" mode={2 if is_tiled else 1}"
where = layer.dataProvider().subsetString()
if where:
gdal_source += f" where='{where}'"

return GdalConnectionDetails(
connection_string=gdal_source,
format='"PostGISRaster"'
)

ogrstr = str(layer.source()).split("|")[0]
path, ext = os.path.splitext(ogrstr)
Expand Down
18 changes: 2 additions & 16 deletions src/providers/postgres/raster/qgspostgresrasterprovider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2439,26 +2439,12 @@ Qgis::DataType QgsPostgresRasterProvider::sourceDataType( int bandNo ) const

int QgsPostgresRasterProvider::xBlockSize() const
{
if ( mInput )
{
return mInput->xBlockSize();
}
else
{
return static_cast<int>( mWidth );
}
return mTileWidth;
}

int QgsPostgresRasterProvider::yBlockSize() const
{
if ( mInput )
{
return mInput->yBlockSize();
}
else
{
return static_cast<int>( mHeight );
}
return mTileHeight;
}

QgsRasterBandStats QgsPostgresRasterProvider::bandStatistics( int bandNo, Qgis::RasterBandStatistics stats, const QgsRectangle &extent, int sampleSize, QgsRasterBlockFeedback *feedback )
Expand Down
1 change: 1 addition & 0 deletions tests/src/python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ ADD_PYTHON_TEST(PyQgsSelectiveMasking test_selective_masking.py)
ADD_PYTHON_TEST(PyQgsAttributeEditorAction test_qgsattributeeditoraction.py)
ADD_PYTHON_TEST(PyQgsVectorTile test_qgsvectortile.py)
ADD_PYTHON_TEST(PyQgsVtpk test_qgsvtpk.py)
ADD_PYTHON_TEST(PyQgsProcessingAlgsGdalGdalUtils test_processing_algs_gdal_gdalutils.py)

if (NOT WIN32)
ADD_PYTHON_TEST(PyQgsLogger test_qgslogger.py)
Expand Down
82 changes: 82 additions & 0 deletions tests/src/python/test_processing_algs_gdal_gdalutils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""QGIS Unit tests for GdalUtils class

.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Stefanos Natsis'
__date__ = '03/07/2024'
__copyright__ = 'Copyright 2024, The QGIS Project'


import unittest
from qgis.testing import start_app, QgisTestCase
from qgis.core import QgsApplication, QgsRasterLayer, QgsDataSourceUri, QgsAuthMethodConfig
from processing.algs.gdal.GdalUtils import (
GdalUtils,
GdalConnectionDetails
)

start_app()


class TestProcessingAlgsGdalGdalUtils(QgisTestCase):

def test_gdal_connection_details_from_layer_postgresraster(self):
"""
Test GdalUtils.gdal_connection_details_from_layer
"""

rl = QgsRasterLayer(
"dbname='mydb' host=localhost port=5432 user='asdf' password='42'"
" sslmode=disable table=some_table schema=some_schema column=rast sql=pk = 2",
'pg_layer', 'postgresraster')

self.assertEqual(rl.providerType(), 'postgresraster')

connection_details = GdalUtils.gdal_connection_details_from_layer(rl)
s = connection_details.connection_string

self.assertTrue(s.lower().startswith('pg:'))
self.assertTrue("schema='some_schema'" in s)
self.assertTrue("password='42'" in s)
self.assertTrue("column='rast'" in s)
self.assertTrue("mode=1" in s)
self.assertTrue("where='pk = 2'" in s)
self.assertEqual(connection_details.format, '"PostGISRaster"')

# test different uri:
# - authcfg is expanded
# - column is parsed
# - where is skipped
authm = QgsApplication.authManager()
self.assertTrue(authm.setMasterPassword('masterpassword', True))
nyalldawson marked this conversation as resolved.
Show resolved Hide resolved
config = QgsAuthMethodConfig()
config.setName('Basic')
config.setMethod('Basic')
config.setConfig('username', 'asdf')
config.setConfig('password', '42')
self.assertTrue(authm.storeAuthenticationConfig(config, True))

rl = QgsRasterLayer(
f"dbname='mydb' host=localhost port=5432 authcfg={config.id()}"
f" sslmode=disable table=\"some_schema\".\"some_table\" (rast)",
'pg_layer', 'postgresraster')

self.assertEqual(rl.providerType(), 'postgresraster')

connection_details = GdalUtils.gdal_connection_details_from_layer(rl)
s = connection_details.connection_string

self.assertTrue(s.lower().startswith('pg:'))
self.assertTrue("schema='some_schema'" in s)
self.assertTrue("user='asdf'" in s)
self.assertTrue("password='42'" in s)
self.assertTrue("column='rast'" in s)
self.assertTrue("mode=1" in s)
self.assertFalse("where=" in s)


if __name__ == '__main__':
unittest.main()
31 changes: 31 additions & 0 deletions tests/src/python/test_provider_postgresraster.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,37 @@ def testSparseTiles(self):
self.assertTrue(b.isNoData(0, 0))
self.assertTrue(b.isNoData(0, 1))

def testBlockSize(self):
"""Check that tiled raster returns correct block size"""

# untiled have blocksize == size
rl = QgsRasterLayer(
self.dbconn + " sslmode=disable table={table} schema={schema} sql=\"pk\" = 2".format(
table='raster_3035_untiled_multiple_rows', schema='public'), 'pg_layer', 'postgresraster')

self.assertTrue(rl.isValid())

dp = rl.dataProvider()

self.assertEqual(dp.xSize(), 2)
self.assertEqual(dp.ySize(), 2)
self.assertEqual(dp.xBlockSize(), 2)
self.assertEqual(dp.yBlockSize(), 2)

# tiled have blocksize != size
rl = QgsRasterLayer(
self.dbconn + " srid=3035 sslmode=disable table={table} schema={schema}".format(
table='raster_3035_tiled_no_overviews', schema='public'), 'pg_layer', 'postgresraster')

self.assertTrue(rl.isValid())

dp = rl.dataProvider()

self.assertEqual(dp.xSize(), 6)
self.assertEqual(dp.ySize(), 5)
self.assertEqual(dp.xBlockSize(), 2)
self.assertEqual(dp.yBlockSize(), 2)


if __name__ == '__main__':
unittest.main()
Loading