diff options
author | Boris Kolpackov <boris@codesynthesis.com> | 2012-10-17 09:31:54 +0200 |
---|---|---|
committer | Boris Kolpackov <boris@codesynthesis.com> | 2012-10-17 09:31:54 +0200 |
commit | 8338bb049db44d9b470b2a76acc5853b92915238 (patch) | |
tree | 19f95ec98adadec6e4a8254a720c0b059d2bd927 | |
parent | 1eb99114e1d7741ecdb5a6b2396c9cfd86c5dee4 (diff) |
Add example for prepared query usage
-rw-r--r-- | README | 3 | ||||
-rw-r--r-- | makefile | 1 | ||||
-rw-r--r-- | prepared/README | 65 | ||||
-rw-r--r-- | prepared/database.hxx | 94 | ||||
-rw-r--r-- | prepared/driver.cxx | 232 | ||||
-rw-r--r-- | prepared/makefile | 120 | ||||
-rw-r--r-- | prepared/person.hxx | 61 |
7 files changed, 576 insertions, 0 deletions
@@ -47,6 +47,9 @@ inheritance/polymorphism view Shows how to define and use object, table, mixed, and native views. +prepared + Shows how to use prepared queries. + optimistic Shows how to use optimistic concurrency in ODB. @@ -15,6 +15,7 @@ query \ mapping \ optimistic \ pimpl \ +prepared \ schema/embedded tr1_dirs := relationship inverse schema/custom view diff --git a/prepared/README b/prepared/README new file mode 100644 index 0000000..1fc6a0f --- /dev/null +++ b/prepared/README @@ -0,0 +1,65 @@ +This example shows how to use prepared queries. In particular, it includes +examples of cached and uncached queries, with and without by-reference +parameters, as well as the use of a prepared query factory. + +The example consists of the following files: + +person.hxx + Header file defining the 'person' persistent class as well as the + 'person_count' view. + +person-odb.hxx +person-odb.ixx +person-odb.cxx +person.sql + The first three files contain the database support code and the last file + contains the database schema for the person.hxx header. + + These files are generated by the ODB compiler from person.hxx using the + following command line: + + odb -d <database> --generate-query --generate-prepared \ +--generate-schema person.hxx + + Where <database> stands for the database system we are using, for example, + 'mysql'. + + The --generate-prepared option requests the generation of the prepared + query support code. + +database.hxx + Contains the create_database() function which instantiates the concrete + database class corresponding to the database system we are using. + +driver.cxx + Driver for the example. It includes the person.hxx and person-odb.hxx + headers to gain access to the persistent classes and their database support + code. It also includes database.hxx for the create_database() function + declaration. + + In main() the driver first calls create_database() to obtain the database + instance and creates a number of persistent objects. It then prepares and + executes a number of queries to illustrate various usage scenarios. + +To compile and link the example manually from the command line we can use +the following commands (using MySQL as an example; replace 'c++' with your +C++ compiler name): + +c++ -c person-odb.cxx +c++ -DDATABASE_MYSQL -c driver.cxx +c++ -o driver driver.o person-odb.o -lodb-mysql -lodb + +To run the example we may first need to create the database schema (for some +database systems, such as SQLite, the schema is embedded into the generated +code which makes this step unnecessary). Using MySQL as an example, this +can be achieved with the following command: + +mysql --user=odb_test --database=odb_test < person.sql + +Here we use 'odb_test' as the database login and also 'odb_test' as the +database name. + +Once the database schema is ready, we can run the example (using MySQL as +the database): + +./driver --user odb_test --database odb_test diff --git a/prepared/database.hxx b/prepared/database.hxx new file mode 100644 index 0000000..2e9316a --- /dev/null +++ b/prepared/database.hxx @@ -0,0 +1,94 @@ +// file : prepared/database.hxx +// copyright : not copyrighted - public domain + +// +// Create concrete database instance based on the DATABASE_* macros. +// + +#ifndef DATABASE_HXX +#define DATABASE_HXX + +#include <string> +#include <memory> // std::auto_ptr +#include <cstdlib> // std::exit +#include <iostream> + +#include <odb/database.hxx> + +#if defined(DATABASE_MYSQL) +# include <odb/mysql/database.hxx> +#elif defined(DATABASE_SQLITE) +# include <odb/connection.hxx> +# include <odb/transaction.hxx> +# include <odb/schema-catalog.hxx> +# include <odb/sqlite/database.hxx> +#elif defined(DATABASE_PGSQL) +# include <odb/pgsql/database.hxx> +#elif defined(DATABASE_ORACLE) +# include <odb/oracle/database.hxx> +#elif defined(DATABASE_MSSQL) +# include <odb/mssql/database.hxx> +#else +# error unknown database; did you forget to define the DATABASE_* macros? +#endif + +inline std::auto_ptr<odb::database> +create_database (int& argc, char* argv[]) +{ + using namespace std; + using namespace odb::core; + + if (argc > 1 && argv[1] == string ("--help")) + { + cout << "Usage: " << argv[0] << " [options]" << endl + << "Options:" << endl; + +#if defined(DATABASE_MYSQL) + odb::mysql::database::print_usage (cout); +#elif defined(DATABASE_SQLITE) + odb::sqlite::database::print_usage (cout); +#elif defined(DATABASE_PGSQL) + odb::pgsql::database::print_usage (cout); +#elif defined(DATABASE_ORACLE) + odb::oracle::database::print_usage (cout); +#elif defined(DATABASE_MSSQL) + odb::mssql::database::print_usage (cout); +#endif + + exit (0); + } + +#if defined(DATABASE_MYSQL) + auto_ptr<database> db (new odb::mysql::database (argc, argv)); +#elif defined(DATABASE_SQLITE) + auto_ptr<database> db ( + new odb::sqlite::database ( + argc, argv, false, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)); + + // Create the database schema. Due to bugs in SQLite foreign key + // support for DDL statements, we need to temporarily disable + // foreign keys. + // + { + connection_ptr c (db->connection ()); + + c->execute ("PRAGMA foreign_keys=OFF"); + + transaction t (c->begin ()); + schema_catalog::create_schema (*db); + t.commit (); + + c->execute ("PRAGMA foreign_keys=ON"); + } +#elif defined(DATABASE_PGSQL) + auto_ptr<database> db (new odb::pgsql::database (argc, argv)); +#elif defined(DATABASE_ORACLE) + auto_ptr<database> db (new odb::oracle::database (argc, argv)); +#elif defined(DATABASE_MSSQL) + auto_ptr<database> db (new odb::mssql::database (argc, argv)); +#endif + + return db; +} + +#endif // DATABASE_HXX diff --git a/prepared/driver.cxx b/prepared/driver.cxx new file mode 100644 index 0000000..470d0b8 --- /dev/null +++ b/prepared/driver.cxx @@ -0,0 +1,232 @@ +// file : prepared/driver.cxx +// copyright : not copyrighted - public domain + +#include <memory> // std::auto_ptr +#include <cassert> +#include <iostream> + +#include <odb/database.hxx> +#include <odb/connection.hxx> +#include <odb/transaction.hxx> + +#include "database.hxx" // create_database + +#include "person.hxx" +#include "person-odb.hxx" + +using namespace std; +using namespace odb::core; + +struct params +{ + unsigned short age; + string first; +}; + +static void +query_factory (const char* name, connection& c) +{ + typedef odb::query<person> query; + + auto_ptr<params> p (new params); + query q (query::age > query::_ref (p->age) && + query::first == query::_ref (p->first)); + prepared_query<person> pq (c.prepare_query<person> (name, q)); + c.cache_query (pq, p); +} + +static void +print_ages (unsigned short age, odb::result<person> r) +{ + cout << "over " << age << ':'; + + for (odb::result<person>::iterator i (r.begin ()); i != r.end (); ++i) + cout << ' ' << i->age (); + + cout << endl; +} + +int +main (int argc, char* argv[]) +{ + try + { + auto_ptr<database> db (create_database (argc, argv)); + + // Create a few persistent person objects. + // + { + person p1 ("John", "First", 91); + person p2 ("John", "Second", 81); + person p3 ("John", "Third", 71); + person p4 ("John", "Fourth", 61); + person p5 ("John", "Fifth", 51); + + transaction t (db->begin ()); + db->persist (p1); + db->persist (p2); + db->persist (p3); + db->persist (p4); + db->persist (p5); + t.commit (); + } + + typedef odb::query<person> query; + typedef odb::prepared_query<person> prep_query; + typedef odb::result<person> result; + + // Example of an uncached prepared query in the same transaction. + // + { + transaction t (db->begin ()); + + unsigned short age; + query q (query::age > query::_ref (age)); + prep_query pq (db->prepare_query<person> ("person-age-query", q)); + + for (age = 90; age > 40; age -= 10) + { + result r (pq.execute ()); + print_ages (age, r); + } + + t.commit (); + } + + // Example of an uncached prepared query in multiple transactions. + // + // Note that here we have to first obtain a connection, then prepare + // the query using this connection, and finally start each transaction + // that uses the prepared query on this connection. + // + { + connection_ptr conn (db->connection ()); + + unsigned short age; + query q (query::age > query::_ref (age)); + prep_query pq (conn->prepare_query<person> ("person-age-query", q)); + + for (age = 90; age > 40; age -= 10) + { + transaction t (conn->begin ()); + + result r (pq.execute ()); + print_ages (age, r); + + t.commit (); + } + } + + // Example of a cached prepared query without by-reference parameters. + // + for (unsigned short i (0); i < 5; ++i) + { + transaction t (db->begin ()); + + prep_query pq (db->lookup_query<person> ("person-val-age-query")); + + if (!pq) + { + pq = db->prepare_query<person> ( + "person-val-age-query", query::age > 50); + db->cache_query (pq); + } + + result r (pq.execute ()); + print_ages (50, r); + + t.commit (); + } + + // Example of a cached prepared query with by-reference parameters. + // + for (unsigned short age (90); age > 40; age -= 10) + { + transaction t (db->begin ()); + + unsigned short* age_param; + prep_query pq ( + db->lookup_query<person> ("person-ref-age-query", age_param)); + + if (!pq) + { + auto_ptr<unsigned short> p (new unsigned short); + age_param = p.get (); + query q (query::age > query::_ref (*age_param)); + pq = db->prepare_query<person> ("person-ref-age-query", q); + db->cache_query (pq, p); // Assumes ownership of p. + } + + *age_param = age; // Initialize the parameter. + result r (pq.execute ()); + print_ages (age, r); + + t.commit (); + } + + // Example of a cached prepared query that uses a query factory. + // + db->query_factory ("person-age-name-query", &query_factory); + + for (unsigned short age (90); age > 40; age -= 10) + { + transaction t (db->begin ()); + + params* p; + prep_query pq (db->lookup_query<person> ("person-age-name-query", p)); + assert (pq); + + p->age = age; + p->first = "John"; + result r (pq.execute ()); + print_ages (age, r); + + t.commit (); + } + + // In C++11 the above call to query_factory() can be re-written to + // use a lambda function, for example: + // + /* + db->query_factory ( + "person-age-name-query", + [] (const char* name, connection& c) + { + auto_ptr<params> p (new params); + query q (query::age > query::_ref (p->age) && + query::first == query::_ref (p->first)); + prepared_query<person> pq (c.prepare_query<person> (name, q)); + c.cache_query (pq, p); + }); + */ + + // Prepared queries can also be used with views, as shown in the + // following example. + // + { + typedef odb::query<person_count> query; + typedef odb::prepared_query<person_count> prep_query; + typedef odb::result<person_count> result; + + transaction t (db->begin ()); + + unsigned short age; + query q (query::age > query::_ref (age)); + prep_query pq ( + db->prepare_query<person_count> ("person-count-age-query", q)); + + for (age = 90; age > 40; age -= 10) + { + result r (pq.execute ()); + cout << "over " << age << ": " << r.begin ()->count << endl; + } + + t.commit (); + } + } + catch (const odb::exception& e) + { + cerr << e.what () << endl; + return 1; + } +} diff --git a/prepared/makefile b/prepared/makefile new file mode 100644 index 0000000..c013f81 --- /dev/null +++ b/prepared/makefile @@ -0,0 +1,120 @@ +# file : prepared/makefile +# copyright : Copyright (c) 2009-2012 Code Synthesis Tools CC +# license : GNU GPL v2; see accompanying LICENSE file + +include $(dir $(lastword $(MAKEFILE_LIST)))../build/bootstrap.make + +cxx_tun := driver.cxx +odb_hdr := person.hxx +cxx_obj := $(addprefix $(out_base)/,$(cxx_tun:.cxx=.o) $(odb_hdr:.hxx=-odb.o)) +cxx_od := $(cxx_obj:.o=.o.d) + +driver := $(out_base)/driver +dist := $(out_base)/.dist +test := $(out_base)/.test +clean := $(out_base)/.clean + +# Import. +# +$(call import,\ + $(scf_root)/import/odb/stub.make,\ + odb: odb,odb-rules: odb_rules) + +$(call import,\ + $(scf_root)/import/libodb/stub.make,\ + l: odb.l,cpp-options: odb.l.cpp-options) + +ifdef db_id +$(call import,\ + $(scf_root)/import/libodb-$(db_id)/stub.make,\ + l: odb_db.l,cpp-options: odb_db.l.cpp-options) +endif + +ifeq ($(odb_db.l.cpp-options),) +odb_db.l.cpp-options := $(out_base)/.unbuildable +endif + +# Build. +# +$(driver): $(cxx_obj) $(odb_db.l) $(odb.l) +$(cxx_obj) $(cxx_od): cpp_options := -I$(out_base) -I$(src_base) -D$(db_macro) +$(cxx_obj) $(cxx_od): $(odb.l.cpp-options) $(odb_db.l.cpp-options) + +genf := $(addprefix $(odb_hdr:.hxx=-odb),.hxx .ixx .cxx) $(odb_hdr:.hxx=.sql) +gen := $(addprefix $(out_base)/,$(genf)) + +$(gen): $(odb) +$(gen): odb := $(odb) +$(gen) $(dist): export odb_options += --database $(db_id) --generate-query \ +--generate-prepared --generate-schema +$(gen): cpp_options := -I$(src_base) +$(gen): $(odb.l.cpp-options) + +$(call include-dep,$(cxx_od),$(cxx_obj),$(gen)) + +# Alias for default target. +# +$(out_base)/: $(driver) + +# Dist +# +name := $(subst /,-,$(subst $(src_root)/,,$(src_base))) + +$(dist): db_id := @database@ +$(dist): sources := $(cxx_tun) +$(dist): headers := $(odb_hdr) +$(dist): export name := $(name) +$(dist): export odb_header_stem := $(basename $(odb_hdr)) +$(dist): export extra_dist := README $(call vc9projs,$(name)) \ +$(call vc10projs,$(name)) $(call vc11projs,$(name)) +$(dist): + $(call dist-data,$(sources) $(headers) README database.hxx) + $(call meta-automake,../template/Makefile.am) + $(call meta-vc9projs,../template/template,$(name)) + $(call meta-vc10projs,../template/template,$(name)) + $(call meta-vc11projs,../template/template,$(name)) + +# Test. +# +$(test): header := $(odb_hdr) +$(test): $(driver) + $(call schema) + $(call message,test $<,$< --options-file $(dcf_root)/db.options) + +# Clean. +# +$(clean): \ + $(driver).o.clean \ + $(addsuffix .cxx.clean,$(cxx_obj)) \ + $(addsuffix .cxx.clean,$(cxx_od)) \ + $(addprefix $(out_base)/,$(odb_hdr:.hxx=-odb.cxx.hxx.clean)) + +# Generated .gitignore. +# +ifeq ($(out_base),$(src_base)) +$(driver): | $(out_base)/.gitignore + +$(out_base)/.gitignore: files := driver $(genf) +$(clean): $(out_base)/.gitignore.clean + +$(call include,$(bld_root)/git/gitignore.make) +endif + +# How to. +# +$(call include,$(bld_root)/dist.make) +$(call include,$(bld_root)/meta/vc9proj.make) +$(call include,$(bld_root)/meta/vc10proj.make) +$(call include,$(bld_root)/meta/vc11proj.make) +$(call include,$(bld_root)/meta/automake.make) + +$(call include,$(bld_root)/cxx/standard.make) # cxx_standard +ifdef cxx_standard +$(gen): odb_options += --std $(cxx_standard) +$(call include,$(odb_rules)) +endif + +$(call include,$(bld_root)/cxx/cxx-d.make) +$(call include,$(bld_root)/cxx/cxx-o.make) +$(call include,$(bld_root)/cxx/o-e.make) + diff --git a/prepared/person.hxx b/prepared/person.hxx new file mode 100644 index 0000000..dc8e6fe --- /dev/null +++ b/prepared/person.hxx @@ -0,0 +1,61 @@ +// file : prepared/person.hxx +// copyright : not copyrighted - public domain + +#ifndef PERSON_HXX +#define PERSON_HXX + +#include <string> +#include <cstddef> // std::size_t + +#include <odb/core.hxx> + +#pragma db object +class person +{ +public: + person (const std::string& first, + const std::string& last, + unsigned short age) + : first_ (first), last_ (last), age_ (age) + { + } + + const std::string& + first () const + { + return first_; + } + + const std::string& + last () const + { + return last_; + } + + unsigned short + age () const + { + return age_; + } + +private: + friend class odb::access; + + person () {} + + #pragma db id auto + unsigned long id_; + + std::string first_; + std::string last_; + unsigned short age_; +}; + +#pragma db view object(person) +struct person_count +{ + #pragma db column("count(" + person::id_ + ")") + std::size_t count; +}; + +#endif // PERSON_HXX |