-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
ogrpgdatasource.cpp
3429 lines (2966 loc) · 126 KB
/
ogrpgdatasource.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
/******************************************************************************
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implements OGRPGDataSource class.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2000, Frank Warmerdam
* Copyright (c) 2008-2014, Even Rouault <even dot rouault at spatialys.com>
*
* 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 <string.h>
#include "ogr_pg.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_hash_set.h"
#include <cctype>
#include <set>
#define PQexec this_is_an_error
static void OGRPGNoticeProcessor(void *arg, const char *pszMessage);
/************************************************************************/
/* OGRPGDataSource() */
/************************************************************************/
OGRPGDataSource::OGRPGDataSource() = default;
/************************************************************************/
/* ~OGRPGDataSource() */
/************************************************************************/
OGRPGDataSource::~OGRPGDataSource()
{
OGRPGDataSource::FlushCache(true);
CPLFree(pszName);
CPLFree(pszForcedTables);
CSLDestroy(papszSchemaList);
for (int i = 0; i < nLayers; i++)
delete papoLayers[i];
CPLFree(papoLayers);
if (hPGConn != nullptr)
{
// If there are prelude statements, don't mess with transactions.
if (CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS") ==
nullptr)
FlushSoftTransaction();
/* --------------------------------------------------------------------
*/
/* Send closing statements */
/* --------------------------------------------------------------------
*/
const char *pszClosingStatements =
CSLFetchNameValue(papszOpenOptions, "CLOSING_STATEMENTS");
if (pszClosingStatements != nullptr)
{
PGresult *hResult =
OGRPG_PQexec(hPGConn, pszClosingStatements, TRUE);
OGRPGClearResult(hResult);
}
/* XXX - mloskot: After the connection is closed, valgrind still
* reports 36 bytes definitely lost, somewhere in the libpq.
*/
PQfinish(hPGConn);
hPGConn = nullptr;
}
}
/************************************************************************/
/* FlushCache() */
/************************************************************************/
OGRErr OGRPGDataSource::FlushCacheWithRet(bool /* bAtClosing */)
{
OGRErr eErr = EndCopy();
if (eErr == OGRERR_NONE)
{
for (int iLayer = 0; iLayer < nLayers; iLayer++)
{
papoLayers[iLayer]->RunDeferredCreationIfNecessary();
}
}
return eErr;
}
CPLErr OGRPGDataSource::FlushCache(bool bAtClosing)
{
return FlushCacheWithRet(bAtClosing) == OGRERR_NONE ? CE_None : CE_Failure;
}
/************************************************************************/
/* GetCurrentSchema() */
/************************************************************************/
CPLString OGRPGDataSource::GetCurrentSchema()
{
/* -------------------------------------------- */
/* Get the current schema */
/* -------------------------------------------- */
PGresult *hResult = OGRPG_PQexec(hPGConn, "SELECT current_schema()");
if (hResult && PQntuples(hResult) == 1 && !PQgetisnull(hResult, 0, 0))
{
osCurrentSchema = PQgetvalue(hResult, 0, 0);
}
OGRPGClearResult(hResult);
return osCurrentSchema;
}
/************************************************************************/
/* OGRPGDecodeVersionString() */
/************************************************************************/
void OGRPGDataSource::OGRPGDecodeVersionString(PGver *psVersion,
const char *pszVer)
{
while (*pszVer == ' ')
pszVer++;
const char *ptr = pszVer;
// get Version string
while (*ptr && *ptr != ' ')
ptr++;
GUInt32 iLen = static_cast<int>(ptr - pszVer);
char szVer[10] = {};
if (iLen > sizeof(szVer) - 1)
iLen = sizeof(szVer) - 1;
strncpy(szVer, pszVer, iLen);
szVer[iLen] = '\0';
ptr = pszVer = szVer;
// get Major number
while (*ptr && *ptr != '.')
ptr++;
iLen = static_cast<int>(ptr - pszVer);
char szNum[25] = {};
if (iLen > sizeof(szNum) - 1)
iLen = sizeof(szNum) - 1;
strncpy(szNum, pszVer, iLen);
szNum[iLen] = '\0';
psVersion->nMajor = atoi(szNum);
if (*ptr == 0)
return;
pszVer = ++ptr;
// get Minor number
while (*ptr && *ptr != '.')
ptr++;
iLen = static_cast<int>(ptr - pszVer);
if (iLen > sizeof(szNum) - 1)
iLen = sizeof(szNum) - 1;
strncpy(szNum, pszVer, iLen);
szNum[iLen] = '\0';
psVersion->nMinor = atoi(szNum);
if (*ptr)
{
pszVer = ++ptr;
// get Release number
while (*ptr && *ptr != '.')
ptr++;
iLen = static_cast<int>(ptr - pszVer);
if (iLen > sizeof(szNum) - 1)
iLen = sizeof(szNum) - 1;
strncpy(szNum, pszVer, iLen);
szNum[iLen] = '\0';
psVersion->nRelease = atoi(szNum);
}
}
/************************************************************************/
/* One entry for each PG table */
/************************************************************************/
struct PGTableEntry
{
char *pszTableName = nullptr;
char *pszSchemaName = nullptr;
char *pszDescription = nullptr;
int nGeomColumnCount = 0;
PGGeomColumnDesc *pasGeomColumns = nullptr; /* list of geometry columns */
int bDerivedInfoAdded =
false; /* set to TRUE if it derives from another table */
};
static unsigned long OGRPGHashTableEntry(const void *_psTableEntry)
{
const PGTableEntry *psTableEntry =
static_cast<const PGTableEntry *>(_psTableEntry);
return CPLHashSetHashStr(CPLString().Printf(
"%s.%s", psTableEntry->pszSchemaName, psTableEntry->pszTableName));
}
static int OGRPGEqualTableEntry(const void *_psTableEntry1,
const void *_psTableEntry2)
{
const PGTableEntry *psTableEntry1 =
static_cast<const PGTableEntry *>(_psTableEntry1);
const PGTableEntry *psTableEntry2 =
static_cast<const PGTableEntry *>(_psTableEntry2);
return strcmp(psTableEntry1->pszTableName, psTableEntry2->pszTableName) ==
0 &&
strcmp(psTableEntry1->pszSchemaName, psTableEntry2->pszSchemaName) ==
0;
}
static void OGRPGTableEntryAddGeomColumn(
PGTableEntry *psTableEntry, const char *pszName,
const char *pszGeomType = nullptr, int GeometryTypeFlags = 0,
int nSRID = UNDETERMINED_SRID, PostgisType ePostgisType = GEOM_TYPE_UNKNOWN,
int bNullable = TRUE)
{
psTableEntry->pasGeomColumns = static_cast<PGGeomColumnDesc *>(CPLRealloc(
psTableEntry->pasGeomColumns,
sizeof(PGGeomColumnDesc) * (psTableEntry->nGeomColumnCount + 1)));
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount].pszName =
CPLStrdup(pszName);
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount].pszGeomType =
(pszGeomType) ? CPLStrdup(pszGeomType) : nullptr;
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount]
.GeometryTypeFlags = GeometryTypeFlags;
/* With PostGIS 2.0, querying geometry_columns can return 0, not only when
*/
/* the SRID is truly set to 0, but also when there's no constraint */
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount].nSRID =
nSRID > 0 ? nSRID : UNDETERMINED_SRID;
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount].ePostgisType =
ePostgisType;
psTableEntry->pasGeomColumns[psTableEntry->nGeomColumnCount].bNullable =
bNullable;
psTableEntry->nGeomColumnCount++;
}
static void
OGRPGTableEntryAddGeomColumn(PGTableEntry *psTableEntry,
const PGGeomColumnDesc *psGeomColumnDesc)
{
OGRPGTableEntryAddGeomColumn(
psTableEntry, psGeomColumnDesc->pszName, psGeomColumnDesc->pszGeomType,
psGeomColumnDesc->GeometryTypeFlags, psGeomColumnDesc->nSRID,
psGeomColumnDesc->ePostgisType, psGeomColumnDesc->bNullable);
}
static void OGRPGFreeTableEntry(void *_psTableEntry)
{
PGTableEntry *psTableEntry = static_cast<PGTableEntry *>(_psTableEntry);
CPLFree(psTableEntry->pszTableName);
CPLFree(psTableEntry->pszSchemaName);
CPLFree(psTableEntry->pszDescription);
for (int i = 0; i < psTableEntry->nGeomColumnCount; i++)
{
CPLFree(psTableEntry->pasGeomColumns[i].pszName);
CPLFree(psTableEntry->pasGeomColumns[i].pszGeomType);
}
CPLFree(psTableEntry->pasGeomColumns);
CPLFree(psTableEntry);
}
static PGTableEntry *OGRPGFindTableEntry(CPLHashSet *hSetTables,
const char *pszTableName,
const char *pszSchemaName)
{
PGTableEntry sEntry;
sEntry.pszTableName = const_cast<char *>(pszTableName);
sEntry.pszSchemaName = const_cast<char *>(pszSchemaName);
return static_cast<PGTableEntry *>(CPLHashSetLookup(hSetTables, &sEntry));
}
static PGTableEntry *OGRPGAddTableEntry(CPLHashSet *hSetTables,
const char *pszTableName,
const char *pszSchemaName,
const char *pszDescription)
{
PGTableEntry *psEntry =
static_cast<PGTableEntry *>(CPLCalloc(1, sizeof(PGTableEntry)));
psEntry->pszTableName = CPLStrdup(pszTableName);
psEntry->pszSchemaName = CPLStrdup(pszSchemaName);
psEntry->pszDescription = CPLStrdup(pszDescription ? pszDescription : "");
CPLHashSetInsert(hSetTables, psEntry);
return psEntry;
}
/************************************************************************/
/* Open() */
/************************************************************************/
int OGRPGDataSource::Open(const char *pszNewName, int bUpdate, int bTestOpen,
char **papszOpenOptionsIn)
{
CPLAssert(nLayers == 0);
papszOpenOptions = CSLDuplicate(papszOpenOptionsIn);
const char *pszPreludeStatements =
CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
if (pszPreludeStatements)
{
// If the prelude statements starts with BEGIN, then don't emit one
// in our code.
if (STARTS_WITH_CI(pszPreludeStatements, "BEGIN"))
nSoftTransactionLevel = 1;
}
/* -------------------------------------------------------------------- */
/* Verify postgresql prefix. */
/* -------------------------------------------------------------------- */
if (STARTS_WITH_CI(pszNewName, "PGB:"))
{
#if defined(BINARY_CURSOR_ENABLED)
bUseBinaryCursor = TRUE;
CPLDebug("PG", "BINARY cursor is used for geometry fetching");
#endif
}
else if (!STARTS_WITH_CI(pszNewName, "PG:") &&
!STARTS_WITH(pszNewName, "postgresql://"))
{
if (!bTestOpen)
CPLError(CE_Failure, CPLE_AppDefined,
"%s does not conform to PostgreSQL naming convention,"
" PG:* or postgresql://\n",
pszNewName);
return FALSE;
}
pszName = CPLStrdup(pszNewName);
const auto QuoteAndEscapeConnectionParam = [](const char *pszParam)
{
CPLString osRet("\'");
for (int i = 0; pszParam[i]; ++i)
{
if (pszParam[i] == '\'')
osRet += "\\'";
else if (pszParam[i] == '\\')
osRet += "\\\\";
else
osRet += pszParam[i];
}
osRet += '\'';
return osRet;
};
CPLString osConnectionName(pszName);
if (osConnectionName.find("PG:postgresql://") == 0)
osConnectionName = osConnectionName.substr(3);
const bool bIsURI = osConnectionName.find("postgresql://") == 0;
const char *const apszOpenOptions[] = {
"service", "dbname", "port", "user", "password", "host",
// Non-postgreSQL options
"active_schema", "schemas", "tables"};
std::string osSchemas;
std::string osForcedTables;
for (const char *pszOpenOption : apszOpenOptions)
{
const char *pszVal = CSLFetchNameValue(papszOpenOptions, pszOpenOption);
if (pszVal && strcmp(pszOpenOption, "active_schema") == 0)
{
osActiveSchema = pszVal;
}
else if (pszVal && strcmp(pszOpenOption, "schemas") == 0)
{
osSchemas = pszVal;
}
else if (pszVal && strcmp(pszOpenOption, "tables") == 0)
{
osForcedTables = pszVal;
}
else if (pszVal)
{
if (bIsURI)
{
osConnectionName +=
osConnectionName.find('?') == std::string::npos ? '?' : '&';
}
else
{
if (osConnectionName.back() != ':')
osConnectionName += ' ';
}
osConnectionName += pszOpenOption;
osConnectionName += "=";
if (bIsURI)
{
char *pszTmp = CPLEscapeString(pszVal, -1, CPLES_URL);
osConnectionName += pszTmp;
CPLFree(pszTmp);
}
else
{
osConnectionName += QuoteAndEscapeConnectionParam(pszVal);
}
}
}
/* -------------------------------------------------------------------- */
/* Set application name if not found in connection string */
/* -------------------------------------------------------------------- */
if (strstr(pszName, "application_name") == nullptr &&
getenv("PGAPPNAME") == nullptr)
{
if (bIsURI)
{
osConnectionName +=
osConnectionName.find('?') == std::string::npos ? '?' : '&';
}
else
{
if (osConnectionName.back() != ':')
osConnectionName += ' ';
}
osConnectionName += "application_name=";
std::string osVal("GDAL ");
osVal += GDALVersionInfo("RELEASE_NAME");
if (bIsURI)
{
char *pszTmp = CPLEscapeString(osVal.c_str(), -1, CPLES_URL);
osConnectionName += pszTmp;
CPLFree(pszTmp);
}
else
{
osConnectionName += QuoteAndEscapeConnectionParam(osVal.c_str());
}
}
const auto ParseAndRemoveParam =
[](char *pszStr, const char *pszParamName, std::string &osValue)
{
const int nParamNameLen = static_cast<int>(strlen(pszParamName));
bool bInSingleQuotedString = false;
for (int i = 0; pszStr[i]; i++)
{
if (bInSingleQuotedString)
{
if (pszStr[i] == '\\')
{
if (pszStr[i + 1] == '\\' || pszStr[i + 1] == '\'')
{
++i;
}
}
else if (pszStr[i] == '\'')
{
bInSingleQuotedString = false;
}
}
else if (pszStr[i] == '\'')
{
bInSingleQuotedString = true;
}
else if (EQUALN(pszStr + i, pszParamName, nParamNameLen) &&
(pszStr[i + nParamNameLen] == '=' ||
pszStr[i + nParamNameLen] == ' '))
{
const int iStart = i;
i += nParamNameLen;
while (pszStr[i] == ' ')
++i;
if (pszStr[i] == '=')
{
++i;
while (pszStr[i] == ' ')
++i;
if (pszStr[i] == '\'')
{
++i;
for (; pszStr[i]; i++)
{
if (pszStr[i] == '\\')
{
if (pszStr[i + 1] == '\\' ||
pszStr[i + 1] == '\'')
{
osValue += pszStr[i + 1];
++i;
}
}
else if (pszStr[i] == '\'')
{
++i;
break;
}
else
{
osValue += pszStr[i];
}
}
}
else
{
for (; pszStr[i] && pszStr[i] != ' '; i++)
{
osValue += pszStr[i];
}
}
// Edit pszStr to remove the parameter and its value
if (pszStr[i] == ' ')
{
memmove(pszStr + iStart, pszStr + i,
strlen(pszStr + i) + 1);
}
else
{
pszStr[iStart] = 0;
}
}
return true;
}
}
return false;
};
char *pszConnectionName = CPLStrdup(osConnectionName);
char *pszConnectionNameNoPrefix =
pszConnectionName + (STARTS_WITH_CI(pszConnectionName, "PGB:") ? 4
: STARTS_WITH_CI(pszConnectionName, "PG:") ? 3
: 0);
/* -------------------------------------------------------------------- */
/* Determine if the connection string contains an optional */
/* ACTIVE_SCHEMA portion. If so, parse it out. */
/* -------------------------------------------------------------------- */
if (osActiveSchema.empty() && !bIsURI &&
!ParseAndRemoveParam(pszConnectionNameNoPrefix, "active_schema",
osActiveSchema))
{
osActiveSchema = "public";
}
/* -------------------------------------------------------------------- */
/* Determine if the connection string contains an optional */
/* SCHEMAS portion. If so, parse it out. */
/* -------------------------------------------------------------------- */
if (!osSchemas.empty() ||
(!bIsURI &&
ParseAndRemoveParam(pszConnectionNameNoPrefix, "schemas", osSchemas)))
{
papszSchemaList = CSLTokenizeString2(osSchemas.c_str(), ",", 0);
/* If there is only one schema specified, make it the active schema */
if (CSLCount(papszSchemaList) == 1)
{
osActiveSchema = papszSchemaList[0];
}
}
/* -------------------------------------------------------------------- */
/* Determine if the connection string contains an optional */
/* TABLES portion. If so, parse it out. The expected */
/* connection string in this case will be, e.g.: */
/* */
/* 'PG:dbname=warmerda user=warmerda tables=s1.t1,[s2.t2,...] */
/* - where sN is schema and tN is table name */
/* We must also strip this information from the connection */
/* string; PQconnectdb() does not like unknown directives */
/* -------------------------------------------------------------------- */
if (!osForcedTables.empty() ||
(!bIsURI && ParseAndRemoveParam(pszConnectionNameNoPrefix, "tables",
osForcedTables)))
{
pszForcedTables = CPLStrdup(osForcedTables.c_str());
}
/* -------------------------------------------------------------------- */
/* Try to establish connection. */
/* -------------------------------------------------------------------- */
hPGConn = PQconnectdb(pszConnectionNameNoPrefix);
CPLFree(pszConnectionName);
pszConnectionName = nullptr;
if (hPGConn == nullptr || PQstatus(hPGConn) == CONNECTION_BAD)
{
CPLError(CE_Failure, CPLE_AppDefined, "PQconnectdb failed.\n%s",
PQerrorMessage(hPGConn));
PQfinish(hPGConn);
hPGConn = nullptr;
return FALSE;
}
bDSUpdate = bUpdate;
/* -------------------------------------------------------------------- */
/* Send prelude statements */
/* -------------------------------------------------------------------- */
if (pszPreludeStatements != nullptr)
{
PGresult *hResult = OGRPG_PQexec(hPGConn, pszPreludeStatements, TRUE);
if (!hResult || PQresultStatus(hResult) != PGRES_COMMAND_OK)
{
OGRPGClearResult(hResult);
return FALSE;
}
OGRPGClearResult(hResult);
}
/* -------------------------------------------------------------------- */
/* Set the encoding to UTF8 as the driver advertises UTF8 */
/* unless PGCLIENTENCODING is defined */
/* -------------------------------------------------------------------- */
if (CPLGetConfigOption("PGCLIENTENCODING", nullptr) == nullptr)
{
const char *encoding = "UTF8";
if (PQsetClientEncoding(hPGConn, encoding) == -1)
{
CPLError(CE_Warning, CPLE_AppDefined,
"PQsetClientEncoding(%s) failed.\n%s", encoding,
PQerrorMessage(hPGConn));
}
}
{
PGresult *hResult = OGRPG_PQexec(hPGConn, "SHOW client_encoding");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) == 1)
{
const char *pszClientEncoding = PQgetvalue(hResult, 0, 0);
if (pszClientEncoding)
{
CPLDebug("PG", "Client encoding: '%s'", pszClientEncoding);
if (EQUAL(pszClientEncoding, "UTF8"))
{
m_bUTF8ClientEncoding = true;
}
}
}
OGRPGClearResult(hResult);
}
/* -------------------------------------------------------------------- */
/* Install a notice processor. */
/* -------------------------------------------------------------------- */
PQsetNoticeProcessor(hPGConn, OGRPGNoticeProcessor, this);
/* -------------------------------------------------------------------- */
/* Detect PostGIS schema */
/* -------------------------------------------------------------------- */
CPLString osPostgisSchema;
{
PGresult *hResult = OGRPG_PQexec(
hPGConn,
"SELECT n.nspname FROM pg_proc p JOIN pg_namespace n "
"ON n.oid = p.pronamespace WHERE proname = 'postgis_version'");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0)
{
const char *pszPostgisSchema = PQgetvalue(hResult, 0, 0);
CPLDebug("PG", "PostGIS schema: '%s'", pszPostgisSchema);
osPostgisSchema = pszPostgisSchema;
}
OGRPGClearResult(hResult);
}
/* -------------------------------------------------------------------- */
/* Get search_path */
/* -------------------------------------------------------------------- */
std::string osSearchPath = "public";
{
PGresult *hResult = OGRPG_PQexec(hPGConn, "SHOW search_path");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0)
{
const char *pszVal = PQgetvalue(hResult, 0, 0);
if (pszVal)
{
osSearchPath = pszVal;
}
}
OGRPGClearResult(hResult);
}
/* -------------------------------------------------------------------- */
/* Set active schema if different from 'public'. Also add */
/* postgis schema if needed. */
/* -------------------------------------------------------------------- */
if (osActiveSchema != "public" ||
(!osPostgisSchema.empty() &&
osSearchPath.find(osPostgisSchema) == std::string::npos))
{
std::string osNewSearchPath;
if (osActiveSchema != "public")
{
osNewSearchPath +=
OGRPGEscapeString(hPGConn, osActiveSchema.c_str());
osNewSearchPath += ',';
}
osNewSearchPath += osSearchPath;
if (!osPostgisSchema.empty() &&
osSearchPath.find(osPostgisSchema) == std::string::npos)
{
osNewSearchPath += ',';
osNewSearchPath +=
OGRPGEscapeString(hPGConn, osPostgisSchema.c_str());
}
CPLDebug("PG", "Modifying search_path from %s to %s",
osSearchPath.c_str(), osNewSearchPath.c_str());
std::string osCommand = "SET search_path=" + osNewSearchPath;
PGresult *hResult = OGRPG_PQexec(hPGConn, osCommand.c_str());
if (!hResult || PQresultStatus(hResult) != PGRES_COMMAND_OK)
{
OGRPGClearResult(hResult);
CPLDebug("PG", "Command \"%s\" failed. Trying without 'public'.",
osCommand.c_str());
osCommand =
CPLSPrintf("SET search_path='%s'", osActiveSchema.c_str());
PGresult *hResult2 = OGRPG_PQexec(hPGConn, osCommand.c_str());
if (!hResult2 || PQresultStatus(hResult2) != PGRES_COMMAND_OK)
{
OGRPGClearResult(hResult2);
CPLError(CE_Failure, CPLE_AppDefined, "%s",
PQerrorMessage(hPGConn));
return FALSE;
}
}
OGRPGClearResult(hResult);
}
/* -------------------------------------------------------------------- */
/* Find out PostgreSQL version */
/* -------------------------------------------------------------------- */
sPostgreSQLVersion.nMajor = -1;
sPostgreSQLVersion.nMinor = -1;
sPostgreSQLVersion.nRelease = -1;
PGresult *hResult = OGRPG_PQexec(hPGConn, "SELECT version()");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0)
{
char *pszVer = PQgetvalue(hResult, 0, 0);
CPLDebug("PG", "PostgreSQL version string : '%s'", pszVer);
/* Should work with "PostgreSQL X.Y.Z ..." or "EnterpriseDB X.Y.Z ..."
*/
const char *pszSpace = strchr(pszVer, ' ');
if (pszSpace != nullptr &&
isdigit(static_cast<unsigned char>(pszSpace[1])))
{
OGRPGDecodeVersionString(&sPostgreSQLVersion, pszSpace + 1);
#if defined(BINARY_CURSOR_ENABLED)
if (sPostgreSQLVersion.nMajor == 7 && sPostgreSQLVersion.nMinor < 4)
{
/* We don't support BINARY CURSOR for PostgreSQL < 7.4. */
/* The binary protocol for arrays seems to be different from
* later versions */
CPLDebug("PG", "BINARY cursor will finally NOT be used because "
"version < 7.4");
bUseBinaryCursor = FALSE;
}
#endif
}
}
OGRPGClearResult(hResult);
CPLAssert(nullptr ==
hResult); /* Test if safe PQclear has not been broken */
/* -------------------------------------------------------------------- */
/* Set standard_conforming_strings=ON */
/* -------------------------------------------------------------------- */
hResult = OGRPG_PQexec(hPGConn, "SET standard_conforming_strings = ON");
if (!(hResult && PQresultStatus(hResult) == PGRES_COMMAND_OK))
{
CPLError(CE_Failure, CPLE_AppDefined, "%s", PQerrorMessage(hPGConn));
OGRPGClearResult(hResult);
return FALSE;
}
OGRPGClearResult(hResult);
/* -------------------------------------------------------------------- */
/* Test if time binary format is int8 or float8 */
/* -------------------------------------------------------------------- */
#if defined(BINARY_CURSOR_ENABLED)
if (bUseBinaryCursor)
{
SoftStartTransaction();
hResult =
OGRPG_PQexec(hPGConn, "DECLARE gettimebinaryformat BINARY CURSOR "
"FOR SELECT CAST ('00:00:01' AS time)");
if (hResult && PQresultStatus(hResult) == PGRES_COMMAND_OK)
{
OGRPGClearResult(hResult);
hResult = OGRPG_PQexec(hPGConn, "FETCH ALL IN gettimebinaryformat");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) == 1)
{
if (PQfformat(hResult, 0) == 1) // Binary data representation
{
CPLAssert(PQgetlength(hResult, 0, 0) == 8);
unsigned int nVal[2] = {0, 0};
memcpy(nVal, PQgetvalue(hResult, 0, 0), 8);
CPL_MSBPTR32(&nVal[0]);
CPL_MSBPTR32(&nVal[1]);
double dVal = 0.0;
memcpy(&dVal, PQgetvalue(hResult, 0, 0), 8);
CPL_MSBPTR64(&dVal);
if (nVal[0] == 0 && nVal[1] == 1000000)
{
bBinaryTimeFormatIsInt8 = TRUE;
CPLDebug("PG", "Time binary format is int8");
}
else if (dVal == 1.)
{
bBinaryTimeFormatIsInt8 = FALSE;
CPLDebug("PG", "Time binary format is float8");
}
else
{
bBinaryTimeFormatIsInt8 = FALSE;
CPLDebug("PG", "Time binary format is unknown");
}
}
}
}
OGRPGClearResult(hResult);
hResult = OGRPG_PQexec(hPGConn, "CLOSE gettimebinaryformat");
OGRPGClearResult(hResult);
SoftCommitTransaction();
}
#endif
#ifdef notdef
/* This would be the quickest fix... instead, ogrpglayer has been updated to
* support */
/* bytea hex format */
if (sPostgreSQLVersion.nMajor >= 9)
{
// Starting with PostgreSQL 9.0, the default output format for values
// of type bytea is hex, whereas we traditionally expect escape.
hResult = OGRPG_PQexec(hPGConn, "SET bytea_output TO escape");
OGRPGClearResult(hResult);
}
#endif
/* -------------------------------------------------------------------- */
/* Test to see if this database instance has support for the */
/* PostGIS Geometry type. If so, disable sequential scanning */
/* so we will get the value of the gist indexes. */
/* -------------------------------------------------------------------- */
hResult =
OGRPG_PQexec(hPGConn, "SELECT oid, typname FROM pg_type WHERE typname "
"IN ('geometry', 'geography') AND typtype='b'");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0 &&
CPLTestBool(CPLGetConfigOption("PG_USE_POSTGIS", "YES")))
{
for (int iRecord = 0; iRecord < PQntuples(hResult); iRecord++)
{
const char *pszOid = PQgetvalue(hResult, iRecord, 0);
const char *pszTypname = PQgetvalue(hResult, iRecord, 1);
if (EQUAL(pszTypname, "geometry"))
{
bHavePostGIS = TRUE;
nGeometryOID = atoi(pszOid);
}
else if (CPLTestBool(CPLGetConfigOption("PG_USE_GEOGRAPHY", "YES")))
{
bHaveGeography = TRUE;
nGeographyOID = atoi(pszOid);
}
}
}
OGRPGClearResult(hResult);
/* -------------------------------------------------------------------- */
/* Find out PostGIS version */
/* -------------------------------------------------------------------- */
sPostGISVersion.nMajor = -1;
sPostGISVersion.nMinor = -1;
sPostGISVersion.nRelease = -1;
if (bHavePostGIS)
{
hResult = OGRPG_PQexec(hPGConn, "SELECT postgis_version()");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0)
{
char *pszVer = PQgetvalue(hResult, 0, 0);
CPLDebug("PG", "PostGIS version string : '%s'", pszVer);
OGRPGDecodeVersionString(&sPostGISVersion, pszVer);
}
OGRPGClearResult(hResult);
if (sPostGISVersion.nMajor == 0 && sPostGISVersion.nMinor < 8)
{
// Turning off sequential scans for PostGIS < 0.8
hResult = OGRPG_PQexec(hPGConn, "SET ENABLE_SEQSCAN = OFF");
CPLDebug("PG", "SET ENABLE_SEQSCAN=OFF");
}
else
{
// PostGIS >=0.8 is correctly integrated with query planner,
// thus PostgreSQL will use indexes whenever appropriate.
hResult = OGRPG_PQexec(hPGConn, "SET ENABLE_SEQSCAN = ON");
}
OGRPGClearResult(hResult);
}
m_bHasGeometryColumns =
OGRPG_Check_Table_Exists(hPGConn, "geometry_columns");
m_bHasSpatialRefSys = OGRPG_Check_Table_Exists(hPGConn, "spatial_ref_sys");
/* -------------------------------------------------------------------- */
/* Find out "unknown SRID" value */
/* -------------------------------------------------------------------- */
if (sPostGISVersion.nMajor >= 2)
{
hResult =
OGRPG_PQexec(hPGConn, "SELECT ST_Srid('POINT EMPTY'::GEOMETRY)");
if (hResult && PQresultStatus(hResult) == PGRES_TUPLES_OK &&
PQntuples(hResult) > 0)
{
nUndefinedSRID = atoi(PQgetvalue(hResult, 0, 0));
}
OGRPGClearResult(hResult);
}
else
nUndefinedSRID = -1;
GetCurrentSchema();
bListAllTables = CPLTestBool(
CSLFetchNameValueDef(papszOpenOptions, "LIST_ALL_TABLES",
CPLGetConfigOption("PG_LIST_ALL_TABLES", "NO")));
m_bSkipViews = CPLTestBool(
CSLFetchNameValueDef(papszOpenOptions, "SKIP_VIEWS",
CPLGetConfigOption("PG_SKIP_VIEWS", "NO")));
return TRUE;
}
/************************************************************************/
/* LoadTables() */
/************************************************************************/
void OGRPGDataSource::LoadTables()
{
if (bHasLoadTables)
return;