File: ogr_sqlite.h

package info (click to toggle)
gdal 3.11.3%2Bdfsg-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 89,016 kB
  • sloc: cpp: 1,165,048; ansic: 208,864; python: 26,958; java: 5,972; xml: 4,611; sh: 3,776; cs: 2,508; yacc: 1,306; makefile: 213
file content (914 lines) | stat: -rw-r--r-- 28,953 bytes parent folder | download
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
/******************************************************************************
 *
 * Project:  OpenGIS Simple Features Reference Implementation
 * Purpose:  Private definitions for OGR/SQLite driver.
 * Author:   Frank Warmerdam, warmerdam@pobox.com
 *
 ******************************************************************************
 * Copyright (c) 2004, Frank Warmerdam <warmerdam@pobox.com>
 * Copyright (c) 2009-2014, Even Rouault <even dot rouault at spatialys.com>
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#ifndef OGR_SQLITE_H_INCLUDED
#define OGR_SQLITE_H_INCLUDED

#include <cstddef>
#include <map>
#include <set>
#include <utility>
#include <vector>

#include "cpl_error.h"
#include "gdal_pam.h"
#include "ogrsf_frmts.h"
#include "ogrsf_frmts.h"
#include "rasterlite2_header.h"

#ifdef SPATIALITE_AMALGAMATION
/*
/ using an AMALGAMATED version of SpatiaLite
/ a private internal copy of SQLite is included:
/ so we are required including the SpatiaLite's
/ own header
/
/ IMPORTANT NOTICE: using AMALAGATION is only
/ useful on Windows (to skip DLL hell related oddities)
/
/ You MUST NOT use AMALGAMATION on Linux or any
/ other "sane" operating system !!!!
*/
#include <spatialite/sqlite3.h>
#else
#include <sqlite3.h>
#endif

#define UNINITIALIZED_SRID -2

#if defined(DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) ||     \
    defined(ALLOW_FORMAT_DUMPS)
// Enable accepting a SQL dump (starting with a "-- SQL SQLITE" or
// "-- SQL RASTERLITE" or "--SQL MBTILES" line) as a valid
// file. This makes fuzzer life easier
#define ENABLE_SQL_SQLITE_FORMAT
#endif

#include "ogrsqlitebase.h"

/************************************************************************/
/*      SpatiaLite's own Geometry type IDs.                             */
/************************************************************************/

