EnumValuesFromConstraint($constraint['CHECK_CLAUSE']);
$default=substr($field['column_default'], 2, -2);
$field['data_type']=$this->enum(Array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
}
$output[$field['column_name']]=$field;
break;
default:
$output[$field['column_name']] = $field;
}
}
return $output;
}
/**
* Create an index on a table.
* @param string $tableName The name of the table.
* @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see Database::requireIndex() for more details.
*/
public function createIndex($tableName, $indexName, $indexSpec) {
$this->query($this->getIndexSqlDefinition($tableName, $indexName, $indexSpec));
}
/*
* This takes the index spec which has been provided by a class (ie static $indexes = blah blah)
* and turns it into a proper string.
* Some indexes may be arrays, such as fulltext and unique indexes, and this allows database-specific
* arrays to be created.
*/
public function convertIndexSpec($indexSpec){
if(is_array($indexSpec)){
//Here we create a db-specific version of whatever index we need to create.
switch($indexSpec['type']){
case 'fulltext':
$indexSpec='fulltext (' . str_replace(' ', '', $indexSpec['value']) . ')';
break;
case 'unique':
$indexSpec='unique (' . $indexSpec['value'] . ')';
break;
}
}
return $indexSpec;
}
protected function getIndexSqlDefinition($tableName, $indexName, $indexSpec) {
if(!is_array($indexSpec)){
$indexSpec=trim($indexSpec, '()');
$bits=explode(',', $indexSpec);
$indexes="\"" . implode("\",\"", $bits) . "\"";
return 'create index ix_' . $tableName . '_' . $indexName . " ON \"" . $tableName . "\" (" . $indexes . ");";
} else {
//create a type-specific index
if($indexSpec['type']=='fulltext'){
$primary_key=$this->getPrimaryKey($tableName);
//First, we need to see if a full text search already exists:
$result=$this->query("SELECT object_id FROM sys.fulltext_indexes WHERE object_id=object_id('$tableName');")->first();
$drop='';
if($result)
$drop="DROP FULLTEXT INDEX ON \"" . $tableName . "\";";
return $drop . "CREATE FULLTEXT INDEX ON \"$tableName\" ({$indexSpec['value']}) KEY INDEX $primary_key ON $this->database WITH CHANGE_TRACKING AUTO;";
}
if($indexSpec['type']=='unique')
return 'create unique index ix_' . $tableName . '_' . $indexName . " ON \"" . $tableName . "\" (\"" . $indexSpec['value'] . "\");";
}
}
function getDbSqlDefinition($tableName, $indexName, $indexSpec){
return $indexName;
}
/**
* Alter an index on a table.
* @param string $tableName The name of the table.
* @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see Database::requireIndex() for more details.
*/
public function alterIndex($tableName, $indexName, $indexSpec) {
$indexSpec = trim($indexSpec);
if($indexSpec[0] != '(') {
list($indexType, $indexFields) = explode(' ',$indexSpec,2);
} else {
$indexFields = $indexSpec;
}
if(!$indexType) {
$indexType = "index";
}
$this->query("DROP INDEX $indexName ON $tableName;");
$this->query("ALTER TABLE \"$tableName\" ADD $indexType \"$indexName\" $indexFields");
}
/**
* Return the list of indexes in a table.
* @param string $table The table name.
* @return array
*/
public function indexList($table) {
$indexes=DB::query("EXEC sp_helpindex '$table';");
$prefix = '';
foreach($indexes as $index) {
//Check for uniques:
if(strpos($index['index_description'], 'unique')!==false)
$prefix='unique ';
$key=str_replace(', ', ',', $index['index_keys']);
$indexList[$key]['indexname']=$index['index_name'];
$indexList[$key]['spec']=$prefix . '(' . $key . ')';
}
//Now we need to check to see if we have any fulltext indexes attached to this table:
$result=DB::query('EXEC sp_help_fulltext_columns;');
$columns='';
foreach($result as $row){
if($row['TABLE_NAME']==$table)
$columns.=$row['FULLTEXT_COLUMN_NAME'] . ',';
}
if($columns!=''){
$columns=trim($columns, ',');
$indexList['SearchFields']['indexname']='SearchFields';
$indexList['SearchFields']['spec']='fulltext (' . $columns . ')';
}
return isset($indexList) ? $indexList : null;
}
/**
* Returns a list of all the tables in the database.
* Table names will all be in lowercase.
* @return array
*/
public function tableList() {
foreach($this->query('EXEC sp_tables;') as $record) {
$table = strtolower($record['TABLE_NAME']);
$tables[$table] = $table;
}
return isset($tables) ? $tables : null;
}
/**
* Return the number of rows affected by the previous operation.
* @return int
*/
public function affectedRows() {
$funcName=$this->funcPrefix . '_rows_affected';
return $funcName($this->dbConn);
}
/**
* A function to return the field names and datatypes for the particular table
*/
public function tableDetails($tableName){
user_error("tableDetails not implemented", E_USER_WARNING);
return array();
/*
$query="SELECT a.attname as \"Column\", pg_catalog.format_type(a.atttypid, a.atttypmod) as \"Datatype\" FROM pg_catalog.pg_attribute a WHERE a.attnum > 0 AND NOT a.attisdropped AND a.attrelid = ( SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ '^($tableName)$' AND pg_catalog.pg_table_is_visible(c.oid));";
$result=DB::query($query);
$table=Array();
while($row=pg_fetch_assoc($result)){
$table[]=Array('Column'=>$row['Column'], 'DataType'=>$row['DataType']);
}
return $table;
*/
}
/**
* Return a boolean type-formatted string
* We use 'bit' so that we can do numeric-based comparisons
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function boolean($values, $asDbValue=false){
//Annoyingly, we need to do a good ol' fashioned switch here:
($values['default']) ? $default='1' : $default='0';
if($asDbValue)
return 'bit';
else
return 'bit not null default ' . $default;
}
/**
* Return a date type-formatted string
* For MySQL, we simply return the word 'date', no other parameters are necessary
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function date($values, $asDbValue=false){
if($asDbValue)
return 'date';
else
return 'date null';
}
/**
* Return a decimal type-formatted string
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function decimal($values, $asDbValue=false){
// Avoid empty strings being put in the db
if($values['precision'] == '') {
$precision = 1;
} else {
$precision = $values['precision'];
}
if($asDbValue)
return Array('data_type'=>'decimal', 'numeric_precision'=>'9,2');
else return 'decimal(' . $precision . ') not null';
}
/**
* Return a enum type-formatted string
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function enum($values){
//Enums are a bit different. We'll be creating a varchar(255) with a constraint of all the usual enum options.
//NOTE: In this one instance, we are including the table name in the values array
return "varchar(255) not null default '" . $values['default'] . "' check (\"" . $values['name'] . "\" in ('" . implode('\', \'', $values['enums']) . "'))";
}
/**
* Return a float type-formatted string
* For MySQL, we simply return the word 'date', no other parameters are necessary
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function float($values, $asDbValue=false){
if($asDbValue)
return Array('data_type'=>'float');
else return 'float';
}
/**
* Return a int type-formatted string
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function int($values, $asDbValue=false){
//We'll be using an 8 digit precision to keep it in line with the serial8 datatype for ID columns
if($asDbValue)
return Array('data_type'=>'numeric', 'numeric_precision'=>'8');
else
return 'numeric(8) not null default ' . (int)$values['default'];
}
/**
* Return a datetime type-formatted string
* For MS SQL, we simply return the word 'timestamp', no other parameters are necessary
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function ssdatetime($values, $asDbValue=false){
if($asDbValue)
return Array('data_type'=>'datetime');
else
return 'datetime null';
}
/**
* Return a text type-formatted string
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function text($values, $asDbValue=false){
if($asDbValue)
return Array('data_type'=>'text');
else
return 'text null';
}
/**
* Return a time type-formatted string
* For MySQL, we simply return the word 'time', no other parameters are necessary
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function time($values){
return 'time';
}
/**
* Return a varchar type-formatted string
*
* @params array $values Contains a tokenised list of info about this data type
* @return string
*/
public function varchar($values, $asDbValue=false){
if($asDbValue)
return Array('data_type'=>'varchar', 'character_maximum_length'=>'255');
else
return 'varchar(' . $values['precision'] . ') null';
}
/*
* Return a 4 digit numeric type. MySQL has a proprietary 'Year' type.
*/
public function year($values, $asDbValue=false){
if($asDbValue)
return Array('data_type'=>'numeric', 'numeric_precision'=>'4');
else return 'numeric(4)';
}
function escape_character($escape=false){
if($escape)
return "\\\"";
else
return "\"";
}
/**
* Create a fulltext search datatype for MySQL
*
* @param array $spec
*/
function fulltext($table, $spec){
//$spec['name'] is the column we've created that holds all the words we want to index.
//This is a coalesced collection of multiple columns if necessary
//$spec='create index ix_' . $table . '_' . $spec['name'] . ' on ' . $table . ' using gist(' . $spec['name'] . ');';
//return $spec;
echo 'full text just got called!
';
return '';
}
/**
* This returns the column which is the primary key for each table
* In Postgres, it is a SERIAL8, which is the equivalent of an auto_increment
*
* @return string
*/
function IdColumn($asDbValue=false, $hasAutoIncPK=true){
if($asDbValue)
return 'bigint';
else {
if($hasAutoIncPK)
return 'bigint identity(1,1)';
else return 'bigint';
}
}
/**
* Returns the SQL command to get all the tables in this database
*/
function allTablesSQL(){
return "SELECT name FROM {$this->database}..sysobjects WHERE xtype = 'U';";
}
/**
* Returns true if this table exists
* @todo Make a proper implementation
*/
function hasTable($tableName) {
return true;
}
/**
* Returns the values of the given enum field
* NOTE: Experimental; introduced for db-abstraction and may changed before 2.4 is released.
*/
public function enumValuesForField($tableName, $fieldName) {
// Get the enum of all page types from the SiteTree table
$constraints=$this->ColumnConstraints($tableName, $fieldName);
$classes=Array();
if($constraints){
$constraints=$this->EnumValuesFromConstraint($constraints['CHECK_CLAUSE']);
$classes=$constraints;
}
return $classes;
}
/**
* Because NOW() doesn't always work...
* MSSQL, I'm looking at you
*
*/
function now(){
return 'CURRENT_TIMESTAMP';
}
/**
* Convert a SQLQuery object into a SQL statement
* @todo There is a lot of duplication between this and MySQLDatabase::sqlQueryToString(). Perhaps they could both call a common
* helper function in Database?
*/
public function sqlQueryToString(SQLQuery $sqlQuery) {
if (!$sqlQuery->from) return '';
//TODO: remove me when the limit function supposedly works
$sqlQuery->limit='';
//Get the limit and offset
$limit='';
$offset='0';
if(is_array($sqlQuery->limit)){
$limit=$sqlQuery->limit['limit'];
if(isset($sqlQuery->limit['start']))
$offset=$sqlQuery->limit['start'];
} else {
//could be a comma delimited string
$bits=explode(',', $sqlQuery->limit);
$limit=trim($bits[0]);
if(isset($bits[1]))
$offset=trim($bits[1]);
}
$text='';
$limitText='';
if($sqlQuery->limit) {
$text='SELECT * FROM ( SELECT ROW_NUMBER() OVER (';
$limitText=' ORDER BY ' . $sqlQuery->orderby . ') AS Number,';
}
$distinct = $sqlQuery->distinct ? "DISTINCT " : "";
//NOTE: Assumes that deletes don't have limit/offset clauses
if($sqlQuery->delete)
$text = 'DELETE ';
else if($sqlQuery->select) {
if($limitText=='')
$text.='SELECT';
$text .= "$limitText $distinct" . implode(", ", $sqlQuery->select);
}
$text .= " FROM " . implode(" ", $sqlQuery->from);
if($sqlQuery->where) $text .= " WHERE (" . $sqlQuery->getFilter(). ")";
if($sqlQuery->groupby) $text .= " GROUP BY " . implode(", ", $sqlQuery->groupby);
if($sqlQuery->having) $text .= " HAVING ( " . implode(" ) AND ( ", $sqlQuery->having) . " )";
if($limitText=='')
if($sqlQuery->orderby) $text .= " ORDER BY " . $sqlQuery->orderby;
// Limit not implemented
if($sqlQuery->limit){
$text.=') AS Numbered WHERE Number BETWEEN ' . $offset . ' AND ' . ($offset+$limit) . ';';
}
//if($sqlQuery->limit) {
/*
* For MSSQL, we need to do something different since it doesn't support LIMIT OFFSET as most normal
* databases do
*
* This is our preferred method, but we need to know the primary key name:
*
select * from (
select row_number() over (order by $this->orderby) as number, * from MyTable
) as numbered
where number between 21 and 30
SELECT * FROM (
SELECT ROW_NUMBER() OVER (SELECT ORDER BY "Sort") AS Number, "SiteTree".*, "GhostPage".*, "ErrorPage".*, "RedirectorPage".*, "VirtualPage".*, "ExamplePage".*, "SiteTree"."ID", CASE WHEN "SiteTree"."ClassName" IS NOT NULL THEN "SiteTree"."ClassName" ELSE 'SiteTree' END AS "RecordClassName" FROM "SiteTree" LEFT JOIN "GhostPage" ON "GhostPage"."ID" = "SiteTree"."ID" LEFT JOIN "ErrorPage" ON "ErrorPage"."ID" = "SiteTree"."ID" LEFT JOIN "RedirectorPage" ON "RedirectorPage"."ID" = "SiteTree"."ID" LEFT JOIN "VirtualPage" ON "VirtualPage"."ID" = "SiteTree"."ID" LEFT JOIN "ExamplePage" ON "ExamplePage"."ID" = "SiteTree"."ID" WHERE ("URLSegment" = 'home') ORDER BY "Sort"
) AS Numbered WHERE Number BETWEEN 0 AND 1;
SELECT * FROM (
select ROW_NUMBER() over (order by SiteTree.Title) AS RowNum, *
FROM SiteTree) as Numbered
WHERE RowNum Between 0 And 1;
*/
//}
return $text;
}
/*
* This will return text which has been escaped in a database-friendly manner
* Using PHP's addslashes method won't work in MSSQL
*/
function addslashes($value){
$value=stripslashes($value);
$value=str_replace("'","''",$value);
$value=str_replace("\0","[NULL]",$value);
return $value;
}
/*
* This changes the index name depending on database requirements.
* MSSQL requires commas to be replaced with underscores
*/
function modifyIndex($index){
return str_replace('_', ',', $index);
}
/**
* The core search engine, used by this class and its subclasses to do fun stuff.
* Searches both SiteTree and File.
*
* TODO: This is a really basic search system, provided purely so we have something...
*
* @param string $keywords Keywords as a string.
*/
public function searchEngine($classesToSearch, $keywords, $pageLength = null, $sortBy = "Relevance DESC", $extraFilter = "", $booleanSearch = false, $alternativeFileFilter = "", $invertedMatch = false) {
$result=DB::query('EXEC sp_help_fulltext_columns;');
//Get a list of all the tables and columns we'll be searching on:
$tables=Array();
foreach($result as $row){
if(substr($row['TABLE_NAME'], -5)!='_Live' && substr($row['TABLE_NAME'], -9)!='_versions')
$tables[]="SELECT ID, '{$row['TABLE_NAME']}' AS Source FROM \"{$row['TABLE_NAME']}\" WHERE CONTAINS(\"{$row['FULLTEXT_COLUMN_NAME']}\", N'$keywords')";
}
//We'll do a union query on all of these tables... it's easeier!
$query=implode(' UNION ', $tables);
$result=DB::query($query);
$searchResults=new DataObjectSet();
foreach($result as $row){
$row_result=DataObject::get_by_id($row['Source'], $row['ID']);
$searchResults->push($row_result);
}
$searchResults->setPageLimits($start, $pageLength, $totalCount);
return $searchResults;
}
}
/**
* A result-set from a MySQL database.
* @package sapphire
* @subpackage model
*/
class MSSQLQuery extends Query {
/**
* The MySQLDatabase object that created this result set.
* @var MySQLDatabase
*/
private $database;
/**
* The internal MySQL handle that points to the result set.
* @var resource
*/
private $handle;
/**
* Holds either mssql or sqlsrv, depending on what's available on the server.
*
* @var string
*/
private $funcPrefix;
/**
* Hook the result-set given into a Query class, suitable for use by sapphire.
* @param database The database object that created this query.
* @param handle the internal mysql handle that is points to the resultset.
*/
public function __construct(MSSQLDatabase $database, $handle) {
if(function_exists('sqlsrv_connect'))
$this->funcPrefix='sqlsrv';
else
$this->funcPrefix='mssql';
$this->database = $database;
$this->handle = $handle;
parent::__construct();
}
public function __destroy() {
$funcName=$this->funcPrefix . '_free_result';
$funcName($this->handle);
}
/*
* Please see the comments below for numRecords
*
*/
public function seek($row) {
if($this->funcPrefix=='mssql')
return mssql_data_seek($this->handle, $row);
else
return false;
}
/*
* If we're running the sqlsrv set of functions, then the dataobject set is a forward-only curser
* Therefore, we do not have access to the number of rows that this result contains
* This is (usually) called from Database::rewind(), which in turn seems to be called when a foreach...
* is started on a recordset
*
* For this function, and seek() (above), we will be returning false.
*
*/
public function numRecords() {
if($this->funcPrefix=='mssql')
return mssql_num_rows($this->handle);
else
return false;
}
public function nextRecord() {
//echo 'running nextRecord
';
// Coalesce rather than replace common fields.
if($this->funcPrefix=='mssql'){
if($data = mssql_fetch_row($this->handle)) {
foreach($data as $columnIdx => $value) {
$columnName = mssql_field_name($this->handle, $columnIdx);
// $value || !$ouput[$columnName] means that the *last* occurring value is shown
// !$ouput[$columnName] means that the *first* occurring value is shown
if(isset($value) || !isset($output[$columnName])) {
$output[$columnName] = $value;
}
}
//echo 'output from nextRecord (MSSQL):';
//print_r($output);
//echo '
';
return $output;
} else {
//echo 'nothing to return from nextRecord
';
return false;
}
} else {
//Data returns true or false, NOT the actual row
if($data = sqlsrv_fetch($this->handle)) {
//Now we need to get each row as a stream
//foreach($data as $columnIdx => $value) {
while($row=sqlsrv_get_field(DB::$lastQuery)){
$columnName = sqlsrv_field_name($this->handle, $columnIdx);
// $value || !$ouput[$columnName] means that the *last* occurring value is shown
// !$ouput[$columnName] means that the *first* occurring value is shown
if(isset($value) || !isset($output[$columnName])) {
$output[$columnName] = $value;
}
}
//echo 'output from nextRecord (SQLSRV):';
//print_r($output);
//echo '
';
return $output;
} else {
//echo 'nothing to return from nextRecord
';
return false;
}
}
}
}
?>