Fixes bug MDL-8234, "New groups code & AS keyword"
[moodle-pu.git] / lib / ddllib.php
blobaffb26a074d177f9401a0dec6db5ae52215a4c25
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.com //
9 // //
10 // Copyright (C) 2001-3001 Martin Dougiamas http://dougiamas.com //
11 // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com //
12 // //
13 // This program is free software; you can redistribute it and/or modify //
14 // it under the terms of the GNU General Public License as published by //
15 // the Free Software Foundation; either version 2 of the License, or //
16 // (at your option) any later version. //
17 // //
18 // This program is distributed in the hope that it will be useful, //
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
21 // GNU General Public License for more details: //
22 // //
23 // http://www.gnu.org/copyleft/gpl.html //
24 // //
25 ///////////////////////////////////////////////////////////////////////////
27 // This library includes all the required functions used to handle the DB
28 // structure (DDL) independently of the underlying RDBMS in use. All the functions
29 // rely on the XMLDBDriver classes to be able to generate the correct SQL
30 // syntax needed by each DB.
32 // To define any structure to be created we'll use the schema defined
33 // by the XMLDB classes, for tables, fields, indexes, keys and other
34 // statements instead of direct handling of SQL sentences.
36 // This library should be used, exclusively, by the installation and
37 // upgrade process of Moodle.
39 // For further documentation, visit http://docs.moodle.org/en/DDL_functions
41 /// Add required XMLDB constants
42 require_once($CFG->libdir . '/xmldb/classes/XMLDBConstants.php');
44 /// Add main XMLDB Generator
45 require_once($CFG->libdir . '/xmldb/classes/generators/XMLDBGenerator.class.php');
47 /// Add required XMLDB DB classes
48 require_once($CFG->libdir . '/xmldb/classes/XMLDBObject.class.php');
49 require_once($CFG->libdir . '/xmldb/classes/XMLDBFile.class.php');
50 require_once($CFG->libdir . '/xmldb/classes/XMLDBStructure.class.php');
51 require_once($CFG->libdir . '/xmldb/classes/XMLDBTable.class.php');
52 require_once($CFG->libdir . '/xmldb/classes/XMLDBField.class.php');
53 require_once($CFG->libdir . '/xmldb/classes/XMLDBKey.class.php');
54 require_once($CFG->libdir . '/xmldb/classes/XMLDBIndex.class.php');
55 require_once($CFG->libdir . '/xmldb/classes/XMLDBStatement.class.php');
57 /// Based on $CFG->dbtype, add the proper generator class
58 if (!file_exists($CFG->libdir . '/xmldb/classes/generators/' . $CFG->dbtype . '/' . $CFG->dbtype . '.class.php')) {
59 error ('DB Type: ' . $CFG->dbtype . ' not supported by XMLDDB');
61 require_once($CFG->libdir . '/xmldb/classes/generators/' . $CFG->dbtype . '/' . $CFG->dbtype . '.class.php');
64 /// Add other libraries
65 require_once($CFG->libdir . '/xmlize.php');
66 /**
67 * Add a new field to a table, or modify an existing one (if oldfield is defined).
68 * Warning: Please be careful on primary keys, as this function will eat auto_increments
70 * @uses $CFG
71 * @uses $db
72 * @param string $table the name of the table to modify. (Without the prefix.)
73 * @param string $oldfield If changing an existing column, the name of that column.
74 * @param string $field The name of the column at the end of the operation.
75 * @param string $type The type of the column at the end of the operation. TEXT, VARCHAR, CHAR, INTEGER, REAL, or TINYINT
76 * @param string $size The size of that column type. As in VARCHAR($size), or INTEGER($size).
77 * @param string $signed For numeric column types, whether that column is 'signed' or 'unsigned'.
78 * @param string $default The new default value for the column.
79 * @param string $null 'not null', or '' to allow nulls.
80 * @param string $after Which column to insert this one after. Not supported on Postgres.
82 * @return boolean Wheter the operation succeeded.
84 function table_column($table, $oldfield, $field, $type='integer', $size='10',
85 $signed='unsigned', $default='0', $null='not null', $after='') {
86 global $CFG, $db, $empty_rs_cache;
88 if (!empty($empty_rs_cache[$table])) { // Clear the recordset cache because it's out of date
89 unset($empty_rs_cache[$table]);
92 switch (strtolower($CFG->dbtype)) {
94 case 'mysql':
95 case 'mysqlt':
97 switch (strtolower($type)) {
98 case 'text':
99 $type = 'TEXT';
100 $signed = '';
101 break;
102 case 'integer':
103 $type = 'INTEGER('. $size .')';
104 break;
105 case 'varchar':
106 $type = 'VARCHAR('. $size .')';
107 $signed = '';
108 break;
109 case 'char':
110 $type = 'CHAR('. $size .')';
111 $signed = '';
112 break;
115 if (!empty($oldfield)) {
116 $operation = 'CHANGE '. $oldfield .' '. $field;
117 } else {
118 $operation = 'ADD '. $field;
121 $default = 'DEFAULT \''. $default .'\'';
123 if (!empty($after)) {
124 $after = 'AFTER `'. $after .'`';
127 return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' '. $operation .' '. $type .' '. $signed .' '. $default .' '. $null .' '. $after);
129 case 'postgres7': // From Petri Asikainen
130 //Check db-version
131 $dbinfo = $db->ServerInfo();
132 $dbver = substr($dbinfo['version'],0,3);
134 //to prevent conflicts with reserved words
135 $realfield = '"'. $field .'"';
136 $field = '"'. $field .'_alter_column_tmp"';
137 $oldfield = '"'. $oldfield .'"';
139 switch (strtolower($type)) {
140 case 'tinyint':
141 case 'integer':
142 if ($size <= 4) {
143 $type = 'INT2';
145 if ($size <= 10) {
146 $type = 'INT';
148 if ($size > 10) {
149 $type = 'INT8';
151 break;
152 case 'varchar':
153 $type = 'VARCHAR('. $size .')';
154 break;
155 case 'char':
156 $type = 'CHAR('. $size .')';
157 $signed = '';
158 break;
161 $default = '\''. $default .'\'';
163 //After is not implemented in postgesql
164 //if (!empty($after)) {
165 // $after = "AFTER '$after'";
168 //Use transactions
169 execute_sql('BEGIN');
171 //Always use temporary column
172 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
173 //Add default values
174 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default);
177 if ($dbver >= '7.3') {
178 // modifying 'not null' is posible before 7.3
179 //update default values to table
180 if (strtoupper($null) == 'NOT NULL') {
181 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .'='. $default .' WHERE '. $field .' IS NULL');
182 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
183 } else {
184 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' DROP NOT NULL');
188 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET DEFAULT '. $default);
190 if ( $oldfield != '""' ) {
192 // We are changing the type of a column. This may require doing some casts...
193 $casting = '';
194 $oldtype = column_type($table, $oldfield);
195 $newtype = column_type($table, $field);
197 // Do we need a cast?
198 if($newtype == 'N' && $oldtype == 'C') {
199 $casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS REAL)';
201 else if($newtype == 'I' && $oldtype == 'C') {
202 $casting = 'CAST(CAST('.$oldfield.' AS TEXT) AS INTEGER)';
204 else {
205 $casting = $oldfield;
208 // Run the update query, casting as necessary
209 execute_sql('UPDATE '. $CFG->prefix . $table .' SET '. $field .' = '. $casting);
210 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' DROP COLUMN '. $oldfield);
213 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $field .' TO '. $realfield);
215 return execute_sql('COMMIT');
217 default:
218 switch (strtolower($type)) {
219 case 'integer':
220 $type = 'INTEGER';
221 break;
222 case 'varchar':
223 $type = 'VARCHAR';
224 break;
227 $default = 'DEFAULT \''. $default .'\'';
229 if (!empty($after)) {
230 $after = 'AFTER '. $after;
233 if (!empty($oldfield)) {
234 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' RENAME COLUMN '. $oldfield .' '. $field);
235 } else {
236 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ADD COLUMN '. $field .' '. $type);
239 execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $null);
240 return execute_sql('ALTER TABLE '. $CFG->prefix . $table .' ALTER COLUMN '. $field .' SET '. $default);
245 * Given one XMLDBTable, check if it exists in DB (true/false)
247 * @param XMLDBTable table to be searched for
248 * @return boolean true/false
250 function table_exists($table) {
252 global $CFG, $db;
254 $exists = true;
256 /// Do this function silenty (to avoid output in install/upgrade process)
257 $olddbdebug = $db->debug;
258 $db->debug = false;
260 /// Load the needed generator
261 $classname = 'XMLDB' . $CFG->dbtype;
262 $generator = new $classname();
263 $generator->setPrefix($CFG->prefix);
264 /// Calculate the name of the table
265 $tablename = $generator->getTableName($table, false);
267 /// Search such tablename in DB
268 $metatables = $db->MetaTables();
269 $metatables = array_flip($metatables);
270 $metatables = array_change_key_case($metatables, CASE_LOWER);
271 if (!array_key_exists($tablename, $metatables)) {
272 $exists = false;
275 /// Re-set original debug
276 $db->debug = $olddbdebug;
278 return $exists;
282 * Given one XMLDBField, check if it exists in DB (true/false)
284 * @uses, $db
285 * @param XMLDBTable the table
286 * @param XMLDBField the field to be searched for
287 * @return boolean true/false
289 function field_exists($table, $field) {
291 global $CFG, $db;
293 $exists = true;
295 /// Do this function silenty (to avoid output in install/upgrade process)
296 $olddbdebug = $db->debug;
297 $db->debug = false;
299 /// Check the table exists
300 if (!table_exists($table)) {
301 $db->debug = $olddbdebug; //Re-set original $db->debug
302 return false;
305 /// Load the needed generator
306 $classname = 'XMLDB' . $CFG->dbtype;
307 $generator = new $classname();
308 $generator->setPrefix($CFG->prefix);
309 /// Calculate the name of the table
310 $tablename = $generator->getTableName($table, false);
312 /// Get list of fields in table
313 $fields = null;
314 if ($fields = $db->MetaColumns($tablename)) {
315 $fields = array_change_key_case($fields, CASE_LOWER);
318 if (!array_key_exists($field->getName(), $fields)) {
319 $exists = false;
322 /// Re-set original debug
323 $db->debug = $olddbdebug;
325 return $exists;
329 * Given one XMLDBIndex, check if it exists in DB (true/false)
331 * @uses, $db
332 * @param XMLDBTable the table
333 * @param XMLDBIndex the index to be searched for
334 * @return boolean true/false
336 function index_exists($table, $index) {
338 global $CFG, $db;
340 $exists = true;
342 /// Do this function silenty (to avoid output in install/upgrade process)
343 $olddbdebug = $db->debug;
344 $db->debug = false;
346 /// Wrap over find_index_name to see if the index exists
347 if (!find_index_name($table, $index)) {
348 $exists = false;
351 /// Re-set original debug
352 $db->debug = $olddbdebug;
354 return $exists;
358 * This function IS NOT IMPLEMENTED. ONCE WE'LL BE USING RELATIONAL
359 * INTEGRITY IT WILL BECOME MORE USEFUL. FOR NOW, JUST CALCULATE "OFFICIAL"
360 * KEY NAMES WITHOUT ACCESSING TO DB AT ALL.
361 * Given one XMLDBKey, the function returns the name of the key in DB (if exists)
362 * of false if it doesn't exist
364 * @uses, $db
365 * @param XMLDBTable the table to be searched
366 * @param XMLDBKey the key to be searched
367 * @return string key name of false
369 function find_key_name($table, $xmldb_key) {
371 global $CFG, $db;
373 /// Extract key columns
374 $keycolumns = $xmldb_key->getFields();
376 /// Get list of keys in table
377 /// first primaries (we aren't going to use this now, because the MetaPrimaryKeys is awful)
378 ///TODO: To implement when we advance in relational integrity
379 /// then uniques (note that Moodle, for now, shouldn't have any UNIQUE KEY for now, but unique indexes)
380 ///TODO: To implement when we advance in relational integrity (note that AdoDB hasn't any MetaXXX for this.
381 /// then foreign (note that Moodle, for now, shouldn't have any FOREIGN KEY for now, but indexes)
382 ///TODO: To implement when we advance in relational integrity (note that AdoDB has one MetaForeignKeys()
383 ///but it's far from perfect.
384 /// TODO: To create the proper functions inside each generator to retrieve all the needed KEY info (name
385 /// columns, reftable and refcolumns
387 /// So all we do is to return the official name of the requested key without any confirmation!)
388 $classname = 'XMLDB' . $CFG->dbtype;
389 $generator = new $classname();
390 $generator->setPrefix($CFG->prefix);
391 /// One exception, harcoded primary constraint names
392 if ($generator->primary_key_name && $xmldb_key->getType() == XMLDB_KEY_PRIMARY) {
393 return $generator->primary_key_name;
394 } else {
395 /// Calculate the name suffix
396 switch ($xmldb_key->getType()) {
397 case XMLDB_KEY_PRIMARY:
398 $suffix = 'pk';
399 break;
400 case XMLDB_KEY_UNIQUE:
401 $suffix = 'uk';
402 break;
403 case XMLDB_KEY_FOREIGN_UNIQUE:
404 case XMLDB_KEY_FOREIGN:
405 $suffix = 'fk';
406 break;
408 /// And simply, return the oficial name
409 return $generator->getNameForObject($table->getName(), implode(', ', $xmldb_key->getFields()), $suffix);
414 * Given one XMLDBIndex, the function returns the name of the index in DB (if exists)
415 * of false if it doesn't exist
417 * @uses, $db
418 * @param XMLDBTable the table to be searched
419 * @param XMLDBIndex the index to be searched
420 * @return string index name of false
422 function find_index_name($table, $index) {
424 global $CFG, $db;
426 /// Do this function silenty (to avoid output in install/upgrade process)
427 $olddbdebug = $db->debug;
428 $db->debug = false;
430 /// Extract index columns
431 $indcolumns = $index->getFields();
433 /// Check the table exists
434 if (!table_exists($table)) {
435 $db->debug = $olddbdebug; //Re-set original $db->debug
436 return false;
439 /// Load the needed generator
440 $classname = 'XMLDB' . $CFG->dbtype;
441 $generator = new $classname();
442 $generator->setPrefix($CFG->prefix);
443 /// Calculate the name of the table
444 $tablename = $generator->getTableName($table, false);
446 /// Get list of indexes in table
447 $indexes = null;
448 if ($indexes = $db->MetaIndexes($tablename)) {
449 $indexes = array_change_key_case($indexes, CASE_LOWER);
452 /// Iterate over them looking for columns coincidence
453 if ($indexes) {
454 foreach ($indexes as $indexname => $index) {
455 $columns = $index['columns'];
456 /// Lower case column names
457 $columns = array_flip($columns);
458 $columns = array_change_key_case($columns, CASE_LOWER);
459 $columns = array_flip($columns);
460 /// Check if index matchs queried index
461 $diferences = array_merge(array_diff($columns, $indcolumns), array_diff($indcolumns, $columns));
462 /// If no diferences, we have find the index
463 if (empty($diferences)) {
464 $db->debug = $olddbdebug; //Re-set original $db->debug
465 return $indexname;
469 /// Arriving here, index not found
470 $db->debug = $olddbdebug; //Re-set original $db->debug
471 return false;
475 * Given one XMLDBTable, the function returns the name of its sequence in DB (if exists)
476 * of false if it doesn't exist
478 * @param XMLDBTable the table to be searched
479 * @return string sequence name of false
481 function find_sequence_name($table) {
483 global $CFG, $db;
485 $sequencename = false;
487 /// Do this function silenty (to avoid output in install/upgrade process)
488 $olddbdebug = $db->debug;
489 $db->debug = false;
491 if (strtolower(get_class($table)) != 'xmldbtable') {
492 $db->debug = $olddbdebug; //Re-set original $db->debug
493 return false;
496 /// Check table exists
497 if (!table_exists($table)) {
498 debugging('Table ' . $table->getName() . ' do not exist. Sequence not found', DEBUG_DEVELOPER);
499 $db->debug = $olddbdebug; //Re-set original $db->debug
500 return false; //Table doesn't exist, nothing to do
503 $sequencename = $table->getSequenceFromDB($CFG->dbtype, $CFG->prefix);
505 $db->debug = $olddbdebug; //Re-set original $db->debug
506 return $sequencename;
510 * This function will load one entire XMLDB file, generating all the needed
511 * SQL statements, specific for each RDBMS ($CFG->dbtype) and, finally, it
512 * will execute all those statements against the DB.
514 * @uses $CFG, $db
515 * @param $file full path to the XML file to be used
516 * @return boolean (true on success, false on error)
518 function install_from_xmldb_file($file) {
520 global $CFG, $db;
522 $status = true;
525 $xmldb_file = new XMLDBFile($file);
527 if (!$xmldb_file->fileExists()) {
528 return false;
531 $loaded = $xmldb_file->loadXMLStructure();
532 if (!$loaded || !$xmldb_file->isLoaded()) {
533 /// Show info about the error if we can find it
534 if ($structure =& $xmldb_file->getStructure()) {
535 if ($errors = $structure->getAllErrors()) {
536 notify('Errors found in XMLDB file: '. implode (', ', $errors));
539 return false;
542 $structure = $xmldb_file->getStructure();
544 if (!$sqlarr = $structure->getCreateStructureSQL($CFG->dbtype, $CFG->prefix, false)) {
545 return true; //Empty array = nothing to do = no error
548 return execute_sql_arr($sqlarr);
552 * This function will create the table passed as argument with all its
553 * fields/keys/indexes/sequences, everything based in the XMLDB object
555 * @uses $CFG, $db
556 * @param XMLDBTable table object (full specs are required)
557 * @param boolean continue to specify if must continue on error (true) or stop (false)
558 * @param boolean feedback to specify to show status info (true) or not (false)
559 * @return boolean true on success, false on error
561 function create_table($table, $continue=true, $feedback=true) {
563 global $CFG, $db;
565 $status = true;
567 if (strtolower(get_class($table)) != 'xmldbtable') {
568 return false;
571 /// Check table doesn't exist
572 if (table_exists($table)) {
573 debugging('Table ' . $table->getName() . ' exists. Create skipped', DEBUG_DEVELOPER);
574 return true; //Table exists, nothing to do
577 if(!$sqlarr = $table->getCreateTableSQL($CFG->dbtype, $CFG->prefix, false)) {
578 return true; //Empty array = nothing to do = no error
581 return execute_sql_arr($sqlarr, $continue, $feedback);
585 * This function will drop the table passed as argument
586 * and all the associated objects (keys, indexes, constaints, sequences, triggers)
587 * will be dropped too.
589 * @uses $CFG, $db
590 * @param XMLDBTable table object (just the name is mandatory)
591 * @param boolean continue to specify if must continue on error (true) or stop (false)
592 * @param boolean feedback to specify to show status info (true) or not (false)
593 * @return boolean true on success, false on error
595 function drop_table($table, $continue=true, $feedback=true) {
597 global $CFG, $db;
599 $status = true;
601 if (strtolower(get_class($table)) != 'xmldbtable') {
602 return false;
605 /// Check table exists
606 if (!table_exists($table)) {
607 debugging('Table ' . $table->getName() . ' do not exist. Delete skipped', DEBUG_DEVELOPER);
608 return true; //Table don't exist, nothing to do
611 if(!$sqlarr = $table->getDropTableSQL($CFG->dbtype, $CFG->prefix, false)) {
612 return true; //Empty array = nothing to do = no error
615 return execute_sql_arr($sqlarr, $continue, $feedback);
619 * This function will rename the table passed as argument
620 * Before renaming the index, the function will check it exists
622 * @uses $CFG, $db
623 * @param XMLDBTable table object (just the name is mandatory)
624 * @param string new name of the index
625 * @param boolean continue to specify if must continue on error (true) or stop (false)
626 * @param boolean feedback to specify to show status info (true) or not (false)
627 * @return boolean true on success, false on error
629 function rename_table($table, $newname, $continue=true, $feedback=true) {
631 global $CFG, $db;
633 $status = true;
635 if (strtolower(get_class($table)) != 'xmldbtable') {
636 return false;
639 /// Check table exists
640 if (!table_exists($table)) {
641 debugging('Table ' . $table->getName() . ' do not exist. Rename skipped', DEBUG_DEVELOPER);
642 return true; //Table doesn't exist, nothing to do
645 /// Check newname isn't empty
646 if (!$newname) {
647 debugging('New name for table ' . $index->getName() . ' is empty! Rename skipped', DEBUG_DEVELOPER);
648 return true; //Table doesn't exist, nothing to do
651 if(!$sqlarr = $table->getRenameTableSQL($CFG->dbtype, $CFG->prefix, $newname, false)) {
652 return true; //Empty array = nothing to do = no error
655 return execute_sql_arr($sqlarr, $continue, $feedback);
659 * This function will add the field to the table passed as arguments
661 * @uses $CFG, $db
662 * @param XMLDBTable table object (just the name is mandatory)
663 * @param XMLDBField field object (full specs are required)
664 * @param boolean continue to specify if must continue on error (true) or stop (false)
665 * @param boolean feedback to specify to show status info (true) or not (false)
666 * @return boolean true on success, false on error
668 function add_field($table, $field, $continue=true, $feedback=true) {
670 global $CFG, $db;
672 $status = true;
674 if (strtolower(get_class($table)) != 'xmldbtable') {
675 return false;
677 if (strtolower(get_class($field)) != 'xmldbfield') {
678 return false;
681 /// Check the field doesn't exist
682 if (field_exists($table, $field)) {
683 debugging('Field ' . $field->getName() . ' exists. Create skipped', DEBUG_DEVELOPER);
684 return true;
687 /// If NOT NULL and no default given, check the table is empty
688 if ($field->getNotNull() && $field->getDefault() === NULL && count_records($table->getName())) {
689 debugging('Field ' . $field->getName() . ' cannot be added. Not null fields added to non empty tables require default value. Create skipped', DEBUG_DEVELOPER);
690 return true;
693 if(!$sqlarr = $table->getAddFieldSQL($CFG->dbtype, $CFG->prefix, $field, false)) {
694 return true; //Empty array = nothing to do = no error
697 return execute_sql_arr($sqlarr, $continue, $feedback);
701 * This function will drop the field from the table passed as arguments
703 * @uses $CFG, $db
704 * @param XMLDBTable table object (just the name is mandatory)
705 * @param XMLDBField field object (just the name is mandatory)
706 * @param boolean continue to specify if must continue on error (true) or stop (false)
707 * @param boolean feedback to specify to show status info (true) or not (false)
708 * @return boolean true on success, false on error
710 function drop_field($table, $field, $continue=true, $feedback=true) {
712 global $CFG, $db;
714 $status = true;
716 if (strtolower(get_class($table)) != 'xmldbtable') {
717 return false;
719 if (strtolower(get_class($field)) != 'xmldbfield') {
720 return false;
723 /// Check the field exists
724 if (!field_exists($table, $field)) {
725 debugging('Field ' . $field->getName() . ' do not exist. Delete skipped', DEBUG_DEVELOPER);
726 return true;
729 if(!$sqlarr = $table->getDropFieldSQL($CFG->dbtype, $CFG->prefix, $field, false)) {
730 return true; //Empty array = nothing to do = no error
733 return execute_sql_arr($sqlarr, $continue, $feedback);
737 * This function will change the type of the field in the table passed as arguments
739 * @uses $CFG, $db
740 * @param XMLDBTable table object (just the name is mandatory)
741 * @param XMLDBField field object (full specs are required)
742 * @param boolean continue to specify if must continue on error (true) or stop (false)
743 * @param boolean feedback to specify to show status info (true) or not (false)
744 * @return boolean true on success, false on error
746 function change_field_type($table, $field, $continue=true, $feedback=true) {
748 global $CFG, $db;
750 $status = true;
752 if (strtolower(get_class($table)) != 'xmldbtable') {
753 return false;
755 if (strtolower(get_class($field)) != 'xmldbfield') {
756 return false;
759 if(!$sqlarr = $table->getAlterFieldSQL($CFG->dbtype, $CFG->prefix, $field, false)) {
760 return true; //Empty array = nothing to do = no error
763 return execute_sql_arr($sqlarr, $continue, $feedback);
767 * This function will change the precision of the field in the table passed as arguments
769 * @uses $CFG, $db
770 * @param XMLDBTable table object (just the name is mandatory)
771 * @param XMLDBField field object (full specs are required)
772 * @param boolean continue to specify if must continue on error (true) or stop (false)
773 * @param boolean feedback to specify to show status info (true) or not (false)
774 * @return boolean true on success, false on error
776 function change_field_precision($table, $field, $continue=true, $feedback=true) {
778 /// Just a wrapper over change_field_type. Does exactly the same processing
779 return change_field_type($table, $field, $continue, $feedback);
783 * This function will change the unsigned/signed of the field in the table passed as arguments
785 * @uses $CFG, $db
786 * @param XMLDBTable table object (just the name is mandatory)
787 * @param XMLDBField field object (full specs are required)
788 * @param boolean continue to specify if must continue on error (true) or stop (false)
789 * @param boolean feedback to specify to show status info (true) or not (false)
790 * @return boolean true on success, false on error
792 function change_field_unsigned($table, $field, $continue=true, $feedback=true) {
794 /// Just a wrapper over change_field_type. Does exactly the same processing
795 return change_field_type($table, $field, $continue, $feedback);
799 * This function will change the nullability of the field in the table passed as arguments
801 * @uses $CFG, $db
802 * @param XMLDBTable table object (just the name is mandatory)
803 * @param XMLDBField field object (full specs are required)
804 * @param boolean continue to specify if must continue on error (true) or stop (false)
805 * @param boolean feedback to specify to show status info (true) or not (false)
806 * @return boolean true on success, false on error
808 function change_field_notnull($table, $field, $continue=true, $feedback=true) {
810 /// Just a wrapper over change_field_type. Does exactly the same processing
811 return change_field_type($table, $field, $continue, $feedback);
815 * This function will change the enum status of the field in the table passed as arguments
817 * @uses $CFG, $db
818 * @param XMLDBTable table object (just the name is mandatory)
819 * @param XMLDBField field object (full specs are required)
820 * @param boolean continue to specify if must continue on error (true) or stop (false)
821 * @param boolean feedback to specify to show status info (true) or not (false)
822 * @return boolean true on success, false on error
824 function change_field_enum($table, $field, $continue=true, $feedback=true) {
826 global $CFG, $db;
828 $status = true;
830 if (strtolower(get_class($table)) != 'xmldbtable') {
831 return false;
833 if (strtolower(get_class($field)) != 'xmldbfield') {
834 return false;
837 if(!$sqlarr = $table->getModifyEnumSQL($CFG->dbtype, $CFG->prefix, $field, false)) {
838 return true; //Empty array = nothing to do = no error
841 return execute_sql_arr($sqlarr, $continue, $feedback);
844 * This function will change the default of the field in the table passed as arguments
845 * One null value in the default field means delete the default
847 * @uses $CFG, $db
848 * @param XMLDBTable table object (just the name is mandatory)
849 * @param XMLDBField field object (full specs are required)
850 * @param boolean continue to specify if must continue on error (true) or stop (false)
851 * @param boolean feedback to specify to show status info (true) or not (false)
852 * @return boolean true on success, false on error
854 function change_field_default($table, $field, $continue=true, $feedback=true) {
856 global $CFG, $db;
858 $status = true;
860 if (strtolower(get_class($table)) != 'xmldbtable') {
861 return false;
863 if (strtolower(get_class($field)) != 'xmldbfield') {
864 return false;
867 if(!$sqlarr = $table->getModifyDefaultSQL($CFG->dbtype, $CFG->prefix, $field, false)) {
868 return true; //Empty array = nothing to do = no error
871 return execute_sql_arr($sqlarr, $continue, $feedback);
875 * This function will rename the field in the table passed as arguments
876 * Before renaming the field, the function will check it exists
878 * @uses $CFG, $db
879 * @param XMLDBTable table object (just the name is mandatory)
880 * @param XMLDBField index object (full specs are required)
881 * @param string new name of the field
882 * @param boolean continue to specify if must continue on error (true) or stop (false)
883 * @param boolean feedback to specify to show status info (true) or not (false)
884 * @return boolean true on success, false on error
886 function rename_field($table, $field, $newname, $continue=true, $feedback=true) {
888 global $CFG, $db;
890 $status = true;
892 if (strtolower(get_class($table)) != 'xmldbtable') {
893 return false;
895 if (strtolower(get_class($field)) != 'xmldbfield') {
896 return false;
899 /// Check field isn't id. Renaming over that field is not allowed
900 if ($field->getName() == 'id') {
901 debugging('Field ' . $field->getName() . ' cannot be renamed. Rename skipped', DEBUG_DEVELOPER);
902 return true; //Field is "id", nothing to do
905 /// Check field exists
906 if (!field_exists($table, $field)) {
907 debugging('Field ' . $field->getName() . ' do not exist. Rename skipped', DEBUG_DEVELOPER);
908 return true; //Field doesn't exist, nothing to do
911 /// Check newname isn't empty
912 if (!$newname) {
913 debugging('New name for field ' . $field->getName() . ' is empty! Rename skipped', DEBUG_DEVELOPER);
914 return true; //Field doesn't exist, nothing to do
917 if(!$sqlarr = $table->getRenameFieldSQL($CFG->dbtype, $CFG->prefix, $field, $newname, false)) {
918 return true; //Empty array = nothing to do = no error
921 return execute_sql_arr($sqlarr, $continue, $feedback);
925 * This function will create the key in the table passed as arguments
927 * @uses $CFG, $db
928 * @param XMLDBTable table object (just the name is mandatory)
929 * @param XMLDBKey index object (full specs are required)
930 * @param boolean continue to specify if must continue on error (true) or stop (false)
931 * @param boolean feedback to specify to show status info (true) or not (false)
932 * @return boolean true on success, false on error
934 function add_key($table, $key, $continue=true, $feedback=true) {
936 global $CFG, $db;
938 $status = true;
940 if (strtolower(get_class($table)) != 'xmldbtable') {
941 return false;
943 if (strtolower(get_class($key)) != 'xmldbkey') {
944 return false;
946 if ($key->getType() == XMLDB_KEY_PRIMARY) { // Prevent PRIMARY to be added (only in create table, being serious :-P)
947 debugging('Primary Keys can be added at table create time only', DEBUG_DEVELOPER);
948 return true;
951 if(!$sqlarr = $table->getAddKeySQL($CFG->dbtype, $CFG->prefix, $key, false)) {
952 return true; //Empty array = nothing to do = no error
955 return execute_sql_arr($sqlarr, $continue, $feedback);
959 * This function will drop the key in the table passed as arguments
961 * @uses $CFG, $db
962 * @param XMLDBTable table object (just the name is mandatory)
963 * @param XMLDBKey key object (full specs are required)
964 * @param boolean continue to specify if must continue on error (true) or stop (false)
965 * @param boolean feedback to specify to show status info (true) or not (false)
966 * @return boolean true on success, false on error
968 function drop_key($table, $key, $continue=true, $feedback=true) {
970 global $CFG, $db;
972 $status = true;
974 if (strtolower(get_class($table)) != 'xmldbtable') {
975 return false;
977 if (strtolower(get_class($key)) != 'xmldbkey') {
978 return false;
980 if ($key->getType() == XMLDB_KEY_PRIMARY) { // Prevent PRIMARY to be dropped (only in drop table, being serious :-P)
981 debugging('Primary Keys can be deleted at table drop time only', DEBUG_DEVELOPER);
982 return true;
985 if(!$sqlarr = $table->getDropKeySQL($CFG->dbtype, $CFG->prefix, $key, false)) {
986 return true; //Empty array = nothing to do = no error
989 return execute_sql_arr($sqlarr, $continue, $feedback);
993 * This function will rename the key in the table passed as arguments
994 * Experimental. Shouldn't be used at all in normal installation/upgrade!
996 * @uses $CFG, $db
997 * @param XMLDBTable table object (just the name is mandatory)
998 * @param XMLDBKey key object (full specs are required)
999 * @param string new name of the key
1000 * @param boolean continue to specify if must continue on error (true) or stop (false)
1001 * @param boolean feedback to specify to show status info (true) or not (false)
1002 * @return boolean true on success, false on error
1004 function rename_key($table, $key, $newname, $continue=true, $feedback=true) {
1006 global $CFG, $db;
1008 debugging('rename_key() is one experimental feature. You must not use it in production!', DEBUG_DEVELOPER);
1010 $status = true;
1012 if (strtolower(get_class($table)) != 'xmldbtable') {
1013 return false;
1015 if (strtolower(get_class($key)) != 'xmldbkey') {
1016 return false;
1019 /// Check newname isn't empty
1020 if (!$newname) {
1021 debugging('New name for key ' . $key->getName() . ' is empty! Rename skipped', DEBUG_DEVELOPER);
1022 return true; //Key doesn't exist, nothing to do
1025 if(!$sqlarr = $table->getRenameKeySQL($CFG->dbtype, $CFG->prefix, $key, $newname, false)) {
1026 debugging('Some DBs do not support key renaming (MySQL, PostgreSQL, MsSQL). Rename skipped', DEBUG_DEVELOPER);
1027 return true; //Empty array = nothing to do = no error
1030 return execute_sql_arr($sqlarr, $continue, $feedback);
1034 * This function will create the index in the table passed as arguments
1035 * Before creating the index, the function will check it doesn't exists
1037 * @uses $CFG, $db
1038 * @param XMLDBTable table object (just the name is mandatory)
1039 * @param XMLDBIndex index object (full specs are required)
1040 * @param boolean continue to specify if must continue on error (true) or stop (false)
1041 * @param boolean feedback to specify to show status info (true) or not (false)
1042 * @return boolean true on success, false on error
1044 function add_index($table, $index, $continue=true, $feedback=true) {
1046 global $CFG, $db;
1048 $status = true;
1050 if (strtolower(get_class($table)) != 'xmldbtable') {
1051 return false;
1053 if (strtolower(get_class($index)) != 'xmldbindex') {
1054 return false;
1057 /// Check index doesn't exist
1058 if (index_exists($table, $index)) {
1059 debugging('Index ' . $index->getName() . ' exists. Create skipped', DEBUG_DEVELOPER);
1060 return true; //Index exists, nothing to do
1063 if(!$sqlarr = $table->getAddIndexSQL($CFG->dbtype, $CFG->prefix, $index, false)) {
1064 return true; //Empty array = nothing to do = no error
1067 return execute_sql_arr($sqlarr, $continue, $feedback);
1071 * This function will drop the index in the table passed as arguments
1072 * Before dropping the index, the function will check it exists
1074 * @uses $CFG, $db
1075 * @param XMLDBTable table object (just the name is mandatory)
1076 * @param XMLDBIndex index object (full specs are required)
1077 * @param boolean continue to specify if must continue on error (true) or stop (false)
1078 * @param boolean feedback to specify to show status info (true) or not (false)
1079 * @return boolean true on success, false on error
1081 function drop_index($table, $index, $continue=true, $feedback=true) {
1083 global $CFG, $db;
1085 $status = true;
1087 if (strtolower(get_class($table)) != 'xmldbtable') {
1088 return false;
1090 if (strtolower(get_class($index)) != 'xmldbindex') {
1091 return false;
1094 /// Check index exists
1095 if (!index_exists($table, $index)) {
1096 debugging('Index ' . $index->getName() . ' do not exist. Delete skipped', DEBUG_DEVELOPER);
1097 return true; //Index doesn't exist, nothing to do
1100 if(!$sqlarr = $table->getDropIndexSQL($CFG->dbtype, $CFG->prefix, $index, false)) {
1101 return true; //Empty array = nothing to do = no error
1104 return execute_sql_arr($sqlarr, $continue, $feedback);
1108 * This function will rename the index in the table passed as arguments
1109 * Before renaming the index, the function will check it exists
1110 * Experimental. Shouldn't be used at all!
1112 * @uses $CFG, $db
1113 * @param XMLDBTable table object (just the name is mandatory)
1114 * @param XMLDBIndex index object (full specs are required)
1115 * @param string new name of the index
1116 * @param boolean continue to specify if must continue on error (true) or stop (false)
1117 * @param boolean feedback to specify to show status info (true) or not (false)
1118 * @return boolean true on success, false on error
1120 function rename_index($table, $index, $newname, $continue=true, $feedback=true) {
1122 global $CFG, $db;
1124 debugging('rename_index() is one experimental feature. You must not use it in production!', DEBUG_DEVELOPER);
1126 $status = true;
1128 if (strtolower(get_class($table)) != 'xmldbtable') {
1129 return false;
1131 if (strtolower(get_class($index)) != 'xmldbindex') {
1132 return false;
1135 /// Check index exists
1136 if (!index_exists($table, $index)) {
1137 debugging('Index ' . $index->getName() . ' do not exist. Rename skipped', DEBUG_DEVELOPER);
1138 return true; //Index doesn't exist, nothing to do
1141 /// Check newname isn't empty
1142 if (!$newname) {
1143 debugging('New name for index ' . $index->getName() . ' is empty! Rename skipped', DEBUG_DEVELOPER);
1144 return true; //Index doesn't exist, nothing to do
1147 if(!$sqlarr = $table->getRenameIndexSQL($CFG->dbtype, $CFG->prefix, $index, $newname, false)) {
1148 debugging('Some DBs do not support index renaming (MySQL). Rename skipped', DEBUG_DEVELOPER);
1149 return true; //Empty array = nothing to do = no error
1152 return execute_sql_arr($sqlarr, $continue, $feedback);
1155 /* trys to change default db encoding to utf8, if empty db
1157 function change_db_encoding() {
1158 global $CFG, $db;
1159 // try forcing utf8 collation, if mysql db and no tables present
1160 if (($CFG->dbfamily=='mysql') && !$db->Metatables()) {
1161 $SQL = 'ALTER DATABASE '.$CFG->dbname.' CHARACTER SET utf8';
1162 execute_sql($SQL, false); // silent, if it fails it fails
1163 if (setup_is_unicodedb()) {
1164 configure_dbconnection();