diff options
author | Boris Kolpackov <boris@codesynthesis.com> | 2015-08-11 15:34:12 +0200 |
---|---|---|
committer | Boris Kolpackov <boris@codesynthesis.com> | 2015-08-23 13:50:07 +0200 |
commit | a7e766e1aa77fff846d8426658befd9a01fe2861 (patch) | |
tree | 734e658aca46fa945994db85ea586d79c8933bcd /brep/shared-database.cxx | |
parent | 63aaad529c9ae9358f22fd9563aeabc679f4defd (diff) |
Share DB object between modules
Diffstat (limited to 'brep/shared-database.cxx')
-rw-r--r-- | brep/shared-database.cxx | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/brep/shared-database.cxx b/brep/shared-database.cxx new file mode 100644 index 0000000..fb952d8 --- /dev/null +++ b/brep/shared-database.cxx @@ -0,0 +1,41 @@ +// file : brep/shared-database.cxx -*- C++ -*- +// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd +// license : MIT; see accompanying LICENSE file + +#include <brep/shared-database> + +#include <memory> // weak_ptr, shared_ptr, make_shared() +#include <stdexcept> // runtime_error + +#include <odb/pgsql/database.hxx> + +using namespace std; +using namespace odb; + +namespace brep +{ + shared_ptr<database> + shared_database (const string& host, unsigned int port) + { + static weak_ptr<pgsql::database> db; + + // In C++11, function-static variable initialization is + // guaranteed to be thread-safe, thought this doesn't + // seem to be enough in our case (because we are re- + // initializing the weak pointer). + // + if (shared_ptr<database> d = db.lock ()) + { + if (h != d->host () || p != d->port ()) + throw runtime_error ("shared database host/port mismatch"); + + return d; + } + else + { + d = make_shared<database> ("", "", "brep", h, p); + db = d; + return d; + } + } +} |