Triggering build against new mac libprotobuf.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
32 #include "sm_globals.h"
33 #include "HandleSys.h"
35 #include "ExtensionSys.h"
36 #include "PluginSys.h"
37 #include "sm_stringutil.h"
39 HandleType_t hStmtType;
41 HandleType_t hCombinedQueryType;
48 class DatabaseHelpers :
50 public IHandleTypeDispatch
53 virtual void OnSourceModAllInitialized()
58 g_HandleSys.InitAccessDefaults(NULL, &acc);
59 acc.access[HandleAccess_Clone] = HANDLE_RESTRICT_OWNER|HANDLE_RESTRICT_IDENTITY;
63 g_HandleSys.InitAccessDefaults(&tacc, NULL);
64 tacc.ident = g_pCoreIdent;
66 hCombinedQueryType = g_HandleSys.CreateType("IQuery", this, 0, &tacc, &acc, g_pCoreIdent, NULL);
67 hStmtType = g_HandleSys.CreateType("IPreparedQuery", this, 0, &tacc, &acc, g_pCoreIdent, NULL);
70 virtual void OnSourceModShutdown()
72 g_HandleSys.RemoveType(hStmtType, g_pCoreIdent);
73 g_HandleSys.RemoveType(hCombinedQueryType, g_pCoreIdent);
76 virtual void OnHandleDestroy(HandleType_t type, void *object)
78 if (type == hCombinedQueryType)
80 CombinedQuery *combined = (CombinedQuery *)object;
81 combined->query->Destroy();
83 } else if (type == hStmtType) {
84 IPreparedQuery *query = (IPreparedQuery *)object;
88 } s_DatabaseNativeHelpers;
90 //is this safe for stmt handles? i think since it's single inheritance, it always will be.
91 inline HandleError ReadQueryHndl(Handle_t hndl, IPluginContext *pContext, IQuery **query)
95 sec.pOwner = pContext->GetIdentity();
96 sec.pIdentity = g_pCoreIdent;
100 if ((ret = g_HandleSys.ReadHandle(hndl, hStmtType, &sec, (void **)query)) != HandleError_None)
102 ret = g_HandleSys.ReadHandle(hndl, hCombinedQueryType, &sec, (void **)&c);
103 if (ret == HandleError_None)
111 inline HandleError ReadQueryAndDbHndl(Handle_t hndl, IPluginContext *pContext, IQuery **query, IDatabase **db)
115 sec.pOwner = pContext->GetIdentity();
116 sec.pIdentity = g_pCoreIdent;
118 HandleError ret = g_HandleSys.ReadHandle(hndl, hCombinedQueryType, &sec, (void **)&c);
119 if (ret == HandleError_None)
127 inline HandleError ReadStmtHndl(Handle_t hndl, IPluginContext *pContext, IPreparedQuery **query)
130 sec.pOwner = pContext->GetIdentity();
131 sec.pIdentity = g_pCoreIdent;
133 return g_HandleSys.ReadHandle(hndl, hStmtType, &sec, (void **)query);
136 inline HandleError ReadDbOrStmtHndl(Handle_t hndl, IPluginContext *pContext, IDatabase **db, IPreparedQuery **query)
139 if ((err = g_DBMan.ReadHandle(hndl, DBHandle_Database, (void **)db)) == HandleError_Type)
142 return ReadStmtHndl(hndl, pContext, query);
147 class TQueryOp : public IDBThreadOperation
150 TQueryOp(IDatabase *db, IPluginFunction *pf, const char *query, cell_t data) :
151 m_pDatabase(db), m_pFunction(pf), m_Query(query), m_Data(data),
152 me(g_PluginSys.GetPluginByCtx(pf->GetParentContext()->GetContext())),
155 /* We always increase the reference count because this is potentially
156 * asynchronous. Otherwise the original handle could be closed while
157 * we're still latched onto it.
159 m_pDatabase->IncReferenceCount();
161 /* Now create our own Handle such that it can only be closed by us.
162 * We allow cloning just in case someone wants to hold onto it.
164 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
166 g_HandleSys.InitAccessDefaults(NULL, &access);
167 access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
168 m_MyHandle = g_HandleSys.CreateHandleEx(g_DBMan.GetDatabaseType(),
181 /* Close our Handle if it's valid. */
182 if (m_MyHandle != BAD_HANDLE)
184 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
185 g_HandleSys.FreeHandle(m_MyHandle, &sec);
187 /* Otherwise, there is an open ref to the db */
188 m_pDatabase->Close();
191 IdentityToken_t *GetOwner()
193 return me->GetIdentity();
195 IDBDriver *GetDriver()
197 return m_pDatabase->GetDriver();
201 m_pDatabase->LockForFullAtomicOperation();
202 m_pQuery = m_pDatabase->DoQuery(m_Query.c_str());
205 UTIL_Format(error, sizeof(error), "%s", m_pDatabase->GetError());
207 m_pDatabase->UnlockFromFullAtomicOperation();
209 void CancelThinkPart()
211 m_pFunction->PushCell(BAD_HANDLE);
212 m_pFunction->PushCell(BAD_HANDLE);
213 m_pFunction->PushString("Driver is unloading");
214 m_pFunction->PushCell(m_Data);
215 m_pFunction->Execute(NULL);
219 /* Create a Handle for our query */
220 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
222 g_HandleSys.InitAccessDefaults(NULL, &access);
223 access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
225 Handle_t qh = BAD_HANDLE;
229 CombinedQuery *c = new CombinedQuery;
233 qh = g_HandleSys.CreateHandle(hCombinedQueryType, c, me->GetIdentity(), g_pCoreIdent, NULL);
234 if (qh != BAD_HANDLE)
238 UTIL_Format(error, sizeof(error), "Could not alloc handle");
243 m_pFunction->PushCell(m_MyHandle);
244 m_pFunction->PushCell(qh);
245 m_pFunction->PushString(qh == BAD_HANDLE ? error : "");
246 m_pFunction->PushCell(m_Data);
247 m_pFunction->Execute(NULL);
249 if (qh != BAD_HANDLE)
251 g_HandleSys.FreeHandle(qh, &sec);
259 IDatabase *m_pDatabase;
260 IPluginFunction *m_pFunction;
269 class TConnectOp : public IDBThreadOperation
272 TConnectOp(IPluginFunction *func, IDBDriver *driver, const char *_dbname, cell_t data)
279 strncopy(dbname, _dbname, sizeof(dbname));
280 me = g_PluginSys.GetPluginByCtx(m_pFunction->GetParentContext()->GetContext());
282 IdentityToken_t *GetOwner()
284 return me->GetIdentity();
286 IDBDriver *GetDriver()
292 g_DBMan.LockConfig();
293 const DatabaseInfo *pInfo = g_DBMan.FindDatabaseConf(dbname);
296 UTIL_Format(error, sizeof(error), "Could not find database config \"%s\"", dbname);
298 m_pDatabase = m_pDriver->Connect(pInfo, false, error, sizeof(error));
300 g_DBMan.UnlockConfig();
302 void CancelThinkPart()
306 m_pDatabase->Close();
308 m_pFunction->PushCell(BAD_HANDLE);
309 m_pFunction->PushCell(BAD_HANDLE);
310 m_pFunction->PushString("Driver is unloading");
311 m_pFunction->PushCell(m_Data);
312 m_pFunction->Execute(NULL);
316 Handle_t hndl = BAD_HANDLE;
320 if ((hndl = g_DBMan.CreateHandle(DBHandle_Database, m_pDatabase, me->GetIdentity()))
323 m_pDatabase->Close();
324 UTIL_Format(error, sizeof(error), "Unable to allocate Handle");
328 m_pFunction->PushCell(m_pDriver->GetHandle());
329 m_pFunction->PushCell(hndl);
330 m_pFunction->PushString(hndl == BAD_HANDLE ? error : "");
331 m_pFunction->PushCell(m_Data);
332 m_pFunction->Execute(NULL);
340 IPluginFunction *m_pFunction;
341 IDBDriver *m_pDriver;
342 IDatabase *m_pDatabase;
348 static cell_t SQL_Connect(IPluginContext *pContext, const cell_t *params)
352 size_t maxlength = (size_t)params[4];
353 bool persistent = params[2] ? true : false;
354 pContext->LocalToString(params[1], &conf);
355 pContext->LocalToString(params[3], &err);
359 if (!g_DBMan.Connect(conf, &driver, &db, persistent, err, maxlength))
364 Handle_t hndl = g_DBMan.CreateHandle(DBHandle_Database, db, pContext->GetIdentity());
371 /* HACK! Add us to the dependency list */
372 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
375 g_Extensions.BindChildPlugin(pExt, g_PluginSys.GetPluginByCtx(pContext->GetContext()));
381 static cell_t SQL_TConnect(IPluginContext *pContext, const cell_t *params)
383 IPluginFunction *pf = pContext->GetFunctionById(params[1]);
386 return pContext->ThrowNativeError("Function id %x is invalid", params[1]);
390 pContext->LocalToString(params[2], &conf);
392 IDBDriver *driver = NULL;
393 const DatabaseInfo *pInfo = g_DBMan.FindDatabaseConf(conf);
397 if (pInfo->driver[0] == '\0')
399 driver = g_DBMan.GetDefaultDriver();
401 driver = g_DBMan.FindOrLoadDriver(pInfo->driver);
407 "Could not find driver \"%s\"",
408 pInfo->driver[0] == '\0' ? g_DBMan.GetDefaultDriverName() : pInfo->driver);
409 } else if (!driver->IsThreadSafe()) {
412 "Driver \"%s\" is not thread safe!",
413 driver->GetIdentifier());
416 UTIL_Format(error, sizeof(error), "Could not find database conf \"%s\"", conf);
419 if (!pInfo || !driver)
421 pf->PushCell(BAD_HANDLE);
422 pf->PushCell(BAD_HANDLE);
423 pf->PushString(error);
429 /* HACK! Add us to the dependency list */
430 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
433 g_Extensions.BindChildPlugin(pExt, g_PluginSys.GetPluginByCtx(pContext->GetContext()));
436 /* Finally, add to the thread if we can */
437 TConnectOp *op = new TConnectOp(pf, driver, conf, params[3]);
438 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
439 if (pPlugin->GetProperty("DisallowDBThreads", NULL)
440 || !g_DBMan.AddToThreadQueue(op, PrioQueue_High))
442 /* Do everything right now */
451 static cell_t SQL_ConnectEx(IPluginContext *pContext, const cell_t *params)
454 if (params[1] == BAD_HANDLE)
456 if ((driver = g_DBMan.GetDefaultDriver()) == NULL)
458 return pContext->ThrowNativeError("Could not find any default driver");
462 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Driver, (void **)&driver))
465 return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err);
469 char *host, *user, *pass, *database, *error;
470 size_t maxlength = (size_t)params[7];
471 bool persistent = params[8] ? true : false;
472 unsigned int port = params[9];
473 unsigned int maxTimeout = params[10];
474 pContext->LocalToString(params[2], &host);
475 pContext->LocalToString(params[3], &user);
476 pContext->LocalToString(params[4], &pass);
477 pContext->LocalToString(params[5], &database);
478 pContext->LocalToString(params[6], &error);
481 info.database = database;
482 info.driver = driver->GetIdentifier();
484 info.maxTimeout = maxTimeout;
489 IDatabase *db = driver->Connect(&info, persistent, error, maxlength);
493 Handle_t hndl = g_DBMan.CreateHandle(DBHandle_Database, db, pContext->GetIdentity());
500 /* HACK! Add us to the dependency list */
501 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
504 g_Extensions.BindChildPlugin(pExt, g_PluginSys.GetPluginByCtx(pContext->GetContext()));
513 static cell_t SQL_GetDriverIdent(IPluginContext *pContext, const cell_t *params)
516 if (params[1] == BAD_HANDLE)
518 if ((driver = g_DBMan.GetDefaultDriver()) == NULL)
520 return pContext->ThrowNativeError("Could not find any default driver");
524 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Driver, (void **)&driver))
527 return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err);
531 pContext->StringToLocalUTF8(params[2], params[3], driver->GetIdentifier(), NULL);
536 static cell_t SQL_GetDriver(IPluginContext *pContext, const cell_t *params)
539 pContext->LocalToString(params[1], &name);
541 IDBDriver *driver = NULL;
544 driver = g_DBMan.GetDefaultDriver();
546 driver = g_DBMan.FindOrLoadDriver(name);
549 return (driver != NULL) ? driver->GetHandle() : BAD_HANDLE;
552 static cell_t SQL_GetDriverProduct(IPluginContext *pContext, const cell_t *params)
555 if (params[1] == BAD_HANDLE)
557 if ((driver = g_DBMan.GetDefaultDriver()) == NULL)
559 return pContext->ThrowNativeError("Could not find any default driver");
563 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Driver, (void **)&driver))
566 return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err);
570 pContext->StringToLocalUTF8(params[2], params[3], driver->GetProductName(), NULL);
575 static cell_t SQL_GetAffectedRows(IPluginContext *pContext, const cell_t *params)
577 IDatabase *db = NULL;
578 IPreparedQuery *stmt = NULL;
579 IQuery *query = NULL;
582 if (((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
583 && ((err = ReadQueryAndDbHndl(params[1], pContext, &query, &db)) != HandleError_None))
585 return pContext->ThrowNativeError("Invalid statement, db, or query Handle %x (error: %d)", params[1], err);
591 return stmt->GetAffectedRows();
595 return db->GetAffectedRowsForQuery(query);
599 return db->GetAffectedRows();
602 return pContext->ThrowNativeError("Unknown error reading db/stmt/query handles");
605 static cell_t SQL_GetInsertId(IPluginContext *pContext, const cell_t *params)
607 IDatabase *db = NULL;
608 IQuery *query = NULL;
609 IPreparedQuery *stmt = NULL;
612 if (((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
613 && ((err = ReadQueryAndDbHndl(params[1], pContext, &query, &db)) != HandleError_None))
615 return pContext->ThrowNativeError("Invalid statement, db, or query Handle %x (error: %d)", params[1], err);
620 return db->GetInsertIDForQuery(query);
624 return db->GetInsertID();
628 return stmt->GetInsertID();
631 return pContext->ThrowNativeError("Unknown error reading db/stmt/query handles");
634 static cell_t SQL_GetError(IPluginContext *pContext, const cell_t *params)
636 IDatabase *db = NULL;
637 IPreparedQuery *stmt = NULL;
640 if ((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
642 return pContext->ThrowNativeError("Invalid statement or db Handle %x (error: %d)", params[1], err);
645 const char *error = "";
648 error = db->GetError();
650 error = stmt->GetError();
653 if (error[0] == '\0')
658 pContext->StringToLocalUTF8(params[2], params[3], error, NULL);
663 static cell_t SQL_QuoteString(IPluginContext *pContext, const cell_t *params)
665 IDatabase *db = NULL;
668 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
671 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
674 char *input, *output;
675 size_t maxlength = (size_t)params[4];
676 pContext->LocalToString(params[2], &input);
677 pContext->LocalToString(params[3], &output);
680 bool s = db->QuoteString(input, output, maxlength, &written);
683 pContext->LocalToPhysAddr(params[5], &addr);
684 *addr = (cell_t)written;
689 static cell_t SQL_FastQuery(IPluginContext *pContext, const cell_t *params)
691 IDatabase *db = NULL;
694 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
697 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
701 pContext->LocalToString(params[2], &query);
703 if (params[0] >= 3 && params[3] != -1)
705 return db->DoSimpleQueryEx(query, params[3]) ? 1 : 0;
708 return db->DoSimpleQuery(query) ? 1 : 0;
711 static cell_t SQL_Query(IPluginContext *pContext, const cell_t *params)
713 IDatabase *db = NULL;
716 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
719 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
723 pContext->LocalToString(params[2], &query);
727 if (params[0] >= 3 && params[3] != -1)
729 qr = db->DoQueryEx(query, params[3]);
733 qr = db->DoQuery(query);
741 CombinedQuery *c = new CombinedQuery;
744 Handle_t hndl = g_HandleSys.CreateHandle(hCombinedQueryType, c, pContext->GetIdentity(), g_pCoreIdent, NULL);
745 if (hndl == BAD_HANDLE)
755 static cell_t SQL_TQuery(IPluginContext *pContext, const cell_t *params)
757 IDatabase *db = NULL;
760 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
763 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
766 if (!db->GetDriver()->IsThreadSafe())
768 return pContext->ThrowNativeError("Driver \"%s\" is not thread safe!", db->GetDriver()->GetIdentifier());
771 IPluginFunction *pf = pContext->GetFunctionById(params[2]);
774 return pContext->ThrowNativeError("Function id %x is invalid", params[2]);
778 pContext->LocalToString(params[3], &query);
780 cell_t data = params[4];
781 PrioQueueLevel level = PrioQueue_Normal;
782 if (params[5] == (cell_t)PrioQueue_High)
784 level = PrioQueue_High;
785 } else if (params[5] == (cell_t)PrioQueue_Low) {
786 level = PrioQueue_Low;
789 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
791 TQueryOp *op = new TQueryOp(db, pf, query, data);
792 if (pPlugin->GetProperty("DisallowDBThreads", NULL)
793 || !g_DBMan.AddToThreadQueue(op, level))
795 /* Do everything right now */
804 static cell_t SQL_LockDatabase(IPluginContext *pContext, const cell_t *params)
806 IDatabase *db = NULL;
809 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
812 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
815 db->LockForFullAtomicOperation();
820 static cell_t SQL_UnlockDatabase(IPluginContext *pContext, const cell_t *params)
822 IDatabase *db = NULL;
825 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
828 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
831 db->UnlockFromFullAtomicOperation();
836 static cell_t SQL_PrepareQuery(IPluginContext *pContext, const cell_t *params)
838 IDatabase *db = NULL;
841 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
844 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
848 size_t maxlength = (size_t)params[4];
849 pContext->LocalToString(params[2], &query);
850 pContext->LocalToString(params[3], &error);
852 IPreparedQuery *qr = db->PrepareQuery(query, error, maxlength);
859 Handle_t hndl = g_HandleSys.CreateHandle(hStmtType, qr, pContext->GetIdentity(), g_pCoreIdent, NULL);
860 if (hndl == BAD_HANDLE)
869 static cell_t SQL_FetchMoreResults(IPluginContext *pContext, const cell_t *params)
874 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
876 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
879 return query->FetchMoreResults() ? 1 : 0;
882 static cell_t SQL_HasResultSet(IPluginContext *pContext, const cell_t *params)
887 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
889 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
892 return query->GetResultSet() != NULL ? true : false;
895 static cell_t SQL_GetRowCount(IPluginContext *pContext, const cell_t *params)
900 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
902 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
905 IResultSet *rs = query->GetResultSet();
911 return rs->GetRowCount();
914 static cell_t SQL_GetFieldCount(IPluginContext *pContext, const cell_t *params)
919 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
921 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
924 IResultSet *rs = query->GetResultSet();
930 return rs->GetFieldCount();
933 static cell_t SQL_FieldNumToName(IPluginContext *pContext, const cell_t *params)
938 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
940 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
943 IResultSet *rs = query->GetResultSet();
946 return pContext->ThrowNativeError("No current result set");
949 unsigned int field = params[2];
952 if ((fldname = rs->FieldNumToName(field)) == NULL)
954 return pContext->ThrowNativeError("Invalid field index %d", field);
957 pContext->StringToLocalUTF8(params[3], params[4], fldname, NULL);
962 static cell_t SQL_FieldNameToNum(IPluginContext *pContext, const cell_t *params)
967 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
969 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
972 IResultSet *rs = query->GetResultSet();
975 return pContext->ThrowNativeError("No current result set");
979 pContext->LocalToString(params[2], &field);
982 pContext->LocalToPhysAddr(params[3], &num);
984 return rs->FieldNameToNum(field, (unsigned int *)num) ? 1 : 0;
987 static cell_t SQL_FetchRow(IPluginContext *pContext, const cell_t *params)
992 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
994 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
997 IResultSet *rs = query->GetResultSet();
1000 return pContext->ThrowNativeError("No current result set");
1003 return (rs->FetchRow() != NULL) ? true : false;
1006 static cell_t SQL_MoreRows(IPluginContext *pContext, const cell_t *params)
1011 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1013 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1016 IResultSet *rs = query->GetResultSet();
1019 return pContext->ThrowNativeError("No current result set");
1022 return rs->MoreRows() ? 1 : 0;
1025 static cell_t SQL_Rewind(IPluginContext *pContext, const cell_t *params)
1030 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1032 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1035 IResultSet *rs = query->GetResultSet();
1038 return pContext->ThrowNativeError("No current result set");
1041 return rs->Rewind() ? 1 : 0;
1044 static cell_t SQL_FetchString(IPluginContext *pContext, const cell_t *params)
1049 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1051 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1054 IResultSet *rs = query->GetResultSet();
1057 return pContext->ThrowNativeError("No current result set");
1060 IResultRow *row = rs->CurrentRow();
1063 return pContext->ThrowNativeError("Current result set has no fetched rows");
1068 DBResult res = row->GetString(params[2], &str, &length);
1070 if (res == DBVal_Error)
1072 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
1073 } else if (res == DBVal_TypeMismatch) {
1074 return pContext->ThrowNativeError("Could not fetch data in field %d as a string", params[2]);
1077 pContext->StringToLocalUTF8(params[3], params[4], str, &length);
1080 pContext->LocalToPhysAddr(params[5], &addr);
1081 *addr = (cell_t)res;
1083 return (cell_t)length;
1086 static cell_t SQL_FetchFloat(IPluginContext *pContext, const cell_t *params)
1091 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1093 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1096 IResultSet *rs = query->GetResultSet();
1099 return pContext->ThrowNativeError("No current result set");
1102 IResultRow *row = rs->CurrentRow();
1105 return pContext->ThrowNativeError("Current result set has no fetched rows");
1109 DBResult res = row->GetFloat(params[2], &f);
1111 if (res == DBVal_Error)
1113 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
1114 } else if (res == DBVal_TypeMismatch) {
1115 return pContext->ThrowNativeError("Could not fetch data in field %d as a float", params[2]);
1119 pContext->LocalToPhysAddr(params[3], &addr);
1120 *addr = (cell_t)res;
1125 static cell_t SQL_FetchInt(IPluginContext *pContext, const cell_t *params)
1130 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1132 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1135 IResultSet *rs = query->GetResultSet();
1138 return pContext->ThrowNativeError("No current result set");
1141 IResultRow *row = rs->CurrentRow();
1144 return pContext->ThrowNativeError("Current result set has no fetched rows");
1148 DBResult res = row->GetInt(params[2], &iv);
1150 if (res == DBVal_Error)
1152 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
1153 } else if (res == DBVal_TypeMismatch) {
1154 return pContext->ThrowNativeError("Could not fetch data in field %d as an integer", params[2]);
1158 pContext->LocalToPhysAddr(params[3], &addr);
1159 *addr = (cell_t)res;
1164 static cell_t SQL_IsFieldNull(IPluginContext *pContext, const cell_t *params)
1169 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1171 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1174 IResultSet *rs = query->GetResultSet();
1177 return pContext->ThrowNativeError("No current result set");
1180 IResultRow *row = rs->CurrentRow();
1183 return pContext->ThrowNativeError("Current result set has no fetched rows");
1186 if ((unsigned)params[2] >= rs->GetFieldCount())
1188 return pContext->ThrowNativeError("Invalid field index %d", params[2]);
1191 return row->IsNull(params[2]) ? 1 : 0;
1194 static cell_t SQL_FetchSize(IPluginContext *pContext, const cell_t *params)
1199 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1201 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1204 IResultSet *rs = query->GetResultSet();
1207 return pContext->ThrowNativeError("No current result set");
1210 IResultRow *row = rs->CurrentRow();
1213 return pContext->ThrowNativeError("Current result set has no fetched rows");
1216 if ((unsigned)params[2] >= rs->GetFieldCount())
1218 return pContext->ThrowNativeError("Invalid field index %d", params[2]);
1221 return row->GetDataSize(params[2]);
1224 static cell_t SQL_BindParamInt(IPluginContext *pContext, const cell_t *params)
1226 IPreparedQuery *stmt;
1229 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1231 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1234 if (!stmt->BindParamInt(params[2], params[3], params[4] ? true : false))
1236 return pContext->ThrowNativeError("Could not bind parameter %d as an integer", params[2]);
1242 static cell_t SQL_BindParamFloat(IPluginContext *pContext, const cell_t *params)
1244 IPreparedQuery *stmt;
1247 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1249 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1252 if (!stmt->BindParamFloat(params[2], sp_ctof(params[3])))
1254 return pContext->ThrowNativeError("Could not bind parameter %d as a float", params[2]);
1260 static cell_t SQL_BindParamString(IPluginContext *pContext, const cell_t *params)
1262 IPreparedQuery *stmt;
1265 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1267 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1271 pContext->LocalToString(params[3], &str);
1273 if (!stmt->BindParamString(params[2], str, params[4] ? true : false))
1275 return pContext->ThrowNativeError("Could not bind parameter %d as a string", params[2]);
1281 static cell_t SQL_Execute(IPluginContext *pContext, const cell_t *params)
1283 IPreparedQuery *stmt;
1286 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1288 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1291 return stmt->Execute() ? 1 : 0;
1294 static cell_t SQL_IsSameConnection(IPluginContext *pContext, const cell_t *params)
1296 IDatabase *db1=NULL, *db2=NULL;
1299 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db1))
1300 != HandleError_None)
1302 return pContext->ThrowNativeError("Invalid database Handle 1/%x (error: %d)", params[1], err);
1305 if ((err = g_DBMan.ReadHandle(params[2], DBHandle_Database, (void **)&db2))
1306 != HandleError_None)
1308 return pContext->ThrowNativeError("Invalid database Handle 2/%x (error: %d)", params[2], err);
1311 return (db1 == db2) ? true : false;
1314 static cell_t SQL_ReadDriver(IPluginContext *pContext, const cell_t *params)
1316 IDatabase *db1=NULL;
1319 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db1))
1320 != HandleError_None)
1322 return pContext->ThrowNativeError("Invalid database Handle 1/%x (error: %d)", params[1], err);
1325 IDBDriver *driver = db1->GetDriver();
1327 pContext->StringToLocalUTF8(params[2], params[3], driver->GetIdentifier(), NULL);
1329 return driver->GetHandle();
1332 static cell_t SQL_CheckConfig(IPluginContext *pContext, const cell_t *params)
1335 pContext->LocalToString(params[1], &name);
1337 return (g_DBMan.FindDatabaseConf(name) != NULL) ? 1 : 0;
1340 static cell_t SQL_ConnectCustom(IPluginContext *pContext, const cell_t *params)
1345 kv = g_SourceMod.ReadKeyValuesHandle(params[1], &err, false);
1348 return pContext->ThrowNativeError("Invalid KeyValues handle %x (error: %d)",
1354 info.database = kv->GetString("database", "");
1355 info.driver = kv->GetString("driver", "default");
1356 info.host = kv->GetString("host", "");
1357 info.maxTimeout = kv->GetInt("timeout", 0);
1358 info.pass = kv->GetString("pass", "");
1359 info.port = kv->GetInt("port", 0);
1360 info.user = kv->GetString("user", "");
1363 if (info.driver[0] == '\0' || strcmp(info.driver, "default") == 0)
1365 driver = g_DBMan.GetDefaultDriver();
1369 driver = g_DBMan.FindOrLoadDriver(info.driver);
1376 UTIL_Format(buffer, sizeof(buffer), "Could not find driver \"%s\"", info.driver);
1377 pContext->StringToLocalUTF8(params[2], params[3], buffer, NULL);
1385 pContext->LocalToString(params[2], &buffer);
1387 db = driver->Connect(&info, params[4] ? true : false, buffer, params[3]);
1393 Handle_t hndl = g_DBMan.CreateHandle(DBHandle_Database, db, pContext->GetIdentity());
1397 return pContext->ThrowNativeError("Out of handles!");
1400 /* HACK! Add us to the dependency list */
1401 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
1404 g_Extensions.BindChildPlugin(pExt, g_PluginSys.GetPluginByCtx(pContext->GetContext()));
1410 REGISTER_NATIVES(dbNatives)
1412 {"SQL_BindParamInt", SQL_BindParamInt},
1413 {"SQL_BindParamFloat", SQL_BindParamFloat},
1414 {"SQL_BindParamString", SQL_BindParamString},\
1415 {"SQL_CheckConfig", SQL_CheckConfig},
1416 {"SQL_Connect", SQL_Connect},
1417 {"SQL_ConnectEx", SQL_ConnectEx},
1418 {"SQL_EscapeString", SQL_QuoteString},
1419 {"SQL_Execute", SQL_Execute},
1420 {"SQL_FastQuery", SQL_FastQuery},
1421 {"SQL_FetchFloat", SQL_FetchFloat},
1422 {"SQL_FetchInt", SQL_FetchInt},
1423 {"SQL_FetchMoreResults", SQL_FetchMoreResults},
1424 {"SQL_FetchRow", SQL_FetchRow},
1425 {"SQL_FetchSize", SQL_FetchSize},
1426 {"SQL_FetchString", SQL_FetchString},
1427 {"SQL_FieldNameToNum", SQL_FieldNameToNum},
1428 {"SQL_FieldNumToName", SQL_FieldNumToName},
1429 {"SQL_GetAffectedRows", SQL_GetAffectedRows},
1430 {"SQL_GetDriver", SQL_GetDriver},
1431 {"SQL_GetDriverIdent", SQL_GetDriverIdent},
1432 {"SQL_GetDriverProduct", SQL_GetDriverProduct},
1433 {"SQL_GetError", SQL_GetError},
1434 {"SQL_GetFieldCount", SQL_GetFieldCount},
1435 {"SQL_GetInsertId", SQL_GetInsertId},
1436 {"SQL_GetRowCount", SQL_GetRowCount},
1437 {"SQL_HasResultSet", SQL_HasResultSet},
1438 {"SQL_IsFieldNull", SQL_IsFieldNull},
1439 {"SQL_IsSameConnection", SQL_IsSameConnection},
1440 {"SQL_LockDatabase", SQL_LockDatabase},
1441 {"SQL_MoreRows", SQL_MoreRows},
1442 {"SQL_PrepareQuery", SQL_PrepareQuery},
1443 {"SQL_Query", SQL_Query},
1444 {"SQL_QuoteString", SQL_QuoteString},
1445 {"SQL_ReadDriver", SQL_ReadDriver},
1446 {"SQL_Rewind", SQL_Rewind},
1447 {"SQL_TConnect", SQL_TConnect},
1448 {"SQL_TQuery", SQL_TQuery},
1449 {"SQL_UnlockDatabase", SQL_UnlockDatabase},
1450 {"SQL_ConnectCustom", SQL_ConnectCustom},