enum OGRSpatialiteGeomType
{
    // 2D [XY]
    OGRSplitePointXY = 1,
    OGRSpliteLineStringXY = 2,
    OGRSplitePolygonXY = 3,
    OGRSpliteMultiPointXY = 4,
    OGRSpliteMultiLineStringXY = 5,
    OGRSpliteMultiPolygonXY = 6,
    OGRSpliteGeometryCollectionXY = 7,
    // 3D [XYZ]
    OGRSplitePointXYZ = 1001,
    OGRSpliteLineStringXYZ = 1002,
    OGRSplitePolygonXYZ = 1003,
    OGRSpliteMultiPointXYZ = 1004,
    OGRSpliteMultiLineStringXYZ = 1005,
    OGRSpliteMultiPolygonXYZ = 1006,
    OGRSpliteGeometryCollectionXYZ = 1007,
    // 2D with Measure [XYM]
    OGRSplitePointXYM = 2001,
    OGRSpliteLineStringXYM = 2002,
    OGRSplitePolygonXYM = 2003,
    OGRSpliteMultiPointXYM = 2004,
    OGRSpliteMultiLineStringXYM = 2005,
    OGRSpliteMultiPolygonXYM = 2006,
    OGRSpliteGeometryCollectionXYM = 2007,
    // 3D with Measure [XYZM]
    OGRSplitePointXYZM = 3001,
    OGRSpliteLineStringXYZM = 3002,
    OGRSplitePolygonXYZM = 3003,
    OGRSpliteMultiPointXYZM = 3004,
    OGRSpliteMultiLineStringXYZM = 3005,
    OGRSpliteMultiPolygonXYZM = 3006,
    OGRSpliteGeometryCollectionXYZM = 3007,
    // COMPRESSED: 2D [XY]
    OGRSpliteComprLineStringXY = 1000002,
    OGRSpliteComprPolygonXY = 1000003,
    OGRSpliteComprMultiPointXY = 1000004,
    OGRSpliteComprMultiLineStringXY = 1000005,
    OGRSpliteComprMultiPolygonXY = 1000006,
    OGRSpliteComprGeometryCollectionXY = 1000007,
    // COMPRESSED: 3D [XYZ]
    OGRSpliteComprLineStringXYZ = 1001002,
    OGRSpliteComprPolygonXYZ = 1001003,
    OGRSpliteComprMultiPointXYZ = 1001004,
    OGRSpliteComprMultiLineStringXYZ = 1001005,
    OGRSpliteComprMultiPolygonXYZ = 1001006,
    OGRSpliteComprGeometryCollectionXYZ = 1001007,
    // COMPRESSED: 2D with Measure [XYM]
    OGRSpliteComprLineStringXYM = 1002002,
    OGRSpliteComprPolygonXYM = 1002003,
    OGRSpliteComprMultiPointXYM = 1002004,
    OGRSpliteComprMultiLineStringXYM = 1002005,
    OGRSpliteComprMultiPolygonXYM = 1002006,
    OGRSpliteComprGeometryCollectionXYM = 1002007,
    // COMPRESSED: 3D with Measure [XYZM]
    OGRSpliteComprLineStringXYZM = 1003002,
    OGRSpliteComprPolygonXYZM = 1003003,
    OGRSpliteComprMultiPointXYZM = 1003004,
    OGRSpliteComprMultiLineStringXYZM = 1003005,
    OGRSpliteComprMultiPolygonXYZM = 1003006,
    OGRSpliteComprGeometryCollectionXYZM = 1003007
};

/************************************************************************/
/*                            OGRSQLiteLayer                            */
/************************************************************************/

class OGRSQLiteDataSource;

