Updated license
[anna.git] / include / anna / dbms / Sentence.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_dbms_Sentence_hpp
38 #define anna_dbms_Sentence_hpp
39
40 #include <anna/core/mt/Mutex.hpp>
41
42 #include <anna/dbms/ResultCode.hpp>
43
44 namespace anna {
45
46 namespace xml {
47 class Node;
48 }
49
50 namespace dbms {
51
52 class Database;
53 class Connection;
54 class Statement;
55
56 /**
57    Clase que facilita la ejecucion de sentencias SQL compuestas y la comprobacion de errores ya que
58    solo devuelve excepciones de tipo anna::RuntimeException.
59 */
60 class Sentence : public Mutex {
61 public:
62   /**
63      Modos de actuar cuando se detecta un error en la ejecucion de las sentencias SQL.
64      \see Sentence
65   */
66   struct Mode { enum _v { ExceptionWhenNotFound, SilentWhenNotFound }; };
67
68   /**
69      Ejecuta la sentencia SQL asociada a este instancia. Antes de invocar a este metodo debemos
70      activar una seccion critica sobre esta instancia.
71      \param connection Conexion usada para ejecutar la sentencia. Debe tener activa una seccion critica.
72   */
73   virtual dbms::ResultCode execute(dbms::Connection& connection) throw(RuntimeException) {
74     return execute(connection, a_dbStatement);
75   }
76
77   /**
78      Devuelve el nombre de la sentencia SQL asociada a esta instancia.
79      \return El nombre de la sentencia SQL asociada a esta instancia.
80      \warning Si todavia no tiene nombre asociado devolvera una cadena vacia.
81   */
82   const std::string& getName() const throw();
83
84   /**
85      Inicializa el estado de esta instancia
86      \param database Instancia de la base de datos usada para definir las sentencias SQL que componen esta
87      instancia.
88   */
89   void initialize(dbms::Database& database) throw(RuntimeException);
90
91   /**
92      Transfiere un registro desde la base de datos a las variables del entorno C++.
93      \return \em false si no hay mas registros o \em true en caso contrario.
94   */
95   bool fetch() throw(RuntimeException);
96
97   /**
98      Transfiere un registro desde la base de datos a las variables del entorno C++.
99      \param resultCode Variable que contiene el resultado de invocar a anna::dbms::Sentence::execute
100      \return \em false si no hay mas registros o \em true en caso contrario.
101   */
102   bool fetch(const ResultCode& resultCode) throw(RuntimeException) {
103     return (resultCode.successful() == true) ? fetch() : false;
104   }
105
106   /**
107      Devuelve una cadena con la informacion referente a esta instancia.
108      \return una cadena con la informacion referente a esta instancia.
109   */
110   virtual std::string asString() const throw();
111
112   /**
113      Devuelve un documento XML con la informacion referente a esta instancia.
114      \param parent Nodo XML del que dependerá la información referente a esta instancia.
115      \return un documento XML con la informacion referente a esta instancia.
116   */
117   virtual xml::Node* asXML(xml::Node* parent) const throw();
118
119 protected:
120   /**
121      Constructor.
122      \param mode Modo de actuacion en caso de detectar errores.
123   */
124   Sentence(const Mode::_v mode = Mode::ExceptionWhenNotFound) :
125     a_mode(mode), a_dbStatement(NULL)
126   {;}
127
128   /**
129      Ejecuta la sentencia SQL asociada a este instancia.
130      \param connection Conexion usada para ejecutar la sentencia. Debe tener activa una seccion critica.
131      \param statement Sentencia a ejecutar.
132   */
133   dbms::ResultCode execute(dbms::Connection& connection, dbms::Statement* statement) throw(RuntimeException);
134
135   /**
136      Metodo que debe inicializar las sentencias asociadas a esta instancia (valores de entrada y salida).
137      \return Retorna la instancia de la sentencia asociada a esta instancia debidamente inicializada.
138   */
139   virtual dbms::Statement* do_initialize(dbms::Database&) throw(RuntimeException) = 0;
140
141 private:
142   const Mode::_v a_mode;
143   dbms::Statement* a_dbStatement;
144 };
145
146 }
147 }
148
149 #endif
150