First commit
[anna.git] / example / dbms.mysql / xInsert / main.cpp
1 // ANNA - Anna is Not 'N' 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 #include <iostream>
38
39 #include <anna/core/core.hpp>
40 #include <anna/dbms/dbms.hpp>
41 #include <anna/app/app.hpp>
42
43 #include <anna/dbms.mysql/Database.hpp>
44 #include <anna/dbms.mysql/OracleTranslator.hpp>
45
46 class Insert : public Application {
47 public:
48    Insert ();
49    ~Insert () { delete a_db; }
50    
51 private:
52    anna::dbms::Database* a_db;
53
54    void initialize () throw (RuntimeException); 
55    void run () throw (RuntimeException);      
56 };
57
58 using namespace std;
59
60 int main (int argc, const char** argv)
61 {
62    CommandLine& commandLine (CommandLine::instantiate ());
63    Insert testNull;
64
65    try {
66       commandLine.initialize (argv, argc);
67       commandLine.verify ();
68
69       Logger::setLevel (Logger::Debug); 
70       Logger::initialize ("copy", new TraceWriter ("xinsert.trace", 1024 * 1024));
71  
72       testNull.start ();
73    }
74    catch (Exception& ex) {
75       cout << ex.asString () << endl;
76    }
77    
78    return 0;
79 }
80
81 Insert::Insert () : 
82    Application ("xinsert", "Copiador de la tabla ad_funcionalidades", "1.0"),
83    a_db (NULL)
84 {
85    CommandLine& cl (CommandLine::instantiate ());
86       
87    cl.add ("user", CommandLine::Argument::Mandatory, "Nombre del usuario");
88    cl.add ("password", CommandLine::Argument::Mandatory, "Clave del usuario");
89    cl.add ("host", CommandLine::Argument::Optional, "Nombre de la máquina donde se ubica el MySQL");
90    cl.add ("db", CommandLine::Argument::Optional, "Nombre de la base de datos");
91 }
92
93 /*
94  * Las sentencias SQL usadas por este programana estaba originalmente escritas para Oracle,
95  * pero no hay que cambiar cada sentencia manualmente, s�lo hay que activar el traductor
96  * correspondiente y anna.dbms.mysql lo hace autom�ticamente.
97  */
98 void Insert::initialize ()
99    throw (RuntimeException)
100 {
101    CommandLine& ccll = CommandLine::instantiate ();
102    const char* host = ccll.exists ("host") ? ccll.getValue ("host"): NULL;
103
104    a_db = new anna::dbms::mysql::Database (ccll.getValue ("db"), host);
105    a_db->setStatementTranslator (dbms::mysql::OracleTranslator::instantiate ());
106 }
107
108 void Insert::run () 
109    throw (RuntimeException)
110 {
111    LOGMETHOD (TraceMethod tm ("Insert", "run", ANNA_FILE_LOCATION)); 
112
113    CommandLine& cl (CommandLine::instantiate ());
114    
115    Statement* create;
116    Statement* insert;
117   
118    dbms::Integer n (true);
119    dbms::String name (15, true);
120    dbms::Float zz (true);
121    dbms::TimeStamp time (true);
122
123    dbms::ResultCode resultCode;
124
125    try {      
126       Connection* connection = a_db->createConnection ("xinsert", cl.getValue ("user"), cl.getValue ("password"));
127
128       {
129          Guard guard (connection);
130
131          try {
132             create = a_db->createStatement (
133                "create", "create table anna_db_test (xx integer, yy varchar (15), zz float, tt datetime)"
134             );
135                         
136             resultCode = connection->execute (create);
137          }
138          catch (Exception& ex) {
139             ex.trace ();
140          }
141          cout << "Creando: " << resultCode.asString () << endl << endl;
142       }
143       Guard guard (connection);     
144
145       /*
146        * Observar que la sentencia indica los parámetros tal y como se haría en Oracle.
147        */
148       insert = a_db->createStatement ("select", "insert into anna_db_test (xx, yy, zz, tt) values (:x,:y,:z, :t)");
149       insert->bindInput ("XX", n);
150       insert->bindInput ("YY", name);
151       insert->bindInput ("zz", zz);
152       insert->bindInput ("tt", time);
153
154       n = 88;
155       name = "El 88";
156       zz = 0.88;
157       time.setValue (anna::functions::second ());
158       cout << endl << " --- Insertando 1 ---" << endl;
159       resultCode = connection->execute (insert);                       
160       cout << resultCode.asString () << endl << endl;  
161       
162       n = 1010;
163       name = "El 1010";
164       zz = 0.1010;
165       time.setNull (true);
166       cout << endl << " --- Insertando 2 (date=null)---" << endl;
167       resultCode = connection->execute (insert);                       
168       cout << resultCode.asString () << endl << endl;  
169       
170       n = 89;
171       name.setNull (true);
172       zz = 0.89;
173       time.setValue ((Second)(anna::functions::second () + 100));
174       cout << endl << " --- Insertando 2 (name=null)---" << endl;
175       resultCode = connection->execute (insert);                       
176       cout << resultCode.asString () << endl << endl;  
177    }
178    catch (dbms::DatabaseException& edb) {
179       throw RuntimeException (edb); 
180    }
181 }
182
183
184