class OGRSQLiteLayer CPL_NON_FINAL : public OGRLayer,
                                     public IOGRSQLiteGetSpatialWhere
{
  private:
    static OGRErr
    createFromSpatialiteInternal(const GByte *pabyData, OGRGeometry **ppoReturn,
                                 int nBytes, OGRwkbByteOrder eByteOrder,
                                 int *pnBytesConsumed, int nRecLevel);

    static int CanBeCompressedSpatialiteGeometry(const OGRGeometry *poGeometry);

    static int ComputeSpatiaLiteGeometrySize(const OGRGeometry *poGeometry,
                                             bool bSpatialite2D,
                                             bool bUseComprGeom);

    static int GetSpatialiteGeometryCode(const OGRGeometry *poGeometry,
                                         bool bSpatialite2D, bool bUseComprGeom,
                                         bool bAcceptMultiGeom);

    static int ExportSpatiaLiteGeometryInternal(const OGRGeometry *poGeometry,
                                                OGRwkbByteOrder eByteOrder,
                                                bool bSpatialite2D,
                                                bool bUseComprGeom,
                                                GByte *pabyData);

    CPL_DISALLOW_COPY_ASSIGN(OGRSQLiteLayer)

  protected:
    OGRSQLiteFeatureDefn *m_poFeatureDefn = nullptr;

    GIntBig m_iNextShapeId = 0;

    sqlite3_stmt *m_hStmt = nullptr;
    bool m_bDoStep = true;
    bool m_bEOF = false;

    OGRSQLiteDataSource *m_poDS = nullptr;

    char *m_pszFIDColumn = nullptr;

    int *m_panFieldOrdinals = nullptr;
    int m_iFIDCol = -1;
    int m_iOGRNativeDataCol = -1;
    int m_iOGRNativeMediaTypeCol = -1;

    bool m_bIsVirtualShape = false;

    void BuildFeatureDefn(const char *pszLayerName, bool bIsSelect,
                          sqlite3_stmt *hStmt,
                          const std::set<CPLString> *paosGeomCols,
                          const std::set<CPLString> &aosIgnoredCols);

    void ClearStatement();
    virtual OGRErr ResetStatement() = 0;

    bool m_bUseComprGeom = false;

    char **m_papszCompressedColumns = nullptr;

    bool m_bAllowMultipleGeomFields = false;

    static CPLString FormatSpatialFilterFromRTree(
        OGRGeometry *poFilterGeom, const char *pszRowIDName,
        const char *pszEscapedTable, const char *pszEscapedGeomCol);

    static CPLString
    FormatSpatialFilterFromMBR(OGRGeometry *poFilterGeom,
                               const char *pszEscapedGeomColName);

    explicit OGRSQLiteLayer(OGRSQLiteDataSource *poDSIn);

  public:
    virtual ~OGRSQLiteLayer();

    void Finalize();

    GDALDataset *GetDataset() override;

    virtual void ResetReading() override;
    virtual OGRFeature *GetNextRawFeature();
    virtual OGRFeature *GetNextFeature() override;

    virtual OGRFeature *GetFeature(GIntBig nFeatureId) override;

    virtual OGRFeatureDefn *GetLayerDefn() override
    {
        return m_poFeatureDefn;
    }

    virtual OGRSQLiteFeatureDefn *myGetLayerDefn()
    {
        return m_poFeatureDefn;
    }

    virtual const char *GetFIDColumn() override;

    virtual int TestCapability(const char *) override;

    virtual OGRErr StartTransaction() override;
    virtual OGRErr CommitTransaction() override;
    virtual OGRErr RollbackTransaction() override;

    virtual void InvalidateCachedFeatureCountAndExtent()
    {
    }

    virtual bool IsTableLayer()
    {
        return false;
    }

    virtual bool HasSpatialIndex(CPL_UNUSED int iGeomField)
    {
        return false;
    }

    virtual bool HasFastSpatialFilter(CPL_UNUSED int iGeomCol) override
    {
        return false;
    }

    virtual CPLString
    GetSpatialWhere(CPL_UNUSED int iGeomCol,
                    CPL_UNUSED OGRGeometry *poFilterGeom) override
    {
        return "";
    }

    static OGRErr GetSpatialiteGeometryHeader(const GByte *pabyData, int nBytes,
                                              int *pnSRID,
                                              OGRwkbGeometryType *peType,
                                              bool *pbIsEmpty, double *pdfMinX,
                                              double *pdfMinY, double *pdfMaxX,
                                              double *pdfMaxY);
    static OGRErr ImportSpatiaLiteGeometry(const GByte *, int, OGRGeometry **);
    static OGRErr ImportSpatiaLiteGeometry(const GByte *, int, OGRGeometry **,
                                           int *pnSRID);
    static OGRErr ExportSpatiaLiteGeometry(const OGRGeometry *, GInt32,
                                           OGRwkbByteOrder, bool,
                                           bool bUseComprGeom, GByte **, int *);
};

/************************************************************************/
/*                         OGRSQLiteTableLayer                          */
/************************************************************************/

class OGRSQLiteTableLayer final : public OGRSQLiteLayer
{
    bool m_bIsTable = true;

    bool m_bLaunderColumnNames = true;
    bool m_bSpatialite2D = false;
    bool m_bStrict = false;

    CPLString m_osWHERE{};
    CPLString m_osQuery{};
    bool m_bDeferredSpatialIndexCreation = false;

    char *m_pszTableName = nullptr;
    char *m_pszEscapedTableName = nullptr;

    bool m_bLayerDefnError = false;

    sqlite3_stmt *m_hInsertStmt = nullptr;
    CPLString m_osLastInsertStmt{};

    bool m_bHasCheckedTriggers = false;
    bool m_bHasTriedDetectingFID64 = false;

    bool m_bStatisticsNeedsToBeFlushed = false;
    GIntBig m_nFeatureCount = -1; /* if -1, means not up-to-date */

    int m_bDeferredCreation = false;

    char *m_pszCreationGeomFormat = nullptr;
    int m_iFIDAsRegularColumnIndex = -1;

