
// Make this server only right now.
if (!SERVER) then return end

// The dll is called gmsv_ so it will only load on the server
require ( "sqlite" )

// Return if there's nothing to add on to
if (!sql) then return end


/*----------------------------------------------------------
	Attempts to make a string safe to put into the database
----------------------------------------------------------*/
function sql.SQLStr( str_in )

	local str = tostring( str_in )
	
	str = str:gsub( "'", '\\\'' )
	str = str:gsub( '"', '\\"' )
	
	return "\"" .. str .. "\"";

end

SQLStr = sql.SQLStr


/*---------------------------------------------------------
    Returns true if the table exists. False if it doesn't
---------------------------------------------------------*/
function sql.TableExists( name )

	local r = sql.Query( "select name FROM sqlite_master WHERE name="..SQLStr( name ).." AND type='table'" );
	
	if ( r ) then return true end
	
	return false

end

/*---------------------------------------------------------
    Query and get a single row
	eg sql.QueryRow( "SELECT * from ratings LIMIT 1" )
---------------------------------------------------------*/
function sql.QueryRow( query, row )

	row = row or 1

	local r = sql.Query( query );
	
	if ( r ) then return r[ row ] end
	
	return r

end

/*---------------------------------------------------------
    Query and get a single value
	eg sql.QueryValue( "SELECT count(*) from ratings" )
---------------------------------------------------------*/
function sql.QueryValue( query )

	local r = sql.QueryRow( query );
	
	if ( r ) then 
	
		// Is this really the best way to get the first/only value in a table
		for k, v in pairs( r ) do return v end
		
	end
	
	return r

end

