DatabaseDemo.cpp 9.8 KB

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