    void ClearInsertStmt();

    void BuildWhere();

    virtual OGRErr ResetStatement() override;

    OGRErr RecomputeOrdinals();

    void AddColumnDef(char *pszNewFieldList, size_t nBufLen,
                      OGRFieldDefn *poFldDefn);

    void InitFieldListForRecrerate(char *&pszNewFieldList,
                                   char *&pszFieldListForSelect,
                                   size_t &nBufLenOut, int nExtraSpace = 0);
    OGRErr RecreateTable(const char *pszFieldListForSelect,
                         const char *pszNewFieldList,
                         const char *pszGenericErrorMessage,
                         const char *pszAdditionalDef = nullptr);
    OGRErr BindValues(OGRFeature *poFeature, sqlite3_stmt *hStmt,
                      bool bBindUnsetAsNull);

    bool CheckSpatialIndexTable(int iGeomCol);

    CPLErr EstablishFeatureDefn(const char *pszGeomCol, bool bMayEmitError);

    void LoadStatistics();
    void LoadStatisticsSpatialite4DB();

    CPLString FieldDefnToSQliteFieldDefn(OGRFieldDefn *poFieldDefn);

    OGRErr RunAddGeometryColumn(const OGRSQLiteGeomFieldDefn *poGeomField,
                                bool bAddColumnsForNonSpatialite);

    CPL_DISALLOW_COPY_ASSIGN(OGRSQLiteTableLayer)

  public:
    explicit OGRSQLiteTableLayer(OGRSQLiteDataSource *);
    virtual ~OGRSQLiteTableLayer();

    CPLErr Initialize(const char *pszTableName, bool bIsTable,
                      bool bIsVirtualShapeIn, bool bDeferredCreation,
                      bool bMayEmitError);
    void SetCreationParameters(const char *pszFIDColumnName,
                               OGRwkbGeometryType eGeomType,
                               const char *pszGeomFormat,
                               const char *pszGeometryName,
                               OGRSpatialReference *poSRS, int nSRSId);
    virtual const char *GetName() override;

    virtual GIntBig GetFeatureCount(int) override;

    virtual OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
                              bool bForce) override;

    virtual OGRFeatureDefn *GetLayerDefn() override;

    bool HasLayerDefnError()
    {
        GetLayerDefn();
        return m_bLayerDefnError;
    }

    virtual OGRErr ISetSpatialFilter(int iGeomField,
                                     const OGRGeometry *) override;
    virtual OGRErr SetAttributeFilter(const char *) override;
    virtual OGRErr ISetFeature(OGRFeature *poFeature) override;
    virtual OGRErr DeleteFeature(GIntBig nFID) override;
    virtual OGRErr ICreateFeature(OGRFeature *poFeature) override;

    virtual OGRErr CreateField(const OGRFieldDefn *poField,
                               int bApproxOK = TRUE) override;
    virtual OGRErr CreateGeomField(const OGRGeomFieldDefn *poGeomFieldIn,
                                   int bApproxOK = TRUE) override;
    virtual OGRErr DeleteField(int iField) override;
    virtual OGRErr ReorderFields(int *panMap) override;
    virtual OGRErr AlterFieldDefn(int iField, OGRFieldDefn *poNewFieldDefn,
                                  int nFlags) override;
    OGRErr AddForeignKeysToTable(const char *pszKeys);

    virtual OGRFeature *GetNextFeature() override;
    virtual OGRFeature *GetFeature(GIntBig nFeatureId) override;

    virtual int TestCapability(const char *) override;

    virtual char **GetMetadata(const char *pszDomain = "") override;
    virtual const char *GetMetadataItem(const char *pszName,
                                        const char *pszDomain = "") override;

    // follow methods are not base class overrides
    void SetLaunderFlag(bool bFlag)
    {
        m_bLaunderColumnNames = bFlag;
    }

    void SetUseCompressGeom(bool bFlag)
    {
        m_bUseComprGeom = bFlag;
    }

    void SetDeferredSpatialIndexCreation(bool bFlag)
    {
        m_bDeferredSpatialIndexCreation = bFlag;
    }

    void SetCompressedColumns(const char *pszCompressedColumns);

    void SetStrictFlag(bool bFlag)
    {
        m_bStrict = bFlag;
    }

    int CreateSpatialIndex(int iGeomCol);

    void CreateSpatialIndexIfNecessary();

    void InitFeatureCount();
    bool DoStatisticsNeedToBeFlushed();
    void ForceStatisticsToBeFlushed();
    bool AreStatisticsValid();
    int SaveStatistics();

    virtual void InvalidateCachedFeatureCountAndExtent() override;

    virtual bool IsTableLayer() override
    {
        return true;
    }

    virtual bool HasSpatialIndex(int iGeomField) override;
    virtual bool HasFastSpatialFilter(int iGeomCol) override;
    virtual CPLString GetSpatialWhere(int iGeomCol,
                                      OGRGeometry *poFilterGeom) override;

    OGRErr RunDeferredCreationIfNecessary();
};

