forked from OSGeo/gdal
/
postgisrasterdataset.cpp
3684 lines (3046 loc) · 124 KB
/
postgisrasterdataset.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
* File : postgisrasterdataset.cpp
* Project: PostGIS Raster driver
* Purpose: GDAL Dataset implementation for PostGIS Raster driver
* Author: Jorge Arevalo, jorge.arevalo@deimos-space.com
* jorgearevalo@libregis.org
*
* Author: David Zwarg, dzwarg@azavea.com
*
* Last changes: $Id: $
*
***********************************************************************
* Copyright (c) 2009 - 2013, Jorge Arevalo, David Zwarg
* Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
**********************************************************************/
#include "gdal_frmts.h"
#include "postgisraster.h"
#include <math.h>
#ifdef _WIN32
#define rint(x) floor((x) + 0.5)
#endif
/* PostgreSQL defaults */
#define DEFAULT_SCHEMA "public"
#define DEFAULT_COLUMN "rast"
/** Note on read performance on mode=2:
There are different situations:
1) the table is registered in the raster_columns table and number of bands, minx,miny,maxx,maxy are available
a) no where clause, the table has a primary key and a GIST index on the raster column.
If the raster_columns advertize a scale_x and scale_y, use it.
Otherwise take the metadata of 10 rasters and compute and average scale_x, scale_y
With above information, we can build the dataset definition.
(Following logic is implemented in LoadSources())
During a IRasterIO() query,
i) we will do a SQL query to retrieve the PKID of tiles that intersect the query window.
ii) If some tiles are not registered as sources, then do a SQL query to fetch their metadata
and instantiate them and register them.
iii) If some tiles are not cached, then determine if the query window is not too big (w.r.t. GDAL cache),
and if not, then do a SQL query to fetch their raster column.
Note: if raster_columns show that all tiles have same dimensions, we can merge the query ii) and iii)
in the same one.
b) otherwise, do a full scan of metadata to build the sources
2) otherwise, throw a warning to the user and do a full scan of metadata is needed to build the sources
For 1b) and 2), during a IRasterIO() query, determine which sources are needed and not cached.
(Following logic is implemented in IRasterIO())
If the query window is not too big,
If there's a primary key, then do a SQL query on the IDs of uncached sources to fetch their raster column
and cache them.
Otherwise if there's a GIST index, do a SQL spatial query on the window to fetch their raster column,
and cache them (identification with registered sources is done with the top-left coordinates)
Otherwise do a SQL query based on the range of top-left coordinates of tiles that intersect the query window.
Conclusion: best performance is achieved with: no where clause, a primary key, a GIST index, known table extent
and, with moderate performance advantage :
- same scale_x, scale_y to save an initial SQL query,
- same blocksize_x, blocksize_y to save one SQL query per IRasterIO()
*/
/************************
* \brief Constructor
************************/
PostGISRasterDataset::PostGISRasterDataset():VRTDataset(0, 0) {
papszSubdatasets = NULL;
nSrid = -1;
nOverviewFactor = 1;
nBandsToCreate = 0;
poConn = NULL;
bRegularBlocking = false;
bAllTilesSnapToSameGrid = false;
bCheckAllTiles = CPLTestBool(
CPLGetConfigOption("PR_ALLOW_WHOLE_TABLE_SCAN", "YES"));
pszSchema = NULL;
pszTable = NULL;
pszColumn = NULL;
pszWhere = NULL;
pszProjection = NULL;
adfGeoTransform[GEOTRSFRM_TOPLEFT_X] = 0.0;
adfGeoTransform[GEOTRSFRM_ROTATION_PARAM1] = 0.0;
adfGeoTransform[GEOTRSFRM_TOPLEFT_Y] = 0.0;
adfGeoTransform[GEOTRSFRM_ROTATION_PARAM2] = 0.0;
adfGeoTransform[GEOTRSFRM_WE_RES] = 0;
adfGeoTransform[GEOTRSFRM_NS_RES] = 0;
adfGeoTransform[GEOTRSFRM_WE_RES] =
CPLAtof(CPLGetConfigOption("PR_WE_RES", NO_VALID_RES));
adfGeoTransform[GEOTRSFRM_NS_RES] =
CPLAtof(CPLGetConfigOption("PR_NS_RES", NO_VALID_RES));
// Default
resolutionStrategy = AVERAGE_APPROX_RESOLUTION;
const char * pszTmp = NULL;
// We ignore this option if we provided the desired resolution
if (CPLIsEqual(adfGeoTransform[GEOTRSFRM_WE_RES], CPLAtof(NO_VALID_RES)) ||
CPLIsEqual(adfGeoTransform[GEOTRSFRM_NS_RES], CPLAtof(NO_VALID_RES))) {
// Resolution didn't have a valid value, so, we initiate it
adfGeoTransform[GEOTRSFRM_WE_RES] = 0.0;
adfGeoTransform[GEOTRSFRM_NS_RES] = 0.0;
pszTmp =
CPLGetConfigOption("PR_RESOLUTION_STRATEGY", "AVERAGE_APPROX");
if (EQUAL(pszTmp, "LOWEST"))
resolutionStrategy = LOWEST_RESOLUTION;
else if (EQUAL(pszTmp, "HIGHEST"))
resolutionStrategy = HIGHEST_RESOLUTION;
else if (EQUAL(pszTmp, "USER"))
resolutionStrategy = USER_RESOLUTION;
else if (EQUAL(pszTmp, "AVERAGE"))
resolutionStrategy = AVERAGE_RESOLUTION;
}
else {
resolutionStrategy = USER_RESOLUTION;
#ifdef DEBUG_VERBOSE
pszTmp = "USER";
#endif
}
#ifdef DEBUG_VERBOSE
CPLDebug("PostGIS_Raster", "PostGISRasterDataset::Constructor:"
"STRATEGY = %s", pszTmp);
#endif
m_nTiles = 0;
nMode = NO_MODE;
poDriver = NULL;
nRasterXSize = nRasterYSize = 0;
pszPrimaryKeyName = NULL;
bIsFastPK = false;
bHasTriedFetchingPrimaryKeyName = false;
papoSourcesHolders = NULL;
hQuadTree = NULL;
bHasBuiltOverviews = false;
nOverviewCount = 0;
papoOverviewDS = NULL;
poParentDS = NULL;
bAssumeMultiBandReadPattern = true;
nNextExpectedBand = 1;
nXOffPrev = 0;
nYOffPrev = 0;
nXSizePrev = 0;
nYSizePrev = 0;
bHasTriedHasSpatialIndex = false;
bHasSpatialIndex = false;
bBuildQuadTreeDynamically = false;
bTilesSameDimension = false;
nTileWidth = 0;
nTileHeight = 0;
SetWritable(false);
/**
* TODO: Parametrize bAllTilesSnapToSameGrid. It controls if all the
* raster rows, in ONE_RASTER_PER_TABLE mode, must be checked to
* test if they snap to the same grid and have the same SRID. It can
* be the user decision, if he/she's sure all the rows pass the
* test and want more speed.
**/
}
/************************
* \brief Constructor
************************/
PostGISRasterDataset::~PostGISRasterDataset() {
if (pszSchema) {
CPLFree(pszSchema);
pszSchema = NULL;
}
if (pszTable) {
CPLFree(pszTable);
pszTable = NULL;
}
if (pszColumn) {
CPLFree(pszColumn);
pszColumn = NULL;
}
if (pszWhere) {
CPLFree(pszWhere);
pszWhere = NULL;
}
if (pszProjection) {
CPLFree(pszProjection);
pszProjection = NULL;
}
if (pszPrimaryKeyName) {
CPLFree(pszPrimaryKeyName);
pszPrimaryKeyName = NULL;
}
if (papszSubdatasets) {
CSLDestroy(papszSubdatasets);
papszSubdatasets = NULL;
}
if (hQuadTree) {
CPLQuadTreeDestroy(hQuadTree);
hQuadTree = NULL;
}
// Call it now so that the VRT sources
// are deleted and that there is no longer any code
// referencing the bands of the source holders.
// Otherwise this would go wrong because
// of the deleting the source holders just below.
CloseDependentDatasets();
if (papoSourcesHolders) {
int i;
for(i = 0; i < m_nTiles; i++) {
if (papoSourcesHolders[i])
delete papoSourcesHolders[i];
}
VSIFree(papoSourcesHolders);
papoSourcesHolders = NULL;
}
}
/************************************************************************/
/* CloseDependentDatasets() */
/************************************************************************/
int PostGISRasterDataset::CloseDependentDatasets()
{
int bHasDroppedRef = VRTDataset::CloseDependentDatasets();
if( nOverviewCount > 0 )
{
int i;
for(i = 0; i < nOverviewCount; i++)
{
delete papoOverviewDS[i];
}
CPLFree(papoOverviewDS);
papoOverviewDS = NULL;
nOverviewCount = 0;
bHasDroppedRef = TRUE;
}
return bHasDroppedRef;
}
/************************************************************************/
/* HasSpatialIndex() */
/************************************************************************/
GBool PostGISRasterDataset::HasSpatialIndex()
{
CPLString osCommand;
PGresult* poResult = NULL;
// If exists, return it
if (bHasTriedHasSpatialIndex) {
return bHasSpatialIndex;
}
bHasTriedHasSpatialIndex = true;
/* For debugging purposes only */
if( CPLTestBool(CPLGetConfigOption("PR_DISABLE_GIST", "FALSE") ) )
return false;
// Copyright dustymugs !!!
osCommand.Printf(
"SELECT n.nspname AS schema_name, c2.relname AS table_name, att.attname AS column_name, "
" c.relname AS index_name, am.amname AS index_type "
"FROM pg_catalog.pg_class c "
"JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid "
"JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid "
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
"JOIN pg_am am ON c.relam = am.oid "
"JOIN pg_attribute att ON att.attrelid = c2.oid "
"AND pg_catalog.format_type(att.atttypid, att.atttypmod) = 'raster' "
"WHERE c.relkind IN ('i') "
"AND am.amname = 'gist' "
"AND strpos(split_part(pg_catalog.pg_get_indexdef(i.indexrelid, 0, true), ' gist ', 2), att.attname) > 0 "
"AND n.nspname = '%s' "
"AND c2.relname = '%s' "
"AND att.attname = '%s' ", pszSchema, pszTable, pszColumn);
#ifdef DEBUG_QUERY
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::HasSpatialIndex(): Query: %s",
osCommand.c_str());
#endif
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) <= 0 )
{
bHasSpatialIndex = false;
CPLDebug("PostGIS_Raster", "For better performance, creating a spatial index "
"with 'CREATE INDEX %s_%s_%s_gist_idx ON %s.%s USING GIST (ST_ConvexHull(%s))' is advised",
pszSchema, pszTable, pszColumn, pszSchema, pszTable, pszColumn);
}
else
{
bHasSpatialIndex = true;
}
if( poResult )
PQclear(poResult);
return bHasSpatialIndex;
}
/***********************************************************************
* \brief Look for a primary key in the table selected by the user
*
* If the table does not have a primary key, it returns NULL
**********************************************************************/
const char * PostGISRasterDataset::GetPrimaryKeyRef()
{
CPLString osCommand;
PGresult* poResult = NULL;
// If exists, return it
if (bHasTriedFetchingPrimaryKeyName) {
return pszPrimaryKeyName;
}
bHasTriedFetchingPrimaryKeyName = true;
/* For debugging purposes only */
if( CPLTestBool(CPLGetConfigOption("PR_DISABLE_PK", "FALSE") ) )
return NULL;
/* Determine the primary key/unique column on the table */
osCommand.Printf("select d.attname from pg_catalog.pg_constraint "
"as a join pg_catalog.pg_indexes as b on a.conname = "
"b.indexname join pg_catalog.pg_class as c on c.relname = "
"b.tablename join pg_catalog.pg_attribute as d on "
"c.relfilenode = d.attrelid where b.schemaname = '%s' and "
"b.tablename = '%s' and d.attnum = a.conkey[1] and a.contype "
"in ('p', 'u')", pszSchema, pszTable);
#ifdef DEBUG_QUERY
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::GetPrimaryKeyRef(): Query: %s",
osCommand.c_str());
#endif
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) <= 0 ) {
PQclear(poResult);
/**
* Maybe there is no primary key or unique constraint; a
* sequence will also suffice; get the first one
**/
osCommand.Printf("select cols.column_name from "
"information_schema.columns as cols join "
"information_schema.sequences as seqs on "
"cols.column_default like '%%'||seqs.sequence_name||'%%' "
"where cols.table_schema = '%s' and cols.table_name = '%s'",
pszSchema, pszTable);
#ifdef DEBUG_QUERY
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::GetPrimaryKeyRef(): Query: %s",
osCommand.c_str());
#endif
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) <= 0) {
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::GetPrimaryKeyRef(): Could not "
"find a primary key or unique column on the specified "
"table %s.%s. For better performance, creating a primary key on the table is advised.",
pszSchema, pszTable);
pszPrimaryKeyName = NULL; // Just in case
}
else {
pszPrimaryKeyName = CPLStrdup(PQgetvalue(poResult, 0, 0));
}
}
// Ok, get the primary key
else {
pszPrimaryKeyName = CPLStrdup(PQgetvalue(poResult, 0, 0));
bIsFastPK = true;
}
PQclear(poResult);
return pszPrimaryKeyName;
}
/***********************************************************************
* \brief Look for raster tables in database and store them as
* subdatasets
*
* If no table is provided in connection string, the driver looks for
* the existent raster tables in the schema given as argument. This
* argument, however, is optional. If a NULL value is provided, the
* driver looks for all raster tables in all schemas of the
* user-provided database.
*
* NOTE: Permissions are managed by libpq. The driver only returns an
* error if an error is returned when trying to access to tables not
* allowed to the current user.
**********************************************************************/
GBool PostGISRasterDataset::BrowseDatabase(const char* pszCurrentSchema,
const char* pszValidConnectionString) {
char* l_pszSchema = NULL;
char* l_pszTable = NULL;
char* l_pszColumn = NULL;
int i = 0;
int nTuples = 0;
PGresult * poResult = NULL;
CPLString osCommand;
/*************************************************************
* Fetch all the raster tables and store them as subdatasets
*************************************************************/
if (pszCurrentSchema == NULL) {
osCommand.Printf("select pg_namespace.nspname as schema, "
"pg_class.relname as table, pg_attribute.attname as column "
"from pg_class, pg_namespace,pg_attribute, pg_type where "
"pg_class.relnamespace = pg_namespace.oid and "
"pg_class.oid = pg_attribute.attrelid and "
"pg_attribute.atttypid = pg_type.oid and "
"pg_type.typname = 'raster'");
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) <= 0) {
ReportError(CE_Failure, CPLE_AppDefined,
"Error browsing database for PostGIS Raster tables: %s",
PQerrorMessage(poConn));
if (poResult != NULL)
PQclear(poResult);
return false;
}
nTuples = PQntuples(poResult);
for (i = 0; i < nTuples; i++) {
l_pszSchema = PQgetvalue(poResult, i, 0);
l_pszTable = PQgetvalue(poResult, i, 1);
l_pszColumn = PQgetvalue(poResult, i, 2);
papszSubdatasets = CSLSetNameValue(papszSubdatasets,
CPLSPrintf("SUBDATASET_%d_NAME", (i + 1)),
CPLSPrintf("PG:%s schema=%s table=%s column=%s",
pszValidConnectionString, l_pszSchema, l_pszTable,
l_pszColumn));
papszSubdatasets = CSLSetNameValue(papszSubdatasets,
CPLSPrintf("SUBDATASET_%d_DESC", (i + 1)),
CPLSPrintf("PostGIS Raster table at %s.%s (%s)",
l_pszSchema, l_pszTable, l_pszColumn));
}
PQclear(poResult);
}
/***************************************************************
* Fetch all the schema's raster tables and store them as
* subdatasets
**************************************************************/
else {
osCommand.Printf("select pg_class.relname as table, "
"pg_attribute.attname as column from pg_class, "
"pg_namespace,pg_attribute, pg_type where "
"pg_class.relnamespace = pg_namespace.oid and "
"pg_class.oid = pg_attribute.attrelid and "
"pg_attribute.atttypid = pg_type.oid and "
"pg_type.typname = 'raster' and "
"pg_namespace.nspname = '%s'", pszCurrentSchema);
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) <= 0) {
ReportError(CE_Failure, CPLE_AppDefined,
"Error browsing database for PostGIS Raster tables: %s",
PQerrorMessage(poConn));
if (poResult != NULL)
PQclear(poResult);
return false;
}
nTuples = PQntuples(poResult);
for (i = 0; i < nTuples; i++) {
l_pszTable = PQgetvalue(poResult, i, 0);
l_pszColumn = PQgetvalue(poResult, i, 1);
papszSubdatasets = CSLSetNameValue(papszSubdatasets,
CPLSPrintf("SUBDATASET_%d_NAME", (i + 1)),
CPLSPrintf("PG:%s schema=%s table=%s column=%s",
pszValidConnectionString, pszCurrentSchema, l_pszTable,
l_pszColumn));
papszSubdatasets = CSLSetNameValue(papszSubdatasets,
CPLSPrintf("SUBDATASET_%d_DESC", (i + 1)),
CPLSPrintf("PostGIS Raster table at %s.%s (%s)",
pszCurrentSchema, l_pszTable, l_pszColumn));
}
PQclear(poResult);
}
return true;
}
/***********************************************************************
* \brief Look for overview tables for the bands of the current dataset
**********************************************************************/
PROverview * PostGISRasterDataset::GetOverviewTables(int * pnOverviews)
{
PROverview * poOV = NULL;
CPLString osCommand;
PGresult * poResult = NULL;
osCommand.Printf("SELECT o_table_name, overview_factor, "
"o_raster_column, o_table_schema FROM raster_overviews "
"WHERE r_table_schema = '%s' AND r_table_name = '%s' AND "
"r_raster_column = '%s' ORDER BY overview_factor", this->pszSchema, this->pszTable,
this->pszColumn);
#ifdef DEBUG_QUERY
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::GetOverviewTables(): Query: %s",
osCommand.c_str());
#endif
poResult = PQexec(poConn, osCommand.c_str());
if (poResult == NULL ||
PQresultStatus(poResult) != PGRES_TUPLES_OK ||
PQntuples(poResult) < 0) {
ReportError(CE_Failure, CPLE_AppDefined,
"Error looking for overview tables: %s",
PQerrorMessage(poConn));
if (poResult)
PQclear(poResult);
return NULL;
}
else if (PQntuples(poResult) == 0) {
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::GetOverviewTables(): No overviews "
"for table %s.%s", pszTable, pszSchema);
if (poResult)
PQclear(poResult);
return NULL;
}
int nTuples = PQntuples(poResult);
poOV = (PROverview *)VSIMalloc2(nTuples, sizeof(PROverview));
if (poOV == NULL) {
ReportError(CE_Failure, CPLE_AppDefined,
"Error looking for overview tables");
PQclear(poResult);
return NULL;
}
int iOVerview = 0;
for(iOVerview = 0; iOVerview < nTuples; iOVerview++) {
poOV[iOVerview].pszSchema =
CPLStrdup(PQgetvalue(poResult, iOVerview, 3));
poOV[iOVerview].pszTable =
CPLStrdup(PQgetvalue(poResult, iOVerview, 0));
poOV[iOVerview].pszColumn =
CPLStrdup(PQgetvalue(poResult, iOVerview, 2));
poOV[iOVerview].nFactor =
atoi(PQgetvalue(poResult, iOVerview, 1));
}
if (pnOverviews)
*pnOverviews = nTuples;
PQclear(poResult);
return poOV;
}
/***********************************************************************
* \brief Build overview datasets
***********************************************************************/
void PostGISRasterDataset::BuildOverviews()
{
if( bHasBuiltOverviews || poParentDS != NULL )
return;
bHasBuiltOverviews = true;
/*******************************************************************
* We also get the names of the overview tables, if they exist. So,
* we'll can use them to create the overview datasets.
******************************************************************/
int nOV = 0;
PROverview * poOV = GetOverviewTables(&nOV);
if (poOV)
{
papoOverviewDS = (PostGISRasterDataset**) CPLCalloc(nOV, sizeof(PostGISRasterDataset*));
nOverviewCount = 0;
int iOV;
for(iOV = 0; iOV < nOV; iOV++)
{
PostGISRasterDataset* poOvrDS = new PostGISRasterDataset();
poOvrDS->nOverviewFactor = poOV[iOV].nFactor;
poOvrDS->poConn = poConn;
poOvrDS->eAccess = eAccess;
poOvrDS->nMode = nMode;
poOvrDS->pszSchema = poOV[iOV].pszSchema; // takes ownership
poOvrDS->pszTable = poOV[iOV].pszTable; // takes ownership
poOvrDS->pszColumn = poOV[iOV].pszColumn; // takes ownership
poOvrDS->pszWhere = pszWhere ? CPLStrdup(pszWhere) : NULL;
poOvrDS->poParentDS = this;
if (!CPLTestBool(CPLGetConfigOption("PG_DEFERRED_OVERVIEWS", "YES")) &&
(!poOvrDS->SetRasterProperties(NULL) ||
poOvrDS->GetRasterCount() != GetRasterCount()))
{
delete poOvrDS;
}
else
{
papoOverviewDS[nOverviewCount ++] = poOvrDS;
}
}
VSIFree(poOV);
}
}
/***********************************************************************
* \brief Returns overview count
***********************************************************************/
int PostGISRasterDataset::GetOverviewCount()
{
BuildOverviews();
return nOverviewCount;
}
/***********************************************************************
* \brief Returns overview dataset
***********************************************************************/
PostGISRasterDataset* PostGISRasterDataset::GetOverviewDS(int iOvr)
{
if( iOvr < 0 || iOvr > GetOverviewCount() )
return NULL;
return papoOverviewDS[iOvr];
}
/***********************************************************************
* \brief Calculates the destination window for a VRT source, taking
* into account that the source is a PostGIS Raster tile and the
* destination is the general dataset itself
*
* This method is adapted from gdalbuildvrt as is in GDAL 1.10.0
***********************************************************************/
GBool PostGISRasterDataset::GetDstWin(
PostGISRasterTileDataset * psDP,
int* pnDstXOff, int* pnDstYOff, int* pnDstXSize, int* pnDstYSize)
{
double we_res = this->adfGeoTransform[GEOTRSFRM_WE_RES];
double ns_res = this->adfGeoTransform[GEOTRSFRM_NS_RES];
double adfTileGeoTransform[6];
psDP->GetGeoTransform(adfTileGeoTransform);
*pnDstXOff = (int)
(0.5 + (adfTileGeoTransform[GEOTRSFRM_TOPLEFT_X] - xmin) / we_res);
if( ns_res < 0 )
*pnDstYOff = (int)
(0.5 + (ymax - adfTileGeoTransform[GEOTRSFRM_TOPLEFT_Y]) / -ns_res);
else
*pnDstYOff = (int)
(0.5 + (adfTileGeoTransform[GEOTRSFRM_TOPLEFT_Y] - ymin) / ns_res);
*pnDstXSize = (int)
(0.5 + psDP->GetRasterXSize() *
adfTileGeoTransform[GEOTRSFRM_WE_RES] / we_res);
*pnDstYSize = (int)
(0.5 + psDP->GetRasterYSize() *
adfTileGeoTransform[GEOTRSFRM_NS_RES] / ns_res);
return true;
}
/***********************************************************************
* \brief Add tiles bands as complex source for raster bands.
**********************************************************************/
GBool PostGISRasterDataset::AddComplexSource(PostGISRasterTileDataset* poRTDS)
{
// Parameters to add the tile bands as sources
int nDstXOff = 0;
int nDstYOff = 0;
int nDstXSize = 0;
int nDstYSize = 0;
// Get src and dst parameters
GBool bValidTile = GetDstWin(poRTDS,
&nDstXOff, &nDstYOff, &nDstXSize, &nDstYSize);
if (!bValidTile)
return false;
#ifdef DEBUG_VERBOSE
CPLDebug("PostGIS_Raster",
"PostGISRasterDataset::AddComplexSource: "
"Tile bounding box from (%d, %d) of size (%d, %d) will "
"cover raster bounding box from (%d, %d) of size "
"(%d, %d)", 0, 0,
poRTDS->GetRasterXSize(),
poRTDS->GetRasterYSize(),
nDstXOff, nDstYOff, nDstXSize, nDstYSize);
#endif
// Add tiles bands as sources for the raster bands
for(int iBand = 0; iBand < nBandsToCreate; iBand++)
{
PostGISRasterRasterBand * prb =
(PostGISRasterRasterBand *)GetRasterBand(iBand + 1);
int bHasNoData = FALSE;
double dfBandNoDataValue = prb->GetNoDataValue(&bHasNoData);
PostGISRasterTileRasterBand * prtb =
(PostGISRasterTileRasterBand *)
poRTDS->GetRasterBand(iBand + 1);
prb->AddComplexSource(prtb, 0, 0,
poRTDS->GetRasterXSize(),
poRTDS->GetRasterYSize(),
nDstXOff, nDstYOff, nDstXSize, nDstYSize,
0.0, 1.0,
(bHasNoData) ? dfBandNoDataValue : VRT_NODATA_UNSET);
prtb->poSource = prb->papoSources[prb->nSources-1];
}
return true;
}
/************************************************************************/
/* GetMatchingSourceRef() */
/************************************************************************/
/**
* \brief Get the tile dataset that matches the given upper left pixel
**/
PostGISRasterTileDataset *
PostGISRasterDataset::GetMatchingSourceRef(double dfUpperLeftX,
double dfUpperLeftY)
{
int i;
PostGISRasterTileDataset * poRTDS = NULL;
for(i = 0; i < m_nTiles; i++)
{
poRTDS = papoSourcesHolders[i];
if (CPLIsEqual(poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_X],
dfUpperLeftX) &&
CPLIsEqual(poRTDS->adfGeoTransform[GEOTRSFRM_TOPLEFT_Y],
dfUpperLeftY)) {
return poRTDS;
}
}
return NULL;
}
/************************************************************************/
/* CacheTile() */
/************************************************************************/
void PostGISRasterDataset::CacheTile(const char* pszMetadata,
const char* pszRaster,
const char *pszPKID,
int nBand,
int bAllBandCaching)
{
/**
* Get metadata record and unpack it
**/
char* pszRes = CPLStrdup(pszMetadata);
// Skip first "("
char* pszFilteredRes = pszRes + 1;
// Skip last ")"
pszFilteredRes[strlen(pszFilteredRes)-1] = '\0';
// Tokenize
char** papszParams =
CSLTokenizeString2(pszFilteredRes, ",",
CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS);
CPLAssert(CSLCount(papszParams) >= ELEMENTS_OF_METADATA_RECORD);
CPLFree(pszRes);
double dfTilePixelSizeX = CPLAtof(papszParams[POS_UPPERLEFTX]);
double dfTilePixelSizeY = CPLAtof(papszParams[POS_UPPERLEFTY]);
int nTileXSize = atoi(papszParams[POS_WIDTH]);
int nTileYSize = atoi(papszParams[POS_HEIGHT]);
CSLDestroy(papszParams);
papszParams = NULL;
/**
* Get actual raster band data
**/
int nBandDataTypeSize = GDALGetDataTypeSize(GetRasterBand(nBand)->GetRasterDataType()) / 8;
int nExpectedBandDataSize =
nTileXSize * nTileYSize * nBandDataTypeSize;
int nWKBLength = 0;
GByte* pbyData = CPLHexToBinary(pszRaster, &nWKBLength);
int nExpectedBands = bAllBandCaching ? GetRasterCount() : 1;
int nExpectedWKBLength = RASTER_HEADER_SIZE + BAND_SIZE(nBandDataTypeSize, nExpectedBandDataSize) * nExpectedBands;
if( nWKBLength != nExpectedWKBLength )
{
CPLDebug("PostGIS_Raster", "nWKBLength=%d, nExpectedWKBLength=%d", nWKBLength, nExpectedWKBLength );
CPLFree(pbyData);
return;
}
// Do byte-swapping if necessary */
int bIsLittleEndian = (pbyData[0] == 1);
#ifdef CPL_LSB
int bSwap = !bIsLittleEndian;
#else
int bSwap = bIsLittleEndian;
#endif
PostGISRasterTileDataset* poRTDS = NULL;
if( GetPrimaryKeyRef() != NULL )
poRTDS = GetMatchingSourceRef(pszPKID);
else
poRTDS = GetMatchingSourceRef(dfTilePixelSizeX,
dfTilePixelSizeY);
if( poRTDS == NULL )
{
CPLFree(pbyData);
return;
}
for(int k=1; k <= nExpectedBands; k++)
{
GByte* pbyDataToRead = (GByte*)GET_BAND_DATA(pbyData, k,
nBandDataTypeSize, nExpectedBandDataSize);
if( bSwap && nBandDataTypeSize > 1 )
{
GDALSwapWords( pbyDataToRead, nBandDataTypeSize,
nTileXSize * nTileYSize,
nBandDataTypeSize );
}
/**
* Get the right PostGISRasterRasterBand
**/
int nCurBand = ( nExpectedBands > 1 ) ? k : nBand;
/**
* Get the right tileband
**/
GDALRasterBand * poRTB = poRTDS->GetRasterBand(nCurBand);
/**
* Manually add each tile data to the cache of the
* matching PostGISRasterTileRasterBand.
**/
if (poRTB)
{
GDALRasterBlock* poBlock = poRTB->GetLockedBlockRef(0, 0, TRUE);
if( poBlock != NULL )
{
// Point block data ref to fetched data
memcpy(poBlock->GetDataRef(), (void *)pbyDataToRead,
nExpectedBandDataSize);
poBlock->DropLock();
}
}
}
CPLFree(pbyData);
}
/************************************************************************/
/* LoadSources() */
/************************************************************************/
GBool PostGISRasterDataset::LoadSources(int nXOff, int nYOff, int nXSize, int nYSize, int nBand)
{
if( !bBuildQuadTreeDynamically )
return false;
CPLString osCommand;
CPLString osSpatialFilter;
CPLString osIDsToFetch;
PGresult * poResult;
int bFetchAll = FALSE;