DatabaseDemo.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Urho3D.h>
  23. #include <Urho3D/Core/CoreEvents.h>
  24. #include <Urho3D/Core/ProcessUtils.h>
  25. #include <Urho3D/Database/Database.h>
  26. #include <Urho3D/Database/DatabaseEvents.h>
  27. #include <Urho3D/Engine/Console.h>
  28. #include <Urho3D/Engine/Engine.h>
  29. #include <Urho3D/Engine/EngineEvents.h>
  30. #include <Urho3D/Input/Input.h>
  31. #include <Urho3D/IO/Log.h>
  32. #include <Urho3D/UI/Button.h>
  33. #include "DatabaseDemo.h"
  34. // Expands to this example's entry-point
  35. DEFINE_APPLICATION_MAIN(DatabaseDemo)
  36. DatabaseDemo::DatabaseDemo(Context* context) :
  37. Sample(context),
  38. connection_(0),
  39. row_(0),
  40. maxRows_(50)
  41. {
  42. }
  43. DatabaseDemo::~DatabaseDemo()
  44. {
  45. // Although the managed database connection will be disconnected by Database subsystem automatically in its destructor,
  46. // it is a good practice for a class to balance the number of connect() and disconnect() calls.
  47. GetSubsystem<Database>()->Disconnect(connection_);
  48. connection_ = 0;
  49. }
  50. void DatabaseDemo::Start()
  51. {
  52. // Execute base class startup
  53. Sample::Start();
  54. // Subscribe to console commands and the frame update
  55. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(DatabaseDemo, HandleConsoleCommand));
  56. SubscribeToEvent(E_UPDATE, HANDLER(DatabaseDemo, HandleUpdate));
  57. // Subscribe key down event
  58. SubscribeToEvent(E_KEYDOWN, HANDLER(DatabaseDemo, HandleEscKeyDown));
  59. // Hide logo to make room for the console
  60. SetLogoVisible(false);
  61. // Show the console by default, make it large. Console will show the text edit field when there is at least one
  62. // subscriber for the console command event
  63. Console* console = GetSubsystem<Console>();
  64. console->SetNumRows((unsigned)(GetSubsystem<Graphics>()->GetHeight() / 16));
  65. console->SetNumBufferedRows(2 * console->GetNumRows());
  66. console->SetCommandInterpreter(GetTypeName());
  67. console->SetVisible(true);
  68. console->GetCloseButton()->SetVisible(false);
  69. // Show OS mouse cursor
  70. GetSubsystem<Input>()->SetMouseVisible(true);
  71. // Open the operating system console window (for stdin / stdout) if not open yet
  72. OpenConsoleWindow();
  73. // In general, the connection string is really the only thing that need to be changed when switching underlying database API
  74. // and that when using ODBC API then the connection string must refer to an already installed ODBC driver
  75. // Although it has not been tested yet but the ODBC API should be able to interface with any vendor provided ODBC drivers
  76. // In this particular demo, however, when using ODBC API then the SQLite-ODBC driver need to be installed
  77. // The SQLite-ODBC driver can be built from source downloaded from http://www.ch-werner.de/sqliteodbc/
  78. // You can try to install other ODBC driver and modify the connection string below to match your ODBC driver
  79. // Both DSN and DSN-less connection string should work
  80. // The ODBC API, i.e. URHO3D_DATABASE_ODBC build option, is only available for native (including RPI) platforms
  81. // and it is designed for development of game server connecting to ODBC-compliant databases in mind
  82. // This demo will always work when using SQLite API as the SQLite database engine is embedded inside Urho3D game engine
  83. // and this is also the case when targeting HTML5 in Emscripten build
  84. // We could have used #ifdef to init the connection string during compile time, but below shows how it is done during runtime
  85. // The "URHO3D_DATABASE_ODBC" compiler define is set when URHO3D_DATABASE_ODBC build option is enabled
  86. // Connect to a temporary in-memory SQLite database
  87. connection_ =
  88. GetSubsystem<Database>()->Connect(Database::GetAPI() == DBAPI_ODBC ? "Driver=SQLite3;Database=:memory:" : "file://");
  89. // Subscribe to database cursor event to loop through query resultset
  90. SubscribeToEvent(E_DBCURSOR, HANDLER(DatabaseDemo, HandleDbCursor));
  91. // Show instruction
  92. Print("This demo connects to temporary in-memory database.\n"
  93. "All the tables and their data will be lost after exiting the demo.\n"
  94. "Enter a valid SQL statement in the console input and press Enter to execute.\n"
  95. "Enter 'get/set maxrows [number]' to get/set the maximum rows to be printed out.\n"
  96. "Enter 'get/set connstr [string]' to get/set the database connection string and establish a new connection to it.\n"
  97. "Enter 'quit' or 'exit' to exit the demo.\n"
  98. "For example:\n ");
  99. HandleInput("create table tbl1(col1 varchar(10), col2 smallint)");
  100. HandleInput("insert into tbl1 values('Hello', 10)");
  101. HandleInput("insert into tbl1 values('World', 20)");
  102. HandleInput("select * from tbl1");
  103. }
  104. void DatabaseDemo::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  105. {
  106. using namespace ConsoleCommand;
  107. if (eventData[P_ID].GetString() == GetTypeName())
  108. HandleInput(eventData[P_COMMAND].GetString());
  109. }
  110. void DatabaseDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  111. {
  112. // Check if there is input from stdin
  113. String input = GetConsoleInput();
  114. if (input.Length())
  115. HandleInput(input);
  116. }
  117. void DatabaseDemo::HandleEscKeyDown(StringHash eventType, VariantMap& eventData)
  118. {
  119. // Unlike the other samples, exiting the engine when ESC is pressed instead of just closing the console
  120. if (eventData[KeyDown::P_KEY].GetInt() == KEY_ESC)
  121. engine_->Exit();
  122. }
  123. void DatabaseDemo::HandleDbCursor(StringHash eventType, VariantMap& eventData)
  124. {
  125. using namespace DbCursor;
  126. // In a real application the P_SQL can be used to do the logic branching in a shared event handler
  127. // However, this is not required in this sample demo
  128. unsigned numCols = eventData[P_NUMCOLS].GetUInt();
  129. const VariantVector& colValues = eventData[P_COLVALUES].GetVariantVector();
  130. const Vector<String>& colHeaders = eventData[P_COLHEADERS].GetStringVector();
  131. // In this sample demo we just use db cursor to dump each row immediately so we can filter out the row to conserve memory
  132. // In a real application this can be used to perform the client-side filtering logic
  133. eventData[P_FILTER] = true;
  134. // In this sample demo we abort the further cursor movement when maximum rows being dumped has been reached
  135. eventData[P_ABORT] = ++row_ >= maxRows_;
  136. for (unsigned i = 0; i < numCols; ++i)
  137. Print(ToString("Row #%d: %s = %s", row_, colHeaders[i].CString(), colValues[i].ToString().CString()));
  138. }
  139. void DatabaseDemo::HandleInput(const String& input)
  140. {
  141. // Echo input string to stdout
  142. Print(input);
  143. row_ = 0;
  144. if (input == "quit" || input == "exit")
  145. engine_->Exit();
  146. else if (input.StartsWith("set") || input.StartsWith("get"))
  147. {
  148. // We expect a key/value pair for 'set' command
  149. Vector<String> tokens = input.Substring(3).Split(' ');
  150. String setting = tokens.Size() ? tokens[0] : "";
  151. if (input.StartsWith("set") && tokens.Size() > 1)
  152. {
  153. if (setting == "maxrows")
  154. maxRows_ = (unsigned)Max(ToUInt(tokens[1]), 1);
  155. else if (setting == "connstr")
  156. {
  157. String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
  158. Database* database = GetSubsystem<Database>();
  159. DbConnection* newConnection = database->Connect(newConnectionString);
  160. if (newConnection)
  161. {
  162. database->Disconnect(connection_);
  163. connection_ = newConnection;
  164. }
  165. }
  166. }
  167. if (tokens.Size())
  168. {
  169. if (setting == "maxrows")
  170. Print(ToString("maximum rows is set to %d", maxRows_));
  171. else if (setting == "connstr")
  172. Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
  173. else
  174. Print(ToString("Unrecognized setting: %s", setting.CString()));
  175. }
  176. else
  177. Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
  178. }
  179. else
  180. {
  181. // In this sample demo we use the dbCursor event to loop through each row as it is being fetched
  182. // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
  183. // unless the dbCursor event handler has instructed to filter out the fetched row from the final result
  184. DbResult result = connection_->Execute(input, true);
  185. // Number of affected rows is only meaningful for DML statements like insert/update/delete
  186. if (result.GetNumAffectedRows() != -1)
  187. Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
  188. }
  189. Print(" ");
  190. }
  191. void DatabaseDemo::Print(const String& output)
  192. {
  193. // Logging appears both in the engine console and stdout
  194. LOGRAW(output + "\n");
  195. }