/************************************************************************/
/*                         OGRSQLiteViewLayer                           */
/************************************************************************/

class OGRSQLiteViewLayer final : public OGRSQLiteLayer
{
    CPLString m_osWHERE{};
    CPLString m_osQuery{};
    bool m_bHasCheckedSpatialIndexTable = false;

    OGRSQLiteGeomFormat m_eGeomFormat = OSGF_None;
    CPLString m_osGeomColumn{};
    bool m_bHasSpatialIndex = false;

    char *m_pszViewName = nullptr;
    char *m_pszEscapedTableName = nullptr;
    char *m_pszEscapedUnderlyingTableName = nullptr;

    bool m_bLayerDefnError = false;

    CPLString m_osUnderlyingTableName{};
    CPLString m_osUnderlyingGeometryColumn{};

    OGRSQLiteLayer *m_poUnderlyingLayer = nullptr;

    OGRSQLiteLayer *GetUnderlyingLayer();

    void BuildWhere();

    virtual OGRErr ResetStatement() override;

    CPLErr EstablishFeatureDefn();

    CPL_DISALLOW_COPY_ASSIGN(OGRSQLiteViewLayer)

  public:
    explicit OGRSQLiteViewLayer(OGRSQLiteDataSource *);
    virtual ~OGRSQLiteViewLayer();

    virtual const char *GetName() override
    {
        return m_pszViewName;
    }

    virtual OGRwkbGeometryType GetGeomType() override;

    CPLErr Initialize(const char *pszViewName, const char *pszViewGeometry,
                      const char *pszViewRowid, const char *pszTableName,
                      const char *pszGeometryColumn);

    virtual OGRFeatureDefn *GetLayerDefn() override;

    bool HasLayerDefnError()
    {
        GetLayerDefn();
        return m_bLayerDefnError;
    }

    virtual OGRFeature *GetNextFeature() override;
    virtual GIntBig GetFeatureCount(int) override;

    virtual OGRErr ISetSpatialFilter(int iGeomField,
                                     const OGRGeometry *poGeom) override;

    virtual OGRErr SetAttributeFilter(const char *) override;

    virtual OGRFeature *GetFeature(GIntBig nFeatureId) override;

    virtual int TestCapability(const char *) override;

    virtual bool HasSpatialIndex(CPL_UNUSED int iGeomField) override
    {
        return m_bHasSpatialIndex;
    }

    virtual CPLString GetSpatialWhere(int iGeomCol,
                                      OGRGeometry *poFilterGeom) override;
};

/************************************************************************/
/*                         OGRSQLiteSelectLayer                         */
/************************************************************************/

