first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+700
View File
@@ -0,0 +1,700 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* MSSQL specific SQL code generator.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/ddl/sql_generator.php');
/**
* This class generate SQL code to be used against MSSQL
* It extends XMLDBgenerator so everything can be
* overridden as needed to generate correct SQL.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mssql_sql_generator extends sql_generator {
// Only set values that are different from the defaults present in XMLDBgenerator
/** @var string To be automatically added at the end of each statement. */
public $statement_end = "\ngo";
/** @var string Proper type for NUMBER(x) in this DB. */
public $number_type = 'DECIMAL';
/** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/
public $default_for_char = '';
/**
* @var bool To force the generator if NULL clauses must be specified. It shouldn't be necessary.
* note: some mssql drivers require them or everything is created as NOT NULL :-(
*/
public $specify_nulls = true;
/** @var bool True if the generator needs to add extra code to generate the sequence fields.*/
public $sequence_extra_code = false;
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name = 'IDENTITY(1,1)';
/** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/
public $sequence_only = false;
/** @var bool True if the generator needs to add code for table comments.*/
public $add_table_comments = false;
/** @var string Characters to be used as concatenation operator.*/
public $concat_character = '+';
/** @var string SQL sentence to rename one table, both 'OLDNAME' and 'NEWNAME' keywords are dynamically replaced.*/
public $rename_table_sql = "sp_rename 'OLDNAME', 'NEWNAME'";
/** @var string SQL sentence to rename one column where 'TABLENAME', 'OLDFIELDNAME' and 'NEWFIELDNAME' keywords are dynamically replaced.*/
public $rename_column_sql = "sp_rename 'TABLENAME.OLDFIELDNAME', 'NEWFIELDNAME', 'COLUMN'";
/** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/
public $drop_index_sql = 'DROP INDEX TABLENAME.INDEXNAME';
/** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/
public $rename_index_sql = "sp_rename 'TABLENAME.OLDINDEXNAME', 'NEWINDEXNAME', 'INDEX'";
/** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/
public $rename_key_sql = null;
/**
* Reset a sequence to the id field of a table.
*
* @param xmldb_table|string $table name of table or the table object.
* @return array of sql statements
*/
public function getResetSequenceSQL($table) {
if (is_string($table)) {
$table = new xmldb_table($table);
}
$value = (int)$this->mdb->get_field_sql('SELECT MAX(id) FROM {'. $table->getName() . '}');
$sqls = array();
// MSSQL has one non-consistent behavior to create the first identity value, depending
// if the table has been truncated or no. If you are really interested, you can find the
// whole description of the problem at:
// http://www.justinneff.com/archive/tag/dbcc-checkident
if ($value == 0) {
// truncate to get consistent result from reseed
$sqls[] = "TRUNCATE TABLE " . $this->getTableName($table);
$value = 1;
}
// From http://msdn.microsoft.com/en-us/library/ms176057.aspx
$sqls[] = "DBCC CHECKIDENT ('" . $this->getTableName($table) . "', RESEED, $value)";
return $sqls;
}
/**
* Given one xmldb_table, returns it's correct name, depending of all the parametrization
* Overridden to allow change of names in temp tables
*
* @param xmldb_table table whose name we want
* @param boolean to specify if the name must be quoted (if reserved word, only!)
* @return string the correct name of the table
*/
public function getTableName(xmldb_table $xmldb_table, $quoted=true) {
// Get the name, supporting special mssql names for temp tables
if ($this->temptables->is_temptable($xmldb_table->getName())) {
$tablename = $this->temptables->get_correct_name($xmldb_table->getName());
} else {
$tablename = $this->prefix . $xmldb_table->getName();
}
// Apply quotes optionally
if ($quoted) {
$tablename = $this->getEncQuoted($tablename);
}
return $tablename;
}
public function getCreateIndexSQL($xmldb_table, $xmldb_index) {
list($indexsql) = parent::getCreateIndexSQL($xmldb_table, $xmldb_index);
// Unique indexes need to work-around non-standard SQL server behaviour.
if ($xmldb_index->getUnique()) {
// Find any nullable columns. We need to add a
// WHERE field IS NOT NULL to the index definition for each one.
//
// For example if you have a unique index on the three columns
// (required, option1, option2) where the first one is non-null,
// and the others nullable, then the SQL will end up as
//
// CREATE UNIQUE INDEX index_name ON table_name (required, option1, option2)
// WHERE option1 IS NOT NULL AND option2 IS NOT NULL
//
// The first line comes from parent calls above. The WHERE is added below.
$extraconditions = [];
foreach ($this->get_nullable_fields_in_index($xmldb_table, $xmldb_index) as $fieldname) {
$extraconditions[] = $this->getEncQuoted($fieldname) .
' IS NOT NULL';
}
if ($extraconditions) {
$indexsql .= ' WHERE ' . implode(' AND ', $extraconditions);
}
}
return [$indexsql];
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to create temporary table (inside one array).
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array of sql statements
*/
public function getCreateTempTableSQL($xmldb_table) {
$this->temptables->add_temptable($xmldb_table->getName());
$sqlarr = $this->getCreateTableSQL($xmldb_table);
return $sqlarr;
}
/**
* Given one XMLDB Type, length and decimals, returns the DB proper SQL type.
*
* @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants.
* @param int $xmldb_length The length of that data type.
* @param int $xmldb_decimals The decimal places of precision of the data type.
* @return string The DB defined data type.
*/
public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // From http://msdn.microsoft.com/library/en-us/tsqlref/ts_da-db_7msw.asp?frame=true
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
if ($xmldb_length > 9) {
$dbtype = 'BIGINT';
} else if ($xmldb_length > 4) {
$dbtype = 'INTEGER';
} else {
$dbtype = 'SMALLINT';
}
break;
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_FLOAT:
$dbtype = 'FLOAT';
if (!empty($xmldb_decimals)) {
if ($xmldb_decimals < 6) {
$dbtype = 'REAL';
}
}
break;
case XMLDB_TYPE_CHAR:
$dbtype = 'NVARCHAR';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ') COLLATE database_default';
break;
case XMLDB_TYPE_TEXT:
$dbtype = 'NVARCHAR(MAX) COLLATE database_default';
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'VARBINARY(MAX)';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'DATETIME';
break;
}
return $dbtype;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table.
* MSSQL overwrites the standard sentence because it needs to do some extra work dropping the default and
* check constraints
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @return array The SQL statement for dropping a field from the table.
*/
public function getDropFieldSQL($xmldb_table, $xmldb_field) {
$results = array();
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $this->getEncQuoted($xmldb_field->getName());
// Look for any default constraint in this field and drop it
if ($defaultname = $this->getDefaultConstraintName($xmldb_table, $xmldb_field)) {
$results[] = 'ALTER TABLE ' . $tablename . ' DROP CONSTRAINT ' . $defaultname;
}
// Build the standard alter table drop column
$results[] = 'ALTER TABLE ' . $tablename . ' DROP COLUMN ' . $fieldname;
return $results;
}
/**
* Given one correct xmldb_field and the new name, returns the SQL statements
* to rename it (inside one array).
*
* MSSQL is special, so we overload the function here. It needs to
* drop the constraints BEFORE renaming the field
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from.
* @param string $newname The new name to rename the field to.
* @return array The SQL statements for renaming the field.
*/
public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) {
$results = array(); //Array where all the sentences will be stored
// Although this is checked in database_manager::rename_field() - double check
// that we aren't trying to rename one "id" field. Although it could be
// implemented (if adding the necessary code to rename sequences, defaults,
// triggers... and so on under each getRenameFieldExtraSQL() function, it's
// better to forbid it, mainly because this field is the default PK and
// in the future, a lot of FKs can be pointing here. So, this field, more
// or less, must be considered immutable!
if ($xmldb_field->getName() == 'id') {
return array();
}
// We can't call to standard (parent) getRenameFieldSQL() function since it would enclose the field name
// with improper quotes in MSSQL: here, we use a stored procedure to rename the field i.e. a column object;
// we need to take care about how this stored procedure expects parameters to be "qualified".
$rename = str_replace('TABLENAME', $this->getTableName($xmldb_table), $this->rename_column_sql);
// Qualifying the column object could require brackets: use them, regardless the column name not being a reserved word.
$rename = str_replace('OLDFIELDNAME', '[' . $xmldb_field->getName() . ']', $rename);
// The new field name should be passed as the actual name, w/o any quote.
$rename = str_replace('NEWFIELDNAME', $newname, $rename);
$results[] = $rename;
return $results;
}
/**
* Returns the code (array of statements) needed to execute extra statements on table rename.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param string $newname The new name for the table.
* @return array Array of extra SQL statements to rename a table.
*/
public function getRenameTableExtraSQL($xmldb_table, $newname) {
$results = array();
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table.
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @param string $skip_type_clause The type clause on alter columns, NULL by default.
* @param string $skip_default_clause The default clause on alter columns, NULL by default.
* @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default.
* @return string The field altering SQL statement.
*/
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
$results = array(); // To store all the needed SQL commands
// Get the quoted name of the table and field
$tablename = $xmldb_table->getName();
$fieldname = $xmldb_field->getName();
// Take a look to field metadata
$meta = $this->mdb->get_columns($tablename);
$metac = $meta[$fieldname];
$oldmetatype = $metac->meta_type;
$oldlength = $metac->max_length;
$olddecimals = empty($metac->scale) ? null : $metac->scale;
$oldnotnull = empty($metac->not_null) ? false : $metac->not_null;
//$olddefault = empty($metac->has_default) ? null : strtok($metac->default_value, ':');
$typechanged = true; //By default, assume that the column type has changed
$lengthchanged = true; //By default, assume that the column length has changed
// Detect if we are changing the type of the column
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') ||
($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') ||
($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR && $oldmetatype == 'C') ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT && $oldmetatype == 'X') ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) {
$typechanged = false;
}
// If the new field (and old) specs are for integer, let's be a bit more specific differentiating
// types of integers. Else, some combinations can cause things like MDL-21868
if ($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') {
if ($xmldb_field->getLength() > 9) { // Convert our new lenghts to detailed meta types
$newmssqlinttype = 'I8';
} else if ($xmldb_field->getLength() > 4) {
$newmssqlinttype = 'I';
} else {
$newmssqlinttype = 'I2';
}
if ($metac->type == 'bigint') { // Convert current DB type to detailed meta type (our metatype is not enough!)
$oldmssqlinttype = 'I8';
} else if ($metac->type == 'smallint') {
$oldmssqlinttype = 'I2';
} else {
$oldmssqlinttype = 'I';
}
if ($newmssqlinttype != $oldmssqlinttype) { // Compare new and old meta types
$typechanged = true; // Change in meta type means change in type at all effects
}
}
// Detect if we are changing the length of the column, not always necessary to drop defaults
// if only the length changes, but it's safe to do it always
if ($xmldb_field->getLength() == $oldlength) {
$lengthchanged = false;
}
// If type or length have changed drop the default if exists
if ($typechanged || $lengthchanged) {
$results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field);
}
// Some changes of type require multiple alter statements, because mssql lacks direct implicit cast between such types
// Here it is the matrix: http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx
// Going to store such intermediate alters in array of objects, storing all the info needed
$multiple_alter_stmt = array();
$targettype = $xmldb_field->getType();
if ($targettype == XMLDB_TYPE_TEXT && $oldmetatype == 'I') { // integer to text
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
} else if ($targettype == XMLDB_TYPE_TEXT && $oldmetatype == 'N') { // decimal to text
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
} else if ($targettype == XMLDB_TYPE_TEXT && $oldmetatype == 'F') { // float to text
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
} else if ($targettype == XMLDB_TYPE_INTEGER && $oldmetatype == 'X') { // text to integer
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
$multiple_alter_stmt[1] = new stdClass; // and also needs conversion to decimal
$multiple_alter_stmt[1]->type = XMLDB_TYPE_NUMBER; // without decimal positions
$multiple_alter_stmt[1]->length = 10;
} else if ($targettype == XMLDB_TYPE_NUMBER && $oldmetatype == 'X') { // text to decimal
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
} else if ($targettype == XMLDB_TYPE_FLOAT && $oldmetatype == 'X') { // text to float
$multiple_alter_stmt[0] = new stdClass; // needs conversion to varchar
$multiple_alter_stmt[0]->type = XMLDB_TYPE_CHAR;
$multiple_alter_stmt[0]->length = 255;
}
// Just prevent default clauses in this type of sentences for mssql and launch the parent one
if (empty($multiple_alter_stmt)) { // Direct implicit conversion allowed, launch it
$results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, NULL, true, NULL));
} else { // Direct implicit conversion forbidden, use the intermediate ones
$final_type = $xmldb_field->getType(); // Save final type and length
$final_length = $xmldb_field->getLength();
foreach ($multiple_alter_stmt as $alter) {
$xmldb_field->setType($alter->type); // Put our intermediate type and length and alter to it
$xmldb_field->setLength($alter->length);
$results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, NULL, true, NULL));
}
$xmldb_field->setType($final_type); // Set the final type and length and alter to it
$xmldb_field->setLength($final_length);
$results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, NULL, true, NULL));
}
// Finally, process the default clause to add it back if necessary
if ($typechanged || $lengthchanged) {
$results = array_merge($results, $this->getCreateDefaultSQL($xmldb_table, $xmldb_field));
}
// Return results
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to modify the default of the field in the table.
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to get the modified default value from.
* @return array The SQL statement for modifying the default value.
*/
public function getModifyDefaultSQL($xmldb_table, $xmldb_field) {
// MSSQL is a bit special with default constraints because it implements them as external constraints so
// normal ALTER TABLE ALTER COLUMN don't work to change defaults. Because this, we have this method overloaded here
$results = array();
// Decide if we are going to create/modify or to drop the default
if ($xmldb_field->getDefault() === null) {
$results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field); //Drop but, under some circumstances, re-enable
$default_clause = $this->getDefaultClause($xmldb_field);
if ($default_clause) { //If getDefaultClause() it must have one default, create it
$results = array_merge($results, $this->getCreateDefaultSQL($xmldb_table, $xmldb_field)); //Create/modify
}
} else {
$results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field); //Drop (only if exists)
$results = array_merge($results, $this->getCreateDefaultSQL($xmldb_table, $xmldb_field)); //Create/modify
}
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default
* (usually invoked from getModifyDefaultSQL()
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*/
public function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
// MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped
$results = array();
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $this->getEncQuoted($xmldb_field->getName());
// Now, check if, with the current field attributes, we have to build one default
$default_clause = $this->getDefaultClause($xmldb_field);
if ($default_clause) {
// We need to build the default (Moodle) default, so do it
$sql = 'ALTER TABLE ' . $tablename . ' ADD' . $default_clause . ' FOR ' . $fieldname;
$results[] = $sql;
}
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default
* (usually invoked from getModifyDefaultSQL()
*
* Note that this method may be dropped in future.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*
* @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL()
*/
public function getDropDefaultSQL($xmldb_table, $xmldb_field) {
// MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped
$results = array();
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $this->getEncQuoted($xmldb_field->getName());
// Look for the default contraint and, if found, drop it
if ($defaultname = $this->getDefaultConstraintName($xmldb_table, $xmldb_field)) {
$results[] = 'ALTER TABLE ' . $tablename . ' DROP CONSTRAINT ' . $defaultname;
}
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, returns the name of its default constraint in DB
* or false if not found
* This function should be considered internal and never used outside from generator
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return mixed
*/
protected function getDefaultConstraintName($xmldb_table, $xmldb_field) {
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $xmldb_field->getName();
// Look for any default constraint in this field and drop it
if ($default = $this->mdb->get_record_sql("SELECT object_id, object_name(default_object_id) AS defaultconstraint
FROM sys.columns
WHERE object_id = object_id(?)
AND name = ?", array($tablename, $fieldname))) {
return $default->defaultconstraint;
} else {
return false;
}
}
/**
* Given three strings (table name, list of fields (comma separated) and suffix),
* create the proper object name quoting it if necessary.
*
* IMPORTANT: This function must be used to CALCULATE NAMES of objects TO BE CREATED,
* NEVER TO GUESS NAMES of EXISTING objects!!!
*
* IMPORTANT: We are overriding this function for the MSSQL generator because objects
* belonging to temporary tables aren't searchable in the catalog neither in information
* schema tables. So, for temporary tables, we are going to add 4 randomly named "virtual"
* fields, so the generated names won't cause concurrency problems. Really nasty hack,
* but the alternative involves modifying all the creation table code to avoid naming
* constraints for temp objects and that will dupe a lot of code.
*
* @param string $tablename The table name.
* @param string $fields A list of comma separated fields.
* @param string $suffix A suffix for the object name.
* @return string Object's name.
*/
public function getNameForObject($tablename, $fields, $suffix='') {
if ($this->temptables->is_temptable($tablename)) { // Is temp table, inject random field names
$random = strtolower(random_string(12)); // 12cc to be split in 4 parts
$fields = $fields . ', ' . implode(', ', str_split($random, 3));
}
return parent::getNameForObject($tablename, $fields, $suffix); // Delegate to parent (common) algorithm
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg).
*
* (MySQL requires the whole xmldb_table object to be specified, so we add it always)
*
* This is invoked from getNameForObject().
* Only some DB have this implemented.
*
* @param string $object_name The object's name to check for.
* @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg).
* @param string $table_name The table's name to check in
* @return bool If such name is currently in use (true) or no (false)
*/
public function isNameInUse($object_name, $type, $table_name) {
switch($type) {
case 'seq':
case 'trg':
case 'pk':
case 'uk':
case 'fk':
case 'ck':
if ($check = $this->mdb->get_records_sql("SELECT name
FROM sys.objects
WHERE lower(name) = ?", array(strtolower($object_name)))) {
return true;
}
break;
case 'ix':
case 'uix':
if ($check = $this->mdb->get_records_sql("SELECT name
FROM sys.indexes
WHERE lower(name) = ?", array(strtolower($object_name)))) {
return true;
}
break;
}
return false; //No name in use found
}
/**
* Returns the code (array of statements) needed to add one comment to the table.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of SQL statements to add one comment to the table.
*/
public function getCommentSQL($xmldb_table) {
return array();
}
/**
* Adds slashes to string.
* @param string $s
* @return string The escaped string.
*/
public function addslashes($s) {
// do not use php addslashes() because it depends on PHP quote settings!
$s = str_replace("'", "''", $s);
return $s;
}
/**
* Returns an array of reserved words (lowercase) for this DB
* @return array An array of database specific reserved words
*/
public static function getReservedWords() {
// This file contains the reserved words for MSSQL databases
// from http://msdn2.microsoft.com/en-us/library/ms189822.aspx
// Should be identical to sqlsrv_native_moodle_database::$reservewords.
$reserved_words = array (
"add", "all", "alter", "and", "any", "as", "asc", "authorization", "avg", "backup", "begin", "between", "break",
"browse", "bulk", "by", "cascade", "case", "check", "checkpoint", "close", "clustered", "coalesce", "collate", "column",
"commit", "committed", "compute", "confirm", "constraint", "contains", "containstable", "continue", "controlrow",
"convert", "count", "create", "cross", "current", "current_date", "current_time", "current_timestamp", "current_user",
"cursor", "database", "dbcc", "deallocate", "declare", "default", "delete", "deny", "desc", "disk", "distinct",
"distributed", "double", "drop", "dummy", "dump", "else", "end", "errlvl", "errorexit", "escape", "except", "exec",
"execute", "exists", "exit", "external", "fetch", "file", "fillfactor", "floppy", "for", "foreign", "freetext",
"freetexttable", "from", "full", "function", "goto", "grant", "group", "having", "holdlock", "identity",
"identity_insert", "identitycol", "if", "in", "index", "inner", "insert", "intersect", "into", "is", "isolation",
"join", "key", "kill", "left", "level", "like", "lineno", "load", "max", "merge", "min", "mirrorexit", "national",
"nocheck", "nonclustered", "not", "null", "nullif", "of", "off", "offsets", "on", "once", "only", "open",
"opendatasource", "openquery", "openrowset", "openxml", "option", "or", "order", "outer", "over", "percent", "perm",
"permanent", "pipe", "pivot", "plan", "precision", "prepare", "primary", "print", "privileges", "proc", "procedure",
"processexit", "public", "raiserror", "read", "readtext", "reconfigure", "references", "repeatable", "replication",
"restore", "restrict", "return", "revert", "revoke", "right", "rollback", "rowcount", "rowguidcol", "rule", "save",
"schema", "securityaudit", "select", "semantickeyphrasetable", "semanticsimilaritydetailstable",
"semanticsimilaritytable", "serializable", "session_user", "set", "setuser", "shutdown", "some", "statistics", "sum",
"system_user", "table", "tablesample", "tape", "temp", "temporary", "textsize", "then", "to", "top", "tran",
"transaction", "trigger", "truncate", "try_convert", "tsequal", "uncommitted", "union", "unique", "unpivot", "update",
"updatetext", "use", "user", "values", "varying", "view", "waitfor", "when", "where", "while", "with", "within group",
"work", "writetext"
);
return $reserved_words;
}
}
+648
View File
@@ -0,0 +1,648 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Mysql specific SQL code generator.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/ddl/sql_generator.php');
/**
* This class generate SQL code to be used against MySQL
* It extends XMLDBgenerator so everything can be
* overridden as needed to generate correct SQL.
*
* @property mysqli_native_moodle_database $mdb
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mysql_sql_generator extends sql_generator {
// Only set values that are different from the defaults present in XMLDBgenerator
/** @var string Used to quote names. */
public $quote_string = '`';
/** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/
public $default_for_char = '';
/** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/
public $drop_default_value_required = true;
/** @var string The DEFAULT clause required to drop defaults.*/
public $drop_default_value = null;
/** @var string To force primary key names to one string (null=no force).*/
public $primary_key_name = '';
/** @var string Template to drop PKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY';
/** @var string Template to drop UKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME';
/** @var string Template to drop FKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME';
/** @var bool True if the generator needs to add extra code to generate the sequence fields.*/
public $sequence_extra_code = false;
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name = 'auto_increment';
public $add_after_clause = true; // Does the generator need to add the after clause for fields
/** @var string Characters to be used as concatenation operator.*/
public $concat_character = null;
/** @var string The SQL template to alter columns where the 'TABLENAME' and 'COLUMNSPECS' keywords are dynamically replaced.*/
public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY COLUMN COLUMNSPECS';
/** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/
public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME';
/** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/
public $rename_index_sql = null;
/** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/
public $rename_key_sql = null;
/** Maximum size of InnoDB row in Antelope file format */
const ANTELOPE_MAX_ROW_SIZE = 8126;
/**
* Reset a sequence to the id field of a table.
*
* @param xmldb_table|string $table name of table or the table object.
* @return array of sql statements
*/
public function getResetSequenceSQL($table) {
if ($table instanceof xmldb_table) {
$tablename = $table->getName();
} else {
$tablename = $table;
}
// From http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
$value = (int)$this->mdb->get_field_sql('SELECT MAX(id) FROM {'.$tablename.'}');
$value++;
return array("ALTER TABLE $this->prefix$tablename AUTO_INCREMENT = $value");
}
/**
* Calculate proximate row size when using InnoDB
* tables in Antelope row format.
*
* Note: the returned value is a bit higher to compensate for
* errors and changes of column data types.
*
* @deprecated since Moodle 2.9 MDL-49723 - please do not use this function any more.
*/
public function guess_antolope_row_size(array $columns) {
throw new coding_exception('guess_antolope_row_size() can not be used any more, please use guess_antelope_row_size() instead.');
}
/**
* Calculate proximate row size when using InnoDB tables in Antelope row format.
*
* Note: the returned value is a bit higher to compensate for errors and changes of column data types.
*
* @param xmldb_field[]|database_column_info[] $columns
* @return int approximate row size in bytes
*/
public function guess_antelope_row_size(array $columns) {
if (empty($columns)) {
return 0;
}
$size = 0;
$first = reset($columns);
if (count($columns) > 1) {
// Do not start with zero because we need to cover changes of field types and
// this calculation is most probably not be accurate.
$size += 1000;
}
if ($first instanceof xmldb_field) {
foreach ($columns as $field) {
switch ($field->getType()) {
case XMLDB_TYPE_TEXT:
$size += 768;
break;
case XMLDB_TYPE_BINARY:
$size += 768;
break;
case XMLDB_TYPE_CHAR:
$bytes = $field->getLength() * 3;
if ($bytes > 768) {
$bytes = 768;
}
$size += $bytes;
break;
default:
// Anything else is usually maximum 8 bytes.
$size += 8;
}
}
} else if ($first instanceof database_column_info) {
foreach ($columns as $column) {
switch ($column->meta_type) {
case 'X':
$size += 768;
break;
case 'B':
$size += 768;
break;
case 'C':
$bytes = $column->max_length * 3;
if ($bytes > 768) {
$bytes = 768;
}
$size += $bytes;
break;
default:
// Anything else is usually maximum 8 bytes.
$size += 8;
}
}
}
return $size;
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to create it (inside one array).
*
* @param xmldb_table $xmldb_table An xmldb_table instance.
* @return array An array of SQL statements, starting with the table creation SQL followed
* by any of its comments, indexes and sequence creation SQL statements.
*/
public function getCreateTableSQL($xmldb_table) {
// First find out if want some special db engine.
$engine = $this->mdb->get_dbengine();
// Do we know collation?
$collation = $this->mdb->get_dbcollation();
// Do we need to use compressed format for rows?
$rowformat = "";
$size = $this->guess_antelope_row_size($xmldb_table->getFields());
if ($size > self::ANTELOPE_MAX_ROW_SIZE) {
if ($this->mdb->is_compressed_row_format_supported()) {
$rowformat = "\n ROW_FORMAT=Compressed";
}
}
$utf8mb4rowformat = $this->mdb->get_row_format_sql($engine, $collation);
$rowformat = ($utf8mb4rowformat == '') ? $rowformat : $utf8mb4rowformat;
$sqlarr = parent::getCreateTableSQL($xmldb_table);
// This is a very nasty hack that tries to use just one query per created table
// because MySQL is stupidly slow when modifying empty tables.
// Note: it is safer to inject everything on new lines because there might be some trailing -- comments.
$sqls = array();
$prevcreate = null;
$matches = null;
foreach ($sqlarr as $sql) {
if (preg_match('/^CREATE TABLE ([^ ]+)/', $sql, $matches)) {
$prevcreate = $matches[1];
$sql = preg_replace('/\s*\)\s*$/s', '/*keyblock*/)', $sql);
// Let's inject the extra MySQL tweaks here.
if ($engine) {
$sql .= "\n ENGINE = $engine";
}
if ($collation) {
if (strpos($collation, 'utf8_') === 0) {
$sql .= "\n DEFAULT CHARACTER SET utf8";
}
$sql .= "\n DEFAULT COLLATE = $collation ";
}
if ($rowformat) {
$sql .= $rowformat;
}
$sqls[] = $sql;
continue;
}
if ($prevcreate) {
if (preg_match('/^ALTER TABLE '.$prevcreate.' COMMENT=(.*)$/s', $sql, $matches)) {
$prev = array_pop($sqls);
$prev .= "\n COMMENT=$matches[1]";
$sqls[] = $prev;
continue;
}
if (preg_match('/^CREATE INDEX ([^ ]+) ON '.$prevcreate.' (.*)$/s', $sql, $matches)) {
$prev = array_pop($sqls);
if (strpos($prev, '/*keyblock*/')) {
$prev = str_replace('/*keyblock*/', "\n, KEY $matches[1] $matches[2]/*keyblock*/", $prev);
$sqls[] = $prev;
continue;
} else {
$sqls[] = $prev;
}
}
if (preg_match('/^CREATE UNIQUE INDEX ([^ ]+) ON '.$prevcreate.' (.*)$/s', $sql, $matches)) {
$prev = array_pop($sqls);
if (strpos($prev, '/*keyblock*/')) {
$prev = str_replace('/*keyblock*/', "\n, UNIQUE KEY $matches[1] $matches[2]/*keyblock*/", $prev);
$sqls[] = $prev;
continue;
} else {
$sqls[] = $prev;
}
}
}
$prevcreate = null;
$sqls[] = $sql;
}
foreach ($sqls as $key => $sql) {
$sqls[$key] = str_replace('/*keyblock*/', "\n", $sql);
}
return $sqls;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add the field to the table.
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @param string $skip_type_clause The type clause on alter columns, NULL by default.
* @param string $skip_default_clause The default clause on alter columns, NULL by default.
* @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default.
* @return array The SQL statement for adding a field to the table.
*/
public function getAddFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
$sqls = parent::getAddFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause);
if ($this->table_exists($xmldb_table)) {
$tablename = $xmldb_table->getName();
$size = $this->guess_antelope_row_size($this->mdb->get_columns($tablename));
$size += $this->guess_antelope_row_size(array($xmldb_field));
if ($size > self::ANTELOPE_MAX_ROW_SIZE) {
if ($this->mdb->is_compressed_row_format_supported()) {
$format = strtolower($this->mdb->get_row_format($tablename));
if ($format === 'compact' or $format === 'redundant') {
// Change the format before conversion so that we do not run out of space.
array_unshift($sqls, "ALTER TABLE {$this->prefix}$tablename ROW_FORMAT=Compressed");
}
}
}
}
return $sqls;
}
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL)
{
$tablename = $xmldb_table->getName();
$dbcolumnsinfo = $this->mdb->get_columns($tablename);
if (($this->mdb->has_breaking_change_sqlmode()) &&
($dbcolumnsinfo[$xmldb_field->getName()]->meta_type == 'X') &&
($xmldb_field->getType() == XMLDB_TYPE_INTEGER)) {
// Ignore 1292 ER_TRUNCATED_WRONG_VALUE Truncated incorrect INTEGER value: '%s'.
$altercolumnsqlorig = $this->alter_column_sql;
$this->alter_column_sql = str_replace('ALTER TABLE', 'ALTER IGNORE TABLE', $this->alter_column_sql);
$result = parent::getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause);
// Restore the original ALTER SQL statement pattern.
$this->alter_column_sql = $altercolumnsqlorig;
return $result;
}
return parent::getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause);
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to create temporary table (inside one array).
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array of sql statements
*/
public function getCreateTempTableSQL($xmldb_table) {
// Do we know collation?
$collation = $this->mdb->get_dbcollation();
$this->temptables->add_temptable($xmldb_table->getName());
$sqlarr = parent::getCreateTableSQL($xmldb_table);
// Let's inject the extra MySQL tweaks.
foreach ($sqlarr as $i=>$sql) {
if (strpos($sql, 'CREATE TABLE ') === 0) {
// We do not want the engine hack included in create table SQL.
$sqlarr[$i] = preg_replace('/^CREATE TABLE (.*)/s', 'CREATE TEMPORARY TABLE $1', $sql);
if ($collation) {
if (strpos($collation, 'utf8_') === 0) {
$sqlarr[$i] .= " DEFAULT CHARACTER SET utf8";
}
$sqlarr[$i] .= " DEFAULT COLLATE $collation ROW_FORMAT=DYNAMIC";
}
}
}
return $sqlarr;
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to drop it (inside one array).
*
* @param xmldb_table $xmldb_table The table to drop.
* @return array SQL statement(s) for dropping the specified table.
*/
public function getDropTableSQL($xmldb_table) {
$sqlarr = parent::getDropTableSQL($xmldb_table);
if ($this->temptables->is_temptable($xmldb_table->getName())) {
$sqlarr = preg_replace('/^DROP TABLE/', "DROP TEMPORARY TABLE", $sqlarr);
}
return $sqlarr;
}
/**
* Given one XMLDB Type, length and decimals, returns the DB proper SQL type.
*
* @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants.
* @param int $xmldb_length The length of that data type.
* @param int $xmldb_decimals The decimal places of precision of the data type.
* @return string The DB defined data type.
*/
public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // From http://mysql.com/doc/refman/5.0/en/numeric-types.html!
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
if ($xmldb_length > 9) {
$dbtype = 'BIGINT';
} else if ($xmldb_length > 6) {
$dbtype = 'INT';
} else if ($xmldb_length > 4) {
$dbtype = 'MEDIUMINT';
} else if ($xmldb_length > 2) {
$dbtype = 'SMALLINT';
} else {
$dbtype = 'TINYINT';
}
$dbtype .= '(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_FLOAT:
$dbtype = 'DOUBLE';
if (!empty($xmldb_decimals)) {
if ($xmldb_decimals < 6) {
$dbtype = 'FLOAT';
}
}
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
} else {
$dbtype .= ', 0'; // In MySQL, if length is specified, decimals are mandatory for FLOATs
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_CHAR:
$dbtype = 'VARCHAR';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ')';
if ($collation = $this->mdb->get_dbcollation()) {
if (strpos($collation, 'utf8_') === 0) {
$dbtype .= " CHARACTER SET utf8";
}
$dbtype .= " COLLATE $collation";
}
break;
case XMLDB_TYPE_TEXT:
$dbtype = 'LONGTEXT';
if ($collation = $this->mdb->get_dbcollation()) {
if (strpos($collation, 'utf8_') === 0) {
$dbtype .= " CHARACTER SET utf8";
}
$dbtype .= " COLLATE $collation";
}
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'LONGBLOB';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'DATETIME';
}
return $dbtype;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default
* (usually invoked from getModifyDefaultSQL()
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*/
public function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for MySQL that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one correct xmldb_field and the new name, returns the SQL statements
* to rename it (inside one array).
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from.
* @param string $newname The new name to rename the field to.
* @return array The SQL statements for renaming the field.
*/
public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) {
// NOTE: MySQL is pretty different from the standard to justify this overloading.
// Need a clone of xmldb_field to perform the change leaving original unmodified
$xmldb_field_clone = clone($xmldb_field);
// Change the name of the field to perform the change
$xmldb_field_clone->setName($newname);
$fieldsql = $this->getFieldSQL($xmldb_table, $xmldb_field_clone);
$sql = 'ALTER TABLE ' . $this->getTableName($xmldb_table) . ' CHANGE ' .
$this->getEncQuoted($xmldb_field->getName()) . ' ' . $fieldsql;
return array($sql);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default
* (usually invoked from getModifyDefaultSQL()
*
* Note that this method may be dropped in future.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*
* @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL()
*/
public function getDropDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for MySQL that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Returns the code (array of statements) needed to add one comment to the table.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of SQL statements to add one comment to the table.
*/
function getCommentSQL($xmldb_table) {
$comment = '';
if ($xmldb_table->getComment()) {
$comment .= 'ALTER TABLE ' . $this->getTableName($xmldb_table);
$comment .= " COMMENT='" . $this->addslashes(substr($xmldb_table->getComment(), 0, 60)) . "'";
}
return array($comment);
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg).
*
* (MySQL requires the whole xmldb_table object to be specified, so we add it always)
*
* This is invoked from getNameForObject().
* Only some DB have this implemented.
*
* @param string $object_name The object's name to check for.
* @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg).
* @param string $table_name The table's name to check in
* @return bool If such name is currently in use (true) or no (false)
*/
public function isNameInUse($object_name, $type, $table_name) {
switch($type) {
case 'ix':
case 'uix':
// First of all, check table exists
$metatables = $this->mdb->get_tables();
if (isset($metatables[$table_name])) {
// Fetch all the indexes in the table
if ($indexes = $this->mdb->get_indexes($table_name)) {
// Look for existing index in array
if (isset($indexes[$object_name])) {
return true;
}
}
}
break;
}
return false; //No name in use found
}
/**
* Returns an array of reserved words (lowercase) for this DB
* @return array An array of database specific reserved words
*/
public static function getReservedWords() {
// This file contains the reserved words for MySQL databases.
$reserved_words = array (
// From http://dev.mysql.com/doc/refman/6.0/en/reserved-words.html.
'accessible', 'add', 'all', 'alter', 'analyze', 'and', 'as', 'asc',
'asensitive', 'before', 'between', 'bigint', 'binary',
'blob', 'both', 'by', 'call', 'cascade', 'case', 'change',
'char', 'character', 'check', 'collate', 'column',
'condition', 'connection', 'constraint', 'continue',
'convert', 'create', 'cross', 'current_date', 'current_time',
'current_timestamp', 'current_user', 'cursor', 'database',
'databases', 'day_hour', 'day_microsecond',
'day_minute', 'day_second', 'dec', 'decimal', 'declare',
'default', 'delayed', 'delete', 'desc', 'describe',
'deterministic', 'distinct', 'distinctrow', 'div', 'double',
'drop', 'dual', 'each', 'else', 'elseif', 'enclosed', 'escaped',
'exists', 'exit', 'explain', 'false', 'fetch', 'float', 'float4',
'float8', 'for', 'force', 'foreign', 'from', 'fulltext', 'grant',
'group', 'having', 'high_priority', 'hour_microsecond',
'hour_minute', 'hour_second', 'if', 'ignore', 'in', 'index',
'infile', 'inner', 'inout', 'insensitive', 'insert', 'int', 'int1',
'int2', 'int3', 'int4', 'int8', 'integer', 'interval', 'into', 'is',
'iterate', 'join', 'key', 'keys', 'kill', 'leading', 'leave', 'left',
'like', 'limit', 'linear', 'lines', 'load', 'localtime', 'localtimestamp',
'lock', 'long', 'longblob', 'longtext', 'loop', 'low_priority', 'master_heartbeat_period',
'master_ssl_verify_server_cert', 'match', 'mediumblob', 'mediumint', 'mediumtext',
'middleint', 'minute_microsecond', 'minute_second',
'mod', 'modifies', 'natural', 'not', 'no_write_to_binlog',
'null', 'numeric', 'on', 'optimize', 'option', 'optionally',
'or', 'order', 'out', 'outer', 'outfile', 'overwrite', 'precision', 'primary',
'procedure', 'purge', 'raid0', 'range', 'read', 'read_only', 'read_write', 'reads', 'real',
'references', 'regexp', 'release', 'rename', 'repeat', 'replace',
'require', 'restrict', 'return', 'revoke', 'right', 'rlike', 'schema',
'schemas', 'second_microsecond', 'select', 'sensitive',
'separator', 'set', 'show', 'smallint', 'soname', 'spatial',
'specific', 'sql', 'sqlexception', 'sqlstate', 'sqlwarning',
'sql_big_result', 'sql_calc_found_rows', 'sql_small_result',
'ssl', 'starting', 'straight_join', 'table', 'terminated', 'then',
'tinyblob', 'tinyint', 'tinytext', 'to', 'trailing', 'trigger', 'true',
'undo', 'union', 'unique', 'unlock', 'unsigned', 'update',
'upgrade', 'usage', 'use', 'using', 'utc_date', 'utc_time',
'utc_timestamp', 'values', 'varbinary', 'varchar', 'varcharacter',
'varying', 'when', 'where', 'while', 'with', 'write', 'x509',
'xor', 'year_month', 'zerofill',
// Added in MySQL 8.0, compared to MySQL 5.7:
// https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-new-in-current-series.
'_filename', 'admin', 'cume_dist', 'dense_rank', 'empty', 'except', 'first_value', 'grouping', 'groups',
'json_table', 'lag', 'last_value', 'lead', 'nth_value', 'ntile',
'of', 'over', 'percent_rank', 'persist', 'persist_only', 'rank', 'recursive', 'row_number',
'system', 'window',
// Added in Amazon Aurora MySQL version 3.06.0:
// https://docs.aws.amazon.com/AmazonRDS/latest/AuroraMySQLReleaseNotes/AuroraMySQL.Updates.3060.html .
'accept', 'aws_bedrock_invoke_model', 'aws_sagemaker_invoke_endpoint', 'content_type', 'timeout_ms',
);
return $reserved_words;
}
}
+756
View File
@@ -0,0 +1,756 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Oracle specific SQL code generator.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/ddl/sql_generator.php');
/**
* This class generate SQL code to be used against Oracle
* It extends XMLDBgenerator so everything can be
* overridden as needed to generate correct SQL.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class oracle_sql_generator extends sql_generator {
// Only set values that are different from the defaults present in XMLDBgenerator
/**
* @var string To be automatically added at the end of each statement.
* note: Using "/" because the standard ";" isn't good for stored procedures (triggers)
*/
public $statement_end = "\n/";
/** @var string Proper type for NUMBER(x) in this DB. */
public $number_type = 'NUMBER';
/**
* @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).
* note: Using this whitespace here because Oracle doesn't distinguish empty and null! :-(
*/
public $default_for_char = ' ';
/** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/
public $drop_default_value_required = true;
/** @var string The DEFAULT clause required to drop defaults.*/
public $drop_default_value = null;
/** @var bool To decide if the default clause of each field must go after the null clause.*/
public $default_after_null = false;
/** @var bool True if the generator needs to add extra code to generate the sequence fields.*/
public $sequence_extra_code = true;
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name = '';
/** @var string The SQL template to alter columns where the 'TABLENAME' and 'COLUMNSPECS' keywords are dynamically replaced.*/
public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)';
/** @var int var ugly Oracle hack - size of the sequences values cache (20 = Default)*/
public $sequence_cache_size = 20;
/**
* Reset a sequence to the id field of a table.
*
* @param xmldb_table|string $table name of table or the table object.
* @return array of sql statements
*/
public function getResetSequenceSQL($table) {
if (is_string($table)) {
$tablename = $table;
$xmldb_table = new xmldb_table($tablename);
} else {
$tablename = $table->getName();
$xmldb_table = $table;
}
// From http://www.acs.ilstu.edu/docs/oracle/server.101/b10759/statements_2011.htm
$value = (int)$this->mdb->get_field_sql('SELECT MAX(id) FROM {'.$tablename.'}');
$value++;
$seqname = $this->getSequenceFromDB($xmldb_table);
if (!$seqname) {
// Fallback, seqname not found, something is wrong. Inform and use the alternative getNameForObject() method
$seqname = $this->getNameForObject($table, 'id', 'seq');
}
return array ("DROP SEQUENCE $seqname",
"CREATE SEQUENCE $seqname START WITH $value INCREMENT BY 1 NOMAXVALUE CACHE $this->sequence_cache_size");
}
/**
* Given one xmldb_table, returns it's correct name, depending of all the parametrization
* Overridden to allow change of names in temp tables
*
* @param xmldb_table table whose name we want
* @param boolean to specify if the name must be quoted (if reserved word, only!)
* @return string the correct name of the table
*/
public function getTableName(xmldb_table $xmldb_table, $quoted=true) {
// Get the name, supporting special oci names for temp tables
if ($this->temptables->is_temptable($xmldb_table->getName())) {
$tablename = $this->temptables->get_correct_name($xmldb_table->getName());
} else {
$tablename = $this->prefix . $xmldb_table->getName();
}
// Apply quotes optionally
if ($quoted) {
$tablename = $this->getEncQuoted($tablename);
}
return $tablename;
}
public function getCreateIndexSQL($xmldb_table, $xmldb_index) {
if ($error = $xmldb_index->validateDefinition($xmldb_table)) {
throw new coding_exception($error);
}
$indexfields = $this->getEncQuoted($xmldb_index->getFields());
$unique = '';
$suffix = 'ix';
if ($xmldb_index->getUnique()) {
$unique = ' UNIQUE';
$suffix = 'uix';
$nullablefields = $this->get_nullable_fields_in_index($xmldb_table, $xmldb_index);
if ($nullablefields) {
// If this is a unique index with nullable fields, then we have to
// apply the work-around from https://community.oracle.com/message/9518046#9518046.
//
// For example if you have a unique index on the three columns
// (required, option1, option2) where the first one is non-null,
// and the others nullable, then the SQL will end up as
//
// CREATE UNIQUE INDEX index_name ON table_name (
// CASE WHEN option1 IS NOT NULL AND option2 IS NOT NULL THEN required ELSE NULL END,
// CASE WHEN option1 IS NOT NULL AND option2 IS NOT NULL THEN option1 ELSE NULL END,
// CASE WHEN option1 IS NOT NULL AND option2 IS NOT NULL THEN option2 ELSE NULL END)
//
// Basically Oracle behaves according to the standard if either
// none of the columns are NULL or all columns contain NULL. Therefore,
// if any column is NULL, we treat them all as NULL for the index.
$conditions = [];
foreach ($nullablefields as $fieldname) {
$conditions[] = $this->getEncQuoted($fieldname) .
' IS NOT NULL';
}
$condition = implode(' AND ', $conditions);
$updatedindexfields = [];
foreach ($indexfields as $fieldname) {
$updatedindexfields[] = 'CASE WHEN ' . $condition . ' THEN ' .
$fieldname . ' ELSE NULL END';
}
$indexfields = $updatedindexfields;
}
}
$index = 'CREATE' . $unique . ' INDEX ';
$index .= $this->getNameForObject($xmldb_table->getName(), implode(', ', $xmldb_index->getFields()), $suffix);
$index .= ' ON ' . $this->getTableName($xmldb_table);
$index .= ' (' . implode(', ', $indexfields) . ')';
return array($index);
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to create temporary table (inside one array).
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array of sql statements
*/
public function getCreateTempTableSQL($xmldb_table) {
$this->temptables->add_temptable($xmldb_table->getName());
$sqlarr = $this->getCreateTableSQL($xmldb_table);
$sqlarr = preg_replace('/^CREATE TABLE (.*)/s', 'CREATE GLOBAL TEMPORARY TABLE $1 ON COMMIT PRESERVE ROWS', $sqlarr);
return $sqlarr;
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to drop it (inside one array).
*
* @param xmldb_table $xmldb_table The table to drop.
* @return array SQL statement(s) for dropping the specified table.
*/
public function getDropTableSQL($xmldb_table) {
$sqlarr = parent::getDropTableSQL($xmldb_table);
if ($this->temptables->is_temptable($xmldb_table->getName())) {
array_unshift($sqlarr, "TRUNCATE TABLE ". $this->getTableName($xmldb_table)); // oracle requires truncate before being able to drop a temp table
}
return $sqlarr;
}
/**
* Given one XMLDB Type, length and decimals, returns the DB proper SQL type.
*
* @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants.
* @param int $xmldb_length The length of that data type.
* @param int $xmldb_decimals The decimal places of precision of the data type.
* @return string The DB defined data type.
*/
public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // See http://www.acs.ilstu.edu/docs/oracle/server.101/b10759/sql_elements001.htm#sthref86.
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
$dbtype = 'NUMBER(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_FLOAT:
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_CHAR:
// Do not use NVARCHAR2 here because it has hardcoded 1333 char limit,
// VARCHAR2 allows us to create larger fields that error out later during runtime
// only when too many non-ascii utf-8 chars present.
$dbtype = 'VARCHAR2';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ' CHAR)'; // CHAR is required because BYTE is the default
break;
case XMLDB_TYPE_TEXT:
$dbtype = 'CLOB';
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'BLOB';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'DATE';
break;
}
return $dbtype;
}
/**
* Returns the code (array of statements) needed
* to create one sequence for the xmldb_table and xmldb_field passed in.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create the sequence.
*/
public function getCreateSequenceSQL($xmldb_table, $xmldb_field) {
$results = array();
$sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq');
$sequence = "CREATE SEQUENCE $sequence_name START WITH 1 INCREMENT BY 1 NOMAXVALUE CACHE $this->sequence_cache_size";
$results[] = $sequence;
$results = array_merge($results, $this->getCreateTriggerSQL ($xmldb_table, $xmldb_field, $sequence_name));
return $results;
}
/**
* Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @param string $sequence_name
* @return array Array of SQL statements to create the sequence.
*/
public function getCreateTriggerSQL($xmldb_table, $xmldb_field, $sequence_name) {
$trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg');
$trigger = "CREATE TRIGGER " . $trigger_name;
$trigger.= "\n BEFORE INSERT";
$trigger.= "\nON " . $this->getTableName($xmldb_table);
$trigger.= "\n FOR EACH ROW";
$trigger.= "\nBEGIN";
$trigger.= "\n IF :new." . $this->getEncQuoted($xmldb_field->getName()) . ' IS NULL THEN';
$trigger.= "\n SELECT " . $sequence_name . '.nextval INTO :new.' . $this->getEncQuoted($xmldb_field->getName()) . " FROM dual;";
$trigger.= "\n END IF;";
$trigger.= "\nEND;";
return array($trigger);
}
/**
* Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed
* Can, optionally, specify if the underlying trigger will be also dropped
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @param bool $include_trigger
* @return array Array of SQL statements to create the sequence.
*/
public function getDropSequenceSQL($xmldb_table, $xmldb_field, $include_trigger=false) {
$result = array();
if ($sequence_name = $this->getSequenceFromDB($xmldb_table)) {
$result[] = "DROP SEQUENCE " . $sequence_name;
}
if ($trigger_name = $this->getTriggerFromDB($xmldb_table) && $include_trigger) {
$result[] = "DROP TRIGGER " . $trigger_name;
}
return $result;
}
/**
* Returns the code (array of statements) needed to add one comment to the table.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of SQL statements to add one comment to the table.
*/
function getCommentSQL($xmldb_table) {
$comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table);
$comment.= " IS '" . $this->addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'";
return array($comment);
}
/**
* Returns the code (array of statements) needed to execute extra statements on table drop
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of extra SQL statements to drop a table.
*/
public function getDropTableExtraSQL($xmldb_table) {
$xmldb_field = new xmldb_field('id'); // Fields having sequences should be exclusively, id.
return $this->getDropSequenceSQL($xmldb_table, $xmldb_field, false);
}
/**
* Returns the code (array of statements) needed to execute extra statements on table rename.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param string $newname The new name for the table.
* @return array Array of extra SQL statements to rename a table.
*/
public function getRenameTableExtraSQL($xmldb_table, $newname) {
$results = array();
$xmldb_field = new xmldb_field('id'); // Fields having sequences should be exclusively, id.
$oldseqname = $this->getSequenceFromDB($xmldb_table);
$newseqname = $this->getNameForObject($newname, $xmldb_field->getName(), 'seq');
$oldtriggername = $this->getTriggerFromDB($xmldb_table);
$newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg');
// Drop old trigger (first of all)
$results[] = "DROP TRIGGER " . $oldtriggername;
// Rename the sequence, disablig CACHE before and enablig it later
// to avoid consuming of values on rename
$results[] = 'ALTER SEQUENCE ' . $oldseqname . ' NOCACHE';
$results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname;
$results[] = 'ALTER SEQUENCE ' . $newseqname . ' CACHE ' . $this->sequence_cache_size;
// Create new trigger
$newt = new xmldb_table($newname); // Temp table for trigger code generation
$results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field, $newseqname));
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table.
*
* Oracle has some severe limits:
* - clob and blob fields doesn't allow type to be specified
* - error is dropped if the null/not null clause is specified and hasn't changed
* - changes in precision/decimals of numeric fields drop an ORA-1440 error
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @param string $skip_type_clause The type clause on alter columns, NULL by default.
* @param string $skip_default_clause The default clause on alter columns, NULL by default.
* @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default.
* @return string The field altering SQL statement.
*/
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
$skip_type_clause = is_null($skip_type_clause) ? $this->alter_column_skip_type : $skip_type_clause;
$skip_default_clause = is_null($skip_default_clause) ? $this->alter_column_skip_default : $skip_default_clause;
$skip_notnull_clause = is_null($skip_notnull_clause) ? $this->alter_column_skip_notnull : $skip_notnull_clause;
$results = array(); // To store all the needed SQL commands
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $xmldb_field->getName();
// Take a look to field metadata
$meta = $this->mdb->get_columns($xmldb_table->getName());
$metac = $meta[$fieldname];
$oldmetatype = $metac->meta_type;
$oldlength = $metac->max_length;
// To calculate the oldlength if the field is numeric, we need to perform one extra query
// because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883
if ($oldmetatype == 'N') {
$uppertablename = strtoupper($tablename);
$upperfieldname = strtoupper($fieldname);
if ($col = $this->mdb->get_record_sql("SELECT cname, precision
FROM col
WHERE tname = ? AND cname = ?",
array($uppertablename, $upperfieldname))) {
$oldlength = $col->precision;
}
}
$olddecimals = empty($metac->scale) ? null : $metac->scale;
$oldnotnull = empty($metac->not_null) ? false : $metac->not_null;
$olddefault = empty($metac->default_value) || strtoupper($metac->default_value) == 'NULL' ? null : $metac->default_value;
$typechanged = true; //By default, assume that the column type has changed
$precisionchanged = true; //By default, assume that the column precision has changed
$decimalchanged = true; //By default, assume that the column decimal has changed
$defaultchanged = true; //By default, assume that the column default has changed
$notnullchanged = true; //By default, assume that the column notnull has changed
$from_temp_fields = false; //By default don't assume we are going to use temporal fields
// Detect if we are changing the type of the column
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') ||
($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') ||
($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR && $oldmetatype == 'C') ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT && $oldmetatype == 'X') ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) {
$typechanged = false;
}
// Detect if precision has changed
if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
($oldlength == -1) ||
($xmldb_field->getLength() == $oldlength)) {
$precisionchanged = false;
}
// Detect if decimal has changed
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR) ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
(!$xmldb_field->getDecimals()) ||
(!$olddecimals) ||
($xmldb_field->getDecimals() == $olddecimals)) {
$decimalchanged = false;
}
// Detect if we are changing the default
if (($xmldb_field->getDefault() === null && $olddefault === null) ||
($xmldb_field->getDefault() === $olddefault) || //Check both equality and
("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes
$defaultchanged = false;
}
// Detect if we are changing the nullability
if (($xmldb_field->getNotnull() === $oldnotnull)) {
$notnullchanged = false;
}
// If type has changed or precision or decimal has changed and we are in one numeric field
// - create one temp column with the new specs
// - fill the new column with the values from the old one
// - drop the old column
// - rename the temp column to the original name
if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) {
$tempcolname = $xmldb_field->getName() . '___tmp'; // Short tmp name, surely not conflicting ever
if (strlen($tempcolname) > 30) { // Safeguard we don't excess the 30cc limit
$tempcolname = 'ongoing_alter_column_tmp';
}
// Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints
$skip_notnull_clause = true;
$skip_default_clause = true;
$xmldb_field->setName($tempcolname);
// Drop the temp column, in case it exists (due to one previous failure in conversion)
// really ugly but we cannot enclose DDL into transaction :-(
if (isset($meta[$tempcolname])) {
$results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field));
}
// Create the temporal column
$results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_type_clause, $skip_notnull_clause));
// Copy contents from original col to the temporal one
// From TEXT to integer/number we need explicit conversion
if ($oldmetatype == 'X' && $xmldb_field->GetType() == XMLDB_TYPE_INTEGER) {
$results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = CAST(' . $this->mdb->sql_compare_text($fieldname) . ' AS INT)';
} else if ($oldmetatype == 'X' && $xmldb_field->GetType() == XMLDB_TYPE_NUMBER) {
$results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = CAST(' . $this->mdb->sql_compare_text($fieldname) . ' AS NUMBER)';
// Normal cases, implicit conversion
} else {
$results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname;
}
// Drop the old column
$xmldb_field->setName($fieldname); //Set back the original field name
$results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field));
// Rename the temp column to the original one
$results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname;
// Mark we have performed one change based in temp fields
$from_temp_fields = true;
// Re-enable the notnull and default sections so the general AlterFieldSQL can use it
$skip_notnull_clause = false;
$skip_default_clause = false;
// Disable the type section because we have done it with the temp field
$skip_type_clause = true;
// If new field is nullable, nullability hasn't changed
if (!$xmldb_field->getNotnull()) {
$notnullchanged = false;
}
// If new field hasn't default, default hasn't changed
if ($xmldb_field->getDefault() === null) {
$defaultchanged = false;
}
}
// If type and precision and decimals hasn't changed, prevent the type clause
if (!$typechanged && !$precisionchanged && !$decimalchanged) {
$skip_type_clause = true;
}
// If NULL/NOT NULL hasn't changed
// prevent null clause to be specified
if (!$notnullchanged) {
$skip_notnull_clause = true; // Initially, prevent the notnull clause
// But, if we have used the temp field and the new field is not null, then enforce the not null clause
if ($from_temp_fields && $xmldb_field->getNotnull()) {
$skip_notnull_clause = false;
}
}
// If default hasn't changed
// prevent default clause to be specified
if (!$defaultchanged) {
$skip_default_clause = true; // Initially, prevent the default clause
// But, if we have used the temp field and the new field has default clause, then enforce the default clause
if ($from_temp_fields) {
$default_clause = $this->getDefaultClause($xmldb_field);
if ($default_clause) {
$skip_notnull_clause = false;
}
}
}
// If arriving here, something is not being skipped (type, notnull, default), calculate the standard AlterFieldSQL
if (!$skip_type_clause || !$skip_notnull_clause || !$skip_default_clause) {
$results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause));
return $results;
}
// Finally return results
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default
* (usually invoked from getModifyDefaultSQL()
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*/
public function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for Oracle that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default
* (usually invoked from getModifyDefaultSQL()
*
* Note that this method may be dropped in future.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*
* @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL()
*/
public function getDropDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for Oracle that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one xmldb_table returns one string with the sequence of the table
* in the table (fetched from DB)
* The sequence name for oracle is calculated by looking the corresponding
* trigger and retrieving the sequence name from it (because sequences are
* independent elements)
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return string|bool If no sequence is found, returns false
*/
public function getSequenceFromDB($xmldb_table) {
$tablename = strtoupper($this->getTableName($xmldb_table));
$prefixupper = strtoupper($this->prefix);
$sequencename = false;
if ($trigger = $this->mdb->get_record_sql("SELECT trigger_name, trigger_body
FROM user_triggers
WHERE table_name = ? AND trigger_name LIKE ?",
array($tablename, "{$prefixupper}%_ID%_TRG"))) {
// If trigger found, regexp it looking for the sequence name
preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches);
if (isset($matches[1])) {
$sequencename = $matches[1];
}
}
return $sequencename;
}
/**
* Given one xmldb_table returns one string with the trigger
* in the table (fetched from DB)
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return string|bool If no trigger is found, returns false
*/
public function getTriggerFromDB($xmldb_table) {
$tablename = strtoupper($this->getTableName($xmldb_table));
$prefixupper = strtoupper($this->prefix);
$triggername = false;
if ($trigger = $this->mdb->get_record_sql("SELECT trigger_name, trigger_body
FROM user_triggers
WHERE table_name = ? AND trigger_name LIKE ?",
array($tablename, "{$prefixupper}%_ID%_TRG"))) {
$triggername = $trigger->trigger_name;
}
return $triggername;
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg).
*
* (MySQL requires the whole xmldb_table object to be specified, so we add it always)
*
* This is invoked from getNameForObject().
* Only some DB have this implemented.
*
* @param string $object_name The object's name to check for.
* @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg).
* @param string $table_name The table's name to check in
* @return bool If such name is currently in use (true) or no (false)
*/
public function isNameInUse($object_name, $type, $table_name) {
switch($type) {
case 'ix':
case 'uix':
case 'seq':
case 'trg':
if ($check = $this->mdb->get_records_sql("SELECT object_name
FROM user_objects
WHERE lower(object_name) = ?", array(strtolower($object_name)))) {
return true;
}
break;
case 'pk':
case 'uk':
case 'fk':
case 'ck':
if ($check = $this->mdb->get_records_sql("SELECT constraint_name
FROM user_constraints
WHERE lower(constraint_name) = ?", array(strtolower($object_name)))) {
return true;
}
break;
}
return false; //No name in use found
}
/**
* Adds slashes to string.
* @param string $s
* @return string The escaped string.
*/
public function addslashes($s) {
// do not use php addslashes() because it depends on PHP quote settings!
$s = str_replace("'", "''", $s);
return $s;
}
/**
* Returns an array of reserved words (lowercase) for this DB
* @return array An array of database specific reserved words
*/
public static function getReservedWords() {
// This file contains the reserved words for Oracle databases
// from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm
$reserved_words = array (
'access', 'add', 'all', 'alter', 'and', 'any',
'as', 'asc', 'audit', 'between', 'by', 'char',
'check', 'cluster', 'column', 'comment',
'compress', 'connect', 'create', 'current',
'date', 'decimal', 'default', 'delete', 'desc',
'distinct', 'drop', 'else', 'exclusive', 'exists',
'file', 'float', 'for', 'from', 'grant', 'group',
'having', 'identified', 'immediate', 'in',
'increment', 'index', 'initial', 'insert',
'integer', 'intersect', 'into', 'is', 'level',
'like', 'lock', 'long', 'maxextents', 'minus',
'mlslabel', 'mode', 'modify', 'nchar', 'nclob', 'noaudit',
'nocompress', 'not', 'nowait', 'null', 'number', 'nvarchar2',
'of', 'offline', 'on', 'online', 'option', 'or',
'order', 'pctfree', 'prior', 'privileges',
'public', 'raw', 'rename', 'resource', 'revoke',
'row', 'rowid', 'rownum', 'rows', 'select',
'session', 'set', 'share', 'size', 'smallint',
'start', 'successful', 'synonym', 'sysdate',
'table', 'then', 'to', 'trigger', 'uid', 'union',
'unique', 'update', 'user', 'validate', 'values',
'varchar', 'varchar2', 'view', 'whenever',
'where', 'with'
);
return $reserved_words;
}
}
+520
View File
@@ -0,0 +1,520 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* PostgreSQL specific SQL code generator.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/ddl/sql_generator.php');
/**
* This class generate SQL code to be used against PostgreSQL
* It extends XMLDBgenerator so everything can be
* overridden as needed to generate correct SQL.
*
* @package core_ddl
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* 2001-3001 Eloy Lafuente (stronk7) http://contiento.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class postgres_sql_generator extends sql_generator {
// Only set values that are different from the defaults present in XMLDBgenerator
/** @var string Proper type for NUMBER(x) in this DB. */
public $number_type = 'NUMERIC';
/** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/
public $default_for_char = '';
/** @var bool True if the generator needs to add extra code to generate the sequence fields.*/
public $sequence_extra_code = false;
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name = 'BIGSERIAL';
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name_small = 'SERIAL';
/** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/
public $sequence_only = true;
/** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/
public $rename_index_sql = 'ALTER TABLE OLDINDEXNAME RENAME TO NEWINDEXNAME';
/** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/
public $rename_key_sql = null;
/** @var string type of string quoting used - '' or \' quotes*/
protected $std_strings = null;
/**
* Reset a sequence to the id field of a table.
*
* @param xmldb_table|string $table name of table or the table object.
* @return array of sql statements
*/
public function getResetSequenceSQL($table) {
if ($table instanceof xmldb_table) {
$tablename = $table->getName();
} else {
$tablename = $table;
}
// From http://www.postgresql.org/docs/7.4/static/sql-altersequence.html
$value = (int)$this->mdb->get_field_sql('SELECT MAX(id) FROM {'.$tablename.'}');
$value++;
return array("ALTER SEQUENCE $this->prefix{$tablename}_id_seq RESTART WITH $value");
}
/**
* Given one correct xmldb_table, returns the SQL statements
* to create temporary table (inside one array).
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array of sql statements
*/
public function getCreateTempTableSQL($xmldb_table) {
$this->temptables->add_temptable($xmldb_table->getName());
$sqlarr = $this->getCreateTableSQL($xmldb_table);
$sqlarr = preg_replace('/^CREATE TABLE/', "CREATE TEMPORARY TABLE", $sqlarr);
return $sqlarr;
}
/**
* Given one correct xmldb_index, returns the SQL statements
* needed to create it (in array).
*
* @param xmldb_table $xmldb_table The xmldb_table instance to create the index on.
* @param xmldb_index $xmldb_index The xmldb_index to create.
* @return array An array of SQL statements to create the index.
* @throws coding_exception Thrown if the xmldb_index does not validate with the xmldb_table.
*/
public function getCreateIndexSQL($xmldb_table, $xmldb_index) {
$sqls = parent::getCreateIndexSQL($xmldb_table, $xmldb_index);
$hints = $xmldb_index->getHints();
$fields = $xmldb_index->getFields();
if (in_array('varchar_pattern_ops', $hints) and count($fields) == 1) {
// Add the pattern index and keep the normal one, keep unique only the standard index to improve perf.
foreach ($sqls as $sql) {
$field = reset($fields);
$count = 0;
$newindex = preg_replace("/^CREATE( UNIQUE)? INDEX ([a-z0-9_]+) ON ([a-z0-9_]+) \($field\)$/", "CREATE INDEX \\2_pattern ON \\3 USING btree ($field varchar_pattern_ops)", $sql, -1, $count);
if ($count != 1) {
debugging('Unexpected getCreateIndexSQL() structure.');
continue;
}
$sqls[] = $newindex;
}
}
return $sqls;
}
/**
* Given one XMLDB Type, length and decimals, returns the DB proper SQL type.
*
* @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants.
* @param int $xmldb_length The length of that data type.
* @param int $xmldb_decimals The decimal places of precision of the data type.
* @return string The DB defined data type.
*/
public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // From http://www.postgresql.org/docs/7.4/interactive/datatype.html
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
if ($xmldb_length > 9) {
$dbtype = 'BIGINT';
} else if ($xmldb_length > 4) {
$dbtype = 'INTEGER';
} else {
$dbtype = 'SMALLINT';
}
break;
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_FLOAT:
$dbtype = 'DOUBLE PRECISION';
if (!empty($xmldb_decimals)) {
if ($xmldb_decimals < 6) {
$dbtype = 'REAL';
}
}
break;
case XMLDB_TYPE_CHAR:
$dbtype = 'VARCHAR';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_TEXT:
$dbtype = 'TEXT';
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'BYTEA';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'TIMESTAMP';
break;
}
return $dbtype;
}
/**
* Returns the code (array of statements) needed to add one comment to the table.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of SQL statements to add one comment to the table.
*/
function getCommentSQL($xmldb_table) {
$comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table);
$comment.= " IS '" . $this->addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'";
return array($comment);
}
/**
* Returns the code (array of statements) needed to execute extra statements on table rename.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param string $newname The new name for the table.
* @return array Array of extra SQL statements to rename a table.
*/
public function getRenameTableExtraSQL($xmldb_table, $newname) {
$results = array();
$newt = new xmldb_table($newname);
$xmldb_field = new xmldb_field('id'); // Fields having sequences should be exclusively, id.
$oldseqname = $this->getTableName($xmldb_table) . '_' . $xmldb_field->getName() . '_seq';
$newseqname = $this->getTableName($newt) . '_' . $xmldb_field->getName() . '_seq';
// Rename de sequence
$results[] = 'ALTER TABLE ' . $oldseqname . ' RENAME TO ' . $newseqname;
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table.
*
* PostgreSQL has some severe limits:
* - Any change of type or precision requires a new temporary column to be created, values to
* be transfered potentially casting them, to apply defaults if the column is not null and
* finally, to rename it
* - Changes in null/not null require the SET/DROP NOT NULL clause
* - Changes in default require the SET/DROP DEFAULT clause
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @param string $skip_type_clause The type clause on alter columns, NULL by default.
* @param string $skip_default_clause The default clause on alter columns, NULL by default.
* @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default.
* @return string The field altering SQL statement.
*/
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
$results = array(); // To store all the needed SQL commands
// Get the normal names of the table and field
$tablename = $xmldb_table->getName();
$fieldname = $xmldb_field->getName();
// Take a look to field metadata
$meta = $this->mdb->get_columns($tablename);
$metac = $meta[$xmldb_field->getName()];
$oldmetatype = $metac->meta_type;
$oldlength = $metac->max_length;
$olddecimals = empty($metac->scale) ? null : $metac->scale;
$oldnotnull = empty($metac->not_null) ? false : $metac->not_null;
$olddefault = empty($metac->has_default) ? null : $metac->default_value;
$typechanged = true; //By default, assume that the column type has changed
$precisionchanged = true; //By default, assume that the column precision has changed
$decimalchanged = true; //By default, assume that the column decimal has changed
$defaultchanged = true; //By default, assume that the column default has changed
$notnullchanged = true; //By default, assume that the column notnull has changed
// Detect if we are changing the type of the column
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') ||
($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') ||
($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR && $oldmetatype == 'C') ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT && $oldmetatype == 'X') ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) {
$typechanged = false;
}
// Detect if we are changing the precision
if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
($oldlength == -1) ||
($xmldb_field->getLength() == $oldlength)) {
$precisionchanged = false;
}
// Detect if we are changing the decimals
if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) ||
($xmldb_field->getType() == XMLDB_TYPE_CHAR) ||
($xmldb_field->getType() == XMLDB_TYPE_TEXT) ||
($xmldb_field->getType() == XMLDB_TYPE_BINARY) ||
(!$xmldb_field->getDecimals()) ||
(!$olddecimals) ||
($xmldb_field->getDecimals() == $olddecimals)) {
$decimalchanged = false;
}
// Detect if we are changing the default
if (($xmldb_field->getDefault() === null && $olddefault === null) ||
($xmldb_field->getDefault() === $olddefault)) {
$defaultchanged = false;
}
// Detect if we are changing the nullability
if (($xmldb_field->getNotnull() === $oldnotnull)) {
$notnullchanged = false;
}
// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$fieldname = $this->getEncQuoted($xmldb_field->getName());
// Decide if we have changed the column specs (type/precision/decimals)
$specschanged = $typechanged || $precisionchanged || $decimalchanged;
// if specs have changed, need to alter column
if ($specschanged) {
// Always drop any exiting default before alter column (some type changes can cause casting error in default for column)
if ($olddefault !== null) {
$results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; // Drop default clause
}
$alterstmt = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $this->getEncQuoted($xmldb_field->getName()) .
' TYPE' . $this->getFieldSQL($xmldb_table, $xmldb_field, null, true, true, null, false);
// Some castings must be performed explicitly (mainly from text|char to numeric|integer)
if (($oldmetatype == 'C' || $oldmetatype == 'X') &&
($xmldb_field->getType() == XMLDB_TYPE_NUMBER || $xmldb_field->getType() == XMLDB_TYPE_FLOAT)) {
$alterstmt .= ' USING CAST('.$fieldname.' AS NUMERIC)'; // from char or text to number or float
} else if (($oldmetatype == 'C' || $oldmetatype == 'X') &&
$xmldb_field->getType() == XMLDB_TYPE_INTEGER) {
$alterstmt .= ' USING CAST(CAST('.$fieldname.' AS NUMERIC) AS INTEGER)'; // From char to integer
}
$results[] = $alterstmt;
}
// If the default has changed or we have performed one change in specs
if ($defaultchanged || $specschanged) {
$default_clause = $this->getDefaultClause($xmldb_field);
if ($default_clause) {
$sql = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' SET' . $default_clause; // Add default clause
$results[] = $sql;
} else {
if (!$specschanged) { // Only drop default if we haven't performed one specs change
$results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; // Drop default clause
}
}
}
// If the not null has changed
if ($notnullchanged) {
if ($xmldb_field->getNotnull()) {
$results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' SET NOT NULL';
} else {
$results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP NOT NULL';
}
}
// Return the results
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default
* (usually invoked from getModifyDefaultSQL()
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*/
public function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default
* (usually invoked from getModifyDefaultSQL()
*
* Note that this method may be dropped in future.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*
* @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL()
*/
public function getDropDefaultSQL($xmldb_table, $xmldb_field) {
// Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that
// is capable of handling defaults
return $this->getAlterFieldSQL($xmldb_table, $xmldb_field);
}
/**
* Adds slashes to string.
* @param string $s
* @return string The escaped string.
*/
public function addslashes($s) {
// Postgres is gradually switching to ANSI quotes, we need to check what is expected
if (!isset($this->std_strings)) {
$this->std_strings = ($this->mdb->get_field_sql("select setting from pg_settings where name = 'standard_conforming_strings'") === 'on');
}
if ($this->std_strings) {
$s = str_replace("'", "''", $s);
} else {
// do not use php addslashes() because it depends on PHP quote settings!
$s = str_replace('\\','\\\\',$s);
$s = str_replace("\0","\\\0", $s);
$s = str_replace("'", "\\'", $s);
}
return $s;
}
/**
* Given one xmldb_table returns one string with the sequence of the table
* in the table (fetched from DB)
* The sequence name for Postgres has one standard name convention:
* tablename_fieldname_seq
* so we just calculate it and confirm it's present in pg_class
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return string|bool If no sequence is found, returns false
*/
function getSequenceFromDB($xmldb_table) {
$tablename = $this->getTableName($xmldb_table);
$sequencename = $tablename . '_id_seq';
if (!$this->mdb->get_record_sql("SELECT c.*
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace as ns ON ns.oid = c.relnamespace
WHERE c.relname = ? AND c.relkind = 'S'
AND (ns.nspname = current_schema() OR ns.oid = pg_my_temp_schema())",
array($sequencename))) {
$sequencename = false;
}
return $sequencename;
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg).
*
* (MySQL requires the whole xmldb_table object to be specified, so we add it always)
*
* This is invoked from getNameForObject().
* Only some DB have this implemented.
*
* @param string $object_name The object's name to check for.
* @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg).
* @param string $table_name The table's name to check in
* @return bool If such name is currently in use (true) or no (false)
*/
public function isNameInUse($object_name, $type, $table_name) {
switch($type) {
case 'ix':
case 'uix':
case 'seq':
if ($check = $this->mdb->get_records_sql("SELECT c.relname
FROM pg_class c
JOIN pg_catalog.pg_namespace as ns ON ns.oid = c.relnamespace
WHERE lower(c.relname) = ?
AND (ns.nspname = current_schema() OR ns.oid = pg_my_temp_schema())", array(strtolower($object_name)))) {
return true;
}
break;
case 'pk':
case 'uk':
case 'fk':
case 'ck':
if ($check = $this->mdb->get_records_sql("SELECT c.conname
FROM pg_constraint c
JOIN pg_catalog.pg_namespace as ns ON ns.oid = c.connamespace
WHERE lower(c.conname) = ?
AND (ns.nspname = current_schema() OR ns.oid = pg_my_temp_schema())", array(strtolower($object_name)))) {
return true;
}
break;
case 'trg':
if ($check = $this->mdb->get_records_sql("SELECT tgname
FROM pg_trigger
WHERE lower(tgname) = ?", array(strtolower($object_name)))) {
return true;
}
break;
}
return false; //No name in use found
}
/**
* Returns an array of reserved words (lowercase) for this DB
* @return array An array of database specific reserved words
*/
public static function getReservedWords() {
// This file contains the reserved words for PostgreSQL databases
// This file contains the reserved words for PostgreSQL databases
// http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html
$reserved_words = array (
'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc',
'asymmetric', 'authorization', 'between', 'binary', 'both', 'case',
'cast', 'check', 'collate', 'column', 'constraint', 'create', 'cross',
'current_date', 'current_role', 'current_time', 'current_timestamp',
'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do',
'else', 'end', 'except', 'false', 'for', 'foreign', 'freeze', 'from',
'full', 'grant', 'group', 'having', 'ilike', 'in', 'initially', 'inner',
'intersect', 'into', 'is', 'isnull', 'join', 'leading', 'left', 'like',
'limit', 'localtime', 'localtimestamp', 'natural', 'new', 'not',
'notnull', 'null', 'off', 'offset', 'old', 'on', 'only', 'or', 'order',
'outer', 'overlaps', 'placing', 'primary', 'references', 'returning', 'right', 'select',
'session_user', 'similar', 'some', 'symmetric', 'table', 'then', 'to',
'trailing', 'true', 'union', 'unique', 'user', 'using', 'verbose',
'when', 'where', 'with'
);
return $reserved_words;
}
}
File diff suppressed because it is too large Load Diff
+463
View File
@@ -0,0 +1,463 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Experimental SQLite specific SQL code generator.
*
* @package core_ddl
* @copyright 2008 Andrei Bautu
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/ddl/sql_generator.php');
/// This class generate SQL code to be used against SQLite
/// It extends XMLDBgenerator so everything can be
/// overridden as needed to generate correct SQL.
class sqlite_sql_generator extends sql_generator {
/// Only set values that are different from the defaults present in XMLDBgenerator
/** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/
public $drop_default_value_required = true;
/** @var string The DEFAULT clause required to drop defaults.*/
public $drop_default_value = NULL;
/** @var string Template to drop PKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY';
/** @var string Template to drop UKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME';
/** @var string Template to drop FKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/
public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME';
/** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/
public $default_for_char = '';
/** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/
public $sequence_only = true;
/** @var bool True if the generator needs to add extra code to generate the sequence fields.*/
public $sequence_extra_code = false;
/** @var string The particular name for inline sequences in this generator.*/
public $sequence_name = 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL';
/** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/
public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME';
/** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/
public $rename_index_sql = null;
/** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/
public $rename_key_sql = null;
/**
* Creates one new XMLDBmysql
*/
public function __construct($mdb) {
parent::__construct($mdb);
}
/**
* Reset a sequence to the id field of a table.
*
* @param xmldb_table|string $table name of table or the table object.
* @return array of sql statements
*/
public function getResetSequenceSQL($table) {
if ($table instanceof xmldb_table) {
$table = $table->getName();
}
// From http://sqlite.org/autoinc.html
$value = (int)$this->mdb->get_field_sql('SELECT MAX(id) FROM {'.$table.'}');
return array("UPDATE sqlite_sequence SET seq=$value WHERE name='{$this->prefix}{$table}'");
}
/**
* Given one correct xmldb_key, returns its specs
*/
public function getKeySQL($xmldb_table, $xmldb_key) {
$key = '';
switch ($xmldb_key->getType()) {
case XMLDB_KEY_PRIMARY:
if ($this->primary_keys && count($xmldb_key->getFields())>1) {
if ($this->primary_key_name !== null) {
$key = $this->getEncQuoted($this->primary_key_name);
} else {
$key = $this->getNameForObject($xmldb_table->getName(), implode(', ', $xmldb_key->getFields()), 'pk');
}
$key .= ' PRIMARY KEY (' . implode(', ', $this->getEncQuoted($xmldb_key->getFields())) . ')';
}
break;
case XMLDB_KEY_UNIQUE:
if ($this->unique_keys) {
$key = $this->getNameForObject($xmldb_table->getName(), implode(', ', $xmldb_key->getFields()), 'uk');
$key .= ' UNIQUE (' . implode(', ', $this->getEncQuoted($xmldb_key->getFields())) . ')';
}
break;
case XMLDB_KEY_FOREIGN:
case XMLDB_KEY_FOREIGN_UNIQUE:
if ($this->foreign_keys) {
$key = $this->getNameForObject($xmldb_table->getName(), implode(', ', $xmldb_key->getFields()), 'fk');
$key .= ' FOREIGN KEY (' . implode(', ', $this->getEncQuoted($xmldb_key->getFields())) . ')';
$key .= ' REFERENCES ' . $this->getEncQuoted($this->prefix . $xmldb_key->getRefTable());
$key .= ' (' . implode(', ', $this->getEncQuoted($xmldb_key->getRefFields())) . ')';
}
break;
}
return $key;
}
/**
* Given one XMLDB Type, length and decimals, returns the DB proper SQL type.
*
* @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants.
* @param int $xmldb_length The length of that data type.
* @param int $xmldb_decimals The decimal places of precision of the data type.
* @return string The DB defined data type.
*/
public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) {
switch ($xmldb_type) {
case XMLDB_TYPE_INTEGER: // From http://www.sqlite.org/datatype3.html
if (empty($xmldb_length)) {
$xmldb_length = 10;
}
$dbtype = 'INTEGER(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_NUMBER:
$dbtype = $this->number_type;
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_FLOAT:
$dbtype = 'REAL';
if (!empty($xmldb_length)) {
$dbtype .= '(' . $xmldb_length;
if (!empty($xmldb_decimals)) {
$dbtype .= ',' . $xmldb_decimals;
}
$dbtype .= ')';
}
break;
case XMLDB_TYPE_CHAR:
$dbtype = 'VARCHAR';
if (empty($xmldb_length)) {
$xmldb_length='255';
}
$dbtype .= '(' . $xmldb_length . ')';
break;
case XMLDB_TYPE_BINARY:
$dbtype = 'BLOB';
break;
case XMLDB_TYPE_DATETIME:
$dbtype = 'DATETIME';
default:
case XMLDB_TYPE_TEXT:
$dbtype = 'TEXT';
break;
}
return $dbtype;
}
/**
* Function to emulate full ALTER TABLE which SQLite does not support.
* The function can be used to drop a column ($xmldb_delete_field != null and
* $xmldb_add_field == null), add a column ($xmldb_delete_field == null and
* $xmldb_add_field != null), change/rename a column ($xmldb_delete_field == null
* and $xmldb_add_field == null).
* @param xmldb_table $xmldb_table table to change
* @param xmldb_field $xmldb_add_field column to create/modify (full specification is required)
* @param xmldb_field $xmldb_delete_field column to delete/modify (only name field is required)
* @return array of strings (SQL statements to alter the table structure)
*/
protected function getAlterTableSchema($xmldb_table, $xmldb_add_field=NULL, $xmldb_delete_field=NULL) {
/// Get the quoted name of the table and field
$tablename = $this->getTableName($xmldb_table);
$oldname = $xmldb_delete_field ? $xmldb_delete_field->getName() : NULL;
$newname = $xmldb_add_field ? $xmldb_add_field->getName() : NULL;
if($xmldb_delete_field) {
$xmldb_table->deleteField($oldname);
}
if($xmldb_add_field) {
$xmldb_table->addField($xmldb_add_field);
}
if($oldname) {
// alter indexes
$indexes = $xmldb_table->getIndexes();
foreach($indexes as $index) {
$fields = $index->getFields();
$i = array_search($oldname, $fields);
if($i!==FALSE) {
if($newname) {
$fields[$i] = $newname;
} else {
unset($fields[$i]);
}
$xmldb_table->deleteIndex($index->getName());
if(count($fields)) {
$index->setFields($fields);
$xmldb_table->addIndex($index);
}
}
}
// alter keys
$keys = $xmldb_table->getKeys();
foreach($keys as $key) {
$fields = $key->getFields();
$reffields = $key->getRefFields();
$i = array_search($oldname, $fields);
if($i!==FALSE) {
if($newname) {
$fields[$i] = $newname;
} else {
unset($fields[$i]);
unset($reffields[$i]);
}
$xmldb_table->deleteKey($key->getName());
if(count($fields)) {
$key->setFields($fields);
$key->setRefFields($fields);
$xmldb_table->addkey($key);
}
}
}
}
// prepare data copy
$fields = $xmldb_table->getFields();
foreach ($fields as $key => $field) {
$fieldname = $field->getName();
if($fieldname == $newname && $oldname && $oldname != $newname) {
// field rename operation
$fields[$key] = $this->getEncQuoted($oldname) . ' AS ' . $this->getEncQuoted($newname);
} else {
$fields[$key] = $this->getEncQuoted($field->getName());
}
}
$fields = implode(',', $fields);
$results[] = 'BEGIN TRANSACTION';
$results[] = 'CREATE TEMPORARY TABLE temp_data AS SELECT * FROM ' . $tablename;
$results[] = 'DROP TABLE ' . $tablename;
$results = array_merge($results, $this->getCreateTableSQL($xmldb_table));
$results[] = 'INSERT INTO ' . $tablename . ' SELECT ' . $fields . ' FROM temp_data';
$results[] = 'DROP TABLE temp_data';
$results[] = 'COMMIT';
return $results;
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table.
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @param string $skip_type_clause The type clause on alter columns, NULL by default.
* @param string $skip_default_clause The default clause on alter columns, NULL by default.
* @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default.
* @return string The field altering SQL statement.
*/
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field);
}
/**
* Given one xmldb_table and one xmldb_key, return the SQL statements needed to add the key to the table
* note that underlying indexes will be added as parametrised by $xxxx_keys and $xxxx_index parameters
*/
public function getAddKeySQL($xmldb_table, $xmldb_key) {
$xmldb_table->addKey($xmldb_key);
return $this->getAlterTableSchema($xmldb_table);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default
* (usually invoked from getModifyDefaultSQL()
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*/
public function getCreateDefaultSQL($xmldb_table, $xmldb_field) {
return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field);
}
/**
* Given one correct xmldb_field and the new name, returns the SQL statements
* to rename it (inside one array).
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from.
* @param string $newname The new name to rename the field to.
* @return array The SQL statements for renaming the field.
*/
public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) {
$oldfield = clone($xmldb_field);
$xmldb_field->setName($newname);
return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $oldfield);
}
/**
* Given one xmldb_table and one xmldb_index, return the SQL statements needed to rename the index in the table
*/
function getRenameIndexSQL($xmldb_table, $xmldb_index, $newname) {
/// Get the real index name
$dbindexname = $this->mdb->get_manager()->find_index_name($xmldb_table, $xmldb_index);
$xmldb_index->setName($newname);
$results = array('DROP INDEX ' . $dbindexname);
$results = array_merge($results, $this->getCreateIndexSQL($xmldb_table, $xmldb_index));
return $results;
}
/**
* Given one xmldb_table and one xmldb_key, return the SQL statements needed to rename the key in the table
* Experimental! Shouldn't be used at all!
*/
public function getRenameKeySQL($xmldb_table, $xmldb_key, $newname) {
$xmldb_table->deleteKey($xmldb_key->getName());
$xmldb_key->setName($newname);
$xmldb_table->addkey($xmldb_key);
return $this->getAlterTableSchema($xmldb_table);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table.
*
* @param xmldb_table $xmldb_table The table related to $xmldb_field.
* @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from.
* @return array The SQL statement for dropping a field from the table.
*/
public function getDropFieldSQL($xmldb_table, $xmldb_field) {
return $this->getAlterTableSchema($xmldb_table, NULL, $xmldb_field);
}
/**
* Given one xmldb_table and one xmldb_index, return the SQL statements needed to drop the index from the table
*/
public function getDropIndexSQL($xmldb_table, $xmldb_index) {
$xmldb_table->deleteIndex($xmldb_index->getName());
return $this->getAlterTableSchema($xmldb_table);
}
/**
* Given one xmldb_table and one xmldb_index, return the SQL statements needed to drop the index from the table
*/
public function getDropKeySQL($xmldb_table, $xmldb_key) {
$xmldb_table->deleteKey($xmldb_key->getName());
return $this->getAlterTableSchema($xmldb_table);
}
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default
* (usually invoked from getModifyDefaultSQL()
*
* Note that this method may be dropped in future.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @param xmldb_field $xmldb_field The xmldb_field object instance.
* @return array Array of SQL statements to create a field's default.
*
* @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL()
*/
public function getDropDefaultSQL($xmldb_table, $xmldb_field) {
return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field);
}
/**
* Returns the code (array of statements) needed to add one comment to the table.
*
* @param xmldb_table $xmldb_table The xmldb_table object instance.
* @return array Array of SQL statements to add one comment to the table.
*/
function getCommentSQL($xmldb_table) {
return array();
}
/**
* Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg).
*
* (MySQL requires the whole xmldb_table object to be specified, so we add it always)
*
* This is invoked from getNameForObject().
* Only some DB have this implemented.
*
* @param string $object_name The object's name to check for.
* @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg).
* @param string $table_name The table's name to check in
* @return bool If such name is currently in use (true) or no (false)
*/
public function isNameInUse($object_name, $type, $table_name) {
// TODO: add introspection code
return false; //No name in use found
}
/**
* Returns an array of reserved words (lowercase) for this DB
* @return array An array of database specific reserved words
*/
public static function getReservedWords() {
/// From http://www.sqlite.org/lang_keywords.html
$reserved_words = array (
'add', 'all', 'alter', 'and', 'as', 'autoincrement',
'between', 'by',
'case', 'check', 'collate', 'column', 'commit', 'constraint', 'create', 'cross',
'default', 'deferrable', 'delete', 'distinct', 'drop',
'else', 'escape', 'except', 'exists',
'foreign', 'from', 'full',
'group',
'having',
'in', 'index', 'inner', 'insert', 'intersect', 'into', 'is', 'isnull',
'join',
'left', 'limit',
'natural', 'not', 'notnull', 'null',
'on', 'or', 'order', 'outer',
'primary',
'references', 'regexp', 'right', 'rollback',
'select', 'set',
'table', 'then', 'to', 'transaction',
'union', 'unique', 'update', 'using',
'values',
'when', 'where'
);
return $reserved_words;
}
/**
* Adds slashes to string.
* @param string $s
* @return string The escaped string.
*/
public function addslashes($s) {
// do not use php addslashes() because it depends on PHP quote settings!
$s = str_replace("'", "''", $s);
return $s;
}
}
File diff suppressed because it is too large Load Diff
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="lib/ddl/tests/fixtures" VERSION="20120122" COMMENT="This is an invalid xml file used for testing.">
<TABLES>
<TABLE NAME="test_table1" COMMENT="Just a test table">
<FIELDS>
<FIELD NAME="id" LENGTH="10" NOTNULL="true" SEQUENCE="true"/> <!-- missing TYPE -->
<FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="name" TYPE="char" LENGTH="30" NOTNULL="false" SEQUENCE="false" DEFAULT="Moodle"/>
<FIELD NAME="secondname" TYPE="char" LENGTH="30" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="intro" TYPE="text" LENGTH="medium" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="avatar" TYPE="binary" LENGTH="medium" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="grade" TYPE="number" LENGTH="20" DECIMALS="10" NOTNULL="false" SEQUENCE="false"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" />
</KEYS>
</TABLE>
</TABLES>
</XMLDB>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" ?>
<XMLDB PATH="lib/ddl/tests/fixtures" VERSION="20120122" COMMENT="XMLDB file DLL unit tests">
<TABLES>
<TABLE NAME="test_table1" COMMENT="Just a test table">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true"/>
<FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="name" TYPE="char" LENGTH="30" NOTNULL="false" SEQUENCE="false" DEFAULT="Moodle"/>
<FIELD NAME="secondname" TYPE="char" LENGTH="30" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="intro" TYPE="text" LENGTH="medium" NOTNULL="true" SEQUENCE="false"/>
<FIELD NAME="avatar" TYPE="binary" LENGTH="medium" NOTNULL="false" UNSIGNED="false" SEQUENCE="false"/>
<FIELD NAME="grade" TYPE="number" LENGTH="20" DECIMALS="10" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="bignum" TYPE="number" LENGTH="38" DECIMALS="18" NOTNULL="false" SEQUENCE="false"/>
<FIELD NAME="path" TYPE="char" LENGTH="255" NOTNULL="true"/>
</FIELDS>
<KEYS>
<KEY NAME="primary" TYPE="primary" FIELDS="id" />
</KEYS>
<INDEXES>
<INDEX NAME="course" UNIQUE="false" FIELDS="course"/>
<INDEX NAME="path" UNIQUE="false" FIELDS="path" HINTS="varchar_pattern_ops,unknownxyz"/>
</INDEXES>
</TABLE>
</TABLES>
</XMLDB>