SQLiteObject.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //
  22. // Additional Copyrights
  23. // Copyright 2004 John Vanderbeck
  24. // Copyright 2016 Chris Calef
  25. //-----------------------------------------------------------------------------
  26. //-----------------------------------------------------------------------------
  27. // This code implements support for SQLite into Torque and TorqueScript
  28. //
  29. // Essentially this creates a scriptable object that interfaces with SQLite.
  30. //-----------------------------------------------------------------------------
  31. #include "SQLiteObject.h"
  32. #include "console/simBase.h"
  33. #include "console/engineAPI.h"
  34. #include "console/consoleInternal.h"
  35. #include <cstdlib>
  36. IMPLEMENT_CONOBJECT(SQLiteObject);
  37. SQLiteObject::SQLiteObject()
  38. {
  39. m_pDatabase = NULL;
  40. m_szErrorString = NULL;
  41. m_iLastResultSet = 0;
  42. m_iNextResultSet = 1;
  43. }
  44. SQLiteObject::~SQLiteObject()
  45. {
  46. S32 index;
  47. // if we still have a database open, close it
  48. CloseDatabase();
  49. // Clear out any error string we may have left
  50. ClearErrorString();
  51. // Clean up result sets
  52. //
  53. // Boy oh boy this is such a crazy hack!
  54. // I can't seem to iterate through a vector and clean it up without screwing the vector.
  55. // So (HACK HACK HACK) what i'm doing for now is making a temporary vector that
  56. // contains a list of the result sets that the user hasn't cleaned up.
  57. // Clean up all those result sets, then delete the temp vector.
  58. Vector<S32> vTemp;
  59. Vector<S32>::iterator iTemp;
  60. VectorPtr<sqlite_resultset*>::iterator i;
  61. for (i = m_vResultSets.begin(); i != m_vResultSets.end(); i++)
  62. {
  63. vTemp.push_back((*i)->iResultSet);
  64. }
  65. index = 0;
  66. for (iTemp = vTemp.begin(); iTemp != vTemp.end(); iTemp++)
  67. {
  68. Con::warnf("SQLiteObject Warning: Result set #%i was not cleared by script. Clearing it now.", vTemp[index]);
  69. ClearResultSet(vTemp[index]);
  70. index++;
  71. }
  72. m_vResultSets.clear();
  73. }
  74. bool SQLiteObject::processArguments(S32 argc, const char **argv)
  75. {
  76. if (argc == 0)
  77. return true;
  78. else
  79. return true;
  80. }
  81. bool SQLiteObject::onAdd()
  82. {
  83. if (!Parent::onAdd())
  84. return false;
  85. const char *name = getName();
  86. if (name && name[0] && getClassRep())
  87. {
  88. Namespace *parent = getClassRep()->getNameSpace();
  89. Con::linkNamespaces(parent->mName, name);
  90. mNameSpace = Con::lookupNamespace(name);
  91. }
  92. return true;
  93. }
  94. // This is the function that gets called when an instance
  95. // of your object is being removed from the system and being
  96. // destroyed. Use this to do your clean up and what not.
  97. void SQLiteObject::onRemove()
  98. {
  99. CloseDatabase();
  100. Parent::onRemove();
  101. }
  102. // To be honest i'm not 100% sure on when this is called yet.
  103. // Basically its used to set the values of any persistant fields
  104. // the object has. Similiar to the way datablocks work. I'm
  105. // just not sure how and when this gets called.
  106. void SQLiteObject::initPersistFields()
  107. {
  108. Parent::initPersistFields();
  109. }
  110. //-----------------------------------------------------------------------
  111. // These functions below are our custom functions that we will tie into
  112. // script.
  113. S32 Callback(void *pArg, S32 argc, char **argv, char **columnNames)
  114. {
  115. // basically this callback is called for each row in the SQL query result.
  116. // for each row, argc indicates how many columns are returned.
  117. // columnNames[i] is the name of the column
  118. // argv[i] is the value of the column
  119. sqlite_resultrow* pRow;
  120. sqlite_resultset* pResultSet;
  121. char* name;
  122. char* value;
  123. S32 i;
  124. if (argc == 0)
  125. return 0;
  126. pResultSet = (sqlite_resultset*)pArg;
  127. if (!pResultSet)
  128. return -1;
  129. // create a new result row
  130. pRow = new sqlite_resultrow;
  131. pResultSet->iNumCols = argc;
  132. // loop through all the columns and stuff them into our row
  133. for (i = 0; i < argc; i++)
  134. {
  135. // DBEUG CODE
  136. // Con::printf("%s = %s\n", columnNames[i], argv[i] ? argv[i] : "NULL");
  137. dsize_t columnNameLen = dStrlen(columnNames[i]) + 1;
  138. name = new char[columnNameLen];
  139. dStrcpy(name, columnNames[i], columnNameLen);
  140. pRow->vColumnNames.push_back(name);
  141. if (argv[i])
  142. {
  143. dsize_t valueLen = dStrlen(argv[i]) + 1;
  144. value = new char[valueLen];
  145. dStrcpy(value, argv[i], valueLen);
  146. pRow->vColumnValues.push_back(value);
  147. }
  148. else
  149. {
  150. value = new char[10];
  151. dStrcpy(value, "NULL", 10);
  152. pRow->vColumnValues.push_back(value);
  153. }
  154. }
  155. pResultSet->iNumRows++;
  156. pResultSet->vRows.push_back(pRow);
  157. // return 0 or else the sqlexec will be aborted.
  158. return 0;
  159. }
  160. bool SQLiteObject::OpenDatabase(const char* filename)
  161. {
  162. // check to see if we already have an open database, and
  163. // if so, close it.
  164. CloseDatabase();
  165. Con::printf("CALLING THE OLD OPEN DATABASE FUNCTION!!!!!!!!!!!!!!!!!!");
  166. // We persist the error string so that the script may make a
  167. // GetLastError() call at any time. However when we get
  168. // ready to make a call which could result in a new error,
  169. // we need to clear what we have to avoid a memory leak.
  170. ClearErrorString();
  171. S32 isOpen = sqlite3_open(filename, &m_pDatabase);
  172. if (isOpen == SQLITE_ERROR)
  173. {
  174. // there was an error and the database could not
  175. // be opened.
  176. m_szErrorString = (char *)sqlite3_errmsg(m_pDatabase);
  177. Con::executef(this, "2", "onOpenFailed()", m_szErrorString);
  178. return false;
  179. }
  180. else
  181. {
  182. // database was opened without error
  183. Con::executef(this, "1", "onOpened()");
  184. //Now, for OpenSimEarth, load spatialite dll, so we can have GIS functions.
  185. //S32 canLoadExt = sqlite3_load_extension(m_pDatabase,"mod_spatialite.dll",0,0);
  186. //Con::printf("opened spatialite extension: %d",canLoadExt);
  187. //Sigh, no luck yet. Cannot find function GeomFromText().
  188. }
  189. return true;
  190. }
  191. S32 SQLiteObject::ExecuteSQL(const char* sql)
  192. {
  193. S32 iResult;
  194. sqlite_resultset* pResultSet;
  195. // create a new resultset
  196. pResultSet = new sqlite_resultset;
  197. if (pResultSet)
  198. {
  199. pResultSet->bValid = false;
  200. pResultSet->iCurrentColumn = 0;
  201. pResultSet->iCurrentRow = 0;
  202. pResultSet->iNumCols = 0;
  203. pResultSet->iNumRows = 0;
  204. pResultSet->iResultSet = m_iNextResultSet;
  205. pResultSet->vRows.clear();
  206. m_iLastResultSet = m_iNextResultSet;
  207. m_iNextResultSet++;
  208. }
  209. else
  210. return 0;
  211. iResult = sqlite3_exec(m_pDatabase, sql, Callback, (void*)pResultSet, &m_szErrorString);
  212. if (iResult == 0)
  213. {
  214. //SQLITE_OK
  215. SaveResultSet(pResultSet);
  216. Con::executef(this, "1", "onQueryFinished()");
  217. return pResultSet->iResultSet;
  218. }
  219. else
  220. {
  221. // error occured
  222. Con::executef(this, "2", "onQueryFailed", m_szErrorString);
  223. Con::errorf("SQLite failed to execute query, error %s", m_szErrorString);
  224. delete pResultSet;
  225. return 0;
  226. }
  227. return 0;
  228. }
  229. void SQLiteObject::CloseDatabase()
  230. {
  231. if (m_pDatabase)
  232. sqlite3_close(m_pDatabase);
  233. m_pDatabase = NULL;
  234. }
  235. //(The following function is courtesy of sqlite.org, minus changes to use m_pDatabase instead of pInMemory.)
  236. /*
  237. ** This function is used to load the contents of a database file on disk
  238. ** into the "main" database of open database connection pInMemory, or
  239. ** to save the current contents of the database opened by pInMemory into
  240. ** a database file on disk. pInMemory is probably an in-memory database,
  241. ** but this function will also work fine if it is not.
  242. **
  243. ** Parameter zFilename points to a null-terminated string containing the
  244. ** name of the database file on disk to load from or save to. If parameter
  245. ** isSave is non-zero, then the contents of the file zFilename are
  246. ** overwritten with the contents of the database opened by pInMemory. If
  247. ** parameter isSave is zero, then the contents of the database opened by
  248. ** pInMemory are replaced by data loaded from the file zFilename.
  249. **
  250. ** If the operation is successful, SQLITE_OK is returned. Otherwise, if
  251. ** an error occurs, an SQLite error code is returned.
  252. */
  253. S32 SQLiteObject::loadOrSaveDb(const char *zFilename, bool isSave)
  254. {
  255. S32 rc; /* Function return code */
  256. sqlite3 *pFile; /* Database connection opened on zFilename */
  257. sqlite3_backup *pBackup; /* Backup object used to copy data */
  258. sqlite3 *pTo; /* Database to copy to (pFile or pInMemory) */
  259. sqlite3 *pFrom; /* Database to copy from (pFile or pInMemory) */
  260. /* Open the database file identified by zFilename. Exit early if this fails
  261. ** for any reason. */
  262. Con::printf("calling loadOrSaveDb, isSave = %d", isSave);
  263. if (isSave == false)
  264. {//If we're loading, have to create the memory database.
  265. if (!(SQLITE_OK == sqlite3_open(":memory:", &m_pDatabase)))
  266. {
  267. Con::printf("Unable to open a memory database!");
  268. return 0;
  269. }
  270. }
  271. rc = sqlite3_open(zFilename, &pFile);
  272. if (rc == SQLITE_OK) {
  273. /* If this is a 'load' operation (isSave==0), then data is copied
  274. ** from the database file just opened to database pInMemory.
  275. ** Otherwise, if this is a 'save' operation (isSave==1), then data
  276. ** is copied from pInMemory to pFile. Set the variables pFrom and
  277. ** pTo accordingly. */
  278. pFrom = (isSave ? m_pDatabase : pFile);
  279. pTo = (isSave ? pFile : m_pDatabase);
  280. /* Set up the backup procedure to copy from the "main" database of
  281. ** connection pFile to the main database of connection pInMemory.
  282. ** If something goes wrong, pBackup will be set to NULL and an error
  283. ** code and message left in connection pTo.
  284. **
  285. ** If the backup object is successfully created, call backup_step()
  286. ** to copy data from pFile to pInMemory. Then call backup_finish()
  287. ** to release resources associated with the pBackup object. If an
  288. ** error occurred, then an error code and message will be left in
  289. ** connection pTo. If no error occurred, then the error code belonging
  290. ** to pTo is set to SQLITE_OK.
  291. */
  292. pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
  293. if (pBackup) {
  294. (void)sqlite3_backup_step(pBackup, -1);
  295. (void)sqlite3_backup_finish(pBackup);
  296. }
  297. rc = sqlite3_errcode(pTo);
  298. }
  299. /* Close the database connection opened on database file zFilename
  300. ** and return the result of this function. */
  301. (void)sqlite3_close(pFile);
  302. //if (isSave == true) // Actually, cancel this, I'm sure it will happen automatically and if we don't do it here, we can also use
  303. //{ // this function for periodic saves, such as after saving mission.
  304. // sqlite3_close(m_pDatabase);
  305. //}
  306. Con::printf("finished loadOrSaveDb, rc = %d", rc);
  307. if (rc == 0)
  308. return true;
  309. else
  310. return false;
  311. }
  312. void SQLiteObject::NextRow(S32 resultSet)
  313. {
  314. sqlite_resultset* pResultSet;
  315. pResultSet = GetResultSet(resultSet);
  316. if (!pResultSet)
  317. return;
  318. pResultSet->iCurrentRow++;
  319. }
  320. bool SQLiteObject::EndOfResult(S32 resultSet)
  321. {
  322. sqlite_resultset* pResultSet;
  323. pResultSet = GetResultSet(resultSet);
  324. if (!pResultSet)
  325. return true;
  326. if (pResultSet->iCurrentRow >= pResultSet->iNumRows)
  327. return true;
  328. return false;
  329. }
  330. void SQLiteObject::ClearErrorString()
  331. {
  332. if (m_szErrorString)
  333. sqlite3_free(m_szErrorString);
  334. m_szErrorString = NULL;
  335. }
  336. void SQLiteObject::ClearResultSet(S32 index)
  337. {
  338. if (index <= 0)
  339. return;
  340. sqlite_resultset* resultSet;
  341. S32 iResultSet;
  342. // Get the result set specified by index
  343. resultSet = GetResultSet(index);
  344. iResultSet = GetResultSetIndex(index);
  345. if ((!resultSet) || (!resultSet->bValid))
  346. {
  347. Con::warnf("Warning SQLiteObject::ClearResultSet(%i) failed to retrieve specified result set. Result set was NOT cleared.", index);
  348. return;
  349. }
  350. // Now we have the specific result set to be cleared.
  351. // What we need to do now is iterate through each "Column" in each "Row"
  352. // and free the strings, then delete the entries.
  353. VectorPtr<sqlite_resultrow*>::iterator iRow;
  354. VectorPtr<char*>::iterator iColumnName;
  355. VectorPtr<char*>::iterator iColumnValue;
  356. for (iRow = resultSet->vRows.begin(); iRow != resultSet->vRows.end(); iRow++)
  357. {
  358. // Iterate through rows
  359. // for each row iterate through all the column values and names
  360. for (iColumnName = (*iRow)->vColumnNames.begin(); iColumnName != (*iRow)->vColumnNames.end(); iColumnName++)
  361. {
  362. // Iterate through column names. Free the memory.
  363. delete[](*iColumnName);
  364. }
  365. for (iColumnValue = (*iRow)->vColumnValues.begin(); iColumnValue != (*iRow)->vColumnValues.end(); iColumnValue++)
  366. {
  367. // Iterate through column values. Free the memory.
  368. delete[](*iColumnValue);
  369. }
  370. // free memory used by the row
  371. delete (*iRow);
  372. }
  373. // empty the resultset
  374. resultSet->vRows.clear();
  375. resultSet->bValid = false;
  376. delete resultSet;
  377. m_vResultSets.erase_fast(iResultSet);
  378. }
  379. sqlite_resultset* SQLiteObject::GetResultSet(S32 iResultSet)
  380. {
  381. // Get the result set specified by iResultSet
  382. VectorPtr<sqlite_resultset*>::iterator i;
  383. for (i = m_vResultSets.begin(); i != m_vResultSets.end(); i++)
  384. {
  385. if ((*i)->iResultSet == iResultSet)
  386. break;
  387. }
  388. return *i;
  389. }
  390. S32 SQLiteObject::GetResultSetIndex(S32 iResultSet)
  391. {
  392. S32 iIndex;
  393. // Get the result set specified by iResultSet
  394. VectorPtr<sqlite_resultset*>::iterator i;
  395. iIndex = 0;
  396. for (i = m_vResultSets.begin(); i != m_vResultSets.end(); i++)
  397. {
  398. if ((*i)->iResultSet == iResultSet)
  399. break;
  400. iIndex++;
  401. }
  402. return iIndex;
  403. }
  404. bool SQLiteObject::SaveResultSet(sqlite_resultset* pResultSet)
  405. {
  406. // Basically just add this to our vector. It should already be filled up.
  407. pResultSet->bValid = true;
  408. m_vResultSets.push_back(pResultSet);
  409. return true;
  410. }
  411. S32 SQLiteObject::GetColumnIndex(S32 iResult, const char* columnName)
  412. {
  413. S32 iIndex;
  414. VectorPtr<char*>::iterator i;
  415. sqlite_resultset* pResultSet;
  416. sqlite_resultrow* pRow;
  417. pResultSet = GetResultSet(iResult);
  418. if (!pResultSet)
  419. return 0;
  420. pRow = pResultSet->vRows[0];
  421. if (!pRow)
  422. return 0;
  423. iIndex = 0;
  424. for (i = pRow->vColumnNames.begin(); i != pRow->vColumnNames.end(); i++)
  425. {
  426. if (dStricmp((*i), columnName) == 0)
  427. return iIndex + 1;
  428. iIndex++;
  429. }
  430. return 0;
  431. }
  432. S32 SQLiteObject::numResultSets()
  433. {
  434. return m_vResultSets.size();
  435. }
  436. void SQLiteObject::escapeSingleQuotes(const char* source, char *dest)
  437. {
  438. //To Do: This function needs to step through the source string and insert another single quote
  439. //immediately after every single quote it finds.
  440. }
  441. //-----------------------------------------------------------------------
  442. // These functions are the code that actually tie our object into the scripting
  443. // language. As you can see each one of these is called by script and in turn
  444. // calls the C++ class function.
  445. // FIX: change all these to DefineEngineMethod!
  446. DefineEngineMethod(SQLiteObject, openDatabase, bool, (const char* filename),, "(const char* filename) Opens the database specifed by filename. Returns true or false.")
  447. {
  448. return object->OpenDatabase(filename);
  449. }
  450. DefineEngineMethod(SQLiteObject, loadOrSaveDb, bool, (const char* filename, bool isSave),,
  451. "Loads or saves a cached database from the disk db specifed by filename. Second argument determines loading (false) or saving (true). Returns true or false.")
  452. {
  453. return object->loadOrSaveDb(filename, isSave);
  454. }
  455. DefineEngineMethod(SQLiteObject, closeDatabase, void, (),, "Closes the active database.")
  456. {
  457. object->CloseDatabase();
  458. }
  459. DefineEngineStringlyVariadicMethod(SQLiteObject, query, S32, 1, 5,
  460. "(const char* sql, S32 mode) Performs an SQL query on the open database and returns an identifier to a valid result set. mode is currently unused, and is reserved for future use.")
  461. {
  462. S32 iCount;
  463. S32 iIndex, iLen, iNewIndex, iArg, iArgLen, i;
  464. char* szNew;
  465. if (argc == 4)
  466. return object->ExecuteSQL(argv[1]);
  467. else if (argc > 4)
  468. {
  469. // Support for printf type querys, as per Ben Garney's suggestion
  470. // Basically what this does is allow the user to insert question marks into their query that will
  471. // be replaced with actual data. For example:
  472. // "SELECT * FROM data WHERE id=? AND age<7 AND name LIKE ?"
  473. // scan the query and count the question marks
  474. iCount = 0;
  475. iLen = dStrlen(argv[1]);
  476. for (iIndex = 0; iIndex < iLen; iIndex++)
  477. {
  478. if (argv[1][iIndex] == '?')
  479. iCount++;
  480. }
  481. // now that we know how many replacements we have, we need to make sure we
  482. // have enough arguments to replace them all. All arguments above 4 should be our data
  483. if (argc - 4 == iCount)
  484. {
  485. // ok we have the correct number of arguments
  486. // so now we need to calc the length of the new query string. This is easily achieved.
  487. // We simply take our base string length, subtract the question marks, then add in
  488. // the number of total characters used by our arguments.
  489. iLen = dStrlen(argv[1]) - iCount;
  490. for (iIndex = 1; iIndex <= iCount; iIndex++)
  491. {
  492. iLen = iLen + dStrlen(argv[iIndex + 3]);
  493. }
  494. // iLen should now be the length of our new string
  495. szNew = new char[iLen];
  496. // now we need to replace all the question marks with the actual arguments
  497. iLen = dStrlen(argv[1]);
  498. iNewIndex = 0;
  499. iArg = 1;
  500. for (iIndex = 0; iIndex <= iLen; iIndex++)
  501. {
  502. if (argv[1][iIndex] == '?')
  503. {
  504. // ok we need to replace this question mark with the actual argument
  505. // and iterate our pointers and everything as needed. This is no doubt
  506. // not the best way to do this, but it works for me for now.
  507. // My god this is really a mess.
  508. iArgLen = dStrlen(argv[iArg + 3]);
  509. // copy first character
  510. szNew[iNewIndex] = argv[iArg + 3][0];
  511. // copy rest of characters, and increment iNewIndex
  512. for (i = 1; i < iArgLen; i++)
  513. {
  514. iNewIndex++;
  515. szNew[iNewIndex] = argv[iArg + 3][i];
  516. }
  517. iArg++;
  518. }
  519. else
  520. szNew[iNewIndex] = argv[1][iIndex];
  521. iNewIndex++;
  522. }
  523. }
  524. else
  525. return 0; // incorrect number of question marks vs arguments
  526. Con::printf("Old SQL: %s\nNew SQL: %s", argv[1].getString(), szNew);
  527. return object->ExecuteSQL(szNew);
  528. }
  529. return 0;
  530. }
  531. DefineEngineMethod(SQLiteObject, clearResult, void, (S32 resultSet),, "(S32 resultSet) Clears memory used by the specified result set, and deletes the result set.")
  532. {
  533. object->ClearResultSet(resultSet);
  534. }
  535. DefineEngineMethod(SQLiteObject, nextRow, void, (S32 resultSet),, "(S32 resultSet) Moves the result set's row pointer to the next row.")
  536. {
  537. sqlite_resultset* pResultSet;
  538. pResultSet = object->GetResultSet(resultSet);
  539. if (pResultSet)
  540. {
  541. pResultSet->iCurrentRow++;
  542. }
  543. }
  544. DefineEngineMethod(SQLiteObject, previousRow, void, (S32 resultSet),, "(S32 resultSet) Moves the result set's row pointer to the previous row")
  545. {
  546. sqlite_resultset* pResultSet;
  547. pResultSet = object->GetResultSet(resultSet);
  548. if (pResultSet)
  549. {
  550. pResultSet->iCurrentRow--;
  551. }
  552. }
  553. DefineEngineMethod(SQLiteObject, firstRow, void, (S32 resultSet),, "(S32 resultSet) Moves the result set's row pointer to the very first row in the result set.")
  554. {
  555. sqlite_resultset* pResultSet;
  556. pResultSet = object->GetResultSet(resultSet);
  557. if (pResultSet)
  558. {
  559. pResultSet->iCurrentRow = 0;
  560. }
  561. }
  562. DefineEngineMethod(SQLiteObject, lastRow, void, (S32 resultSet),, "(S32 resultSet) Moves the result set's row pointer to the very last row in the result set.")
  563. {
  564. sqlite_resultset* pResultSet;
  565. pResultSet = object->GetResultSet(resultSet);
  566. if (pResultSet)
  567. {
  568. pResultSet->iCurrentRow = pResultSet->iNumRows - 1;
  569. }
  570. }
  571. DefineEngineMethod(SQLiteObject, setRow, void, (S32 resultSet, S32 row),, "(S32 resultSet S32 row) Moves the result set's row pointer to the row specified. Row indices start at 1 not 0.")
  572. {
  573. sqlite_resultset* pResultSet;
  574. pResultSet = object->GetResultSet(resultSet);
  575. if (pResultSet)
  576. {
  577. pResultSet->iCurrentRow = row - 1;
  578. }
  579. }
  580. DefineEngineMethod(SQLiteObject, getRow, S32, (S32 resultSet),, "(S32 resultSet) Returns what row the result set's row pointer is currently on.")
  581. {
  582. sqlite_resultset* pResultSet;
  583. pResultSet = object->GetResultSet(resultSet);
  584. if (pResultSet)
  585. {
  586. return pResultSet->iCurrentRow + 1;
  587. }
  588. else
  589. return 0;
  590. }
  591. DefineEngineMethod(SQLiteObject, numRows, S32, (S32 resultSet),, "(S32 resultSet) Returns the number of rows in the result set.")
  592. {
  593. sqlite_resultset* pResultSet;
  594. pResultSet = object->GetResultSet(resultSet);
  595. if (pResultSet)
  596. {
  597. return pResultSet->iNumRows;
  598. }
  599. else
  600. return 0;
  601. }
  602. DefineEngineMethod(SQLiteObject, numColumns, S32, (S32 resultSet),, "(S32 resultSet) Returns the number of columns in the result set.")
  603. {
  604. sqlite_resultset* pResultSet;
  605. pResultSet = object->GetResultSet(resultSet);
  606. if (pResultSet)
  607. {
  608. return pResultSet->iNumCols;
  609. }
  610. else
  611. return 0;
  612. }
  613. DefineEngineMethod(SQLiteObject, endOfResult, bool, (S32 resultSet),, "(S32 resultSet) Checks to see if the internal pointer for the specified result set is at the end, indicating there are no more rows left to read.")
  614. {
  615. return object->EndOfResult(resultSet);
  616. }
  617. DefineEngineMethod(SQLiteObject, EOR, bool, (S32 resultSet),, "(S32 resultSet) Same as endOfResult().")
  618. {
  619. return object->EndOfResult(resultSet);
  620. }
  621. DefineEngineMethod(SQLiteObject, EOFile, bool, (S32 resultSet),, "(S32 resultSet) Same as endOfResult().")
  622. {
  623. return object->EndOfResult(resultSet);
  624. }
  625. DefineEngineMethod(SQLiteObject, getColumnIndex, S32, (S32 resultSet, String columnName),, "(resultSet columnName) Looks up the specified column name in the specified result set, and returns the columns index number. A return value of 0 indicates the lookup failed for some reason (usually this indicates you specified a column name that doesn't exist or is spelled wrong).")
  626. {
  627. return object->GetColumnIndex(resultSet, columnName);
  628. }
  629. DefineEngineMethod(SQLiteObject, getColumnName, const char *, (S32 resultSet, S32 columnIndex), , "(resultSet columnIndex) Looks up the specified column index in the specified result set, and returns the column's name. A return value of an empty string indicates the lookup failed for some reason (usually this indicates you specified a column index that is invalid or exceeds the number of columns in the result set). Columns are index starting with 1 not 0")
  630. {
  631. sqlite_resultset* pResultSet;
  632. sqlite_resultrow* pRow;
  633. S32 iColumn;
  634. pResultSet = object->GetResultSet(resultSet);
  635. if (pResultSet)
  636. {
  637. pRow = pResultSet->vRows[pResultSet->iCurrentRow];
  638. if (!pRow)
  639. return "";
  640. // We assume they specified column by index. If they know the column name they wouldn't be calling this function :)
  641. iColumn = columnIndex;
  642. if (iColumn == 0)
  643. return ""; // column indices start at 1, not 0
  644. // now we should have an index for our column name
  645. if (pRow->vColumnNames[iColumn])
  646. return pRow->vColumnNames[iColumn];
  647. else
  648. return "";
  649. }
  650. else
  651. return "";
  652. }
  653. DefineEngineStringlyVariadicMethod(SQLiteObject, getColumn, const char *, 4, 4, "(resultSet column) Returns the value of the specified column (Column can be specified by name or index) in the current row of the specified result set. If the call fails, the returned string will indicate the error.")
  654. {
  655. sqlite_resultset* pResultSet;
  656. sqlite_resultrow* pRow;
  657. S32 iColumn;
  658. pResultSet = object->GetResultSet(dAtoi(argv[2]));
  659. if (pResultSet)
  660. {
  661. if (pResultSet->vRows.size() == 0)
  662. return "NULL";
  663. pRow = pResultSet->vRows[pResultSet->iCurrentRow];
  664. if (!pRow)
  665. return "invalid_row";
  666. // Is column specified by a name or an index?
  667. iColumn = dAtoi(argv[3]);
  668. if (iColumn == 0)
  669. {
  670. // column was specified by a name
  671. iColumn = object->GetColumnIndex(dAtoi(argv[2]), argv[3]);
  672. // if this is still 0 then we have some error
  673. if (iColumn == 0)
  674. return "invalid_column";
  675. }
  676. // We temporarily padded the index in GetColumnIndex() so we could return a
  677. // 0 for error. So now we need to drop it back down.
  678. iColumn--;
  679. // now we should have an index for our column data
  680. if (pRow->vColumnValues[iColumn])
  681. return pRow->vColumnValues[iColumn];
  682. else
  683. return "NULL";
  684. }
  685. else
  686. return "invalid_result_set";
  687. }
  688. DefineEngineStringlyVariadicMethod(SQLiteObject, getColumnNumeric, F32, 4, 4, "(resultSet column) Returns the value of the specified column (Column can be specified by name or index) in the current row of the specified result set. If the call fails, the returned string will indicate the error.")
  689. {
  690. sqlite_resultset* pResultSet;
  691. sqlite_resultrow* pRow;
  692. S32 iColumn;
  693. pResultSet = object->GetResultSet(dAtoi(argv[2]));
  694. if (pResultSet)
  695. {
  696. if (pResultSet->vRows.size() == 0)
  697. return -1;
  698. pRow = pResultSet->vRows[pResultSet->iCurrentRow];
  699. if (!pRow)
  700. return -1;//"invalid_row";
  701. // Is column specified by a name or an index?
  702. iColumn = dAtoi(argv[3]);
  703. if (iColumn == 0)
  704. {
  705. // column was specified by a name
  706. iColumn = object->GetColumnIndex(dAtoi(argv[2]), argv[3]);
  707. // if this is still 0 then we have some error
  708. if (iColumn == 0)
  709. return -1;//"invalid_column";
  710. }
  711. // We temporarily padded the index in GetColumnIndex() so we could return a
  712. // 0 for error. So now we need to drop it back down.
  713. iColumn--;
  714. // now we should have an index for our column data
  715. if (pRow->vColumnValues[iColumn])
  716. return dAtof(pRow->vColumnValues[iColumn]);
  717. else
  718. return 0;
  719. }
  720. else
  721. return -1;//"invalid_result_set";
  722. }
  723. DefineEngineMethod(SQLiteObject, escapeString, const char *, (String string),, "(string) Escapes the given string, making it safer to pass into a query.")
  724. {
  725. // essentially what we need to do here is scan the string for any occurrences of: ', ", and \
  726. // and prepend them with a slash: \', \", \\
  727. // to do this we first need to know how many characters we are replacing so we can calculate
  728. // the size of the new string
  729. S32 iCount;
  730. S32 iIndex, iLen, iNewIndex;
  731. char* szNew;
  732. iCount = 0;
  733. iLen = dStrlen(string);
  734. for (iIndex = 0; iIndex < iLen; iIndex++)
  735. {
  736. if (string[iIndex] == '\'')
  737. iCount++;
  738. else if (string[iIndex] == '\"')
  739. iCount++;
  740. else if (string[iIndex] == '\\')
  741. iCount++;
  742. }
  743. // Con::printf("escapeString counts %i instances of characters to be escaped. New string will be %i characters longer for a total of %i characters.", iCount, iCount, iLen+iCount);
  744. szNew = new char[iLen + iCount];
  745. iNewIndex = 0;
  746. for (iIndex = 0; iIndex <= iLen; iIndex++)
  747. {
  748. if (string[iIndex] == '\'')
  749. {
  750. szNew[iNewIndex] = '\\';
  751. iNewIndex++;
  752. szNew[iNewIndex] = '\'';
  753. }
  754. else if (string[iIndex] == '\"')
  755. {
  756. szNew[iNewIndex] = '\\';
  757. iNewIndex++;
  758. szNew[iNewIndex] = '\"';
  759. }
  760. else if (string[iIndex] == '\\')
  761. {
  762. szNew[iNewIndex] = '\\';
  763. iNewIndex++;
  764. szNew[iNewIndex] = '\\';
  765. }
  766. else
  767. szNew[iNewIndex] = string[iIndex];
  768. iNewIndex++;
  769. }
  770. // Con::printf("Last characters of each string (new, old): %s, %s", argv[2][iIndex-1], szNew[iNewIndex-1]);
  771. // Con::printf("Old String: %s\nNew String: %s", argv[2], szNew);
  772. return szNew;
  773. }
  774. DefineEngineMethod(SQLiteObject, numResultSets, S32, (),, "numResultSets()")
  775. {
  776. return object->numResultSets();
  777. }
  778. DefineEngineMethod(SQLiteObject, getLastRowId, S32, (), , "getLastRowId()")
  779. {
  780. return object->getLastRowId();
  781. }