extensions/sqlite/driver/SqDriver.cpp
author David Anderson <dvander@alliedmods.net>
Sun Jul 29 14:56:24 2007 +0000 (2007-07-29)
changeset 1210 18e60c8737a2
parent 1203 633c25ce6405
child 1226 478550a4d5ec
permissions -rw-r--r--
fixed an sqlite bug where empty results would count as no result set
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod SQLite Driver Extension
     5  * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
     6  * ===============================================================
     7  *
     8  * This program is free software; you can redistribute it and/or
     9  * modify it under the terms of the GNU General Public License
    10  * as published by the Free Software Foundation; either version 2
    11  * of the License, or (at your option) any later version.
    12  * This program is distributed in the hope that it will be useful,
    13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15  * GNU General Public License for more details.
    16  * 
    17  * You should have received a copy of the GNU General Public License
    18  * along with this program; if not, write to the Free Software
    19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    20  *
    21  * Version: $Id$
    22  */
    23 
    24 #include <sm_platform.h>
    25 #include "extension.h"
    26 #include "SqDriver.h"
    27 #include "SqDatabase.h"
    28 
    29 SqDriver g_SqDriver;
    30 
    31 unsigned int strncopy(char *dest, const char *src, size_t count)
    32 {
    33 	if (!count)
    34 	{
    35 		return 0;
    36 	}
    37 
    38 	char *start = dest;
    39 	while ((*src) && (--count))
    40 	{
    41 		*dest++ = *src++;
    42 	}
    43 	*dest = '\0';
    44 
    45 	return (dest - start);
    46 }
    47 
    48 SqDriver::SqDriver()
    49 {
    50 	m_Handle = BAD_HANDLE;
    51 	m_pOpenLock = NULL;
    52 }
    53 
    54 void SqDriver::Initialize()
    55 {
    56 	m_pOpenLock = threader->MakeMutex();
    57 }
    58 
    59 void SqDriver::Shutdown()
    60 {
    61 	if (m_pOpenLock)
    62 	{
    63 		m_pOpenLock->DestroyThis();
    64 	}
    65 }
    66 
    67 bool SqDriver::IsThreadSafe()
    68 {
    69 	return true;
    70 }
    71 
    72 bool SqDriver::InitializeThreadSafety()
    73 {
    74 	/* sqlite should be thread safe if the locks are done right.
    75 	 * we don't enable the "shared cache" because it can corrupt
    76 	 * open databases!
    77 	 */
    78 	return true;
    79 }
    80 
    81 void SqDriver::ShutdownThreadSafety()
    82 {
    83 	return;
    84 }
    85 
    86 IdentityToken_t *SqDriver::GetIdentity()
    87 {
    88 	return myself->GetIdentity();
    89 }
    90 
    91 const char *SqDriver::GetProductName()
    92 {
    93 	return "SQLite";
    94 }
    95 
    96 const char *SqDriver::GetIdentifier()
    97 {
    98 	return "sqlite";
    99 }
   100 
   101 Handle_t SqDriver::GetHandle()
   102 {
   103 	if (m_Handle == BAD_HANDLE)
   104 	{
   105 		m_Handle = dbi->CreateHandle(DBHandle_Driver, this, myself->GetIdentity());
   106 	}
   107 
   108 	return m_Handle;
   109 }
   110 
   111 inline bool IsPathSepChar(char c)
   112 {
   113 #if defined PLATFORM_WINDOWS
   114 	return (c == '\\' || c == '/');
   115 #elif defined PLATFORM_LINUX
   116 	return (c == '/');
   117 #endif
   118 }
   119 
   120 IDatabase *SqDriver::Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength)
   121 {
   122 	/* We wrap most of the open process in a mutex just to be safe */
   123 	m_pOpenLock->Lock();
   124 
   125 	/* Format our path */
   126 	char path[PLATFORM_MAX_PATH];
   127 	size_t len = libsys->PathFormat(path, sizeof(path), "sqlite/%s", info->database);
   128 
   129 	/* Chop any filename off */
   130 	for (size_t i = len-1;
   131 		 i >= 0 && i <= len-1;
   132 		 i--)
   133 	{
   134 		if (IsPathSepChar(path[i]))
   135 		{
   136 			path[i] = '\0';
   137 			break;
   138 		}
   139 	}
   140 
   141 	/* Test the full path */
   142 	char fullpath[PLATFORM_MAX_PATH];
   143 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/%s", path);
   144 	if (!libsys->IsPathDirectory(fullpath))
   145 	{
   146 		/* Make sure the data folder exists */
   147 		len = g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data");
   148 		if (!libsys->IsPathDirectory(fullpath))
   149 		{
   150 			if (!libsys->CreateFolder(fullpath))
   151 			{
   152 				strncopy(error, "Could not create or open \"data\" folder\"", maxlength);
   153 				m_pOpenLock->Unlock();
   154 				return NULL;
   155 			}
   156 		}
   157 
   158 		/* The data folder exists - create each subdir as needed! */
   159 		char *cur_ptr = path;
   160 
   161 		do
   162 		{
   163 			/* Find the next suitable path */
   164 			char *next_ptr = cur_ptr;
   165 			while (*next_ptr != '\0')
   166 			{
   167 				if (IsPathSepChar(*next_ptr))
   168 				{
   169 					*next_ptr = '\0';
   170 					next_ptr++;
   171 					break;
   172 				}
   173 				next_ptr++;
   174 			}
   175 			if (*next_ptr == '\0')
   176 			{
   177 				next_ptr = NULL;
   178 			}
   179 			len += libsys->PathFormat(&fullpath[len], sizeof(fullpath)-len, "/%s", cur_ptr);
   180 			if (!libsys->IsPathDirectory(fullpath) && !libsys->CreateFolder(fullpath))
   181 			{
   182 				break;
   183 			}
   184 			cur_ptr = next_ptr;
   185 		} while (cur_ptr);
   186 	}
   187 
   188 	/* Build the FINAL path. */
   189 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/sqlite/%s.sq3", info->database);
   190 
   191 	/* If we're requesting a persistent connection, see if something is already open */
   192 	if (persistent)
   193 	{
   194 		/* See if anything in the cache matches */
   195 		List<SqDbInfo>::iterator iter;
   196 		for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   197 		{
   198 			if ((*iter).path.compare(fullpath) == 0)
   199 			{
   200 				(*iter).db->IncReferenceCount();
   201 				m_pOpenLock->Unlock();
   202 				return (*iter).db;
   203 			}
   204 		}
   205 	}
   206 
   207 	/* Try to open a new connection */
   208 	sqlite3 *sql;
   209 	int err = sqlite3_open(fullpath, &sql);
   210 	if (err != SQLITE_OK)
   211 	{
   212 		strncopy(error, sqlite3_errmsg(sql), maxlength);
   213 		sqlite3_close(sql);
   214 		m_pOpenLock->Unlock();
   215 		return NULL;
   216 	}
   217 
   218 	SqDatabase *pdb = new SqDatabase(sql, persistent);
   219 
   220 	if (persistent)
   221 	{
   222 		SqDbInfo pinfo;
   223 		pinfo.path = fullpath;
   224 		pinfo.db = pdb;
   225 		m_Cache.push_back(pinfo);
   226 	}
   227 
   228 	m_pOpenLock->Unlock();
   229 
   230 	return pdb;
   231 }
   232 
   233 void SqDriver::RemovePersistent(IDatabase *pdb)
   234 {
   235 	List<SqDbInfo>::iterator iter;
   236 	for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   237 	{
   238 		if ((*iter).db == pdb)
   239 		{
   240 			iter = m_Cache.erase(iter);
   241 			return;
   242 		}
   243 	}
   244 }