atcprintf() is now fully re-entrant, meaning translations can be used from inside translations
3 * =============================================================================
5 * Copyright (C) 2004-2007 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 hQueryType;
40 HandleType_t hStmtType;
42 class DatabaseHelpers :
44 public IHandleTypeDispatch
47 virtual void OnSourceModAllInitialized()
52 g_HandleSys.InitAccessDefaults(NULL, &acc);
53 acc.access[HandleAccess_Clone] = HANDLE_RESTRICT_OWNER|HANDLE_RESTRICT_IDENTITY;
57 g_HandleSys.InitAccessDefaults(&tacc, NULL);
58 tacc.ident = g_pCoreIdent;
60 hQueryType = g_HandleSys.CreateType("IQuery", this, 0, &tacc, &acc, g_pCoreIdent, NULL);
61 hStmtType = g_HandleSys.CreateType("IPreparedQuery", this, hQueryType, &tacc, &acc, g_pCoreIdent, NULL);
64 virtual void OnSourceModShutdown()
66 g_HandleSys.RemoveType(hStmtType, g_pCoreIdent);
67 g_HandleSys.RemoveType(hQueryType, g_pCoreIdent);
70 virtual void OnHandleDestroy(HandleType_t type, void *object)
72 if (type == hQueryType)
74 IQuery *query = (IQuery *)object;
76 } else if (type == hStmtType) {
77 IPreparedQuery *query = (IPreparedQuery *)object;
81 } s_DatabaseNativeHelpers;
83 //is this safe for stmt handles? i think since it's single inheritance, it always will be.
84 inline HandleError ReadQueryHndl(Handle_t hndl, IPluginContext *pContext, IQuery **query)
87 sec.pOwner = pContext->GetIdentity();
88 sec.pIdentity = g_pCoreIdent;
90 return g_HandleSys.ReadHandle(hndl, hQueryType, &sec, (void **)query);
93 inline HandleError ReadStmtHndl(Handle_t hndl, IPluginContext *pContext, IPreparedQuery **query)
96 sec.pOwner = pContext->GetIdentity();
97 sec.pIdentity = g_pCoreIdent;
99 return g_HandleSys.ReadHandle(hndl, hStmtType, &sec, (void **)query);
102 inline HandleError ReadDbOrStmtHndl(Handle_t hndl, IPluginContext *pContext, IDatabase **db, IPreparedQuery **query)
105 if ((err = g_DBMan.ReadHandle(hndl, DBHandle_Database, (void **)db)) == HandleError_Type)
108 return ReadStmtHndl(hndl, pContext, query);
113 class TQueryOp : public IDBThreadOperation
116 TQueryOp(IDatabase *db, IPluginFunction *pf, const char *query, cell_t data) :
117 m_pDatabase(db), m_pFunction(pf), m_Query(query), m_Data(data),
118 me(g_PluginSys.GetPluginByCtx(pf->GetParentContext()->GetContext())),
121 /* We always increase the reference count because this is potentially
122 * asynchronous. Otherwise the original handle could be closed while
123 * we're still latched onto it.
125 m_pDatabase->IncReferenceCount();
127 /* Now create our own Handle such that it can only be closed by us.
128 * We allow cloning just in case someone wants to hold onto it.
130 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
132 g_HandleSys.InitAccessDefaults(NULL, &access);
133 access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
134 m_MyHandle = g_HandleSys.CreateHandleEx(g_DBMan.GetDatabaseType(),
147 /* Close our Handle if it's valid. */
148 if (m_MyHandle != BAD_HANDLE)
150 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
151 g_HandleSys.FreeHandle(m_MyHandle, &sec);
153 /* Otherwise, there is an open ref to the db */
154 m_pDatabase->Close();
157 IdentityToken_t *GetOwner()
159 return me->GetIdentity();
161 IDBDriver *GetDriver()
163 return m_pDatabase->GetDriver();
167 m_pDatabase->LockForFullAtomicOperation();
168 m_pQuery = m_pDatabase->DoQuery(m_Query.c_str());
171 UTIL_Format(error, sizeof(error), "%s", m_pDatabase->GetError());
173 m_pDatabase->UnlockFromFullAtomicOperation();
175 void CancelThinkPart()
177 m_pFunction->PushCell(BAD_HANDLE);
178 m_pFunction->PushCell(BAD_HANDLE);
179 m_pFunction->PushString("Driver is unloading");
180 m_pFunction->PushCell(m_Data);
181 m_pFunction->Execute(NULL);
185 /* Create a Handle for our query */
186 HandleSecurity sec(me->GetIdentity(), g_pCoreIdent);
188 g_HandleSys.InitAccessDefaults(NULL, &access);
189 access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
191 Handle_t qh = BAD_HANDLE;
195 qh = g_HandleSys.CreateHandle(hQueryType, m_pQuery, me->GetIdentity(), g_pCoreIdent, NULL);
196 if (qh != BAD_HANDLE)
200 UTIL_Format(error, sizeof(error), "Could not alloc handle");
204 m_pFunction->PushCell(m_MyHandle);
205 m_pFunction->PushCell(qh);
206 m_pFunction->PushString(qh == BAD_HANDLE ? error : "");
207 m_pFunction->PushCell(m_Data);
208 m_pFunction->Execute(NULL);
210 if (qh != BAD_HANDLE)
212 g_HandleSys.FreeHandle(qh, &sec);
220 IDatabase *m_pDatabase;
221 IPluginFunction *m_pFunction;
230 class TConnectOp : public IDBThreadOperation
233 TConnectOp(IPluginFunction *func, IDBDriver *driver, const char *_dbname, cell_t data)
240 strncopy(dbname, _dbname, sizeof(dbname));
241 me = g_PluginSys.GetPluginByCtx(m_pFunction->GetParentContext()->GetContext());
243 IdentityToken_t *GetOwner()
245 return me->GetIdentity();
247 IDBDriver *GetDriver()
253 g_DBMan.LockConfig();
254 const DatabaseInfo *pInfo = g_DBMan.FindDatabaseConf(dbname);
257 UTIL_Format(error, sizeof(error), "Could not find database config \"%s\"", dbname);
259 m_pDatabase = m_pDriver->Connect(pInfo, false, error, sizeof(error));
261 g_DBMan.UnlockConfig();
263 void CancelThinkPart()
267 m_pDatabase->Close();
269 m_pFunction->PushCell(BAD_HANDLE);
270 m_pFunction->PushCell(BAD_HANDLE);
271 m_pFunction->PushString("Driver is unloading");
272 m_pFunction->PushCell(m_Data);
273 m_pFunction->Execute(NULL);
277 Handle_t hndl = BAD_HANDLE;
281 if ((hndl = g_DBMan.CreateHandle(DBHandle_Database, m_pDatabase, me->GetIdentity()))
284 m_pDatabase->Close();
285 UTIL_Format(error, sizeof(error), "Unable to allocate Handle");
289 m_pFunction->PushCell(m_pDriver->GetHandle());
290 m_pFunction->PushCell(hndl);
291 m_pFunction->PushString(hndl == BAD_HANDLE ? error : "");
292 m_pFunction->PushCell(m_Data);
293 m_pFunction->Execute(NULL);
301 IPluginFunction *m_pFunction;
302 IDBDriver *m_pDriver;
303 IDatabase *m_pDatabase;
309 static cell_t SQL_Connect(IPluginContext *pContext, const cell_t *params)
313 size_t maxlength = (size_t)params[4];
314 bool persistent = params[2] ? true : false;
315 pContext->LocalToString(params[1], &conf);
316 pContext->LocalToString(params[3], &err);
320 if (!g_DBMan.Connect(conf, &driver, &db, persistent, err, maxlength))
325 Handle_t hndl = g_DBMan.CreateHandle(DBHandle_Database, db, pContext->GetIdentity());
332 /* HACK! Add us to the dependency list */
333 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
336 g_Extensions.BindChildPlugin(pExt, g_PluginSys.FindPluginByContext(pContext->GetContext()));
342 static cell_t SQL_TConnect(IPluginContext *pContext, const cell_t *params)
344 IPluginFunction *pf = pContext->GetFunctionById(params[1]);
347 return pContext->ThrowNativeError("Function id %x is invalid", params[1]);
351 pContext->LocalToString(params[2], &conf);
353 IDBDriver *driver = NULL;
354 const DatabaseInfo *pInfo = g_DBMan.FindDatabaseConf(conf);
358 if (pInfo->driver[0] == '\0')
360 driver = g_DBMan.GetDefaultDriver();
362 driver = g_DBMan.FindOrLoadDriver(pInfo->driver);
368 "Could not find driver \"%s\"",
369 pInfo->driver[0] == '\0' ? g_DBMan.GetDefaultDriverName() : pInfo->driver);
370 } else if (!driver->IsThreadSafe()) {
373 "Driver \"%s\" is not thread safe!",
374 driver->GetIdentifier());
377 UTIL_Format(error, sizeof(error), "Could not find database conf \"%s\"", conf);
380 if (!pInfo || !driver)
382 pf->PushCell(BAD_HANDLE);
383 pf->PushCell(BAD_HANDLE);
384 pf->PushString(error);
390 /* HACK! Add us to the dependency list */
391 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
394 g_Extensions.BindChildPlugin(pExt, g_PluginSys.FindPluginByContext(pContext->GetContext()));
397 /* Finally, add to the thread if we can */
398 TConnectOp *op = new TConnectOp(pf, driver, conf, params[3]);
399 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
400 if (pPlugin->GetProperty("DisallowDBThreads", NULL)
401 || !g_DBMan.AddToThreadQueue(op, PrioQueue_High))
403 /* Do everything right now */
412 static cell_t SQL_ConnectEx(IPluginContext *pContext, const cell_t *params)
415 if (params[1] == BAD_HANDLE)
417 if ((driver = g_DBMan.GetDefaultDriver()) == NULL)
419 return pContext->ThrowNativeError("Could not find any default driver");
423 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Driver, (void **)&driver))
426 return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err);
430 char *host, *user, *pass, *database, *error;
431 size_t maxlength = (size_t)params[7];
432 bool persistent = params[8] ? true : false;
433 unsigned int port = params[9];
434 unsigned int maxTimeout = params[10];
435 pContext->LocalToString(params[2], &host);
436 pContext->LocalToString(params[3], &user);
437 pContext->LocalToString(params[4], &pass);
438 pContext->LocalToString(params[5], &database);
439 pContext->LocalToString(params[6], &error);
442 info.database = database;
443 info.driver = driver->GetIdentifier();
445 info.maxTimeout = maxTimeout;
450 IDatabase *db = driver->Connect(&info, persistent, error, maxlength);
454 Handle_t hndl = g_DBMan.CreateHandle(DBHandle_Database, db, pContext->GetIdentity());
461 /* HACK! Add us to the dependency list */
462 CExtension *pExt = g_Extensions.GetExtensionFromIdent(driver->GetIdentity());
465 g_Extensions.BindChildPlugin(pExt, g_PluginSys.FindPluginByContext(pContext->GetContext()));
474 static cell_t SQL_GetDriverIdent(IPluginContext *pContext, const cell_t *params)
477 if (params[1] == BAD_HANDLE)
479 if ((driver = g_DBMan.GetDefaultDriver()) == NULL)
481 return pContext->ThrowNativeError("Could not find any default driver");
485 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Driver, (void **)&driver))
488 return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err);
492 pContext->StringToLocalUTF8(params[2], params[3], driver->GetIdentifier(), NULL);
497 static cell_t SQL_GetDriver(IPluginContext *pContext, const cell_t *params)
500 pContext->LocalToString(params[1], &name);
502 IDBDriver *driver = NULL;
505 driver = g_DBMan.GetDefaultDriver();
507 driver = g_DBMan.FindOrLoadDriver(name);
510 return (driver != NULL) ? driver->GetHandle() : BAD_HANDLE;
513 static cell_t SQL_GetDriverProduct(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->GetProductName(), NULL);
536 static cell_t SQL_GetAffectedRows(IPluginContext *pContext, const cell_t *params)
538 IDatabase *db = NULL;
539 IPreparedQuery *stmt = NULL;
542 if ((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
544 return pContext->ThrowNativeError("Invalid statement or db Handle %x (error: %d)", params[1], err);
549 return db->GetAffectedRows();
551 return stmt->GetAffectedRows();
554 return pContext->ThrowNativeError("Unknown error reading db/stmt handles");
557 static cell_t SQL_GetInsertId(IPluginContext *pContext, const cell_t *params)
559 IDatabase *db = NULL;
560 IPreparedQuery *stmt = NULL;
563 if ((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
565 return pContext->ThrowNativeError("Invalid statement or db Handle %x (error: %d)", params[1], err);
570 return db->GetInsertID();
572 return stmt->GetInsertID();
575 return pContext->ThrowNativeError("Unknown error reading db/stmt handles");
578 static cell_t SQL_GetError(IPluginContext *pContext, const cell_t *params)
580 IDatabase *db = NULL;
581 IPreparedQuery *stmt = NULL;
584 if ((err = ReadDbOrStmtHndl(params[1], pContext, &db, &stmt)) != HandleError_None)
586 return pContext->ThrowNativeError("Invalid statement or db Handle %x (error: %d)", params[1], err);
589 const char *error = "";
592 error = db->GetError();
594 error = stmt->GetError();
597 if (error[0] == '\0')
602 pContext->StringToLocalUTF8(params[2], params[3], error, NULL);
607 static cell_t SQL_QuoteString(IPluginContext *pContext, const cell_t *params)
609 IDatabase *db = NULL;
612 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
615 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
618 char *input, *output;
619 size_t maxlength = (size_t)params[4];
620 pContext->LocalToString(params[2], &input);
621 pContext->LocalToString(params[3], &output);
624 bool s = db->QuoteString(input, output, maxlength, &written);
627 pContext->LocalToPhysAddr(params[5], &addr);
628 *addr = (cell_t)written;
633 static cell_t SQL_FastQuery(IPluginContext *pContext, const cell_t *params)
635 IDatabase *db = NULL;
638 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
641 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
645 pContext->LocalToString(params[2], &query);
647 return db->DoSimpleQuery(query) ? 1 : 0;
650 static cell_t SQL_Query(IPluginContext *pContext, const cell_t *params)
652 IDatabase *db = NULL;
655 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
658 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
662 pContext->LocalToString(params[2], &query);
664 IQuery *qr = db->DoQuery(query);
671 Handle_t hndl = g_HandleSys.CreateHandle(hQueryType, qr, pContext->GetIdentity(), g_pCoreIdent, NULL);
672 if (hndl == BAD_HANDLE)
681 static cell_t SQL_TQuery(IPluginContext *pContext, const cell_t *params)
683 IDatabase *db = NULL;
686 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
689 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
692 if (!db->GetDriver()->IsThreadSafe())
694 return pContext->ThrowNativeError("Driver \"%s\" is not thread safe!", db->GetDriver()->GetIdentifier());
697 IPluginFunction *pf = pContext->GetFunctionById(params[2]);
700 return pContext->ThrowNativeError("Function id %x is invalid", params[2]);
704 pContext->LocalToString(params[3], &query);
706 cell_t data = params[4];
707 PrioQueueLevel level = PrioQueue_Normal;
708 if (params[5] == (cell_t)PrioQueue_High)
710 level = PrioQueue_High;
711 } else if (params[5] == (cell_t)PrioQueue_Low) {
712 level = PrioQueue_Low;
715 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
717 TQueryOp *op = new TQueryOp(db, pf, query, data);
718 if (pPlugin->GetProperty("DisallowDBThreads", NULL)
719 || !g_DBMan.AddToThreadQueue(op, level))
721 /* Do everything right now */
730 static cell_t SQL_LockDatabase(IPluginContext *pContext, const cell_t *params)
732 IDatabase *db = NULL;
735 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
738 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
741 db->LockForFullAtomicOperation();
746 static cell_t SQL_UnlockDatabase(IPluginContext *pContext, const cell_t *params)
748 IDatabase *db = NULL;
751 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
754 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
757 db->UnlockFromFullAtomicOperation();
762 static cell_t SQL_PrepareQuery(IPluginContext *pContext, const cell_t *params)
764 IDatabase *db = NULL;
767 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db))
770 return pContext->ThrowNativeError("Invalid database Handle %x (error: %d)", params[1], err);
774 size_t maxlength = (size_t)params[4];
775 pContext->LocalToString(params[2], &query);
776 pContext->LocalToString(params[3], &error);
778 IPreparedQuery *qr = db->PrepareQuery(query, error, maxlength);
785 Handle_t hndl = g_HandleSys.CreateHandle(hStmtType, qr, pContext->GetIdentity(), g_pCoreIdent, NULL);
786 if (hndl == BAD_HANDLE)
795 static cell_t SQL_FetchMoreResults(IPluginContext *pContext, const cell_t *params)
800 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
802 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
805 return query->FetchMoreResults() ? 1 : 0;
808 static cell_t SQL_HasResultSet(IPluginContext *pContext, const cell_t *params)
813 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
815 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
818 return query->GetResultSet() != NULL ? true : false;
821 static cell_t SQL_GetRowCount(IPluginContext *pContext, const cell_t *params)
826 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
828 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
831 IResultSet *rs = query->GetResultSet();
837 return rs->GetRowCount();
840 static cell_t SQL_GetFieldCount(IPluginContext *pContext, const cell_t *params)
845 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
847 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
850 IResultSet *rs = query->GetResultSet();
856 return rs->GetFieldCount();
859 static cell_t SQL_FieldNumToName(IPluginContext *pContext, const cell_t *params)
864 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
866 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
869 IResultSet *rs = query->GetResultSet();
872 return pContext->ThrowNativeError("No current result set");
875 unsigned int field = params[2];
878 if ((fldname = rs->FieldNumToName(field)) == NULL)
880 return pContext->ThrowNativeError("Invalid field index %d", field);
883 pContext->StringToLocalUTF8(params[3], params[4], fldname, NULL);
888 static cell_t SQL_FieldNameToNum(IPluginContext *pContext, const cell_t *params)
893 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
895 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
898 IResultSet *rs = query->GetResultSet();
901 return pContext->ThrowNativeError("No current result set");
905 pContext->LocalToString(params[2], &field);
908 pContext->LocalToPhysAddr(params[3], &num);
910 return rs->FieldNameToNum(field, (unsigned int *)num) ? 1 : 0;
913 static cell_t SQL_FetchRow(IPluginContext *pContext, const cell_t *params)
918 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
920 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
923 IResultSet *rs = query->GetResultSet();
926 return pContext->ThrowNativeError("No current result set");
929 return (rs->FetchRow() != NULL) ? true : false;
932 static cell_t SQL_MoreRows(IPluginContext *pContext, const cell_t *params)
937 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
939 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
942 IResultSet *rs = query->GetResultSet();
945 return pContext->ThrowNativeError("No current result set");
948 return rs->MoreRows() ? 1 : 0;
951 static cell_t SQL_Rewind(IPluginContext *pContext, const cell_t *params)
956 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
958 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
961 IResultSet *rs = query->GetResultSet();
964 return pContext->ThrowNativeError("No current result set");
967 return rs->Rewind() ? 1 : 0;
970 static cell_t SQL_FetchString(IPluginContext *pContext, const cell_t *params)
975 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
977 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
980 IResultSet *rs = query->GetResultSet();
983 return pContext->ThrowNativeError("No current result set");
986 IResultRow *row = rs->CurrentRow();
989 return pContext->ThrowNativeError("Current result set has no fetched rows");
994 DBResult res = row->GetString(params[2], &str, &length);
996 if (res == DBVal_Error)
998 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
999 } else if (res == DBVal_TypeMismatch) {
1000 return pContext->ThrowNativeError("Could not fetch data in field %d as a string", params[2]);
1003 pContext->StringToLocalUTF8(params[3], params[4], str, &length);
1006 pContext->LocalToPhysAddr(params[5], &addr);
1007 *addr = (cell_t)res;
1009 return (cell_t)length;
1012 static cell_t SQL_FetchFloat(IPluginContext *pContext, const cell_t *params)
1017 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1019 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1022 IResultSet *rs = query->GetResultSet();
1025 return pContext->ThrowNativeError("No current result set");
1028 IResultRow *row = rs->CurrentRow();
1031 return pContext->ThrowNativeError("Current result set has no fetched rows");
1035 DBResult res = row->GetFloat(params[2], &f);
1037 if (res == DBVal_Error)
1039 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
1040 } else if (res == DBVal_TypeMismatch) {
1041 return pContext->ThrowNativeError("Could not fetch data in field %d as a float", params[2]);
1045 pContext->LocalToPhysAddr(params[3], &addr);
1046 *addr = (cell_t)res;
1051 static cell_t SQL_FetchInt(IPluginContext *pContext, const cell_t *params)
1056 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1058 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1061 IResultSet *rs = query->GetResultSet();
1064 return pContext->ThrowNativeError("No current result set");
1067 IResultRow *row = rs->CurrentRow();
1070 return pContext->ThrowNativeError("Current result set has no fetched rows");
1074 DBResult res = row->GetInt(params[2], &iv);
1076 if (res == DBVal_Error)
1078 return pContext->ThrowNativeError("Error fetching data from field %d", params[2]);
1079 } else if (res == DBVal_TypeMismatch) {
1080 return pContext->ThrowNativeError("Could not fetch data in field %d as an integer", params[2]);
1084 pContext->LocalToPhysAddr(params[3], &addr);
1085 *addr = (cell_t)res;
1090 static cell_t SQL_IsFieldNull(IPluginContext *pContext, const cell_t *params)
1095 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1097 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1100 IResultSet *rs = query->GetResultSet();
1103 return pContext->ThrowNativeError("No current result set");
1106 IResultRow *row = rs->CurrentRow();
1109 return pContext->ThrowNativeError("Current result set has no fetched rows");
1112 if ((unsigned)params[2] >= rs->GetFieldCount())
1114 return pContext->ThrowNativeError("Invalid field index %d", params[2]);
1117 return row->IsNull(params[2]) ? 1 : 0;
1120 static cell_t SQL_FetchSize(IPluginContext *pContext, const cell_t *params)
1125 if ((err = ReadQueryHndl(params[1], pContext, &query)) != HandleError_None)
1127 return pContext->ThrowNativeError("Invalid query Handle %x (error: %d)", params[1], err);
1130 IResultSet *rs = query->GetResultSet();
1133 return pContext->ThrowNativeError("No current result set");
1136 IResultRow *row = rs->CurrentRow();
1139 return pContext->ThrowNativeError("Current result set has no fetched rows");
1142 if ((unsigned)params[2] >= rs->GetFieldCount())
1144 return pContext->ThrowNativeError("Invalid field index %d", params[2]);
1147 return row->GetDataSize(params[2]);
1150 static cell_t SQL_BindParamInt(IPluginContext *pContext, const cell_t *params)
1152 IPreparedQuery *stmt;
1155 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1157 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1160 if (!stmt->BindParamInt(params[2], params[3], params[4] ? true : false))
1162 return pContext->ThrowNativeError("Could not bind parameter %d as an integer", params[2]);
1168 static cell_t SQL_BindParamFloat(IPluginContext *pContext, const cell_t *params)
1170 IPreparedQuery *stmt;
1173 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1175 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1178 if (!stmt->BindParamFloat(params[2], sp_ctof(params[3])))
1180 return pContext->ThrowNativeError("Could not bind parameter %d as a float", params[2]);
1186 static cell_t SQL_BindParamString(IPluginContext *pContext, const cell_t *params)
1188 IPreparedQuery *stmt;
1191 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1193 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1197 pContext->LocalToString(params[3], &str);
1199 if (!stmt->BindParamString(params[2], str, params[4] ? true : false))
1201 return pContext->ThrowNativeError("Could not bind parameter %d as a string", params[2]);
1207 static cell_t SQL_Execute(IPluginContext *pContext, const cell_t *params)
1209 IPreparedQuery *stmt;
1212 if ((err = ReadStmtHndl(params[1], pContext, &stmt)) != HandleError_None)
1214 return pContext->ThrowNativeError("Invalid statement Handle %x (error: %d)", params[1], err);
1217 return stmt->Execute() ? 1 : 0;
1220 static cell_t SQL_IsSameConnection(IPluginContext *pContext, const cell_t *params)
1222 IDatabase *db1=NULL, *db2=NULL;
1225 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db1))
1226 != HandleError_None)
1228 return pContext->ThrowNativeError("Invalid database Handle 1/%x (error: %d)", params[1], err);
1231 if ((err = g_DBMan.ReadHandle(params[2], DBHandle_Database, (void **)&db2))
1232 != HandleError_None)
1234 return pContext->ThrowNativeError("Invalid database Handle 2/%x (error: %d)", params[2], err);
1237 return (db1 == db2) ? true : false;
1240 static cell_t SQL_ReadDriver(IPluginContext *pContext, const cell_t *params)
1242 IDatabase *db1=NULL;
1245 if ((err = g_DBMan.ReadHandle(params[1], DBHandle_Database, (void **)&db1))
1246 != HandleError_None)
1248 return pContext->ThrowNativeError("Invalid database Handle 1/%x (error: %d)", params[1], err);
1251 IDBDriver *driver = db1->GetDriver();
1253 pContext->StringToLocalUTF8(params[2], params[3], driver->GetIdentifier(), NULL);
1255 return driver->GetHandle();
1258 static cell_t SQL_CheckConfig(IPluginContext *pContext, const cell_t *params)
1261 pContext->LocalToString(params[1], &name);
1263 return (g_DBMan.FindDatabaseConf(name) != NULL) ? 1 : 0;
1266 REGISTER_NATIVES(dbNatives)
1268 {"SQL_BindParamInt", SQL_BindParamInt},
1269 {"SQL_BindParamFloat", SQL_BindParamFloat},
1270 {"SQL_BindParamString", SQL_BindParamString},\
1271 {"SQL_CheckConfig", SQL_CheckConfig},
1272 {"SQL_Connect", SQL_Connect},
1273 {"SQL_ConnectEx", SQL_ConnectEx},
1274 {"SQL_Execute", SQL_Execute},
1275 {"SQL_FastQuery", SQL_FastQuery},
1276 {"SQL_FetchFloat", SQL_FetchFloat},
1277 {"SQL_FetchInt", SQL_FetchInt},
1278 {"SQL_FetchMoreResults", SQL_FetchMoreResults},
1279 {"SQL_FetchRow", SQL_FetchRow},
1280 {"SQL_FetchSize", SQL_FetchSize},
1281 {"SQL_FetchString", SQL_FetchString},
1282 {"SQL_FieldNameToNum", SQL_FieldNameToNum},
1283 {"SQL_FieldNumToName", SQL_FieldNumToName},
1284 {"SQL_GetAffectedRows", SQL_GetAffectedRows},
1285 {"SQL_GetDriver", SQL_GetDriver},
1286 {"SQL_GetDriverIdent", SQL_GetDriverIdent},
1287 {"SQL_GetDriverProduct", SQL_GetDriverProduct},
1288 {"SQL_GetError", SQL_GetError},
1289 {"SQL_GetFieldCount", SQL_GetFieldCount},
1290 {"SQL_GetInsertId", SQL_GetInsertId},
1291 {"SQL_GetRowCount", SQL_GetRowCount},
1292 {"SQL_HasResultSet", SQL_HasResultSet},
1293 {"SQL_IsFieldNull", SQL_IsFieldNull},
1294 {"SQL_IsSameConnection", SQL_IsSameConnection},
1295 {"SQL_LockDatabase", SQL_LockDatabase},
1296 {"SQL_MoreRows", SQL_MoreRows},
1297 {"SQL_PrepareQuery", SQL_PrepareQuery},
1298 {"SQL_Query", SQL_Query},
1299 {"SQL_QuoteString", SQL_QuoteString},
1300 {"SQL_ReadDriver", SQL_ReadDriver},
1301 {"SQL_Rewind", SQL_Rewind},
1302 {"SQL_TConnect", SQL_TConnect},
1303 {"SQL_TQuery", SQL_TQuery},
1304 {"SQL_UnlockDatabase", SQL_UnlockDatabase},