BeSQLite.h
Go to the documentation of this file.
1 /*--------------------------------------------------------------------------------------+
2 |
3 | Supplied under applicable software license agreement.
4 |
5 | Copyright (c) 2018 Bentley Systems, Incorporated. All rights reserved.
6 |
7 +---------------------------------------------------------------------------------------*/
8 #pragma once
9 #include <Bentley/Bentley.h>
10 #include <Bentley/bset.h>
11 #if defined (SUPPORT_BRIEFCASE)
12 #include <Bentley/BeId.h>
13 #endif
14 #include <list>
15 #include <type_traits>
16 
17 #ifndef NDEBUG
18 #include <Logging/bentleylogging.h>
19 #endif
20 
23 /****
24 @page BeSQLiteOverview BeSQLite Overview
25 
26 BeSQLite is a Bentley-authored layer to leverage and extend the unique features of SQLite
27 (http://www.sqlite.org/index.html). SQLite is a full-featured SQL database engine that can be embedded inside an
28 application. Unlike enterprise SQL database systems, SQLite has no client/server architecture, and a "SQLte Database" is
29 a disk file. This makes SQLite a wonderful solution for fast and flexible access to locally stored data, but
30 intrinsically limits its relevance for multi-user scenarios. In fact, there are very few scenarios where SQLite and
31 enterprise-level databases are interchangeable. Despite the fact that SQLite supports multiple connections to the same
32 database file from separate processes, BeSQLite is explicitly designed for use cases where the file is stored on a local
33 disk and is only accessed by a single process from a single connection.
34 
35 It is important to recognize that while BeSQLite extends the capabilities of SQLite, <em>it is a strict superset of
36 SQLite</em> and a BeSQLite database file <b>is a</b> SQLite file. Therefore, all SQLite-based utilities and tools will
37 work on a BeSQLite file. Further, the SQL grammar, rules, and idiosyncrasies of SQLite apply equally to BeSQLite. To
38 find the answer to specific SQL-related questions, please consult the SQLite website at http://sqlite.org/lang.html. All
39 SQLite documentation is considered "incorporated by reference" in the BeSQLite documentation and is not repeated here.
40 Exceptions are clearly noted.
41 
42 @section OVRBeSQLiteTransactions 1. Transactions in BeSQLite
43 
44 BeSQLite's transactions are based on SQLite's transactions, and inherit the same guarantees of ACID compliance (see
45 http://sqlite.org/transactional.html). All changes to persistent data are made in the context of a SQLite transaction
46 and are not saved to the database unless and until committed. However, to help coordinate the synchronization of in-memory
47 application data with related persistent data, BeSQLite wraps the SQL- based transaction system with the SavePoint api.
48 Further, SQLite supports a concept called "implicit transactions" that is almost never desirable for a BeSQLite
49 application. Therefore, BeSQLite will start a "default transaction" unless explicitly directed otherwise. When
50 the default transaction is committed, it is automatically restarted.
51 
52 <b>For this reason, it is important that you do not use any of the SQLite Transaction SQL statements BEGIN, END,
53 COMMIT, or ROLLBACK (http://www.sqlite.org/lang_transaction.html) directly in your code.</b> Doing so will cause
54 unpredictable results. Instead, use the methods #BeSQlite::Db::SaveChanges and #BeSQlite::Db::AbandonChanges.
55 
56 Generally, the methods in BeSQLite do not do transaction management themselves, leaving the control of transaction to
57 the application. So, if you call method that changes persistent data, it may potentially make partial changes to the
58 data before encountering an error. When this happens, the active transaction can potentially hold inconsistent data
59 from the perspective of your application. When this happens, you may choose to abandon the entire transaction as appropriate
60 (note: changes are never permanently saved to disk until you call SaveChanges.)
61 
62 @section OVRBeSQLiteRepositories 2. Repositories in BeSQLite
63 
64 Many layers that use BeSQLite are designed to work with a single process with a single (exclusive) connection to a
65 database file. That means that in a multi-user scenario, every user must have their own @i private copy of the
66 database. We refer to each user's copy of the database as a "briefcase" (following the convention of Mercurial and Git
67 for Distributed Revision Control, see http://en.wikipedia.org/wiki/Distributed_revision_control.) Each briefcase stores
68 its own 4-byte identifier, referred to as its @c BeBriefcaseId, that distinguishes it from all other repositories.
69 Changes made in each briefcase can then be merged together in an orderly fashion by coordinating with a team server.
70 Team servers are also responsible for assigning and tracking BeBriefcaseIds.
71 
72 @section OVRBeSQLiteIds 3. Ids in BeSQLite
73 
74 Since each user has a local copy of the briefcase, Ids in BeSQLite must be carefully managed. There are several
75 approaches:
76 
77  -# Use Globally Unique Identifiers (GUID, See #BeGuid). A globally unique identifier is a 16 byte randomly assigned
78 value. 16 bytes hold enough data that there is virtually no chance of collision. Unfortunately, 16 bytes will not fit
79 into registers of current generation computers, making them relatively expensive to handle programmatically. For large
80 tables, GUIDs can add significant overhead for lookups and are much more expensive than 8-byte values. This usually
81 makes them a <i>poor choice for primary keys.</i> However, as the name implies, when you use a GUID, you never need to
82 worry about uniqueness.
83 
84  -# Use #BeBriefcaseBasedIds. A BeBriefcaseBasedId is an 8-byte number that is designed to be unique by combining the
85 4-byte BeBriefcaseId with a unique-within-the-briefcase 4-byte value. This limits the number of potential values
86 within a BeBriefcase to 2^32 (4 billion). Of course it permits 4 billion different BeRepositories. It is often the best
87 compromise of performance and flexibility for tables with lots of activity.
88 
89  -# Use #BeServerIssuedId. A BeServerIssuedId is an 8-byte number that is unique because it is issued by a
90 synchronized id-administration server, enforced outside of the scope of BeSQLite. BeServerIssuedIds therefore cannot be
91 created locally and require a connection to the (one, globally administered) server to obtain a new value. Generally
92 they are useful for "rarely changed but often used" ids such as styles and fonts, etc.
93 
94 @section OVRBeSQLiteProperties 4. Properties and Settings
95 
96 Every BeSQlite database has a table named "be_Prop" that can be used to save name-id-value triplets, referred to as
97 Properties. Properties are often used for storing ad-hoc values that don't warrant the creation of a specific
98 class/table. The "name" for a Property is defined by a #PropertySpec that includes a two-part namespace/name to uniquely
99 identify the property. The id for a Property is also a two-part majorId/subId pair to permit arrays.
100 
101 A PropertySpec has a flag that indicates that it is a "Setting." When Settings are changed, their value remains in
102 effect only for the duration of the session, unless an explicit call to #Db::SaveSettings is made. If the database is
103 closed without a call to Db::SaveSettings, the changes are not saved.
104 
105 @section OVRBeSQLiteProperties 5. Briefcase Local Values
106 
107 Every BeSQLite database has a table named "be_local" that can be used to save name-value pairs that are specific to the
108 BeBriefcase and not merged with the team server. They are used to keep track of the state of the local file and are not
109 considered part of the "real" database.
110 
111 @section OVRBeSQLiteEmbeddedFiles 6. Embedded Files
112 
113 Every BeSQLite database has a table named "be_EmbedFile" that holds copies of files that are "embedded in" the database.
114 These files are stored as blobs, and are not directly accessible by external applications. Instead, BeSQLite provides
115 methods to extract them into temporary locations.
116 
117 @section OVRBeSQLiteLanguageSupport 7. Support for language-specific collation and case-folding
118 
119 By default, BeSQLite does not support language-specific collation, and performs case-folding only for the ASCII
120 character set. However, applications can extend BeSQLite by implementing the #BeSQLiteLib::ILanguageSupport interface.
121 
122 */
123 
124 #define BE_SQLITE_EXPORT IMPORT_ATTRIBUTE
125 
126 #define TEMP_TABLE_Prefix "temp."
127 #define TEMP_TABLE(name) TEMP_TABLE_Prefix name
128 
129 // the "unique temporary table" macros can be used for temporary tables that shadow a real table, but use a unique name.
130 #define TEMP_TABLE_UniquePrefix TEMP_TABLE_Prefix "t_"
131 #define TEMP_TABLE_UNIQUE(name) TEMP_TABLE_UniquePrefix name
132 
133 #define BEDB_TABLE_Local "be_Local"
134 #define BEDB_TABLE_Property "be_Prop"
135 #define BEDB_TABLE_EmbeddedFile "be_EmbedFile"
136 #define BEDB_MemoryDb ":memory:"
137 
138 #define BEGIN_BENTLEY_SQLITE_NAMESPACE BEGIN_BENTLEY_NAMESPACE namespace BeSQLite {
139 #define END_BENTLEY_SQLITE_NAMESPACE } END_BENTLEY_NAMESPACE
140 #define USING_NAMESPACE_BENTLEY_SQLITE using namespace Bentley::BeSQLite;
141 
142 #include <Bentley/BeFile.h>
143 #include <Bentley/BeThread.h>
144 #include <Bentley/WString.h>
146 #include <Bentley/bvector.h>
147 #include <Bentley/bmap.h>
148 #include <Bentley/RefCounted.h>
149 #include <Bentley/DateTime.h>
150 #include <Bentley/BeVersion.h>
151 
152 
153 // this is used to quiet compiler warnings for variables only used in asserts
154 #define UNUSED_VARIABLE(x) (void)(x)
155 
156 #define BESQLITE_TYPEDEFS(_name_) BEGIN_BENTLEY_SQLITE_NAMESPACE DEFINE_POINTER_SUFFIX_TYPEDEFS(_name_) END_BENTLEY_SQLITE_NAMESPACE
157 
163 
164 #if !defined (DOCUMENTATION_GENERATOR)
165 #ifndef GUID_DEFINED
166 #define GUID_DEFINED
167 typedef struct _GUID
168 {
169  uint32_t Data1;
170  unsigned short Data2;
171  unsigned short Data3;
172  unsigned char Data4[8];
173 } GUID;
174 #endif
175 
176 typedef struct sqlite3_blob* SqlDbBlobP;
177 typedef struct sqlite3* SqlDbP;
178 typedef struct sqlite3& SqlDbR;
179 typedef struct sqlite3_stmt* SqlStatementP;
180 typedef struct sqlite3_session* SqlSessionP;
181 typedef struct sqlite3_changeset_iter* SqlChangesetIterP;
182 typedef struct Mem* SqlValueP;
183 
184 #endif // DOCUMENTATION_GENERATOR
185 
187 
188 //=======================================================================================
190 // @bsiclass Bentley Systems
191 //=======================================================================================
192 struct BeGuid
193 {
194  union{struct _GUID g; uint64_t u[2]; uint32_t i[4]; uint8_t b[16];} m_guid;
195 
199  explicit BeGuid(bool createValue=false) {if (createValue) Create(); else Invalidate();}
200 
202  BeGuid(uint64_t u0, uint64_t u1) {m_guid.u[0]=u0; m_guid.u[1]=u1;}
203 
205  BeGuid(uint32_t i0, uint32_t i1, uint32_t i2, uint32_t i3) {m_guid.i[0]=i0; m_guid.i[1]=i1; m_guid.i[2]=i2; m_guid.i[3]=i3;}
206 
208  bool operator==(BeGuid const& rhs) const {return rhs.m_guid.u[0]==m_guid.u[0] && rhs.m_guid.u[1]==m_guid.u[1];}
209 
211  bool operator!=(BeGuid const& rhs) const {return !(*this==rhs);}
212 
214  bool operator<(BeGuid const& rhs) const {return m_guid.u[0] < rhs.m_guid.u[0] || m_guid.u[0] == rhs.m_guid.u[0] && m_guid.u[1] < rhs.m_guid.u[1];}
215 
217  void Invalidate() {m_guid.u[0] = m_guid.u[1] = 0;}
218 
220  bool IsValid() const {return 0!=m_guid.u[0] && 0!=m_guid.u[1];}
221 
224  BE_SQLITE_EXPORT void Create();
225 
228  BE_SQLITE_EXPORT Utf8String ToString() const;
229 
233  BE_SQLITE_EXPORT BentleyStatus FromString(Utf8CP str);
234 };
235 
236 //=======================================================================================
241 // @bsiclass Bentley Systems
242 //=======================================================================================
244 {
245 protected:
247 
248 public:
249  static uint32_t const MaxRepo() {return 1L<<24;}
250  static uint32_t const Master() {return 0;}
251  static uint32_t const Standalone() {return 1;}
252  static uint32_t const Illegal() {return (uint32_t)0xffffffff;}
253 
255  BeBriefcaseId() {Invalidate();}
256  explicit BeBriefcaseId(uint32_t u) {m_id=u;}
257  void Invalidate() {m_id = Illegal();}
258  bool IsValid() const {return Illegal() != m_id;}
259  bool IsMasterId() const {return Master()==m_id;}
260  bool IsStandaloneId() const {return Standalone()==m_id;}
261  uint32_t GetValue() const {BeAssert(IsValid()); BeAssert(m_id<MaxRepo()); return m_id;}
262  bool operator==(BeBriefcaseId const& rhs) const {return rhs.m_id==m_id;}
263  bool operator!=(BeBriefcaseId const& rhs) const {return !(*this == rhs);}
264 };
265 
266 #if defined (SUPPORT_BRIEFCASE)
267 //=======================================================================================
270 // @bsiclass Bentley Systems
271 //=======================================================================================
272 struct BeBriefcaseBasedId : BeInt64Id
273 {
274  BEINT64_ID_DECLARE_MEMBERS(BeBriefcaseBasedId,BeInt64Id)
275 
276 public:
277  static uint64_t const MaxLocal() {return 1LL<<40;} // top 24 bits are BeBriefcaseId, lower 40 bits are local id
278 
280  BeBriefcaseBasedId(BeBriefcaseId briefcaseId, uint64_t id) {BeAssert(id<MaxLocal()); m_id = ((briefcaseId.GetValue() * MaxLocal()) + id);}
281 
282  BeBriefcaseId GetBriefcaseId() const {return BeBriefcaseId((uint32_t) (m_id / MaxLocal()));}
283 
286  BE_SQLITE_EXPORT void UseNext(Db&);
287 
294  BE_SQLITE_EXPORT BeBriefcaseBasedId(Db& db, Utf8CP tableName, Utf8CP columnName);
295 };
296 
297 #define BEBRIEFCASEBASED_ID_SUBCLASS(classname,superclass) struct classname : superclass { \
298  classname(BeSQLite::BeBriefcaseId briefcaseId, uint64_t id) : superclass(briefcaseId,id){} \
299  classname(BeSQLite::Db& db, Utf8CP tableName, Utf8CP columnName) : superclass(db,tableName,columnName){} \
300  BEINT64_ID_DECLARE_MEMBERS(classname,superclass) };
301 
302 #define BEBRIEFCASEBASED_ID_CLASS(classname) BEBRIEFCASEBASED_ID_SUBCLASS(classname,BeSQLite::BeBriefcaseBasedId)
303 
304 //=======================================================================================
306 // @bsiclass Bentley Systems
307 //=======================================================================================
308 struct BeServerIssuedId : BeInt64Id
309 {
310  BEINT64_ID_DECLARE_MEMBERS(BeServerIssuedId,BeInt64Id)
311 };
312 
313 #define BESERVER_ISSUED_ID_SUBCLASS(classname,superclass) struct classname : superclass {BEINT64_ID_DECLARE_MEMBERS(classname,superclass)};
314 #define BESERVER_ISSUED_ID_CLASS(classname) BESERVER_ISSUED_ID_SUBCLASS(classname,BeSQLite::BeServerIssuedId)
315 
316 #endif
317 
318 //=======================================================================================
319 // @bsiclass Bentley Systems
320 //=======================================================================================
322 {
328 };
329 
330 //=======================================================================================
331 // The profile version for BeSQLite database files created by this version of the BeSQLite library
332 // @bsiclass Bentley Systems
333 //=======================================================================================
335  {
340 
341  BEDB_SUPPORTED_VERSION_Major = BEDB_CURRENT_VERSION_Major, // oldest version of the db schema supported by current api
345  };
346 
347 //=======================================================================================
349 // @bsiclass Bentley Systems
350 //=======================================================================================
352 {
353 public:
354  ProfileVersion(uint16_t major, uint16_t minor, uint16_t sub1, uint16_t sub2) : BeVersion(major, minor, sub1, sub2) {}
355  explicit ProfileVersion(Utf8CP json) {FromJson(json);}
356  BE_SQLITE_EXPORT Utf8String ToJson() const;
357  BE_SQLITE_EXPORT void FromJson(Utf8CP);
358 };
359 
360 //=======================================================================================
361 // @bsiclass Bentley Systems
362 //=======================================================================================
364 {
394 
418 
433 
442 
444 
446 
450 
452 
456 
458 
468 };
469 
470 //=======================================================================================
471 // @bsiclass Bentley Systems
472 //=======================================================================================
473 enum class DbOpcode : int
474 {
475  Delete = 9,
476  Insert = 18,
477  Update = 23,
478 };
479 
480 //=======================================================================================
481 // @bsiclass Bentley Systems
482 //=======================================================================================
483 enum class DbValueType : int
484 {
485  IntegerVal = 1,
486  FloatVal = 2,
487  TextVal = 3,
488  BlobVal = 4,
489  NullVal = 5,
490 };
491 
492 //=======================================================================================
493 // Utility class to initialize the BeSQLite library and directly use a few SQLite APIs.
494 // @bsiclass Bentley Systems
495 //=======================================================================================
497 {
498 public:
499  //=======================================================================================
502  // @bsiclass Bentley Systems
503  //=======================================================================================
505  {
507  typedef void(*CollationUserDataFreeFunc)(void*);
508 
512  {
514  void* m_collator;
515  };
516 
519  virtual void _Lower(Utf16CP source, int sourceLen, Utf16CP result, int resultLen) = 0;
520 
523  virtual void _Upper(Utf16CP source, int sourceLen, Utf16CP result, int resultLen) = 0;
524 
527  virtual void _InitCollation(bvector<CollationEntry>& collations, CollationUserDataFreeFunc& collatorFreeFunc) = 0;
528 
531  virtual int _Collate(Utf16CP lhs, int lhsLen, Utf16CP rhs, int rhsLen, void* collator) = 0;
532 
535  virtual uint32_t _FoldCase(uint32_t) = 0;
536  };
537 
538  enum class LogErrors : bool {Yes=1, No=0};
539 
546  BE_SQLITE_EXPORT static DbResult Initialize(BeFileNameCR tempDir, LogErrors wantLogging=LogErrors::No);
547 
552  BE_SQLITE_EXPORT static void Randomness(int numBytes, void* random);
553 
555  static void* MallocMem(int sz);
556 
558  static void* ReallocMem(void* p, int sz);
559 
561  static void FreeMem(void* p);
562 
563  BE_SQLITE_EXPORT static int CloseSqlDb(void* p);
564 
565  BE_SQLITE_EXPORT static void SetDownloadAdmin(struct IDownloadAdmin&);
566 
567  BE_SQLITE_EXPORT static struct IDownloadAdmin* GetDownloadAdmin();
568 
571  BE_SQLITE_EXPORT static void SetLanguageSupport(ILanguageSupport*);
572 
574  BE_SQLITE_EXPORT static ILanguageSupport* GetLanguageSupport();
575 
576  static int GetBaseDbResult(DbResult val) {return 0xff & val;}
577  static bool TestBaseDbResult(DbResult val1, DbResult val2) {return GetBaseDbResult(val1) == GetBaseDbResult(val2);}
578  static bool IsConstraintDbResult(DbResult val1) {return GetBaseDbResult(val1) == BE_SQLITE_CONSTRAINT_BASE;}
579 };
580 
581 //=======================================================================================
584 // @bsiclass Bentley Systems
585 //=======================================================================================
587 {
588 private:
589  SqlStatementP m_stmt;
590 
591  DbResult DoPrepare(DbFileCR, Utf8CP sql);
592 
593 public:
594  enum class MakeCopy : bool {No=0, Yes=1};
595  explicit Statement(SqlStatementP stmt) {m_stmt=stmt;}
596 
598  Statement() {m_stmt=nullptr;}
599  Statement(DbCR db, Utf8CP sql) {m_stmt=nullptr; Prepare(db, sql);}
600  ~Statement() {Finalize();}
601 
602  SqlStatementP& GetStmtR() {return m_stmt;}
603  DbResult Prepare(DbFileCR, Utf8CP sql, bool suppressDiagnostics = false);
604 
606  bool IsPrepared() const {return nullptr != m_stmt;}
607 
609  BE_SQLITE_EXPORT void Finalize();
610 
615  BE_SQLITE_EXPORT DbResult Prepare(DbCR db, Utf8CP sql);
616 
621  BE_SQLITE_EXPORT DbResult TryPrepare(DbCR db, Utf8CP sql);
622 
625  BE_SQLITE_EXPORT DbResult Step();
626 
629  BE_SQLITE_EXPORT DbResult Reset();
630 
633  BE_SQLITE_EXPORT DbResult ClearBindings();
634 
639  BE_SQLITE_EXPORT DbResult BindInt(int paramNum, int value);
640 
645  BE_SQLITE_EXPORT DbResult BindInt64(int paramNum, int64_t value);
646 
651  DbResult BindUInt64(int paramNum, uint64_t value) {return BindInt64(paramNum, (int64_t) value);}
652 
656  DbResult BindBoolean(int paramNum, bool value) {return BindInt(paramNum, value ? 1 : 0);}
657 
658 #if defined (SUPPORT_BRIEFCASE)
659  DbResult BindId(int paramNum, BeInt64Id value) {return value.IsValid() ? BindUInt64(paramNum,value.GetValue()) : BindNull(paramNum);}
663 #endif
664 
669  BE_SQLITE_EXPORT DbResult BindDouble(int paramNum, double value);
670 
676  DbResult BindText(int paramNum, Utf8StringCR stringValue, MakeCopy makeCopy) {return BindText(paramNum, stringValue.c_str(), makeCopy, (int)stringValue.size());}
677 
684  BE_SQLITE_EXPORT DbResult BindText(int paramNum, Utf8CP stringValue, MakeCopy makeCopy, int nBytes=-1);
685 
690  BE_SQLITE_EXPORT DbResult BindGuid(int paramNum, BeGuidCR value);
691 
696  BE_SQLITE_EXPORT DbResult BindZeroBlob(int paramNum, int size);
697 
704  BE_SQLITE_EXPORT DbResult BindBlob(int paramNum, void const* blobValue, int size, MakeCopy makeCopy);
705 
709  BE_SQLITE_EXPORT DbResult BindNull(int paramNum);
710 
715  BE_SQLITE_EXPORT DbResult BindVirtualSet(int paramNum, struct VirtualSet const& vSet);
716 
719  BE_SQLITE_EXPORT DbResult BindDbValue(int paramNum, struct DbValue const& dbVal);
720 
723  BE_SQLITE_EXPORT int GetColumnCount();
724 
728  BE_SQLITE_EXPORT DbValueType GetColumnType(int col);
729 
733  BE_SQLITE_EXPORT Utf8CP GetColumnTableName(int col);
734 
738  BE_SQLITE_EXPORT Utf8CP GetColumnDeclaredType(int col);
739 
741  bool IsColumnNull(int col) {return DbValueType::NullVal == GetColumnType(col);}
742 
746  BE_SQLITE_EXPORT Utf8CP GetColumnName(int col);
747 
751  BE_SQLITE_EXPORT int GetColumnBytes(int col);
752 
756  BE_SQLITE_EXPORT int GetColumnBytes16(int col);
757 
761  BE_SQLITE_EXPORT void const* GetValueBlob(int col);
762 
766  BE_SQLITE_EXPORT Utf8CP GetValueText(int col);
767 
771  BE_SQLITE_EXPORT int GetValueInt(int col);
772 
776  BE_SQLITE_EXPORT int64_t GetValueInt64(int col);
777 
781  uint64_t GetValueUInt64(int col) {return (uint64_t) GetValueInt64(col);}
782 
788  bool GetValueBoolean(int col) {return GetValueInt(col) != 0;}
789 
793  BE_SQLITE_EXPORT double GetValueDouble(int col);
794 
797  template <class T_Id> T_Id GetValueId(int col) {if (!IsColumnNull(col)) {return T_Id(GetValueUInt64(col));} return T_Id();}
798 
802  BE_SQLITE_EXPORT BeGuid GetValueGuid(int col);
803 
808  BE_SQLITE_EXPORT struct DbDupValue GetDbValue(int col);
809 
813  BE_SQLITE_EXPORT int GetParameterIndex(Utf8CP name);
814 
820  BE_SQLITE_EXPORT int GetParameterCount();
821 
824  BE_SQLITE_EXPORT Utf8CP GetSql() const;
825 
827  BE_SQLITE_EXPORT void DumpResults();
828 
829  SqlStatementP GetSqlStatementP() const {return m_stmt;} // for direct use of sqlite3 api
830  operator SqlStatementP(){return m_stmt;} // for direct use of sqlite3 api
831 };
832 
833 #define DIAGNOSTICS_PREPARE_LOGGER_NAME L"Diagnostics.BeSQLite.Prepare"
834 #define DIAGNOSTICS_QUERYPLAN_LOGGER_NAME L"Diagnostics.BeSQLite.QueryPlan"
835 #define DIAGNOSTICS_QUERYPLANWITHTABLESCANS_LOGGER_NAME L"Diagnostics.BeSQLite.QueryPlanWithTableScans"
836 
837 #ifdef NDEBUG
838 #define STATEMENT_DIAGNOSTICS_ON
839 #define STATEMENT_DIAGNOSTICS_OFF
840 #define STATEMENT_DIAGNOSTICS_LOGCOMMENT(comment)
841 #else
842 #define STATEMENT_DIAGNOSTICS_ON StatementDiagnostics::SetIsEnabled(true);
843 #define STATEMENT_DIAGNOSTICS_OFF StatementDiagnostics::SetIsEnabled(false);
844 #define STATEMENT_DIAGNOSTICS_LOGCOMMENT(comment) StatementDiagnostics::LogComment(comment)
845 
846 //=======================================================================================
876 // @bsiclass Bentley Systems
877 //=======================================================================================
879  {
880 private:
882 
883 public:
888  BE_SQLITE_EXPORT static void SetIsEnabled(bool isEnabled);
889 
891  BE_SQLITE_EXPORT static void LogComment(Utf8CP comment);
892  };
893 #endif
894 
895 //=======================================================================================
897 // @bsiclass Bentley Systems
898 //=======================================================================================
899 struct BlobIO
900 {
901 private:
902  SqlDbBlobP m_blob;
903 
904 public:
905  SqlDbBlobP GetBlobP() {return m_blob;}
906  BlobIO() {m_blob=0;}
907  ~BlobIO() {Close();}
908 
918  BE_SQLITE_EXPORT DbResult Open(DbR db, Utf8CP tableName, Utf8CP columnName, uint64_t row, bool writable, Utf8CP dbName=0);
919 
924  BE_SQLITE_EXPORT DbResult ReOpen(uint64_t row);
925 
929  BE_SQLITE_EXPORT DbResult Close();
930 
937  BE_SQLITE_EXPORT DbResult Read(void* data, int numBytes, int offset);
938 
945  BE_SQLITE_EXPORT DbResult Write(const void* data, int numBytes, int offset);
946 
950  BE_SQLITE_EXPORT int GetNumBytes() const;
951 
953  bool IsValid() const {return nullptr != m_blob;}
954 };
955 
956 //=======================================================================================
958 // @bsiclass Bentley Systems
959 //=======================================================================================
960 struct DbValue
961 {
962 protected:
963  SqlValueP m_val;
964 
965 public:
966  DbValue(SqlValueP val) : m_val(val) {}
967 
968  bool IsValid() const {return nullptr != m_val;}
969  bool IsNull() const {return DbValueType::NullVal == GetValueType();}
970  SqlValueP GetSqlValueP() const {return m_val;}
971 
972  BE_SQLITE_EXPORT DbValueType GetValueType() const;
973  BE_SQLITE_EXPORT DbValueType GetNumericType() const;
974  BE_SQLITE_EXPORT int GetValueBytes() const;
975  BE_SQLITE_EXPORT void const* GetValueBlob() const;
976  BE_SQLITE_EXPORT Utf8CP GetValueText() const;
977  BE_SQLITE_EXPORT int GetValueInt() const;
978  BE_SQLITE_EXPORT int64_t GetValueInt64() const;
979  uint64_t GetValueUInt64() const {return (uint64_t) GetValueInt64();}
980  BE_SQLITE_EXPORT double GetValueDouble() const;
981  BE_SQLITE_EXPORT BeGuid GetValueGuid() const;
982  template <class T_Id> T_Id GetValueId() const {return T_Id(GetValueUInt64());}
983 
984  BE_SQLITE_EXPORT Utf8String Format(int detailLevel) const;
985 };
986 
987 //=======================================================================================
991 // @bsiclass Bentley Systems
992 //=======================================================================================
994 {
995  BE_SQLITE_EXPORT DbDupValue(SqlValueP val);
996  DbDupValue(DbDupValue&& other) : DbValue(other.m_val) {other.m_val = nullptr;}
997  BE_SQLITE_EXPORT DbDupValue& operator=(DbDupValue&& other);
998  BE_SQLITE_EXPORT ~DbDupValue();
999 };
1000 
1001 //=======================================================================================
1004 // @bsiclass Bentley Systems
1005 //=======================================================================================
1007 {
1008 public:
1009  //=======================================================================================
1011  // @bsiclass Bentley Systems
1012  //=======================================================================================
1013  struct Context
1014  {
1015  enum class CopyData : int {No = 0, Yes = -1};
1016  BE_SQLITE_EXPORT void SetResultBlob(void const* value, int length, CopyData copy=CopyData::Yes);
1017  BE_SQLITE_EXPORT void SetResultDouble(double);
1018  BE_SQLITE_EXPORT void SetResultError(Utf8CP, int len=-1);
1019  BE_SQLITE_EXPORT void SetResultError_toobig();
1020  BE_SQLITE_EXPORT void SetResultError_nomem();
1021  BE_SQLITE_EXPORT void SetResultError_code(int);
1022  BE_SQLITE_EXPORT void SetResultInt(int);
1023  BE_SQLITE_EXPORT void SetResultInt64(int64_t);
1024  BE_SQLITE_EXPORT void SetResultNull();
1025  BE_SQLITE_EXPORT void SetResultText(Utf8CP value, int length, CopyData);
1026  BE_SQLITE_EXPORT void SetResultZeroblob(int length);
1027  BE_SQLITE_EXPORT void SetResultValue(DbValue);
1028  BE_SQLITE_EXPORT void* GetAggregateContext(int nbytes);
1029  };
1030 
1031 private:
1032  Utf8String m_name;
1033  int m_nArgs;
1034  DbValueType m_returnType;
1035 
1036 protected:
1041  DbFunction(Utf8CP name, int nArgs, DbValueType returnType) : m_name(name), m_nArgs(nArgs), m_returnType(returnType) {}
1042 
1043 public:
1044  virtual bool _IsAggregate() {return false;}
1045  virtual ~DbFunction() {}
1046  Utf8CP GetName() const {return m_name.c_str();}
1047  int GetNumArgs() const {return m_nArgs;}
1048  DbValueType GetReturnType() const {return m_returnType;}
1049 
1051  void SetInputError(Context& ctx) {ctx.SetResultError(Utf8PrintfString("Illegal input to %s", GetName()).c_str());}
1052 };
1053 
1054 //=======================================================================================
1057 // @bsiclass Bentley Systems
1058 //=======================================================================================
1060 {
1061  virtual void _ComputeScalar(Context&, int nArgs, DbValue* args) = 0; //<! see "xFunc" in sqlite3_create_function
1062 
1067  ScalarFunction(Utf8CP name, int nArgs, DbValueType returnType = DbValueType::NullVal) : DbFunction(name, nArgs, returnType) {}
1068 };
1069 //=======================================================================================
1072 // @bsiclass Bentley Systems
1073 //=======================================================================================
1075 {
1076  bool _IsAggregate() override {return true;}
1077  virtual void _StepAggregate(Context&, int nArgs, DbValue* args) = 0; //<! see "xStep" in sqlite3_create_function
1078  virtual void _FinishAggregate(Context&) = 0; //<! see "xFinal" in sqlite3_create_function
1079 
1084  AggregateFunction(Utf8CP name, int nArgs, DbValueType returnType = DbValueType::NullVal) : DbFunction(name, nArgs, returnType) {}
1085 };
1086 
1087 //=======================================================================================
1090 // @bsiclass Bentley Systems
1091 //=======================================================================================
1093 {
1094  enum class Within : int
1095  {
1096  Outside = 0,
1097  Partly = 1,
1098  Inside = 2,
1099  };
1100 
1101  //=======================================================================================
1103  // @bsiclass Bentley Systems
1104  //=======================================================================================
1105  struct QueryInfo
1106  {
1107  void* m_context;
1109  double* m_param;
1110  void* m_user;
1111  void (*m_xDelUser)(void*);
1112  double* m_coords;
1113  unsigned int* m_nQueue;
1115  int m_level;
1120  mutable Within m_within;
1121  mutable double m_score;
1122  DbValue* m_args; // SQL values of parameters
1123  };
1124 
1127  virtual int _TestRange(QueryInfo const&) = 0;
1128 
1129  RTreeMatchFunction(Utf8CP name, int nArgs) : DbFunction(name, nArgs, DbValueType::NullVal) {}
1130 };
1131 
1132 //=======================================================================================
1138 // @bsiclass Bentley Systems
1139 //=======================================================================================
1141 {
1148  virtual bool _IsInSet(int nVals, DbValue const* vals) const = 0;
1149 };
1150 
1151 #if defined (SUPPORT_BRIEFCASE)
1152 //=======================================================================================
1153 // @bsiclass Bentley Systems
1154 //=======================================================================================
1155 struct BeIdSet : bset<BeInt64Id>
1156 {
1157 private:
1158  Utf8String ToReadableString() const;
1159  void FromCompactString(Utf8StringCR);
1160  void FromReadableString(Utf8StringCR);
1161 public:
1162  enum class StringFormat {Compact=0, Readable=1};
1163 
1164  BE_SQLITE_EXPORT void FromString(Utf8StringCR in);
1165  BE_SQLITE_EXPORT Utf8String ToString() const;
1166  BE_SQLITE_EXPORT Utf8String ToCompactString() const; // NB: This method is NOT backwards-compatible!
1167 };
1168 
1169 //=======================================================================================
1170 // @bsiclass Bentley Systems
1171 //=======================================================================================
1172 template<typename IdType> struct IdSet : VirtualSet
1173 {
1174 private:
1175  BeIdSet m_set;
1176 
1177  virtual bool _IsInSet(int nVals, DbValue const* vals) const override
1178  {
1179  BeAssert(nVals == 1);
1180  return Contains(IdType(vals[0].GetValueUInt64()));
1181  }
1182 public:
1183  IdSet() {static_assert(std::is_base_of<BeInt64Id, IdType>::value && sizeof(BeInt64Id) == sizeof(IdType), "IdSet may only contain BeInt64Ids or subclasses of it of the same size.");}
1184  virtual ~IdSet() {}
1185 
1186  typedef IdSet<IdType> T_Self;
1187  typedef bset<IdType> T_SetType;
1188  typedef typename T_SetType::const_iterator const_iterator;
1189  typedef typename T_SetType::iterator iterator;
1190 
1191  const_iterator begin() const {return ((T_SetType&)m_set).begin();}
1192  const_iterator end() const {return ((T_SetType&)m_set).end();}
1193  const_iterator find(IdType id) const {return ((T_SetType&)m_set).find(id);}
1194  bool operator==(T_Self const& other) const {return m_set==other.m_set;}
1195  bool operator!=(T_Self const& other) const {return m_set!=other.m_set;}
1196  bool empty() const {return m_set.empty();}
1197  void clear() {m_set.clear();}
1198  size_t size() const {return m_set.size();}
1199  bpair<iterator,bool> insert(IdType const& val) {BeAssert(val.IsValid()); return ((T_SetType&)m_set).insert(val);}
1200  void insert(const_iterator first, const_iterator last) {((T_SetType&)m_set).insert(first,last);}
1201  size_t erase(IdType const& val) {return ((T_SetType&)m_set).erase(val);}
1202  iterator erase(iterator it) {return ((T_SetType&)m_set).erase(it);}
1203  bool Contains(IdType id) const {return end() != find(id);}
1204  void FromString(Utf8StringCR in) {m_set.FromString(in);}
1205  Utf8String ToString() const {return m_set.ToString();}
1206 
1207  BeIdSet const& GetBeIdSet() const {return m_set;}
1208 };
1209 #endif
1210 
1211 //=======================================================================================
1213 // @bsiclass Bentley Systems
1214 //=======================================================================================
1216 {
1217 private:
1218  Utf8P m_str;
1219 public:
1222  BE_SQLITE_EXPORT ~SqlPrintfString();
1223  operator Utf8CP(){return m_str;}
1224  Utf8CP GetUtf8CP() {return m_str;}
1225 };
1226 
1227 //=======================================================================================
1229 // @bsiclass Bentley Systems
1230 //=======================================================================================
1232 {
1233 private:
1234  void* m_mux;
1235 public:
1236  enum class MutexType : bool {Fast=0, Recursive=1};
1237  BE_SQLITE_EXPORT BeDbMutex(MutexType mutexType=MutexType::Fast);
1239  BE_SQLITE_EXPORT void Enter();
1240  BE_SQLITE_EXPORT void Leave();
1241 #ifndef NDEBUG
1242  BE_SQLITE_EXPORT bool IsHeld();
1243 #endif
1244 };
1245 
1246 //=======================================================================================
1248 // @bsiclass Bentley Systems
1249 //=======================================================================================
1251 {
1253  BeDbMutexHolder(BeDbMutex& mutex) : m_mutex(mutex) {m_mutex.Enter();}
1254  ~BeDbMutexHolder() {m_mutex.Leave();}
1255 };
1256 
1257 //=======================================================================================
1259 // @bsiclass Bentley Systems
1260 //=======================================================================================
1262 {
1263  friend struct StatementCache;
1264 private:
1265  mutable BeAtomic<uint32_t> m_refCount;
1266  bool m_inCache;
1267  struct StatementCache const& m_myCache;
1268  Utf8CP m_sql;
1269  CachedStatement(Utf8CP sql, struct StatementCache const&);
1270  ~CachedStatement();
1271 
1272 public:
1274 
1275  uint32_t AddRef() const {return m_refCount.IncrementAtomicPre();}
1276  uint32_t GetRefCount() const {return m_refCount.load();}
1277  BE_SQLITE_EXPORT uint32_t Release();
1278  Utf8CP GetSQL() const {return m_sql;}
1279 };
1280 
1282 
1283 //=======================================================================================
1288 // @bsiclass Bentley Systems
1289 //=======================================================================================
1291 {
1292  friend struct CachedStatement;
1293 private:
1294  typedef std::list<CachedStatementPtr> Entries;
1295  mutable BeMutex m_mutex;
1296  mutable Entries m_entries;
1297  uint32_t m_size;
1298  Entries::iterator FindEntry(Utf8CP) const;
1299  BE_SQLITE_EXPORT void AddStatement(CachedStatementPtr& newEntry, Utf8CP sql) const;
1300  BE_SQLITE_EXPORT void FindStatement(CachedStatementPtr&, Utf8CP) const;
1301 
1302 public:
1304  ~StatementCache() {Empty();}
1305 
1306  BE_SQLITE_EXPORT DbResult GetPreparedStatement(CachedStatementPtr&, DbFile const& dbFile, Utf8CP sqlString) const;
1307  BE_SQLITE_EXPORT void Dump() const;
1308  BE_SQLITE_EXPORT void Empty();
1309  bool IsEmpty() const {return m_entries.empty();}
1310 };
1311 
1312 //=======================================================================================
1327 // @bsiclass Bentley Systems
1328 //=======================================================================================
1330 {
1331 public:
1333  {
1335  SqlParameter(Utf8CP name) : m_name(name) {}
1336  virtual void _Bind(Statement&) = 0;
1337  };
1338 
1339 private:
1340  typedef RefCountedPtr<SqlParameter> SqlParameterPtr;
1341  Utf8String m_where;
1342  bvector<SqlParameterPtr> m_params;
1343 
1344 public:
1348  void AddSqlParameter(SqlParameter* param) {m_params.push_back(param);}
1349 
1353  BE_SQLITE_EXPORT void AddStringParameter(Utf8CP name, Utf8CP val);
1354 
1358  BE_SQLITE_EXPORT void AddIntegerParameter(Utf8CP name, uint64_t val);
1359 
1363  BE_SQLITE_EXPORT void AddDoubleParameter(Utf8CP name, double val);
1364 
1370  BE_SQLITE_EXPORT void AddBlobParameter(Utf8CP name, void const* data, int size, Statement::MakeCopy copy);
1371 
1374  NamedParams(Utf8CP where=nullptr) {SetWhere(where);}
1375 
1381  BE_SQLITE_EXPORT void SetWhere(Utf8CP where);
1382 
1384  Utf8StringCR GetWhere() const {return m_where;}
1385 
1388  BE_SQLITE_EXPORT void Bind(Statement& stmt) const;
1389 };
1390 
1391 //=======================================================================================
1404 // @bsiclass Bentley Systems
1405 //=======================================================================================
1407 {
1408 protected:
1409  mutable DbP m_db;
1410  mutable CachedStatementPtr m_stmt;
1412 
1413  explicit DbTableIterator(DbCR db) : m_db((DbP)&db) {}
1414 
1416  DbTableIterator(DbTableIterator&& rhs) : m_db(rhs.m_db), m_stmt(std::move(rhs.m_stmt)), m_params(rhs.m_params) {}
1417 
1418  BE_SQLITE_EXPORT Utf8String MakeSqlString(Utf8CP sql, bool hasWhere=false) const;
1419 
1420 public:
1421  struct Entry
1422  {
1423  protected:
1426  Entry(StatementP sql, bool isValid) {m_sql=sql; m_isValid=isValid;}
1427  void Verify() const {BeAssert(nullptr != m_sql->GetSqlStatementP());}
1428 
1429  public:
1430  bool IsValid() const {return m_isValid && (nullptr!=m_sql->GetSqlStatementP());}
1431  void Invalidate() {m_isValid=false;}
1432 
1433  Entry& operator++() {m_isValid=(BeSQLite::BE_SQLITE_ROW == m_sql->Step()); return *this;}
1434  Entry const& operator* () const {return *this;}
1435  bool operator!=(Entry const& rhs) const {return (m_isValid != rhs.m_isValid);}
1436  bool operator==(Entry const& rhs) const {return (m_isValid == rhs.m_isValid);}
1437  };
1438 
1440  Statement* GetStatement() {return m_stmt.get();}
1441 
1444  NamedParams& Params() {return m_params;}
1445 };
1446 
1447 //=======================================================================================
1450 // @bsiclass Bentley Systems
1451 //=======================================================================================
1453 {
1457  virtual StatusInt _Progress(uint64_t inSize, int64_t outSize) = 0;
1458 };
1459 
1460 #if defined (SUPPORT_EMBEDDED_FILE)
1461 //=======================================================================================
1470 // @bsiclass Bentley Systems
1471 //=======================================================================================
1472 struct DbEmbeddedFileTable
1473 {
1474 private:
1475  friend struct Db;
1476  DbR m_db;
1477  DbEmbeddedFileTable(DbR db) : m_db(db) {}
1478 
1479  BeBriefcaseBasedId GetNextEmbedFileId() const;
1480 
1481 public:
1482  //=======================================================================================
1484  // @bsiclass Bentley Systems
1485  //=======================================================================================
1486  struct Iterator : DbTableIterator
1487  {
1488  public:
1489  explicit Iterator(DbCR db) : DbTableIterator(db) {}
1490 
1491  struct Entry : DbTableIterator::Entry, std::iterator<std::input_iterator_tag, Entry const>
1492  {
1493  private:
1494  friend struct Iterator;
1495  Entry(StatementP sql, bool isValid) : DbTableIterator::Entry(sql,isValid) {}
1496  public:
1497  BE_SQLITE_EXPORT Utf8CP GetNameUtf8() const;
1498  BE_SQLITE_EXPORT Utf8CP GetDescriptionUtf8() const;
1499  BE_SQLITE_EXPORT Utf8CP GetTypeUtf8() const;
1500  BE_SQLITE_EXPORT uint64_t GetFileSize() const;
1501  BE_SQLITE_EXPORT uint32_t GetChunkSize() const;
1502  BE_SQLITE_EXPORT DateTime GetLastModified() const;
1503  BE_SQLITE_EXPORT BeBriefcaseBasedId GetId() const;
1504  Entry const& operator* () const {return *this;}
1505  };
1506 
1507  typedef Entry const_iterator;
1508  typedef const_iterator iterator;
1509  BE_SQLITE_EXPORT const_iterator begin() const;
1510  const_iterator end() const {return Entry(nullptr, false);}
1511  BE_SQLITE_EXPORT size_t QueryCount() const;
1512  };
1514  Iterator MakeIterator() const {return Iterator(m_db);}
1515 
1524  BE_SQLITE_EXPORT BeBriefcaseBasedId QueryFile(Utf8CP name, uint64_t* totalSize = nullptr, uint32_t* chunkSize = nullptr, Utf8StringP descr = nullptr, Utf8StringP typeStr = nullptr, DateTime* lastModified = nullptr);
1525 
1538  BE_SQLITE_EXPORT BeBriefcaseBasedId ImportWithoutCompressing(DbResult* stat, Utf8CP name, Utf8CP localFileName, Utf8CP typeStr, Utf8CP description = nullptr, DateTime const* lastModified = nullptr, uint32_t chunkSize = 500 * 1024);
1539 
1562  BE_SQLITE_EXPORT BeBriefcaseBasedId ImportDbFile(DbResult& stat, Utf8CP name, Utf8CP localFileName, Utf8CP typeStr, Utf8CP description = nullptr, DateTime const* lastModified = nullptr, uint32_t chunkSize = 500 * 1024, bool supportRandomAccess = true);
1563 
1576  BE_SQLITE_EXPORT BeBriefcaseBasedId Import(DbResult* stat, Utf8CP name, Utf8CP localFileName, Utf8CP typeStr, Utf8CP description = nullptr, DateTime const* lastModified = nullptr, uint32_t chunkSize = 500 * 1024, bool supportRandomAccess = true);
1577 
1589  DbResult Import(Utf8CP name, Utf8CP localFileName, Utf8CP typeStr, Utf8CP description = nullptr, uint32_t chunkSize = 500 * 1024, bool supportRandomAccess = true)
1590  {
1591  DbResult stat = BE_SQLITE_OK;
1592  Import(&stat, name, localFileName, typeStr, description, nullptr, chunkSize, supportRandomAccess);
1593  return stat;
1594  }
1595 
1613  BE_SQLITE_EXPORT DbResult ExportDbFile(Utf8CP localFileName, Utf8CP name, ICompressProgressTracker* progress=nullptr);
1614 
1620  BE_SQLITE_EXPORT DbResult Export(Utf8CP localFileName, Utf8CP name, ICompressProgressTracker* progress=nullptr);
1621 
1627 
1635  BE_SQLITE_EXPORT DbResult Replace(Utf8CP name, Utf8CP localFileName, uint32_t chunkSize=500*1024, DateTime const* lastModified = nullptr);
1636 
1644  BE_SQLITE_EXPORT DbResult AddEntry(Utf8CP name, Utf8CP typeStr, Utf8CP description = nullptr, DateTime const* lastModified = nullptr);
1645 
1657  BE_SQLITE_EXPORT DbResult Save(void const* data, uint64_t size, Utf8CP name, DateTime const* lastModified = nullptr, bool compress=true, uint32_t chunkSize=500*1024);
1658 
1659 
1664 
1666  DbResult CreateTable() const;
1667 };
1668 #endif
1669 
1671 enum class BeSQLiteTxnMode : int {None=0, Deferred=1, Immediate=2, Exclusive=3,};
1672 
1674 enum class DefaultTxn : int
1675 {
1678  No = (int) BeSQLiteTxnMode::None,
1680  Yes = (int) BeSQLiteTxnMode::Deferred,
1683  Immediate = (int) BeSQLiteTxnMode::Immediate,
1688  Exclusive = (int) BeSQLiteTxnMode::Exclusive
1689 };
1690 
1691 //=======================================================================================
1703 // @bsiclass Bentley Systems
1704 //=======================================================================================
1706 {
1707 #if !defined (DOCUMENTATION_GENERATOR)
1708 protected:
1709  friend struct DbFile;
1710  Db* m_db;
1711  DbFile* m_dbFile;
1712  int32_t m_depth;
1713  BeSQLiteTxnMode m_txnMode;
1714  Utf8String m_name;
1715 
1716  virtual void _OnDeactivate(bool isCommit) {m_depth=-1;}
1717  BE_SQLITE_EXPORT virtual DbResult _Begin(BeSQLiteTxnMode);
1718  BE_SQLITE_EXPORT virtual DbResult _Commit(Utf8CP operation);
1719  BE_SQLITE_EXPORT virtual DbResult _Cancel();
1720 
1721  Savepoint(DbFile& db, Utf8CP name, BeSQLiteTxnMode txnMode) : m_dbFile(&db), m_name(name), m_txnMode(txnMode) {m_db=nullptr; m_depth = -1;}
1722 #endif
1723 
1724 public:
1730  BE_SQLITE_EXPORT Savepoint(Db& db, Utf8CP name, bool beginTxn=true, BeSQLiteTxnMode txnMode=BeSQLiteTxnMode::Deferred);
1731 
1733  virtual ~Savepoint() {Commit(nullptr);}
1734 
1736  bool IsActive() const {return GetDepth() >= 0;}
1737 
1739  int32_t GetDepth() const {return m_depth;}
1740 
1742  Utf8CP GetName() const {return m_name.c_str();}
1743 
1745  BeSQLiteTxnMode GetTxnMode() const {return m_txnMode;}
1746 
1748  void SetTxnMode(BeSQLiteTxnMode mode) {m_txnMode = mode;}
1749 
1754 
1756  DbResult Begin() {return Begin(m_txnMode);}
1757 
1764  BE_SQLITE_EXPORT DbResult Commit(Utf8CP operation=nullptr);
1765 
1768  DbResult Save(Utf8CP operation) {Commit(operation); return Begin();}
1769 
1772 };
1773 
1774 //=======================================================================================
1795 // @bsiclass Bentley Systems
1796 //=======================================================================================
1798 {
1799 public:
1801  enum class Compress
1802  {
1804  No=0,
1805 
1808  Yes=1
1809  };
1810 
1811  enum class Mode {Normal=0, Setting=1, Cached=2,};
1812 
1813 private:
1814  Mode m_mode;
1815  Compress m_compress;
1816  bool m_saveIfNull;
1817  Utf8CP m_name;
1818  Utf8CP m_namespace;
1819 
1820 public:
1829  PropertySpec(Utf8CP name, Utf8CP nameSpace, Mode mode=Mode::Normal, Compress compress=Compress::Yes, bool saveIfNull=false) : m_name(name), m_namespace(nameSpace), m_compress(compress), m_mode(mode), m_saveIfNull(saveIfNull){}
1830 
1832  PropertySpec(PropertySpec const& other, Mode mode) {*this = other; m_mode=mode;}
1833 
1834  Utf8CP GetName() const {return m_name;}
1835  Utf8CP GetNamespace() const {return m_namespace;}
1836 
1837  bool IsSetting() const {return Mode::Setting == m_mode;}
1838  bool IsCached() const {return Mode::Cached == m_mode;}
1839  bool SaveIfNull() const {return m_saveIfNull;}
1840  bool IsCompress() const {return Compress::Yes==m_compress;}
1841 };
1842 
1844 
1845 //=======================================================================================
1847 // @bsiclass Bentley Systems
1848 //=======================================================================================
1850 {
1855  virtual int _OnBusy(int count) const {if (count>4) return 0; BeThreadUtilities::BeSleep(1000); return 1;}
1856 };
1857 
1858 //=======================================================================================
1859 // Cached "briefcase local values"
1861 // @bsiclass Bentley Systems
1862 //=======================================================================================
1863 struct CachedBLV
1864 {
1865 private:
1866  Utf8String m_name;
1867  bool m_isUnset;
1868  mutable bool m_dirty;
1869  uint64_t m_value;
1870 
1871 public:
1872  explicit CachedBLV(Utf8CP name);
1873  Utf8CP GetName() const {return m_name.c_str();}
1874  uint64_t GetValue() const {BeAssert(!m_isUnset); return m_value;}
1875  void ChangeValue(uint64_t value, bool initializing = false);
1876  uint64_t Increment();
1877  bool IsUnset() const {return m_isUnset;}
1878  bool IsDirty() const {BeAssert(!m_isUnset); return m_dirty;}
1879  void SetIsNotDirty() const;
1880  void Reset();
1881 };
1882 
1883 //=======================================================================================
1884 // Cache for uint64_t BriefcaseLocalValues. This is for BLV's that are of type uint64_t and are frequently
1885 // accessed and/or modified. The BLVs are identified in the cache by "registering" their name are thereafter
1886 // accessed by index. The cache is held in memory for performance. It is automatically saved whenever a transaction is committed.
1888 // @bsiclass Bentley Systems
1889 //=======================================================================================
1890 struct BriefcaseLocalValueCache : NonCopyableClass
1891 {
1892 private:
1893  friend struct DbFile;
1894  friend struct Db;
1895  bvector<CachedBLV> m_cache;
1896  DbFile& m_dbFile;
1897  mutable BeMutex m_mutex;
1898 
1899  void Clear();
1900  bool TryQuery(CachedBLV*&, size_t rlvIndex);
1901 
1902 public:
1903  BriefcaseLocalValueCache(DbFile& dbFile) : m_dbFile(dbFile) {}
1904 
1912  BE_SQLITE_EXPORT DbResult Register(size_t& rlvIndex, Utf8CP rlvName);
1913 
1919  BE_SQLITE_EXPORT bool TryGetIndex(size_t& rlvIndex, Utf8CP rlvName);
1920 
1926  BE_SQLITE_EXPORT DbResult SaveValue(size_t rlvIndex, uint64_t value);
1927 
1933  BE_SQLITE_EXPORT DbResult QueryValue(uint64_t& value, size_t rlvIndex);
1934 
1941  BE_SQLITE_EXPORT DbResult IncrementValue(uint64_t& newValue, size_t rlvIndex);
1942 };
1943 
1944 //=======================================================================================
1946 // @bsiclass Bentley Systems
1947 //=======================================================================================
1949 {
1950  friend struct Db;
1951  friend struct Statement;
1952  friend struct Savepoint;
1953 
1954 protected:
1957  typedef bvector<Savepoint*> DbTxns;
1958  typedef DbTxns::iterator DbTxnIter;
1959 
1964  mutable bool m_readonly;
1965  uint64_t m_dataVersion; // for detecting changes from another process
1966  SqlDbP m_sqlDb;
1969  mutable void* m_cachedProps;
1970  BriefcaseLocalValueCache m_blvCache;
1976 
1977  explicit DbFile(SqlDbP sqlDb, BusyRetry* retry, BeSQLiteTxnMode defaultTxnMode);
1978  ~DbFile();
1979  DbResult StartSavepoint(Savepoint&, BeSQLiteTxnMode);
1980  DbResult StopSavepoint(Savepoint&, bool isCommit, Utf8CP operation);
1981  DbResult CreatePropertyTable(Utf8CP tablename, Utf8CP ddl, bool temp);
1982  DbResult SaveCachedProperty(PropertySpecCR spec, uint64_t id, uint64_t subId, Utf8CP stringData, void const* value, uint32_t size) const;
1983  struct CachedProperyMap& GetCachedPropMap() const;
1984  struct CachedPropertyValue& GetCachedProperty(PropertySpecCR spec, uint64_t id, uint64_t subId) const;
1985  struct CachedPropertyValue* FindCachedProperty(PropertySpecCR spec, uint64_t id, uint64_t subId) const;
1986  DbResult QueryCachedProperty(Utf8String*, void** value, uint32_t size, PropertySpecCR spec, uint64_t id, uint64_t subId) const;
1987  void DeleteCachedProperty(PropertySpecCR spec, uint64_t id, uint64_t subId);
1988  void DeleteCachedPropertyMap();
1989  void SaveCachedProperties(bool isCommit);
1990  Utf8String GetLastError(DbResult* lastResult) const;
1991  void SaveCachedBlvs(bool isCommit);
1992  BE_SQLITE_EXPORT DbResult SaveProperty(PropertySpecCR spec, Utf8CP strData, void const* value, uint32_t propsize, uint64_t majorId=0, uint64_t subId=0);
1993  BE_SQLITE_EXPORT bool HasProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const;
1994  BE_SQLITE_EXPORT DbResult QueryPropertySize(uint32_t& propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const;
1995  BE_SQLITE_EXPORT DbResult QueryProperty(void* value, uint32_t propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const;
1996  BE_SQLITE_EXPORT DbResult QueryProperty(Utf8StringR value, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const;
1997  BE_SQLITE_EXPORT void SaveSettings();
1998  BE_SQLITE_EXPORT DbResult DeleteProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0);
1999  BE_SQLITE_EXPORT DbResult DeleteProperties(PropertySpecCR spec, uint64_t* majorId);
2000  BE_SQLITE_EXPORT int AddFunction(DbFunction& function) const;
2001  BE_SQLITE_EXPORT int AddRTreeMatchFunction(RTreeMatchFunction& function) const;
2002  BE_SQLITE_EXPORT int RemoveFunction(DbFunction&) const;
2003  BE_SQLITE_EXPORT BriefcaseLocalValueCache& GetBLVCache();
2004 
2005 public:
2006  Utf8String ExplainQuery(Utf8CP sql, bool explainPlan, bool suppressDiagnostics) const;
2007  int OnCommit();
2008  bool UseSettingsTable(PropertySpecCR spec) const;
2009  void OnSettingsDirtied() {m_settingsDirty=true;}
2010  bool CheckImplicitTxn() const {return m_allowImplicitTxns || m_txns.size() > 0;}
2011  SqlDbP GetSqlDb() const {return m_sqlDb;}
2012 };
2013 
2014 //=======================================================================================
2018 // @bsiclass Bentley Systems
2019 //=======================================================================================
2021 {
2022  friend struct DbFile;
2023 public:
2024  enum class Encoding {Utf8=0, Utf16=1};
2025  enum class PageSize : int
2026  {
2027  PAGESIZE_1K = 1024,
2028  PAGESIZE_512 = PAGESIZE_1K / 2,
2029  PAGESIZE_2K = PAGESIZE_1K * 2,
2030  PAGESIZE_4K = PAGESIZE_1K * 4,
2031  PAGESIZE_8K = PAGESIZE_1K * 8,
2032  PAGESIZE_16K = PAGESIZE_1K * 16,
2033  PAGESIZE_32K = PAGESIZE_1K * 32,
2034  PAGESIZE_64K = PAGESIZE_1K * 64
2035  };
2036 
2038  enum class OpenMode {Readonly = 1<<0, ReadWrite = 1<<1, Create = ReadWrite|(1<<2), SharedCache = 1<<17, };
2039 
2040  //=======================================================================================
2042  // @bsiclass Bentley Systems
2043  //=======================================================================================
2045  {
2048  mutable bool m_forSchemaUpgrade;
2051 
2052  BE_SQLITE_EXPORT virtual bool _ReopenForProfileUpgrade(Db&) const;
2053 
2059  BE_SQLITE_EXPORT explicit OpenParams(OpenMode openMode, DefaultTxn startDefaultTxn=DefaultTxn::Yes, BusyRetry* retry=nullptr);
2060 
2068  void SetRawSQLite() {m_rawSQLite=true;}
2069 
2071  bool IsRawSQLite() const {return m_rawSQLite;}
2072 
2074  bool IsReadonly() const {return m_openMode==OpenMode::Readonly;}
2075 
2077  void SetOpenMode(OpenMode openMode) {m_openMode = openMode;}
2078 
2082  void SetStartDefaultTxn(DefaultTxn val) {m_startDefaultTxn = val;}
2083  };
2084 
2085  //=======================================================================================
2087  // @bsiclass Bentley Systems
2088  //=======================================================================================
2090  {
2093  enum CompressedDb {CompressDb_None=0,CompressDb_Zlib=1,CompressDb_Snappy=2,} m_compressedDb;
2094  enum ApplicationId : uint64_t {APPLICATION_ID_BeSQLiteDb='BeDb',} m_applicationId;
2098 
2107  explicit CreateParams(PageSize pagesize=PageSize::PAGESIZE_4K, Encoding encoding=Encoding::Utf8, bool failIfDbExists=true,
2108  DefaultTxn defaultTxn=DefaultTxn::Yes, BusyRetry* retry=nullptr, bool createStandalone=false)
2109  : OpenParams(OpenMode::Create, defaultTxn, retry), m_encoding(encoding), m_pagesize(pagesize), m_compressedDb(CompressDb_None),
2110  m_failIfDbExists(failIfDbExists), m_applicationId(APPLICATION_ID_BeSQLiteDb), m_createStandalone(createStandalone) {;}
2111 
2113  void SetPageSize(PageSize pagesize) {m_pagesize = pagesize;}
2115  void SetEncoding(Encoding encoding) {m_encoding = encoding;}
2117  void SetFailIfDbExist(bool val) {m_failIfDbExists = val;}
2119  void SetCompressMode(CompressedDb val) {m_compressedDb=val;}
2121  void SetApplicationId(ApplicationId applicationId) {m_applicationId=applicationId;}
2123  void SetExpirationDate(DateTime xdate) {m_expirationDate=xdate;}
2125  void SetCreateStandalone(bool val) {m_createStandalone=val;}
2126  };
2127 
2128  //=======================================================================================
2130  // @bsiclass Bentley Systems
2131  //=======================================================================================
2133  {
2134  struct Key : NonCopyableClass {};
2135  };
2136 
2137 protected:
2140 #if defined (SUPPORT_EMBEDDED_FILE)
2141  DbEmbeddedFileTable m_embeddedFiles;
2142 #endif
2143  mutable bmap<AppData::Key const*, RefCountedPtr<AppData>, std::less<AppData::Key const*>, 8> m_appData;
2144 
2150  virtual DbResult _OnDbCreated(CreateParams const& params) {return BE_SQLITE_OK;}
2151 
2154  virtual void _OnSaveSettings() {}
2155 
2159  virtual DbResult _OnDbOpening() {return QueryDbIds();}
2160 
2164  virtual DbResult _OnDbOpened() {return BE_SQLITE_OK;}
2165 
2168  virtual void _OnDbClose() {}
2169 
2176  BE_SQLITE_EXPORT virtual void _OnDbChangedByOtherConnection();
2177 
2180  virtual DbResult _OnBriefcaseIdChanged(BeBriefcaseId newBriefcaseId) {return BE_SQLITE_OK;}
2181 
2207  virtual DbResult _VerifyProfileVersion(OpenParams const& params) {return BE_SQLITE_OK;}
2208 
2209  virtual int _OnAddFunction(DbFunction& func) const {return 0;}
2210  virtual void _OnRemoveFunction(DbFunction& func) const {}
2211 
2212  friend struct Statement;
2213  friend struct Savepoint;
2214  friend struct BeSQLiteProfileManager;
2215 
2216 private:
2217  BE_SQLITE_EXPORT DbResult QueryDbIds();
2218  DbResult SaveBeDbGuid();
2219  DbResult SaveBriefcaseId();
2220  void DoCloseDb();
2221  DbResult DoOpenDb(Utf8CP dbName, OpenParams const& params);
2222  DbResult TruncateTable(Utf8CP tableName) const;
2223  DbResult ClearBriefcaseLocalValues();
2224  void SetupBlvSaveStmt(Statement& stmt, Utf8CP name);
2225  DbResult ExecBlvQueryStmt(Statement& stmt, Utf8CP name) const;
2226 
2227 public:
2228  BE_SQLITE_EXPORT Db();
2229  BE_SQLITE_EXPORT virtual ~Db();
2230 
2231  DbFile* GetDbFile() {return m_dbFile;}
2232 
2239  BE_SQLITE_EXPORT void SetAllowImplictTransactions(bool val);
2240 
2242  StatementCache& GetStatementCache() const {return const_cast<StatementCache&>(m_statements);}
2243 
2251  BE_SQLITE_EXPORT DbResult GetCachedStatement(CachedStatementPtr& statement, Utf8CP sql) const;
2252 
2253  CachedStatementPtr GetCachedStatement(Utf8CP sql) const {CachedStatementPtr stmt; GetCachedStatement(stmt, sql); return stmt;}
2254 
2258  BE_SQLITE_EXPORT Savepoint* GetSavepoint(int32_t depth) const;
2259 
2261  BE_SQLITE_EXPORT int32_t GetCurrentSavepointDepth() const;
2262 
2264  bool IsTransactionActive() const {return 0 < GetCurrentSavepointDepth();}
2265 
2315  BE_SQLITE_EXPORT DbResult OpenBeSQLiteDb(Utf8CP dbName, OpenParams const& openParams);
2316 
2318  DbResult OpenBeSQLiteDb(BeFileNameCR dbName, OpenParams const& openParams) {return OpenBeSQLiteDb(dbName.GetNameUtf8().c_str(),openParams);}
2319 
2332  BE_SQLITE_EXPORT DbResult CreateNewDb(Utf8CP dbName, BeGuid dbGuid=BeGuid(), CreateParams const& params=CreateParams());
2333 
2335  {return CreateNewDb(dbName.GetNameUtf8().c_str(), dbGuid, params);}
2336 
2338  BE_SQLITE_EXPORT bool IsDbOpen() const;
2339 
2343  BE_SQLITE_EXPORT void CloseDb();
2344 
2346  BE_SQLITE_EXPORT Utf8CP GetDbFileName() const;
2347 
2349  BE_SQLITE_EXPORT void SaveProjectGuid(BeGuid);
2350 
2353  BE_SQLITE_EXPORT BeGuid QueryProjectGuid() const;
2354 
2357  BE_SQLITE_EXPORT DbResult SaveCreationDate();
2358 
2362  BE_SQLITE_EXPORT DbResult QueryCreationDate(DateTime& creationDate) const;
2363 
2369  BE_SQLITE_EXPORT DbResult AttachDb(Utf8CP filename, Utf8CP alias);
2370 
2373  BE_SQLITE_EXPORT DbResult DetachDb(Utf8CP alias);
2374 
2380  BE_SQLITE_EXPORT DbResult ExecuteSql(Utf8CP sql, int(*callback)(void*,int,char**,char**)=0, void* arg=0, char** errmsg=0) const;
2381 
2383  BE_SQLITE_EXPORT DbResult TryExecuteSql(Utf8CP sql, int (*callback)(void*,int,char**,char**)=0, void* arg=0, char** errmsg=0) const;
2384 
2386  BE_SQLITE_EXPORT Utf8String ExplainQuery(Utf8CP sql, bool plan=true) const;
2387 
2391  BE_SQLITE_EXPORT DbResult CreateTable(Utf8CP tableName, Utf8CP ddl) const;
2392 
2394  BE_SQLITE_EXPORT DbResult DropTable(Utf8CP tableName) const;
2395 
2397  BE_SQLITE_EXPORT bool TableExists(Utf8CP tableName) const;
2398 
2405  BE_SQLITE_EXPORT DbResult AddColumnToTable(Utf8CP tableName, Utf8CP columnName, Utf8CP columnDetails);
2406 
2408  BE_SQLITE_EXPORT bool ColumnExists(Utf8CP tableName, Utf8CP columnName) const;
2409 
2413  BE_SQLITE_EXPORT bool GetColumns(bvector<Utf8String>& columns, Utf8CP tableName) const;
2414 
2418  BE_SQLITE_EXPORT DbResult RenameTable(Utf8CP tableName, Utf8CP newTableName);
2419 
2426  BE_SQLITE_EXPORT DbResult CreateIndex(Utf8CP indexName, Utf8CP tableName, bool isUnique, Utf8CP columnName1, Utf8CP columnName2 = nullptr);
2427 
2429  BE_SQLITE_EXPORT void FlushPageCache();
2430 
2433 
2435  DbResult SaveProperty(PropertySpecCR spec, Utf8StringCR strData, void const* value, uint32_t propsize, uint64_t majorId=0, uint64_t subId=0) {return m_dbFile->SaveProperty(spec, strData.c_str(), value, propsize, majorId, subId);}
2436 
2444  DbResult SaveProperty(PropertySpecCR spec, void const* value, uint32_t propsize, uint64_t majorId=0, uint64_t subId=0) {return m_dbFile->SaveProperty(spec, nullptr, value, propsize, majorId, subId);}
2445 
2452  DbResult SavePropertyString(PropertySpecCR spec, Utf8CP value, uint64_t majorId=0, uint64_t subId=0) {return m_dbFile->SaveProperty(spec, value, nullptr, 0, majorId, subId);}
2453 
2460  DbResult SavePropertyString(PropertySpecCR spec, Utf8StringCR value, uint64_t majorId=0, uint64_t subId=0) {return SavePropertyString(spec, value.c_str(), majorId, subId);}
2461 
2467  bool HasProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const {return m_dbFile->HasProperty(spec, majorId, subId);}
2468 
2476  DbResult QueryPropertySize(uint32_t& propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const {return m_dbFile->QueryPropertySize(propsize, spec, majorId, subId);}
2477 
2487  DbResult QueryProperty(void* value, uint32_t propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const {return m_dbFile->QueryProperty(value, propsize, spec, majorId, subId);}
2488 
2496  DbResult QueryProperty(Utf8StringR value, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const {return m_dbFile->QueryProperty(value, spec, majorId, subId);}
2497 
2503  DbResult DeleteProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) {return m_dbFile->DeleteProperty(spec, majorId, subId);}
2504 
2509  DbResult DeleteProperties(PropertySpecCR spec, uint64_t* majorId) {return m_dbFile->DeleteProperties(spec, majorId);}
2510 
2514  BE_SQLITE_EXPORT void SaveSettings();
2516 
2521 
2523  BriefcaseLocalValueCache& GetBLVCache() {return m_dbFile->GetBLVCache();}
2524 
2529  BE_SQLITE_EXPORT DbResult QueryBriefcaseLocalValue(Utf8StringR value, Utf8CP name) const;
2530  BE_SQLITE_EXPORT DbResult QueryBriefcaseLocalValue(uint64_t& value, Utf8CP name) const;
2531 
2536  BE_SQLITE_EXPORT DbResult SaveBriefcaseLocalValue(Utf8CP name, Utf8StringCR value);
2537  BE_SQLITE_EXPORT DbResult SaveBriefcaseLocalValue(Utf8CP name, uint64_t value);
2538 
2540  BE_SQLITE_EXPORT DbResult DeleteBriefcaseLocalValue(Utf8CP name);
2542 
2545  BE_SQLITE_EXPORT int64_t GetLastInsertRowId() const;
2546 
2549  BE_SQLITE_EXPORT int GetModifiedRowCount() const;
2550 
2554  BE_SQLITE_EXPORT Utf8String GetLastError(DbResult* lastResult = nullptr) const;
2555 
2560  BE_SQLITE_EXPORT DbResult SaveChanges(Utf8CP changesetName=nullptr);
2561  DbResult SaveChanges(Utf8StringCR changesetName) {return SaveChanges(changesetName.c_str());}
2562 
2565  BE_SQLITE_EXPORT DbResult AbandonChanges();
2566 
2568  BE_SQLITE_EXPORT SqlDbP GetSqlDb() const;
2569 
2571  BE_SQLITE_EXPORT BeGuid GetDbGuid() const;
2572 
2574  BE_SQLITE_EXPORT BeBriefcaseId GetBriefcaseId() const;
2575 
2576 #if defined (SUPPORT_BRIEFCASE)
2577  BE_SQLITE_EXPORT DbResult GetServerIssuedId(BeServerIssuedId& value, Utf8CP tableName, Utf8CP columnName, Utf8CP json=nullptr);
2583 #endif
2584 
2586  BE_SQLITE_EXPORT bool IsReadonly() const;
2587 
2588 #if defined (SUPPORT_EMBEDDED_FILE)
2589  BE_SQLITE_EXPORT DbEmbeddedFileTable& EmbeddedFiles();
2591 #endif
2592 
2600  BE_SQLITE_EXPORT void AddAppData(AppData::Key const& key, AppData* appData) const;
2601 
2605  BE_SQLITE_EXPORT StatusInt DropAppData(AppData::Key const& key) const;
2606 
2609  BE_SQLITE_EXPORT AppData* FindAppData(AppData::Key const& key) const;
2610 
2612  BE_SQLITE_EXPORT void DumpSqlResults(Utf8CP sql);
2613 
2615  BE_SQLITE_EXPORT static Utf8CP InterpretDbResult(DbResult result);
2616 
2618  BE_SQLITE_EXPORT int SetLimit(int id, int newVal);
2619 
2622  BE_SQLITE_EXPORT int AddFunction(DbFunction& func) const;
2623 
2625  BE_SQLITE_EXPORT int RemoveFunction(DbFunction& func) const;
2626 
2627  BE_SQLITE_EXPORT int AddRTreeMatchFunction(RTreeMatchFunction& func) const;
2628 
2629  BE_SQLITE_EXPORT void ChangeDbGuid(BeGuid);
2630 
2632  BE_SQLITE_EXPORT DbResult ChangeBriefcaseId(BeBriefcaseId);
2633 
2637  BE_SQLITE_EXPORT void SetChangeTracker(ChangeTracker* tracker);
2638 
2639  BE_SQLITE_EXPORT bool IsSettingProperty(Utf8CP space, Utf8CP name, uint64_t id, uint64_t subId) const;
2640  Savepoint* GetDefaultTransaction() const {return (m_dbFile != nullptr) ? &m_dbFile->m_defaultTxn : nullptr;}
2641 
2662  BE_SQLITE_EXPORT static DbResult CheckProfileVersion(bool& fileIsAutoUpgradable, ProfileVersion const& expectedProfileVersion, ProfileVersion const& actualProfileVersion, ProfileVersion const& minimumUpgradableProfileVersion, bool openModeIsReadonly, Utf8CP profileName);
2663 
2668  BE_SQLITE_EXPORT DbResult UpgradeBeSQLiteProfile();
2669 
2672  BE_SQLITE_EXPORT bool IsExpired() const;
2673 
2679  BE_SQLITE_EXPORT DbResult QueryExpirationDate(DateTime& expirationDate) const;
2680 
2685  BE_SQLITE_EXPORT DbResult SaveExpirationDate(DateTime const& expirationDate);
2686 };
2687 
2688 //=======================================================================================
2690 // @bsiclass Bentley Systems
2691 //=======================================================================================
2693 {
2695  ZIP_ERROR_BASE = 0x15000,
2708 };
2709 
2710 //=======================================================================================
2714 // @bsiclass Bentley Systems
2715 //=======================================================================================
2717 {
2718 private:
2719  struct SnappyChunk
2720  {
2721  uint16_t* m_data;
2722  SnappyChunk(uint32_t size) {m_data = (uint16_t*) BeSQLiteLib::MallocMem(size + 2);} // 2 bytes for compressed size at start of data
2723  uint16_t GetChunkSize() {return m_data[0];}
2724  ~SnappyChunk() {BeSQLiteLib::FreeMem(m_data);}
2725  };
2726 
2727  bvector<SnappyChunk*> m_chunks;
2728  Byte* m_rawBuf;
2729  uint32_t m_currChunk;
2730  uint32_t m_rawSize;
2731  uint32_t m_rawCurr;
2732  uint32_t m_rawAvail;
2733  uint32_t m_unsnappedSize;
2734 
2735 public:
2737  BE_SQLITE_EXPORT ~SnappyToBlob();
2738  uint32_t GetCurrChunk() {return m_currChunk;}
2739  Byte* GetChunkData(int i) {return (Byte*) m_chunks[i]->m_data;}
2740 
2742  uint32_t GetUnCompressedSize() const {return m_unsnappedSize;}
2743 
2745  BE_SQLITE_EXPORT uint32_t GetCompressedSize();
2746 
2748  BE_SQLITE_EXPORT void Init();
2749 
2753  BE_SQLITE_EXPORT void Write(Byte const* data, uint32_t size);
2754 
2756  BE_SQLITE_EXPORT void Finish();
2757 
2758  void DoSnappy(Byte const* data, uint32_t size) {Init(); Write(data,size); Finish();}
2759 
2768  BE_SQLITE_EXPORT BentleyStatus SaveToRow(DbR db, Utf8CP tableName, Utf8CP column, int64_t rowId);
2769 
2776  BE_SQLITE_EXPORT BentleyStatus SaveToRow(BlobIO& blobIO);
2777  };
2778 
2779 //=======================================================================================
2780 // @bsiclass Bentley Systems
2781 //=======================================================================================
2783 {
2784  static const uint32_t SNAPPY_UNCOMPRESSED_BUFFER_SIZE = (34*1024);
2785 
2786  virtual ~SnappyReader() {}
2787  virtual ZipErrors _Read(Byte* data, uint32_t size, uint32_t& actuallyRead) = 0;
2788 
2789  static uint32_t GetUncompressedBufferSize() {return SNAPPY_UNCOMPRESSED_BUFFER_SIZE;}
2790 };
2791 
2792 //=======================================================================================
2794 // @bsiclass Bentley Systems
2795 //=======================================================================================
2797 {
2798 private:
2799  Byte* m_uncompressed;
2800  Byte* m_uncompressCurr;
2801  uint16_t m_uncompressAvail;
2802  uint16_t m_uncompressSize;
2803  Byte* m_blobData;
2804  uint32_t m_blobOffset;
2805  uint32_t m_blobBytesLeft;
2806 
2807  ZipErrors ReadNextChunk();
2808  ZipErrors TransferFromBlob(void* data, uint32_t numBytes, int offset);
2809 
2810 public:
2811  BE_SQLITE_EXPORT SnappyFromMemory(void* uncompressedBuffer, uint32_t uncompressedBufferSize);
2812  BE_SQLITE_EXPORT void Init(void* blobBuffer, uint32_t blobBufferSize);
2813  BE_SQLITE_EXPORT virtual ZipErrors _Read(Byte* data, uint32_t size, uint32_t& actuallyRead) override;
2814 };
2815 
2816 //=======================================================================================
2818 // @bsiclass Bentley Systems
2819 //=======================================================================================
2821 {
2822 private:
2823  Byte* m_uncompressed;
2824  Byte* m_uncompressCurr;
2825  Byte* m_blobData;
2826  BlobIO m_blobIO;
2827  uint32_t m_blobBufferSize;
2828  uint32_t m_blobOffset;
2829  uint32_t m_blobBytesLeft;
2830  uint16_t m_uncompressAvail;
2831 
2832  ZipErrors ReadNextChunk();
2833 
2834 public:
2836  BE_SQLITE_EXPORT ZipErrors Init(DbCR db, Utf8CP tableName, Utf8CP column, int64_t rowId);
2837  BE_SQLITE_EXPORT ~SnappyFromBlob();
2838  BE_SQLITE_EXPORT virtual ZipErrors _Read(Byte* data, uint32_t size, uint32_t& actuallyRead) override;
2839  BE_SQLITE_EXPORT void Finish() ;
2840  ZipErrors ReadAndFinish(Byte* data, uint32_t bufSize, uint32_t& bytesActuallyRead) {auto stat=_Read(data, bufSize, bytesActuallyRead); Finish(); return stat;}
2841 };
2842 
2843 #define SQLITE_FORMAT_SIGNATURE "SQLite format 3"
2844 #define DOWNLOAD_FORMAT_SIGNATURE "Download SQLite"
2845 #define SQLZLIB_FORMAT_SIGNATURE "ZV-zlib"
2846 #define SQLSNAPPY_FORMAT_SIGNATURE "ZV-snappy"
2847 
2848 #define BEDB_PROPSPEC_NAMESPACE "be_Db"
2849 #define BEDB_PROPSPEC_EMBEDBLOB_NAME "EmbdBlob"
2850 //=======================================================================================
2853 // @bsiclass Bentley Systems
2854 //=======================================================================================
2856 {
2857  PropSpec(Utf8CP name, PropertySpec::Compress compress = PropertySpec::Compress::Yes) : PropertySpec(name, BEDB_PROPSPEC_NAMESPACE, Mode::Normal, compress) {}
2858 };
2859 
2860 //=======================================================================================
2864 // @bsiclass Bentley Systems
2865 //=======================================================================================
2867 {
2868  static PropSpec DbGuid() {return PropSpec("DbGuid");}
2869  static PropSpec ProfileVersion() {return PropSpec("SchemaVersion");}
2870  static PropSpec ProjectGuid() {return PropSpec("ProjectGuid");}
2871  static PropSpec EmbeddedFileBlob() {return PropSpec(BEDB_PROPSPEC_EMBEDBLOB_NAME, PropertySpec::Compress::No);}
2872  static PropSpec CreationDate() {return PropSpec("CreationDate");}
2873  static PropSpec ExpirationDate() {return PropSpec("ExpirationDate");}
2874 
2876  static PropSpec BeSQLiteBuild() {return PropSpec("BeSQLiteBuild");}
2877 };
2878 
2879 //=======================================================================================
2881 // @bsiclass Bentley Systems
2882 //=======================================================================================
2884 {
2886  static BE_SQLITE_EXPORT ZipErrors CompressDb(BeFileNameCR targetFile, BeFileNameCR sourceFile, ICompressProgressTracker* progressTracker, uint32_t dictionarySize, bool supportRandomAccess);
2887 
2888  // Decompress a Db file
2889  static BE_SQLITE_EXPORT ZipErrors DecompressDb(BeFileNameCR targetFile, BeFileNameCR sourceFile, ICompressProgressTracker* progress);
2890 
2893  static ZipErrors DecompressEmbeddedBlob(bvector<Byte>&out, uint32_t expectedSize, void const*inputBuffer, uint32_t inputSize, Byte*header, uint32_t headerSize);
2894 };
2895 
DefaultTxn
Determines whether and how the default transaction should be started when a Db is created or opened...
Definition: BeSQLite.h:1674
The schemas found in the database are too old, and the DgnDb needs to be recreated after extensive da...
Definition: BeSQLite.h:437
AggregateFunction(Utf8CP name, int nArgs, DbValueType returnType=DbValueType::NullVal)
Initializes a new AggregateFunction instance.
Definition: BeSQLite.h:1084
Contains a UTF-8 encoded string.
Definition: WString.h:275
Definition: BeSQLite.h:416
bmap< AppData::Key const *, RefCountedPtr< AppData >, std::less< AppData::Key const * >, 8 > m_appData
Definition: BeSQLite.h:2143
bool operator<(BeGuid const &rhs) const
Compare two BeGuids.
Definition: BeSQLite.h:214
void SetCreateStandalone(bool val)
Set whether to create a standalone or master database.
Definition: BeSQLite.h:2125
void SetEncoding(Encoding encoding)
Set the text encoding for the newly created database.
Definition: BeSQLite.h:2115
iterator find(const key_type &__x)
Definition: stdcxx/bstdmap.h:269
bool empty() const
Definition: stdcxx/bstdmap.h:210
BeGuid(uint64_t u0, uint64_t u1)
Construct and initialize a BeGuid from two 64 bit values. Caller must ensure these values constitute ...
Definition: BeSQLite.h:202
A "value" from a BeSQLite function.
Definition: BeSQLite.h:960
Definition: BeSQLite.h:2703
The database disk image is malformed.
Definition: BeSQLite.h:376
~StatementCache()
Definition: BeSQLite.h:1304
Definition: BeSQLite.h:2706
virtual void _OnSaveSettings()
Definition: BeSQLite.h:2154
StatementCache m_statements
Definition: BeSQLite.h:1974
DbResult SavePropertyString(PropertySpecCR spec, Utf8StringCR value, uint64_t majorId=0, uint64_t subId=0)
Save a Utf8String as a property value in this Db.
Definition: BeSQLite.h:2460
virtual void _OnRemoveFunction(DbFunction &func) const
Definition: BeSQLite.h:2210
#define END_BENTLEY_SQLITE_NAMESPACE
Definition: BeSQLite.h:139
Utility to compress and write data to a blob using "Snappy" compression.
Definition: BeSQLite.h:2716
DbResult BindText(int paramNum, Utf8StringCR stringValue, MakeCopy makeCopy)
Bind the value of a Utf8String to a parameter of this (previously prepared) Statement.
Definition: BeSQLite.h:676
static bool IsConstraintDbResult(DbResult val1)
Definition: BeSQLite.h:578
StatementCache(uint32_t size)
Definition: BeSQLite.h:1303
This is a copy of sqlite3_rtree_query_info.
Definition: BeSQLite.h:1105
CompressedDb
Definition: BeSQLite.h:2093
PageSize
Definition: BeSQLite.h:2025
uint64_t m_dataVersion
Definition: BeSQLite.h:1965
struct Bentley::BeFileName const & BeFileNameCR
Definition: Bentley.h:242
A wrapper for a SQLite Prepared Statement.
Definition: BeSQLite.h:586
attempt to commit with active changetrack
Definition: BeSQLite.h:431
DbFile * GetDbFile()
Definition: BeSQLite.h:2231
#define BEDB_PROPSPEC_EMBEDBLOB_NAME
Definition: BeSQLite.h:2849
the "user" version of SQLite databases created by this version of the BeSQLite library ...
Definition: BeSQLite.h:323
bool IsActive() const
Determine whether this Savepoint is active or not.
Definition: BeSQLite.h:1736
Data type mismatch.
Definition: BeSQLite.h:385
#define DEFINE_BENTLEY_NEW_DELETE_OPERATORS
Convenience to declare Bentley overrides of new and delete to allow the operations to be inlined in h...
Definition: BentleyAllocator.h:16
Values that can be bound to named parameters of an SQL statement.
Definition: BeSQLite.h:1329
void SetExpirationDate(DateTime xdate)
Set expiration date for the newly created database.
Definition: BeSQLite.h:2123
Upgrade of profile (aka application level BeSQLite schema) of file failed.
Definition: BeSQLite.h:426
DbValue(SqlValueP val)
Definition: BeSQLite.h:966
Construct a Utf8String by creating a formatted string.
Definition: WString.h:414
Definition: BeSQLite.h:2704
static PropSpec ProjectGuid()
Definition: BeSQLite.h:2870
Insertion failed because database is full or write operation failed because disk is full...
Definition: BeSQLite.h:378
Definition: BeSQLite.h:2782
Definition: BeSQLite.h:2696
NamedParams m_params
Definition: BeSQLite.h:1411
do not compress data
Definition: BeSQLite.h:324
BeGuid(bool createValue=false)
Construct a new BeGuid.
Definition: BeSQLite.h:199
static uint32_t GetUncompressedBufferSize()
Definition: BeSQLite.h:2789
Database is empty.
Definition: BeSQLite.h:381
The default file attribute.
OpenMode
Whether to open an BeSQLite::Db readonly or readwrite.
Definition: BeSQLite.h:2038
The schemas found in the database are too new, and the application needs to be upgraded.
Definition: BeSQLite.h:436
A string class that has many of the same capabilities as std::string, plus additional functions such ...
Definition: WString.h:30
long long int64_t
Definition: Bentley.r.h:94
Callback routine requested an abort.
Definition: BeSQLite.h:369
Provides Bentley specific date/time functions (Bentley/BeAssert.h).
DbResult DeleteProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0)
Delete a property from the Db.
Definition: BeSQLite.h:2503
MutexType
Definition: BeSQLite.h:1236
A table in the database is locked.
Definition: BeSQLite.h:371
~BlobIO()
Definition: BeSQLite.h:907
Together with the BeCriticalSection.h file provides Bentley specific thread handling functions (Bentl...
Provides Bentley specific set implementation (Bentley/bset.h).
bool IsReadonly() const
Determine whether the open mode is readonly or not.
Definition: BeSQLite.h:2074
Utf8CP GetName() const
Get the name of this function.
Definition: BeSQLite.h:1046
DbFunction(Utf8CP name, int nArgs, DbValueType returnType)
Initializes a new DbFunction instance.
Definition: BeSQLite.h:1041
void Verify() const
Definition: BeSQLite.h:1427
bvector< Savepoint * > DbTxns
Definition: BeSQLite.h:1957
bool IsValid() const
Test to see whether this BeGuid is non-zero.
Definition: BeSQLite.h:220
Authorization denied.
Definition: BeSQLite.h:388
Attempt to write a readonly database.
Definition: BeSQLite.h:373
Successful result.
Definition: BeSQLite.h:365
DbTxns m_txns
Definition: BeSQLite.h:1975
bool m_settingsDirty
Definition: BeSQLite.h:1961
bool CheckImplicitTxn() const
Definition: BeSQLite.h:2010
Open for write access.
Every BeSQLite::Db has a table for storing "Properties".
Definition: BeSQLite.h:1797
bool m_allowImplicitTxns
Definition: BeSQLite.h:1962
the database name is not a file.
Definition: BeSQLite.h:422
wrong BeSQLite profile version
Definition: BeSQLite.h:424
unsigned int * m_nQueue
Definition: BeSQLite.h:1113
iterator begin()
Definition: stdcxx/bstdmap.h:178
Utility to read Snappy-compressed data from memory, typically from an image of a blob.
Definition: BeSQLite.h:2796
DbResult CreateNewDb(BeFileNameCR dbName, BeGuid dbGuid=BeGuid(), CreateParams const &params=CreateParams())
Definition: BeSQLite.h:2334
SqlParameter(Utf8CP name)
Definition: BeSQLite.h:1335
Statement * GetStatement()
Get the prepared statement for this iterator. This can be used to bind parameters before calling /c b...
Definition: BeSQLite.h:1440
BeGuid m_dbGuid
Definition: BeSQLite.h:1971
SqlDbP GetSqlDb() const
Definition: BeSQLite.h:2011
bool _IsAggregate() override
Definition: BeSQLite.h:1076
DbResult DeleteProperties(PropertySpecCR spec, uint64_t *majorId)
Delete one or more properties from the Db.
Definition: BeSQLite.h:2509
attempt to open a BeSQLite::Db that is already in use somewhere.
Definition: BeSQLite.h:420
void SetRawSQLite()
Use the BeSQLite::Db api on a "raw" SQLite file.
Definition: BeSQLite.h:2068
DbResult Save(Utf8CP operation)
Commit this transaction and then restart it.
Definition: BeSQLite.h:1768
Utility to compress/decompress Db-s.
Definition: BeSQLite.h:2883
Error acquiring schema lock.
Definition: BeSQLite.h:439
Utf16Char const * Utf16CP
Definition: Bentley.h:231
virtual DbResult _OnBriefcaseIdChanged(BeBriefcaseId newBriefcaseId)
Definition: BeSQLite.h:2180
BeBriefcaseId()
Construct an invalid BeBriefcaseId.
Definition: BeSQLite.h:255
A property specification for the "be_Db" namespace.
Definition: BeSQLite.h:2855
Statement()
construct a new blank Statement.
Definition: BeSQLite.h:598
static uint32_t const Standalone()
Definition: BeSQLite.h:251
Abort due to constraint violation. See extended error values.
Definition: BeSQLite.h:384
static PropSpec ExpirationDate()
Definition: BeSQLite.h:2873
PropertySpec(PropertySpec const &other, Mode mode)
Copy a PropertySpec, changing only the setting flag.
Definition: BeSQLite.h:1832
virtual DbResult _OnDbOpening()
override to perform additional processing when Db is opened
Definition: BeSQLite.h:2159
double m_parentScore
Definition: BeSQLite.h:1118
DbFile * m_dbFile
Definition: BeSQLite.h:2138
DbOpcode
Definition: BeSQLite.h:473
Definition: BeSQLite.h:2698
BeDbMutex & m_mutex
Definition: BeSQLite.h:1252
void SetPageSize(PageSize pagesize)
Set the page size for the newly created database.
Definition: BeSQLite.h:2113
uint32_t GetValue() const
Get the briefcase id as a uint32_t.
Definition: BeSQLite.h:261
iterator end()
Definition: stdcxx/bstdmap.h:186
Library used incorrectly.
Definition: BeSQLite.h:386
double m_score
Definition: BeSQLite.h:1121
SqlDbP m_sqlDb
Definition: BeSQLite.h:1966
bool m_createStandalone
Definition: BeSQLite.h:2097
Error reading schemas.
Definition: BeSQLite.h:434
bool operator!=(BeBriefcaseId const &rhs) const
Definition: BeSQLite.h:263
DefaultTxn m_startDefaultTxn
Definition: BeSQLite.h:2047
ZipErrors ReadAndFinish(Byte *data, uint32_t bufSize, uint32_t &bytesActuallyRead)
Definition: BeSQLite.h:2840
Compress
Determine whether a property's data may be compressed.
Definition: BeSQLite.h:1801
Applications subclass from this class to store in-memory data on a Db via AddAppData.
Definition: BeSQLite.h:2132
Profile (aka application level BeSQLite schema) of file could not be determined.
Definition: BeSQLite.h:425
virtual int _OnAddFunction(DbFunction &func) const
Definition: BeSQLite.h:2209
A user-defined function that can be added to a Db connection and then used in SQL.
Definition: BeSQLite.h:1006
Byte * GetChunkData(int i)
Definition: BeSQLite.h:2739
~BeDbMutexHolder()
Definition: BeSQLite.h:1254
size_type count(const key_type &__x) const
Definition: stdcxx/bstdmap.h:277
attempt to open a BeSQLite::Db that doesn't have a property table.
Definition: BeSQLite.h:421
The database schema changed.
Definition: BeSQLite.h:382
Describes a custom collator to register.
Definition: BeSQLite.h:511
CachedStatementPtr GetCachedStatement(Utf8CP sql) const
Definition: BeSQLite.h:2253
The specified position is relative to the beginning of the file.
RefCountedPtr< BusyRetry > BusyRetryPtr
Definition: BeSQLite.h:1956
struct Bentley::Utf8String const & Utf8StringCR
Definition: Bentley.h:241
int int32_t
Definition: Bentley.r.h:92
RefCountedPtr< struct ChangeTracker > ChangeTrackerPtr
Definition: BeSQLite.h:1955
Encoding m_encoding
Definition: BeSQLite.h:2091
int64_t m_rowid
Definition: BeSQLite.h:1117
virtual DbResult _OnDbOpened()
override to perform additional processing when Db is opened
Definition: BeSQLite.h:2164
BusyRetry * m_busyRetry
Definition: BeSQLite.h:2050
MakeCopy
Definition: BeSQLite.h:594
use the fastest compression level (see Zlib documentation for explanation).
Definition: BeSQLite.h:325
Parameters for controlling aspects of the opening of a Db.
Definition: BeSQLite.h:2044
bool operator!=(Entry const &rhs) const
Definition: BeSQLite.h:1435
Class to turn on/off diagnostics for BeSQLite::Statement.
Definition: BeSQLite.h:878
Auxiliary database format error.
Definition: BeSQLite.h:389
Wraps sqlite3_mprintf. Adds convenience that destructor frees memory.
Definition: BeSQLite.h:1215
bool IsNull() const
return true if this value is null
Definition: BeSQLite.h:969
Savepoint m_defaultTxn
Definition: BeSQLite.h:1972
iterator erase(iterator __it)
Definition: stdcxx/bstdmap.h:242
Definition: BeSQLite.h:2707
~Statement()
Definition: BeSQLite.h:600
SqlStatementP GetSqlStatementP() const
Definition: BeSQLite.h:829
Represents an instant in time, typically expressed as a date and time of day.
Definition: DateTime.h:28
Mode
Definition: BeSQLite.h:1811
uint32_t m_id
Definition: BeSQLite.h:246
The database file is locked.
Definition: BeSQLite.h:370
Statement(SqlStatementP stmt)
Definition: BeSQLite.h:595
int m_nParam
Definition: BeSQLite.h:1108
void * m_context
Definition: BeSQLite.h:1107
PropSpec(Utf8CP name, PropertySpec::Compress compress=PropertySpec::Compress::Yes)
Definition: BeSQLite.h:2857
Unable to open the database file.
Definition: BeSQLite.h:379
DbResult QueryProperty(Utf8StringR value, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const
Query the value of the string part of a property from the Db.
Definition: BeSQLite.h:2496
bstdmap & operator=(const bstdmap &__rhs)
Definition: stdcxx/bstdmap.h:170
Supply a BusyRetry handler to BeSQLite (see https://www.sqlite.org/c3ref/busy_handler.html).
Definition: BeSQLite.h:1849
A duplicated "value" from a BeSQLite function.
Definition: BeSQLite.h:993
Utf8String m_name
Definition: BeSQLite.h:1334
Definition: BeSQLite.h:409
static PropSpec BeSQLiteBuild()
Build version of BeSqlite (e.g. 06.10.00.00) used to create this database; useful for diagnostics...
Definition: BeSQLite.h:2876
virtual bool _IsAggregate()
Definition: BeSQLite.h:1044
Utf8Char * Utf8P
Definition: Bentley.h:228
LogErrors
Definition: BeSQLite.h:538
DbValue * m_args
Definition: BeSQLite.h:1122
DbResult BindBoolean(int paramNum, bool value)
Bind a Boolean value to a parameter of this (previously prepared) Statement.
Definition: BeSQLite.h:656
static uint32_t const Illegal()
Definition: BeSQLite.h:252
Utf8CP GetName() const
Definition: BeSQLite.h:1834
void SetOpenMode(OpenMode openMode)
set the open mode
Definition: BeSQLite.h:2077
BeGuid const & BeGuidCR
Definition: BeSQLite.h:158
void SetFailIfDbExist(bool val)
Determine whether the create should fail if a file exists with the specified name.
Definition: BeSQLite.h:2117
The "context" supplied to DbFunctions that can be used to set result values.
Definition: BeSQLite.h:1013
bool IsValid() const
return true if this value is valid
Definition: BeSQLite.h:968
DbResult SaveChanges(Utf8StringCR changesetName)
Definition: BeSQLite.h:2561
bool m_forSchemaUpgrade
Definition: BeSQLite.h:2048
int m_nCoord
Definition: BeSQLite.h:1114
Declares the NonCopyableClass.
DbP m_db
Definition: BeSQLite.h:1409
void * m_user
Definition: BeSQLite.h:1110
invalid version of the revision file is being imported
Definition: BeSQLite.h:432
attempt to create a new file when a file by that name already exists
Definition: BeSQLite.h:419
A reference-counted Statement. Statement is freed when last reference is Released.
Definition: BeSQLite.h:1261
RefCountedPtr< CachedStatement > CachedStatementPtr
Definition: BeSQLite.h:1281
virtual DbResult _OnDbCreated(CreateParams const &params)
Called after a new Db had been created.
Definition: BeSQLite.h:2150
A 16-byte Globally Unique Id. A value of all zeros means "Invalid Id".
Definition: BeSQLite.h:192
DbResult QueryPropertySize(uint32_t &propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const
Determine the size in bytes of the blob part of a property in the Db.
Definition: BeSQLite.h:2476
BriefcaseLocalValueCache & GetBLVCache()
Get a reference to the BriefcaseLocalValueCache for this Db.
Definition: BeSQLite.h:2523
This is an interface class that allows applications to provide custom language processing for SQL cas...
Definition: BeSQLite.h:504
Definition: BeSQLite.h:2695
bool IsRawSQLite() const
Determine whether the "raw sqlite" flag is on or not.
Definition: BeSQLite.h:2071
PageSize m_pagesize
Definition: BeSQLite.h:2092
The names of properties in the "be_Db" namespace.
Definition: BeSQLite.h:2866
T_Id GetValueId(int col)
Get a BeBriefcaseBasedId value from a column returned from Step.
Definition: BeSQLite.h:797
bool IsSetting() const
Determine whether this PropertySpec refers to a setting or not.
Definition: BeSQLite.h:1837
DbResult OpenBeSQLiteDb(BeFileNameCR dbName, OpenParams const &openParams)
Open an existing BeSQLite::Db file.
Definition: BeSQLite.h:2318
BlobIO()
Definition: BeSQLite.h:906
Step() has finished executing.
Definition: BeSQLite.h:393
DbValueType
Definition: BeSQLite.h:483
StatementCache m_statements
Definition: BeSQLite.h:2139
struct Bentley::Utf8String * Utf8StringP
Definition: Bentley.h:241
Statement * StatementP
Definition: BeSQLite.h:161
Savepoint encapsulates SQLite transactions against a BeSQLite::Db.
Definition: BeSQLite.h:1705
there is no transaction active and the database was opened with AllowImplicitTransactions=false ...
Definition: BeSQLite.h:423
BeGuid(uint32_t i0, uint32_t i1, uint32_t i2, uint32_t i3)
Construct and initialize a BeGuid from four 32 bit values. Caller must ensure these values constitute...
Definition: BeSQLite.h:205
DbResult Begin()
Begin a transaction against the database with the default transaction mode.
Definition: BeSQLite.h:1756
unsigned long long uint64_t
Definition: Bentley.r.h:95
A convenience class for acquiring and releasing a mutex lock. Lock is acquired on construction and re...
Definition: BeSQLite.h:1250
void DoSnappy(Byte const *data, uint32_t size)
Definition: BeSQLite.h:2758
DbDupValue(DbDupValue &&other)
Definition: BeSQLite.h:996
Within m_within
Definition: BeSQLite.h:1120
BriefcaseLocalValueCache m_blvCache
Definition: BeSQLite.h:1970
The schemas can and must be imported.
Definition: BeSQLite.h:438
BentleyStatus
Definition: Bentley.h:208
A template that has many of the capabilities of std::pair.
Definition: bpair.h:73
Open for both read and write.
double * m_coords
Definition: BeSQLite.h:1112
virtual ~DbFunction()
Definition: BeSQLite.h:1045
SqlValueP m_val
Definition: BeSQLite.h:963
Definition: BeSQLite.h:2134
Definition: BeSQLite.h:496
int m_maxLevel
Definition: BeSQLite.h:1116
SqlDbBlobP GetBlobP()
Definition: BeSQLite.h:905
DbFile const & DbFileCR
Definition: BeSQLite.h:160
StatementCache & GetStatementCache() const
Get the StatementCache for this Db.
Definition: BeSQLite.h:2242
A user-defined aggregate function.
Definition: BeSQLite.h:1074
void SetApplicationId(ApplicationId applicationId)
Set Application Id to be stored at offset 68 of the SQLite file.
Definition: BeSQLite.h:2121
uint32_t GetUnCompressedSize() const
Get the number of bytes in the raw (uncompressed) stream.
Definition: BeSQLite.h:2742
bool m_readonly
Definition: BeSQLite.h:1964
Some kind of disk I/O error occurred.
Definition: BeSQLite.h:375
NamedParams(Utf8CP where=nullptr)
ctor for NamedParams
Definition: BeSQLite.h:1374
Access permission denied.
Definition: BeSQLite.h:368
PropertySpec(Utf8CP name, Utf8CP nameSpace, Mode mode=Mode::Normal, Compress compress=Compress::Yes, bool saveIfNull=false)
Construct an instance of a PropertySpec with values for name and namespace.
Definition: BeSQLite.h:1829
A user-defined scalar function.
Definition: BeSQLite.h:1059
A Blob handle for incremental I/O. See sqlite3_blob_open for details.
Definition: BeSQLite.h:899
void SetResultError(Utf8CP, int len=-1)
see sqlite3_result_error
void Invalidate()
Set this BeGuid to the invalid id value (all zeros).
Definition: BeSQLite.h:217
ChangeTrackerPtr m_tracker
Definition: BeSQLite.h:1968
T_Id GetValueId() const
Definition: BeSQLite.h:982
AString m_name
Name that query strings will use to use this collation.
Definition: BeSQLite.h:513
Encoding
Definition: BeSQLite.h:2024
virtual DbResult _VerifyProfileVersion(OpenParams const &params)
Gets called when a Db is opened and checks whether the file can be opened, i.e whether the file versi...
Definition: BeSQLite.h:2207
CachedStatementPtr m_stmt
Definition: BeSQLite.h:1410
Defines typedefs and constants that can be used across other namespaces. All Bentley-authored C++ sou...
DbProfileValues
Definition: BeSQLite.h:334
void * m_cachedProps
Definition: BeSQLite.h:1969
#define BEGIN_BENTLEY_SQLITE_NAMESPACE
Definition: BeSQLite.h:138
A Bentley supplied implementation std::vector.
Definition: stdcxx/bvector.h:77
Base class to make a class non-copyable.
Definition: NonCopyableClass.h:23
Within
Definition: BeSQLite.h:1094
#define BE_SQLITE_EXPORT
Definition: BeSQLite.h:124
bool IsCompress() const
Determine whether this PropertySpec requests to compress or not.
Definition: BeSQLite.h:1840
A 4-digit number that specifies the version of the "profile" (schema) of a Db.
Definition: BeSQLite.h:351
the maximum compression level. Can be very slow but results in smallest size.
Definition: BeSQLite.h:327
static uint32_t const Master()
Definition: BeSQLite.h:250
BeBriefcaseId(uint32_t u)
Construct a BeBriefcaseId from a 32 bit value.
Definition: BeSQLite.h:256
Statement(DbCR db, Utf8CP sql)
Definition: BeSQLite.h:599
void Invalidate()
Set this BeBriefcaseId to the invalid id value.
Definition: BeSQLite.h:257
bool m_failIfDbExists
Definition: BeSQLite.h:2095
Open for read access.
CreateParams(PageSize pagesize=PageSize::PAGESIZE_4K, Encoding encoding=Encoding::Utf8, bool failIfDbExists=true, DefaultTxn defaultTxn=DefaultTxn::Yes, BusyRetry *retry=nullptr, bool createStandalone=false)
Definition: BeSQLite.h:2107
Defines a callback for providing information on the progress of a compress or decompress operation...
Definition: BeSQLite.h:1452
Savepoint * GetDefaultTransaction() const
Definition: BeSQLite.h:2640
Profile (aka application level BeSQLite schema) of file is too old. Therefore file cannot be opened...
Definition: BeSQLite.h:428
#define BEDB_PROPSPEC_NAMESPACE
Definition: BeSQLite.h:2848
virtual int _OnBusy(int count) const
Called when SQLite is blocked by another connection to a database.
Definition: BeSQLite.h:1855
Db const & DbCR
Definition: BeSQLite.h:159
bool IsValid() const
Definition: BeSQLite.h:1430
Holds a mutex to synchronize multi-thread access to data.
Definition: BeSQLite.h:1231
static uint32_t const MaxRepo()
Definition: BeSQLite.h:249
uint32_t AddRef() const
Definition: BeSQLite.h:1275
DbTableIterator(DbCR db)
Definition: BeSQLite.h:1413
bool m_isValid
Definition: BeSQLite.h:1424
Utf8CP GetSQL() const
Definition: BeSQLite.h:1278
bool operator==(BeGuid const &rhs) const
Compare two BeGuids for equality.
Definition: BeSQLite.h:208
A synchronization primitive that can be used to protect shared data from being simultaneously accesse...
Definition: BeThread.h:57
bool m_settingsTableCreated
Definition: BeSQLite.h:1960
String or BLOB exceeds size limit.
Definition: BeSQLite.h:383
static int GetBaseDbResult(DbResult val)
Definition: BeSQLite.h:576
static PropSpec DbGuid()
Definition: BeSQLite.h:2868
When enabled, this class maintains a list of "changed rows" (inserts, updates and deletes) for a BeSQ...
Definition: ChangeSet.h:80
DVec3d operator*(Transform const &transform, DVec3d const &vector)
operator overload for multiplication of a transform and a vector li>The vector appears on the left as...
BeDbMutexHolder(BeDbMutex &mutex)
Definition: BeSQLite.h:1253
uint32_t GetCurrChunk()
Definition: BeSQLite.h:2738
void SetInputError(Context &ctx)
Set the result of this function to: error due to illegal input.
Definition: BeSQLite.h:1051
bool operator!=(const BentleyAllocator< _Ty > &, const BentleyAllocator< _Other > &)
Definition: BentleyAllocator.h:152
OpenMode m_openMode
Definition: BeSQLite.h:2046
2nd parameter to Bind out of range
Definition: BeSQLite.h:390
DbValueType GetReturnType() const
Gets the return type of the function.
Definition: BeSQLite.h:1048
Definition: BeSQLite.h:2694
DbConstants
Definition: BeSQLite.h:321
int StatusInt
Definition: Bentley.h:222
Concrete class that can be used to implement the reference-counting pattern.
Definition: RefCounted.h:109
static PropSpec CreationDate()
Definition: BeSQLite.h:2872
StatementP m_sql
Definition: BeSQLite.h:1425
Utf8StringCR GetWhere() const
Get the Where clause for this NamedParam.
Definition: BeSQLite.h:1384
bool IsValid() const
Determine whether this BlobIO was successfully opened.
Definition: BeSQLite.h:953
A unique Id for a BeBriefcase (a particular copy of a BeSQLite::Db is referred to as a BeBriefcase...
Definition: BeSQLite.h:243
int m_level
Definition: BeSQLite.h:1115
void AddSqlParameter(SqlParameter *param)
Add a parameter value to this set of NamedParams.
Definition: BeSQLite.h:1348
uint64_t GetValueUInt64(int col)
Get a UInt64 value from a column returned from Step.
Definition: BeSQLite.h:781
Profile (aka application level schema) of file is too new for read-write access. Therefore file can o...
Definition: BeSQLite.h:429
unsigned short uint16_t
Definition: Bentley.r.h:91
BeBriefcaseId m_briefcaseId
Definition: BeSQLite.h:1973
Base class for an Iterator of a BeSQLite::Db table.
Definition: BeSQLite.h:1406
bool m_rawSQLite
Definition: BeSQLite.h:2049
Definition: BeSQLite.h:2699
Utf8Char const * Utf8CP
Definition: Bentley.h:229
bool IsEmpty() const
Definition: BeSQLite.h:1309
void Invalidate()
Definition: BeSQLite.h:1431
bool operator!=(BeGuid const &rhs) const
Compare two BeGuids for inequality.
Definition: BeSQLite.h:211
bool IsValid() const
Test to see whether this BriefcaseId is valid.
Definition: BeSQLite.h:258
The name of the schema doesn't match the name of the domain.
Definition: BeSQLite.h:441
A 4-digit number that specifies version number.
Definition: BeVersion.h:25
Profile (aka application level SQLite schema) of file is too new. Therefore file cannot be opened...
Definition: BeSQLite.h:430
virtual ~Savepoint()
dtor for Savepoint. If the Savepoint is still active, it is committed.
Definition: BeSQLite.h:1733
DbResult BindUInt64(int paramNum, uint64_t value)
Bind a UInt64 value to a parameter of this (previously prepared) Statement.
Definition: BeSQLite.h:651
RTreeMatchFunction(Utf8CP name, int nArgs)
Definition: BeSQLite.h:1129
bool operator==(Entry const &rhs) const
Definition: BeSQLite.h:1436
ProfileVersion(Utf8CP json)
Definition: BeSQLite.h:355
ProfileVersion(uint16_t major, uint16_t minor, uint16_t sub1, uint16_t sub2)
Definition: BeSQLite.h:354
File opened that is not a database file.
Definition: BeSQLite.h:391
bool m_inCommit
Definition: BeSQLite.h:1963
void clear()
Definition: stdcxx/bstdmap.h:257
CopyData
Definition: BeSQLite.h:1015
#define BeAssert(_Expression)
BeAssert performs the same function as the standard assert, plus it prevents the most common cases of...
Definition: BeAssert.h:56
NamedParams & Params()
Get a reference to the NamedParams for this iterator.
Definition: BeSQLite.h:1444
SQL error or missing database.
Definition: BeSQLite.h:366
ScalarFunction(Utf8CP name, int nArgs, DbValueType returnType=DbValueType::NullVal)
Initializes a new ScalarFunction instance.
Definition: BeSQLite.h:1067
A BeSQLite database file.
Definition: BeSQLite.h:2020
uint64_t GetValueUInt64() const
Definition: BeSQLite.h:979
Utf8CP GetName() const
Get the name of this Savepoint.
Definition: BeSQLite.h:1742
DbTableIterator(DbTableIterator &&rhs)
Move ctor. DbTableIterator are not copyable, but they are movable.
Definition: BeSQLite.h:1416
unsigned char Byte
Definition: Bentley.r.h:143
#define BESQLITE_TYPEDEFS(_name_)
Definition: BeSQLite.h:156
DbResult SaveProperty(PropertySpecCR spec, void const *value, uint32_t propsize, uint64_t majorId=0, uint64_t subId=0)
Save a property value in this Db.
Definition: BeSQLite.h:2444
void SetCompressMode(CompressedDb val)
Set the compression mode for the new Db. Default is CompressDb_None.
Definition: BeSQLite.h:2119
Entry & operator++()
Definition: BeSQLite.h:1433
This interface should be implemented to supply the first argument to the BeSQLite function "InVirtual...
Definition: BeSQLite.h:1140
Error importing schemas.
Definition: BeSQLite.h:440
unsigned int uint32_t
Definition: Bentley.r.h:93
bool HasProperty(PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const
Determine whether a property exists in the Db.
Definition: BeSQLite.h:2467
Operation terminated by interrupt.
Definition: BeSQLite.h:374
Provides Bentley implemented file management functions (Bentley/BeFile.h).
A cache of SharedStatements that can be reused without re-Preparing.
Definition: BeSQLite.h:1290
Utility to read Snappy-compressed data from a blob in a database.
Definition: BeSQLite.h:2820
double * m_param
Definition: BeSQLite.h:1109
bool IsMasterId() const
Determine whether this is the id of the master briefcase (special id==0).
Definition: BeSQLite.h:259
#define EXPORT_VTABLE_ATTRIBUTE
Definition: Bentley.h:67
A malloc() failed.
Definition: BeSQLite.h:372
int GetNumArgs() const
Get the number of arguments to this function.
Definition: BeSQLite.h:1047
bool IsTransactionActive() const
Determine whether there is an active transaction against this Db.
Definition: BeSQLite.h:2264
static PropSpec EmbeddedFileBlob()
Definition: BeSQLite.h:2871
BeSQLiteTxnMode
SQLite Transaction modes corresponding to https://www.sqlite.org/lang_transaction.html.
Definition: BeSQLite.h:1671
void OnSettingsDirtied()
Definition: BeSQLite.h:2009
Upgrade of profile (aka application level SQLite schema) of file failed because the file could not be...
Definition: BeSQLite.h:427
bool operator==(BeBriefcaseId const &rhs) const
Definition: BeSQLite.h:262
DbResult SavePropertyString(PropertySpecCR spec, Utf8CP value, uint64_t majorId=0, uint64_t subId=0)
Save a (Utf8) text string as a property value in this Db.
Definition: BeSQLite.h:2452
use the default compression level. This is pretty good tradeoff for size vs. speed.
Definition: BeSQLite.h:326
bool IsColumnNull(int col)
Determine whether the column value is NULL.
Definition: BeSQLite.h:741
BeSQLiteTxnMode GetTxnMode() const
Get the default transaction mode for this SavePoint.
Definition: BeSQLite.h:1745
Parameters for controlling aspects of creating and then opening a Db.
Definition: BeSQLite.h:2089
uint32_t GetRefCount() const
Definition: BeSQLite.h:1276
DateTime m_expirationDate
Definition: BeSQLite.h:2096
Database lock protocol error.
Definition: BeSQLite.h:380
size_type size() const
Definition: stdcxx/bstdmap.h:214
bool GetValueBoolean(int col)
Get a Boolean value from a column returned from Step.
Definition: BeSQLite.h:788
static PropSpec ProfileVersion()
Definition: BeSQLite.h:2869
The schema was not found in the database.
Definition: BeSQLite.h:435
Write little-endian UTF-16 encoded output file.
DbResult QueryProperty(void *value, uint32_t propsize, PropertySpecCR spec, uint64_t majorId=0, uint64_t subId=0) const
Query the value of the blob part a property from the Db.
Definition: BeSQLite.h:2487
bpair< iterator, bool > insert(const value_type &__x)
Definition: stdcxx/bstdmap.h:228
union Bentley::BeSQLite::BeGuid::@4 m_guid
void * m_collator
User data object provided in the collation callback.
Definition: BeSQLite.h:514
A user-defined implementation of the SQLite sqlite3_rtree_query_callback function for using the MATCH...
Definition: BeSQLite.h:1092
void SetTxnMode(BeSQLiteTxnMode mode)
Sets the default transaction mode for this Savepoint.
Definition: BeSQLite.h:1748
Definition: BeSQLite.h:395
virtual void _OnDbClose()
override to perform processing when Db is closed
Definition: BeSQLite.h:2168
bool IsCached() const
Determine whether this PropertySpec is cached or not.
Definition: BeSQLite.h:1838
NOT USED. Table or record not found.
Definition: BeSQLite.h:377
BusyRetryPtr m_retry
Definition: BeSQLite.h:1967
PropertySpec const & PropertySpecCR
Definition: BeSQLite.h:1843
uint64_t u[2]
Definition: BeSQLite.h:194
SqlStatementP & GetStmtR()
Definition: BeSQLite.h:602
ZipErrors
Error values returned from the ZLib functions. See ZLib documentation for details.
Definition: BeSQLite.h:2692
int32_t GetDepth() const
Get the savepoint depth for this Savepoint. This will always be a number >= 0 if the savepoint is act...
Definition: BeSQLite.h:1739
Uses OS features not supported on host.
Definition: BeSQLite.h:387
A physical Db file.
Definition: BeSQLite.h:1948
virtual ~SnappyReader()
Definition: BeSQLite.h:2786
BeBriefcaseId GetNextBriefcaseId() const
Definition: BeSQLite.h:254
SqlValueP GetSqlValueP() const
for direct use of sqlite3 api
Definition: BeSQLite.h:970
unsigned char uint8_t
Definition: Bentley.r.h:89
Step() has another row ready.
Definition: BeSQLite.h:392
Entry(StatementP sql, bool isValid)
Definition: BeSQLite.h:1426
ApplicationId
Definition: BeSQLite.h:2094
bool IsStandaloneId() const
Determine whether this is the id of a standalone briefcase not associated with any master briefcase (...
Definition: BeSQLite.h:260
Within m_parentWithin
Definition: BeSQLite.h:1119
Utf8CP GetUtf8CP()
Definition: BeSQLite.h:1224
bool SaveIfNull() const
Determine whether this PropertySpec saves NULL values or not.
Definition: BeSQLite.h:1839
Internal logic error.
Definition: BeSQLite.h:367
static bool TestBaseDbResult(DbResult val1, DbResult val2)
Definition: BeSQLite.h:577
bool operator==(const BentleyAllocator< _Ty > &, const BentleyAllocator< _Other > &)
Definition: BentleyAllocator.h:146
DbTxns::iterator DbTxnIter
Definition: BeSQLite.h:1958
void SetStartDefaultTxn(DefaultTxn val)
Determine whether the default transaction should be started on the Db.
Definition: BeSQLite.h:2082
DbResult
Definition: BeSQLite.h:363
Utf8CP GetNamespace() const
Definition: BeSQLite.h:1835

Copyright © 2017 Bentley Systems, Incorporated. All rights reserved.