extensions/sqlite/driver/SqDriver.cpp
author Ruben Gonzalez <drifter01620@gmail.com>
Thu May 22 09:49:27 2014 -0400 (2014-05-22)
changeset 4378 568f4497ef4a
parent 4040 b6924c1a1d71
permissions -rw-r--r--
Update CS:GO team score gamedata.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod SQLite Extension
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <sm_platform.h>
    33 #include "extension.h"
    34 #include "SqDriver.h"
    35 #include "SqDatabase.h"
    36 
    37 SqDriver g_SqDriver;
    38 
    39 unsigned int strncopy(char *dest, const char *src, size_t count)
    40 {
    41 	if (!count)
    42 	{
    43 		return 0;
    44 	}
    45 
    46 	char *start = dest;
    47 	while ((*src) && (--count))
    48 	{
    49 		*dest++ = *src++;
    50 	}
    51 	*dest = '\0';
    52 
    53 	return (dest - start);
    54 }
    55 
    56 int busy_handler(void *unused1, int unused2)
    57 {
    58 #if defined PLATFORM_WINDOWS
    59 	Sleep(100);
    60 #elif defined PLATFORM_POSIX
    61 	usleep(100000);
    62 #endif
    63 	return 1;
    64 }
    65 
    66 SqDriver::SqDriver()
    67 {
    68 	m_Handle = BAD_HANDLE;
    69 	m_bThreadSafe = false;
    70 }
    71 
    72 void SqDriver::Initialize()
    73 {
    74 	InitializeThreadSafety();
    75 }
    76 
    77 void SqDriver::Shutdown()
    78 {
    79 	if (m_bThreadSafe)
    80 	{
    81 		sqlite3_enable_shared_cache(0);
    82 	}
    83 }
    84 
    85 bool SqDriver::IsThreadSafe()
    86 {
    87 	return true;
    88 }
    89 
    90 bool SqDriver::InitializeThreadSafety()
    91 {
    92 	if (m_bThreadSafe)
    93 	{
    94 		return true;
    95 	}
    96 
    97 	if (sqlite3_threadsafe() == 0)
    98 	{
    99 		return false;
   100 	}
   101 
   102 	if (sqlite3_enable_shared_cache(1) != SQLITE_OK)
   103 	{
   104 		return false;
   105 	}
   106 
   107 	m_bThreadSafe = true;
   108 
   109 	return true;
   110 }
   111 
   112 void SqDriver::ShutdownThreadSafety()
   113 {
   114 	return;
   115 }
   116 
   117 IdentityToken_t *SqDriver::GetIdentity()
   118 {
   119 	return myself->GetIdentity();
   120 }
   121 
   122 const char *SqDriver::GetProductName()
   123 {
   124 	return "SQLite";
   125 }
   126 
   127 const char *SqDriver::GetIdentifier()
   128 {
   129 	return "sqlite";
   130 }
   131 
   132 Handle_t SqDriver::GetHandle()
   133 {
   134 	if (m_Handle == BAD_HANDLE)
   135 	{
   136 		m_Handle = dbi->CreateHandle(DBHandle_Driver, this, myself->GetIdentity());
   137 	}
   138 
   139 	return m_Handle;
   140 }
   141 
   142 inline bool IsPathSepChar(char c)
   143 {
   144 #if defined PLATFORM_WINDOWS
   145 	return (c == '\\' || c == '/');
   146 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
   147 	return (c == '/');
   148 #endif
   149 }
   150 
   151 IDatabase *SqDriver::Connect(const DatabaseInfo *info, bool persistent, char *error, size_t maxlength)
   152 {
   153 	ke::AutoLock lock(&m_OpenLock);
   154 
   155 	/* Format our path */
   156 	char path[PLATFORM_MAX_PATH];
   157 	size_t len = libsys->PathFormat(path, sizeof(path), "sqlite/%s", info->database);
   158 
   159 	/* Chop any filename off */
   160 	for (size_t i = len-1;
   161 		 i <= len-1;
   162 		 i--)
   163 	{
   164 		if (IsPathSepChar(path[i]))
   165 		{
   166 			path[i] = '\0';
   167 			break;
   168 		}
   169 	}
   170 
   171 	/* Test the full path */
   172 	char fullpath[PLATFORM_MAX_PATH];
   173 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/%s", path);
   174 	if (!libsys->IsPathDirectory(fullpath))
   175 	{
   176 		/* Make sure the data folder exists */
   177 		len = g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data");
   178 		if (!libsys->IsPathDirectory(fullpath))
   179 		{
   180 			if (!libsys->CreateFolder(fullpath))
   181 			{
   182 				strncopy(error, "Could not create or open \"data\" folder\"", maxlength);
   183 				return NULL;
   184 			}
   185 		}
   186 
   187 		/* The data folder exists - create each subdir as needed! */
   188 		char *cur_ptr = path;
   189 
   190 		do
   191 		{
   192 			/* Find the next suitable path */
   193 			char *next_ptr = cur_ptr;
   194 			while (*next_ptr != '\0')
   195 			{
   196 				if (IsPathSepChar(*next_ptr))
   197 				{
   198 					*next_ptr = '\0';
   199 					next_ptr++;
   200 					break;
   201 				}
   202 				next_ptr++;
   203 			}
   204 			if (*next_ptr == '\0')
   205 			{
   206 				next_ptr = NULL;
   207 			}
   208 			len += libsys->PathFormat(&fullpath[len], sizeof(fullpath)-len, "/%s", cur_ptr);
   209 			if (!libsys->IsPathDirectory(fullpath) && !libsys->CreateFolder(fullpath))
   210 			{
   211 				break;
   212 			}
   213 			cur_ptr = next_ptr;
   214 		} while (cur_ptr);
   215 	}
   216 
   217 	/* Build the FINAL path. */
   218 	g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "data/sqlite/%s.sq3", info->database);
   219 
   220 	/* If we're requesting a persistent connection, see if something is already open */
   221 	if (persistent)
   222 	{
   223 		/* See if anything in the cache matches */
   224 		List<SqDbInfo>::iterator iter;
   225 		for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   226 		{
   227 			if ((*iter).path.compare(fullpath) == 0)
   228 			{
   229 				(*iter).db->IncReferenceCount();
   230 				return (*iter).db;
   231 			}
   232 		}
   233 	}
   234 
   235 	/* Try to open a new connection */
   236 	sqlite3 *sql;
   237 	int err = sqlite3_open(fullpath, &sql);
   238 	if (err != SQLITE_OK)
   239 	{
   240 		strncopy(error, sqlite3_errmsg(sql), maxlength);
   241 		sqlite3_close(sql);
   242 		return NULL;
   243 	}
   244 
   245 	sqlite3_busy_handler(sql, busy_handler, NULL);
   246 
   247 	SqDatabase *pdb = new SqDatabase(sql, persistent);
   248 
   249 	if (persistent)
   250 	{
   251 		SqDbInfo pinfo;
   252 		pinfo.path = fullpath;
   253 		pinfo.db = pdb;
   254 		m_Cache.push_back(pinfo);
   255 	}
   256 
   257 	return pdb;
   258 }
   259 
   260 void SqDriver::RemovePersistent(IDatabase *pdb)
   261 {
   262 	ke::AutoLock lock(&m_OpenLock);
   263 
   264 	List<SqDbInfo>::iterator iter;
   265 	for (iter = m_Cache.begin(); iter != m_Cache.end(); iter++)
   266 	{
   267 		if ((*iter).db == pdb)
   268 		{
   269 			iter = m_Cache.erase(iter);
   270 			return;
   271 		}
   272 	}
   273 }