extensions/sqlite/driver/SqDriver.cpp
author David Anderson <dvander@alliedmods.net>
Wed Aug 01 01:54:53 2007 +0000 (2007-08-01)
changeset 1226 478550a4d5ec
parent 1203 633c25ce6405
child 1330 ab94316bb52b
permissions -rw-r--r--
updated license headers for most extensions
updated sdk bases for most extensions
     1 /**
     2  * vim: set ts=4 :
     3  * ================================================================
     4  * SourceMod SQLite 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  * version 3.0, as published by the Free Software Foundation.
    11  * 
    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, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to 
    21  * link the code of this program (as well as its derivative works) to 
    22  * "Half-Life 2," the "Source Engine," the "SourcePawn JIT," and any 
    23  * Game MODs that run on software by the Valve Corporation.  You must 
    24  * obey the GNU General Public License in all respects for all other 
    25  * code used. Additionally, AlliedModders LLC grants this exception 
    26  * to all derivative works. AlliedModders LLC defines further 
    27  * exceptions, found in LICENSE.txt (as of this writing, version 
    28  * JULY-31-2007), or <http://www.sourcemod.net/license.php>.
    29  *
    30  * Version: $Id$
    31  */
    32 
    33 #include <sm_platform.h>
    34 #include "extension.h"
    35 #include "SqDriver.h"
    36 #include "SqDatabase.h"
    37 
    38 SqDriver g_SqDriver;
    39 
    40 unsigned int strncopy(char *dest, const char *src, size_t count)
    41 {
    42 	if (!count)
    43 	{
    44 		return 0;
    45 	}
    46 
    47 	char *start = dest;
    48 	while ((*src) && (--count))
    49 	{
    50 		*dest++ = *src++;
    51 	}
    52 	*dest = '\0';
    53 
    54 	return (dest - start);
    55 }
    56 
    57 SqDriver::SqDriver()
    58 {
    59 	m_Handle = BAD_HANDLE;
    60 	m_pOpenLock = NULL;
    61 }
    62 
    63 void SqDriver::Initialize()
    64 {
    65 	m_pOpenLock = threader->MakeMutex();
    66 }
    67 
    68 void SqDriver::Shutdown()
    69 {
    70 	if (m_pOpenLock)
    71 	{
    72 		m_pOpenLock->DestroyThis();
    73 	}
    74 }
    75 
    76 bool SqDriver::IsThreadSafe()
    77 {
    78 	return true;
    79 }
    80 
    81 bool SqDriver::InitializeThreadSafety()
    82 {
    83 	/* sqlite should be thread safe if the locks are done right.
    84 	 * we don't enable the "shared cache" because it can corrupt
    85 	 * open databases!
    86 	 */
    87 	return true;
    88 }
    89 
    90 void SqDriver::ShutdownThreadSafety()
    91 {
    92 	return;
    93 }
    94 
    95 IdentityToken_t *SqDriver::GetIdentity()
    96 {
    97 	return myself->GetIdentity();
    98 }
    99 
   100 const char *SqDriver::GetProductName()
   101 {
   102 	return "SQLite";
   103 }
   104 
   105 const char *SqDriver::GetIdentifier()
   106 {
   107 	return "sqlite";
   108 }
   109 
   110 Handle_t SqDriver::GetHandle()
   111 {
   112 	if (m_Handle == BAD_HANDLE)
   113 	{
   114 		m_Handle = dbi->CreateHandle(DBHandle_Driver, this, myself->GetIdentity());
   115 	}
   116 
   117 	return m_Handle;
   118 }
   119 
   120 inline bool IsPathSepChar(char c)
   121 {
   122 #if defined PLATFORM_WINDOWS
   123 	return (c == '\\' || c == '/');
   124 #elif defined PLATFORM_LINUX
   125 	return (c == '/');
   126 #endif
   127 }
   128 
   129 IDatabase *SqDriver::Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength)
   130 {
   131 	/* We wrap most of the open process in a mutex just to be safe */
   132 	m_pOpenLock->Lock();
   133 
   134 	/* Format our path */
   135 	char path[PLATFORM_MAX_PATH];
   136 	size_t len = libsys->PathFormat(path, sizeof(path), "sqlite/%s", info->database);
   137 
   138 	/* Chop any filename off */
   139 	for (size_t i = len-1;
   140 		 i >= 0 && i <= len-1;
   141 		 i--)
   142 	{
   143 		if (IsPathSepChar(path[i]))
   144 		{
   145 			path[i] = '\0';
   146 			break;
   147 		}
   148 	}
   149 
   150 	/* Test the full path */
   151 	char fullpath[PLATFORM_MAX_PATH];
   152 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/%s", path);
   153 	if (!libsys->IsPathDirectory(fullpath))
   154 	{
   155 		/* Make sure the data folder exists */
   156 		len = g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data");
   157 		if (!libsys->IsPathDirectory(fullpath))
   158 		{
   159 			if (!libsys->CreateFolder(fullpath))
   160 			{
   161 				strncopy(error, "Could not create or open \"data\" folder\"", maxlength);
   162 				m_pOpenLock->Unlock();
   163 				return NULL;
   164 			}
   165 		}
   166 
   167 		/* The data folder exists - create each subdir as needed! */
   168 		char *cur_ptr = path;
   169 
   170 		do
   171 		{
   172 			/* Find the next suitable path */
   173 			char *next_ptr = cur_ptr;
   174 			while (*next_ptr != '\0')
   175 			{
   176 				if (IsPathSepChar(*next_ptr))
   177 				{
   178 					*next_ptr = '\0';
   179 					next_ptr++;
   180 					break;
   181 				}
   182 				next_ptr++;
   183 			}
   184 			if (*next_ptr == '\0')
   185 			{
   186 				next_ptr = NULL;
   187 			}
   188 			len += libsys->PathFormat(&fullpath[len], sizeof(fullpath)-len, "/%s", cur_ptr);
   189 			if (!libsys->IsPathDirectory(fullpath) && !libsys->CreateFolder(fullpath))
   190 			{
   191 				break;
   192 			}
   193 			cur_ptr = next_ptr;
   194 		} while (cur_ptr);
   195 	}
   196 
   197 	/* Build the FINAL path. */
   198 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/sqlite/%s.sq3", info->database);
   199 
   200 	/* If we're requesting a persistent connection, see if something is already open */
   201 	if (persistent)
   202 	{
   203 		/* See if anything in the cache matches */
   204 		List<SqDbInfo>::iterator iter;
   205 		for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   206 		{
   207 			if ((*iter).path.compare(fullpath) == 0)
   208 			{
   209 				(*iter).db->IncReferenceCount();
   210 				m_pOpenLock->Unlock();
   211 				return (*iter).db;
   212 			}
   213 		}
   214 	}
   215 
   216 	/* Try to open a new connection */
   217 	sqlite3 *sql;
   218 	int err = sqlite3_open(fullpath, &sql);
   219 	if (err != SQLITE_OK)
   220 	{
   221 		strncopy(error, sqlite3_errmsg(sql), maxlength);
   222 		sqlite3_close(sql);
   223 		m_pOpenLock->Unlock();
   224 		return NULL;
   225 	}
   226 
   227 	SqDatabase *pdb = new SqDatabase(sql, persistent);
   228 
   229 	if (persistent)
   230 	{
   231 		SqDbInfo pinfo;
   232 		pinfo.path = fullpath;
   233 		pinfo.db = pdb;
   234 		m_Cache.push_back(pinfo);
   235 	}
   236 
   237 	m_pOpenLock->Unlock();
   238 
   239 	return pdb;
   240 }
   241 
   242 void SqDriver::RemovePersistent(IDatabase *pdb)
   243 {
   244 	List<SqDbInfo>::iterator iter;
   245 	for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   246 	{
   247 		if ((*iter).db == pdb)
   248 		{
   249 			iter = m_Cache.erase(iter);
   250 			return;
   251 		}
   252 	}
   253 }