DatabaseDemo.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. //
  2. // Copyright (c) 2008-2017 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. URHO3D_DEFINE_APPLICATION_MAIN(DatabaseDemo)
  35. DatabaseDemo::DatabaseDemo(Context* context) :
  36. Sample(context),
  37. connection_(nullptr),
  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_ = nullptr;
  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. // Set the mouse mode to use in the sample
  71. Sample::InitMouseMode(MM_FREE);
  72. // Open the operating system console window (for stdin / stdout) if not open yet
  73. OpenConsoleWindow();
  74. // In general, the connection string is really the only thing that need to be changed when switching underlying database API
  75. // and that when using ODBC API then the connection string must refer to an already installed ODBC driver
  76. // Although it has not been tested yet but the ODBC API should be able to interface with any vendor provided ODBC drivers
  77. // In this particular demo, however, when using ODBC API then the SQLite-ODBC driver need to be installed
  78. // The SQLite-ODBC driver can be built from source downloaded from http://www.ch-werner.de/sqliteodbc/
  79. // You can try to install other ODBC driver and modify the connection string below to match your ODBC driver
  80. // Both DSN and DSN-less connection string should work
  81. // The ODBC API, i.e. URHO3D_DATABASE_ODBC build option, is only available for native (including RPI) platforms
  82. // and it is designed for development of game server connecting to ODBC-compliant databases in mind
  83. // This demo will always work when using SQLite API as the SQLite database engine is embedded inside Urho3D game engine
  84. // and this is also the case when targeting Web platform
  85. // We could have used #ifdef to init the connection string during compile time, but below shows how it is done during runtime
  86. // The "URHO3D_DATABASE_ODBC" compiler define is set when URHO3D_DATABASE_ODBC build option is enabled
  87. // Connect to a temporary in-memory SQLite database
  88. connection_ =
  89. GetSubsystem<Database>()->Connect(Database::GetAPI() == DBAPI_ODBC ? "Driver=SQLite3;Database=:memory:" : "file://");
  90. // Subscribe to database cursor event to loop through query resultset
  91. SubscribeToEvent(E_DBCURSOR, URHO3D_HANDLER(DatabaseDemo, HandleDbCursor));
  92. // Show instruction
  93. Print("This demo connects to temporary in-memory database.\n"
  94. "All the tables and their data will be lost after exiting the demo.\n"
  95. "Enter a valid SQL statement in the console input and press Enter to execute.\n"
  96. "Enter 'get/set maxrows [number]' to get/set the maximum rows to be printed out.\n"
  97. "Enter 'get/set connstr [string]' to get/set the database connection string and establish a new connection to it.\n"
  98. "Enter 'quit' or 'exit' to exit the demo.\n"
  99. "For example:\n ");
  100. HandleInput("create table tbl1(col1 varchar(10), col2 smallint)");
  101. HandleInput("insert into tbl1 values('Hello', 10)");
  102. HandleInput("insert into tbl1 values('World', 20)");
  103. HandleInput("select * from tbl1");
  104. }
  105. void DatabaseDemo::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  106. {
  107. using namespace ConsoleCommand;
  108. if (eventData[P_ID].GetString() == GetTypeName())
  109. HandleInput(eventData[P_COMMAND].GetString());
  110. }
  111. void DatabaseDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
  112. {
  113. // Check if there is input from stdin
  114. String input = GetConsoleInput();
  115. if (input.Length())
  116. HandleInput(input);
  117. }
  118. void DatabaseDemo::HandleEscKeyDown(StringHash eventType, VariantMap& eventData)
  119. {
  120. // Unlike the other samples, exiting the engine when ESC is pressed instead of just closing the console
  121. if (eventData[KeyDown::P_KEY].GetInt() == KEY_ESCAPE)
  122. engine_->Exit();
  123. }
  124. void DatabaseDemo::HandleDbCursor(StringHash eventType, VariantMap& eventData)
  125. {
  126. using namespace DbCursor;
  127. // In a real application the P_SQL can be used to do the logic branching in a shared event handler
  128. // However, this is not required in this sample demo
  129. unsigned numCols = eventData[P_NUMCOLS].GetUInt();
  130. const VariantVector& colValues = eventData[P_COLVALUES].GetVariantVector();
  131. const Vector<String>& colHeaders = eventData[P_COLHEADERS].GetStringVector();
  132. // In this sample demo we just use db cursor to dump each row immediately so we can filter out the row to conserve memory
  133. // In a real application this can be used to perform the client-side filtering logic
  134. eventData[P_FILTER] = true;
  135. // In this sample demo we abort the further cursor movement when maximum rows being dumped has been reached
  136. eventData[P_ABORT] = ++row_ >= maxRows_;
  137. for (unsigned i = 0; i < numCols; ++i)
  138. Print(ToString("Row #%d: %s = %s", row_, colHeaders[i].CString(), colValues[i].ToString().CString()));
  139. }
  140. void DatabaseDemo::HandleInput(const String& input)
  141. {
  142. // Echo input string to stdout
  143. Print(input);
  144. row_ = 0;
  145. if (input == "quit" || input == "exit")
  146. engine_->Exit();
  147. else if (input.StartsWith("set") || input.StartsWith("get"))
  148. {
  149. // We expect a key/value pair for 'set' command
  150. Vector<String> tokens = input.Substring(3).Split(' ');
  151. String setting = tokens.Size() ? tokens[0] : "";
  152. if (input.StartsWith("set") && tokens.Size() > 1)
  153. {
  154. if (setting == "maxrows")
  155. maxRows_ = Max(ToUInt(tokens[1]), 1U);
  156. else if (setting == "connstr")
  157. {
  158. String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
  159. Database* database = GetSubsystem<Database>();
  160. DbConnection* newConnection = database->Connect(newConnectionString);
  161. if (newConnection)
  162. {
  163. database->Disconnect(connection_);
  164. connection_ = newConnection;
  165. }
  166. }
  167. }
  168. if (tokens.Size())
  169. {
  170. if (setting == "maxrows")
  171. Print(ToString("maximum rows is set to %d", maxRows_));
  172. else if (setting == "connstr")
  173. Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
  174. else
  175. Print(ToString("Unrecognized setting: %s", setting.CString()));
  176. }
  177. else
  178. Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
  179. }
  180. else
  181. {
  182. // In this sample demo we use the dbCursor event to loop through each row as it is being fetched
  183. // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
  184. // unless the dbCursor event handler has instructed to filter out the fetched row from the final result
  185. DbResult result = connection_->Execute(input, true);
  186. // Number of affected rows is only meaningful for DML statements like insert/update/delete
  187. if (result.GetNumAffectedRows() != -1)
  188. Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
  189. }
  190. Print(" ");
  191. }
  192. void DatabaseDemo::Print(const String& output)
  193. {
  194. // Logging appears both in the engine console and stdout
  195. URHO3D_LOGRAW(output + "\n");
  196. }