class OGRSQLiteSelectLayer CPL_NON_FINAL : public OGRSQLiteLayer,
                                           public IOGRSQLiteSelectLayer
{
    OGRSQLiteSelectLayerCommonBehaviour *m_poBehavior = nullptr;
    bool m_bCanReopenBaseDS = false;

    virtual OGRErr ResetStatement() override;

    CPL_DISALLOW_COPY_ASSIGN(OGRSQLiteSelectLayer)

  public:
    OGRSQLiteSelectLayer(OGRSQLiteDataSource *, const CPLString &osSQL,
                         sqlite3_stmt *, bool bUseStatementForGetNextFeature,
                         bool bEmptyLayer, bool bAllowMultipleGeomFields,
                         bool bCanReopenBaseDS);
    virtual ~OGRSQLiteSelectLayer();

    virtual void ResetReading() override;

    virtual OGRFeature *GetNextFeature() override;
    virtual GIntBig GetFeatureCount(int) override;

    virtual OGRErr ISetSpatialFilter(int iGeomField,
                                     const OGRGeometry *) override;
    virtual OGRErr SetAttributeFilter(const char *) override;

    virtual int TestCapability(const char *) override;

    virtual OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
                              bool bForce) override;

    virtual OGRFeatureDefn *GetLayerDefn() override
    {
        return OGRSQLiteLayer::GetLayerDefn();
    }

    virtual char *&GetAttrQueryString() override
    {
        return m_pszAttrQueryString;
    }

    virtual OGRFeatureQuery *&GetFeatureQuery() override
    {
        return m_poAttrQuery;
    }

    virtual OGRGeometry *&GetFilterGeom() override
    {
        return m_poFilterGeom;
    }

    virtual int &GetIGeomFieldFilter() override
    {
        return m_iGeomFieldFilter;
    }

    virtual OGRSpatialReference *GetSpatialRef() override
    {
        return OGRSQLiteLayer::GetSpatialRef();
    }

    virtual int InstallFilter(const OGRGeometry *poGeomIn) override
    {
        return OGRSQLiteLayer::InstallFilter(poGeomIn);
    }

    virtual int HasReadFeature() override
    {
        return m_iNextShapeId > 0;
    }

    virtual void BaseResetReading() override
    {
        OGRSQLiteLayer::ResetReading();
    }

    virtual OGRFeature *BaseGetNextFeature() override
    {
        return OGRSQLiteLayer::GetNextFeature();
    }

    virtual OGRErr BaseSetAttributeFilter(const char *pszQuery) override
    {
        return OGRSQLiteLayer::SetAttributeFilter(pszQuery);
    }

    virtual GIntBig BaseGetFeatureCount(int bForce) override
    {
        return OGRSQLiteLayer::GetFeatureCount(bForce);
    }

    virtual int BaseTestCapability(const char *pszCap) override
    {
        return OGRSQLiteLayer::TestCapability(pszCap);
    }

    virtual OGRErr BaseGetExtent(int iGeomField, OGREnvelope *psExtent,
                                 bool bForce) override
    {
        return OGRSQLiteLayer::IGetExtent(iGeomField, psExtent, bForce);
    }

    bool
    ValidateGeometryFieldIndexForSetSpatialFilter(int iGeomField,
                                                  const OGRGeometry *poGeomIn,
                                                  bool bIsSelectLayer) override
    {
        return OGRSQLiteLayer::ValidateGeometryFieldIndexForSetSpatialFilter(
            iGeomField, poGeomIn, bIsSelectLayer);
    }
};

/************************************************************************/
/*                         OGRSQLiteDataSource                          */
/************************************************************************/

class OGR2SQLITEModule;

class OGRSQLiteDataSource final : public OGRSQLiteBaseDataSource
{
    std::vector<std::unique_ptr<OGRSQLiteLayer>> m_apoLayers{};

    // We maintain a list of known SRID to reduce the number of trips to
    // the database to get SRSes.
    std::map<int,
             std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>>
        m_oSRSCache{};

    OGRSpatialReference *AddSRIDToCache(
        int nId,
        std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
            &&poSRS);

    bool m_bHaveGeometryColumns = false;
    bool m_bIsSpatiaLiteDB = false;
    bool m_bSpatialite4Layout = false;

    int m_nUndefinedSRID = -1;

    virtual void DeleteLayer(const char *pszLayer);

    const char *GetSRTEXTColName();

