From 8338bb049db44d9b470b2a76acc5853b92915238 Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Wed, 17 Oct 2012 09:31:54 +0200 Subject: Add example for prepared query usage --- README | 3 + makefile | 1 + prepared/README | 65 ++++++++++++++ prepared/database.hxx | 94 ++++++++++++++++++++ prepared/driver.cxx | 232 ++++++++++++++++++++++++++++++++++++++++++++++++++ prepared/makefile | 120 ++++++++++++++++++++++++++ prepared/person.hxx | 61 +++++++++++++ 7 files changed, 576 insertions(+) create mode 100644 prepared/README create mode 100644 prepared/database.hxx create mode 100644 prepared/driver.cxx create mode 100644 prepared/makefile create mode 100644 prepared/person.hxx diff --git a/README b/README index 8b26963..bbaea80 100644 --- a/README +++ b/README @@ -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. diff --git a/makefile b/makefile index 31672fb..8f9c314 100644 --- a/makefile +++ b/makefile @@ -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 --generate-query --generate-prepared \ +--generate-schema person.hxx + + Where 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 +#include // std::auto_ptr +#include // std::exit +#include + +#include + +#if defined(DATABASE_MYSQL) +# include +#elif defined(DATABASE_SQLITE) +# include +# include +# include +# include +#elif defined(DATABASE_PGSQL) +# include +#elif defined(DATABASE_ORACLE) +# include +#elif defined(DATABASE_MSSQL) +# include +#else +# error unknown database; did you forget to define the DATABASE_* macros? +#endif + +inline std::auto_ptr +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 db (new odb::mysql::database (argc, argv)); +#elif defined(DATABASE_SQLITE) + auto_ptr 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 db (new odb::pgsql::database (argc, argv)); +#elif defined(DATABASE_ORACLE) + auto_ptr db (new odb::oracle::database (argc, argv)); +#elif defined(DATABASE_MSSQL) + auto_ptr 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 // std::auto_ptr +#include +#include + +#include +#include +#include + +#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 query; + + auto_ptr p (new params); + query q (query::age > query::_ref (p->age) && + query::first == query::_ref (p->first)); + prepared_query pq (c.prepare_query (name, q)); + c.cache_query (pq, p); +} + +static void +print_ages (unsigned short age, odb::result r) +{ + cout << "over " << age << ':'; + + for (odb::result::iterator i (r.begin ()); i != r.end (); ++i) + cout << ' ' << i->age (); + + cout << endl; +} + +int +main (int argc, char* argv[]) +{ + try + { + auto_ptr 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 query; + typedef odb::prepared_query prep_query; + typedef odb::result 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-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-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-val-age-query")); + + if (!pq) + { + pq = db->prepare_query ( + "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-ref-age-query", age_param)); + + if (!pq) + { + auto_ptr p (new unsigned short); + age_param = p.get (); + query q (query::age > query::_ref (*age_param)); + pq = db->prepare_query ("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-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 p (new params); + query q (query::age > query::_ref (p->age) && + query::first == query::_ref (p->first)); + prepared_query pq (c.prepare_query (name, q)); + c.cache_query (pq, p); + }); + */ + + // Prepared queries can also be used with views, as shown in the + // following example. + // + { + typedef odb::query query; + typedef odb::prepared_query prep_query; + typedef odb::result result; + + transaction t (db->begin ()); + + unsigned short age; + query q (query::age > query::_ref (age)); + prep_query pq ( + db->prepare_query ("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 +#include // std::size_t + +#include + +#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 -- cgit v1.1