helpers.h
Go to the documentation of this file.
1 #ifndef cetlib_sqlite_helpers_h
2 #define cetlib_sqlite_helpers_h
3 
4 // ====================================================================
5 // These are general utilities for interacting with a database and any
6 // tables therein.
7 // ====================================================================
8 
9 #include "cetlib/sqlite/column.h"
11 #include "cetlib/sqlite/exec.h"
12 
13 #include "sqlite3.h"
14 
15 #include <string>
16 
17 using namespace std::string_literals;
18 
19 namespace cet::sqlite {
20 
22  bool hasTableWithSchema(sqlite3* db,
23  std::string const& tablename,
24  std::string expectedSchema);
25  unsigned nrows(sqlite3* db, std::string const& tablename);
26 
27  void delete_from(sqlite3* db, std::string const& tablename);
28  void drop_table(sqlite3* db, std::string const& tablename);
29  void drop_table_if_exists(sqlite3* db, std::string const& tablename);
30 
31  // Could arguably go in detail namespace due to obscurity of
32  // permissive_column.
33  template <typename... Args>
35  bool const delete_contents,
36  std::string const& tablename,
37  permissive_column<Args> const&... cols);
38 
39 } // namespace cet::sqlite
40 
41 //====================================================
42 // Implementation below
43 
44 template <typename... Args>
45 void
47  bool const delete_contents,
48  std::string const& tablename,
49  permissive_column<Args> const&... cols)
50 {
51  auto const& sqlddl = detail::create_table_ddl(tablename, cols...);
52  if (hasTableWithSchema(db, tablename, sqlddl)) {
53  if (delete_contents) {
54  delete_from(db, tablename); // Prefer drop_table, but failure-to-prepare
55  // exception ends up being thrown.
56  }
57  } else {
58  exec(db, sqlddl);
59  }
60 }
61 
62 #endif /* cetlib_sqlite_helpers_h */
63 
64 // Local Variables:
65 // mode: c++
66 // End:
bool hasTableWithSchema(sqlite3 *db, std::string const &tablename, std::string expectedSchema)
Definition: helpers.cc:29
void delete_from(sqlite3 *db, std::string const &tablename)
Definition: helpers.cc:63
void createTableIfNeeded(sqlite3 *db, bool const delete_contents, std::string const &tablename, permissive_column< Args > const &...cols)
Definition: helpers.h:46
std::string string
Definition: nybbler.cc:12
string filename
Definition: train.py:213
std::string assembleNoLockURI(std::string const &filename)
Definition: helpers.cc:8
std::string create_table_ddl(std::string const &tablename, Cols const &...cols)
Definition: create_table.h:96
void drop_table_if_exists(sqlite3 *db, std::string const &tablename)
Definition: helpers.cc:75
struct sqlite3 sqlite3
void drop_table(sqlite3 *db, std::string const &tablename)
Definition: helpers.cc:69
unsigned nrows(sqlite3 *db, std::string const &tablename)
Definition: helpers.cc:82
void exec(sqlite3 *db, std::string const &ddl)
Definition: exec.cc:5