    bool InitWithEPSG();

    bool OpenVirtualTable(const char *pszName, const char *pszSQL);

    GIntBig m_nFileTimestamp = 0;
    bool m_bLastSQLCommandIsUpdateLayerStatistics = false;

    std::map<CPLString, std::set<CPLString>> m_aoMapTableToSetOfGeomCols{};

    void SaveStatistics();

    std::vector<std::unique_ptr<OGRLayer>> m_apoInvisibleLayers{};

#ifdef HAVE_RASTERLITE2
    void *m_hRL2Ctxt = nullptr;
    bool InitRasterLite2();
    void FinishRasterLite2();

    CPLString m_osCoverageName{};
    GIntBig m_nSectionId = -1;
    rl2CoveragePtr m_pRL2Coverage = nullptr;
    bool m_bRL2MixedResolutions = false;
#endif
    CPLStringList m_aosSubDatasets{};
    bool m_bGeoTransformValid = false;
    double m_adfGeoTransform[6];
    OGRSpatialReference m_oSRS{};
    bool m_bPromote1BitAs8Bit = false;
    bool OpenRaster();
    bool OpenRasterSubDataset(const char *pszConnectionId);
    OGRSQLiteDataSource *m_poParentDS = nullptr;
    std::vector<OGRSQLiteDataSource *> m_apoOverviewDS{};

    OGR2SQLITEModule *m_poSQLiteModule = nullptr;

#ifdef HAVE_RASTERLITE2
    void ListOverviews();
    void CreateRL2OverviewDatasetIfNeeded(double dfXRes, double dfYRes);
#endif

    bool OpenOrCreateDB(int flags, bool bRegisterOGR2SQLiteExtensions);

    CPLErr Close() override;

    void PostInitSpatialite();

    CPL_DISALLOW_COPY_ASSIGN(OGRSQLiteDataSource)

  public:
    OGRSQLiteDataSource();
    virtual ~OGRSQLiteDataSource();

    bool Open(GDALOpenInfo *poOpenInfo);
    bool Create(const char *, char **papszOptions);

    bool OpenTable(const char *pszTableName, bool IsTable, bool bIsVirtualShape,
                   bool bMayEmitError);
    bool OpenView(const char *pszViewName, const char *pszViewGeometry,
                  const char *pszViewRowid, const char *pszTableName,
                  const char *pszGeometryColumn);

    virtual int GetLayerCount() override
    {
        return static_cast<int>(m_apoLayers.size());
    }

    virtual OGRLayer *GetLayer(int) override;
    virtual OGRLayer *GetLayerByName(const char *) override;
    virtual bool IsLayerPrivate(int) const override;
    OGRLayer *GetLayerByNameNotVisible(const char *);
    virtual std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    GetLayerWithGetSpatialWhereByName(const char *pszName) override;

    virtual OGRLayer *ICreateLayer(const char *pszName,
                                   const OGRGeomFieldDefn *poGeomFieldDefn,
                                   CSLConstList papszOptions) override;
    virtual OGRErr DeleteLayer(int) override;

    virtual int TestCapability(const char *) override;

    virtual OGRLayer *ExecuteSQL(const char *pszSQLCommand,
                                 OGRGeometry *poSpatialFilter,
                                 const char *pszDialect) override;
    virtual void ReleaseResultSet(OGRLayer *poLayer) override;

    virtual CPLErr FlushCache(bool bAtClosing) override;

    virtual OGRErr StartTransaction(int bForce = FALSE) override;
    virtual OGRErr CommitTransaction() override;
    virtual OGRErr RollbackTransaction() override;

    virtual char **GetMetadata(const char *pszDomain = "") override;

    virtual CPLErr GetGeoTransform(double *padfGeoTransform) override;
    const OGRSpatialReference *GetSpatialRef() const override;

    static char *LaunderName(const char *);
    int FetchSRSId(const OGRSpatialReference *poSRS);
    OGRSpatialReference *FetchSRS(int nSRID);

    void DisableUpdate()
    {
        eAccess = GA_ReadOnly;
    }

    void SetName(const char *pszNameIn);

    const std::set<CPLString> &GetGeomColsForTable(const char *pszTableName)
    {
        return m_aoMapTableToSetOfGeomCols[pszTableName];
    }

    GIntBig GetFileTimestamp() const
    {
        return m_nFileTimestamp;
    }

    bool IsSpatialiteDB() const
    {
        return m_bIsSpatiaLiteDB;
    }

    bool HasSpatialite4Layout() const
    {
        return m_bSpatialite4Layout;
    }

    int GetUndefinedSRID() const
    {
        return m_nUndefinedSRID;
    }

    bool HasGeometryColumns() const
    {
        return m_bHaveGeometryColumns;
    }

    bool AddRelationship(std::unique_ptr<GDALRelationship> &&relationship,
                         std::string &failureReason) override;
    bool ValidateRelationship(const GDALRelationship *poRelationship,
                              std::string &failureReason);

    void ReloadLayers();

#ifdef HAVE_RASTERLITE2
    void *GetRL2Context() const
    {
        return m_hRL2Ctxt;
    }

    rl2CoveragePtr GetRL2CoveragePtr() const
    {
        return m_pRL2Coverage;
    }

    GIntBig GetSectionId() const
    {
        return m_nSectionId;
    }

    const double *GetGeoTransform() const
    {
        return m_adfGeoTransform;
    }

    bool IsRL2MixedResolutions() const
    {
        return m_bRL2MixedResolutions;
    }

    virtual CPLErr IBuildOverviews(const char *, int, const int *, int,
                                   const int *, GDALProgressFunc, void *,
                                   CSLConstList papszOptions) override;

#endif
    OGRSQLiteDataSource *GetParentDS() const
    {
        return m_poParentDS;
    }

    const std::vector<OGRSQLiteDataSource *> &GetOverviews() const
    {
        return m_apoOverviewDS;
    }

    bool HasPromote1BitAS8Bit() const
    {
        return m_bPromote1BitAs8Bit;
    }
};

#ifdef HAVE_RASTERLITE2
/************************************************************************/
/*                           RL2RasterBand                              */
/************************************************************************/

class RL2RasterBand final : public GDALPamRasterBand
{
    bool m_bHasNoData = false;
    double m_dfNoDataValue = 0;
    GDALColorInterp m_eColorInterp = GCI_Undefined;
    GDALColorTable *m_poCT = nullptr;

    CPL_DISALLOW_COPY_ASSIGN(RL2RasterBand)

  public:
    RL2RasterBand(int nBandIn, int nPixelType, GDALDataType eDT, int nBits,
                  bool bPromote1BitAs8Bit, int nBlockXSizeIn, int nBlockYSizeIn,
                  bool bHasNoDataIn, double dfNoDataValueIn);
    explicit RL2RasterBand(const RL2RasterBand *poOther);

    virtual ~RL2RasterBand();

  protected:
    virtual CPLErr IReadBlock(int, int, void *) override;

    virtual GDALColorInterp GetColorInterpretation() override
    {
        return m_eColorInterp;
    }

    virtual double GetNoDataValue(int *pbSuccess = nullptr) override;
    virtual GDALColorTable *GetColorTable() override;
    virtual int GetOverviewCount() override;
    virtual GDALRasterBand *GetOverview(int) override;
};
#endif  // HAVE_RASTERLITE2

CPLString OGRSQLiteFieldDefnToSQliteFieldDefn(const OGRFieldDefn *poFieldDefn,
                                              bool bSQLiteDialectInternalUse,
                                              bool bStrict);

void OGRSQLiteRegisterInflateDeflate(sqlite3 *hDB);

void OGRSQLiteDriverUnload(GDALDriver *);

#ifdef HAVE_RASTERLITE2
GDALDataset *OGRSQLiteDriverCreateCopy(const char *, GDALDataset *, int,
                                       char **, GDALProgressFunc pfnProgress,
                                       void *pProgressData);
#endif

#endif /* ndef OGR_SQLITE_H_INCLUDED */