6 * @copyright (c) 2007 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
20 * Database Tools for handling cross-db actions such as altering columns, etc.
21 * Currently not supported is returning SQL for creating tables.
24 * @note currently not used within phpBB3, but may be utilized later.
34 * @var object DB object
39 * The Column types for every database we support
42 var $dbms_type_map = array(
45 'BINT' => 'bigint(20)',
46 'UINT' => 'mediumint(8) UNSIGNED',
47 'UINT:' => 'int(%d) UNSIGNED',
48 'TINT:' => 'tinyint(%d)',
49 'USINT' => 'smallint(4) UNSIGNED',
50 'BOOL' => 'tinyint(1) UNSIGNED',
51 'VCHAR' => 'varchar(255)',
52 'VCHAR:' => 'varchar(%d)',
53 'CHAR:' => 'char(%d)',
55 'XSTEXT_UNI'=> 'varchar(100)',
57 'STEXT_UNI' => 'varchar(255)',
60 'MTEXT' => 'mediumtext',
61 'MTEXT_UNI' => 'mediumtext',
62 'TIMESTAMP' => 'int(11) UNSIGNED',
63 'DECIMAL' => 'decimal(5,2)',
64 'DECIMAL:' => 'decimal(%d,2)',
65 'PDECIMAL' => 'decimal(6,3)',
66 'PDECIMAL:' => 'decimal(%d,3)',
67 'VCHAR_UNI' => 'varchar(255)',
68 'VCHAR_UNI:'=> 'varchar(%d)',
69 'VCHAR_CI' => 'varchar(255)',
70 'VARBINARY' => 'varbinary(255)',
75 'BINT' => 'bigint(20)',
76 'UINT' => 'mediumint(8) UNSIGNED',
77 'UINT:' => 'int(%d) UNSIGNED',
78 'TINT:' => 'tinyint(%d)',
79 'USINT' => 'smallint(4) UNSIGNED',
80 'BOOL' => 'tinyint(1) UNSIGNED',
81 'VCHAR' => 'varbinary(255)',
82 'VCHAR:' => 'varbinary(%d)',
83 'CHAR:' => 'binary(%d)',
85 'XSTEXT_UNI'=> 'blob',
87 'STEXT_UNI' => 'blob',
90 'MTEXT' => 'mediumblob',
91 'MTEXT_UNI' => 'mediumblob',
92 'TIMESTAMP' => 'int(11) UNSIGNED',
93 'DECIMAL' => 'decimal(5,2)',
94 'DECIMAL:' => 'decimal(%d,2)',
95 'PDECIMAL' => 'decimal(6,3)',
96 'PDECIMAL:' => 'decimal(%d,3)',
97 'VCHAR_UNI' => 'blob',
98 'VCHAR_UNI:'=> array('varbinary(%d)', 'limit' => array('mult', 3, 255, 'blob')),
100 'VARBINARY' => 'varbinary(255)',
105 'BINT' => 'DOUBLE PRECISION',
107 'UINT:' => 'INTEGER',
108 'TINT:' => 'INTEGER',
109 'USINT' => 'INTEGER',
111 'VCHAR' => 'VARCHAR(255) CHARACTER SET NONE',
112 'VCHAR:' => 'VARCHAR(%d) CHARACTER SET NONE',
113 'CHAR:' => 'CHAR(%d) CHARACTER SET NONE',
114 'XSTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
115 'STEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
116 'TEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
117 'MTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
118 'XSTEXT_UNI'=> 'VARCHAR(100) CHARACTER SET UTF8',
119 'STEXT_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
120 'TEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
121 'MTEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
122 'TIMESTAMP' => 'INTEGER',
123 'DECIMAL' => 'DOUBLE PRECISION',
124 'DECIMAL:' => 'DOUBLE PRECISION',
125 'PDECIMAL' => 'DOUBLE PRECISION',
126 'PDECIMAL:' => 'DOUBLE PRECISION',
127 'VCHAR_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
128 'VCHAR_UNI:'=> 'VARCHAR(%d) CHARACTER SET UTF8',
129 'VCHAR_CI' => 'VARCHAR(255) CHARACTER SET UTF8',
130 'VARBINARY' => 'CHAR(255) CHARACTER SET NONE',
141 'VCHAR' => '[varchar] (255)',
142 'VCHAR:' => '[varchar] (%d)',
143 'CHAR:' => '[char] (%d)',
144 'XSTEXT' => '[varchar] (1000)',
145 'STEXT' => '[varchar] (3000)',
146 'TEXT' => '[varchar] (8000)',
148 'XSTEXT_UNI'=> '[varchar] (100)',
149 'STEXT_UNI' => '[varchar] (255)',
150 'TEXT_UNI' => '[varchar] (4000)',
151 'MTEXT_UNI' => '[text]',
152 'TIMESTAMP' => '[int]',
153 'DECIMAL' => '[float]',
154 'DECIMAL:' => '[float]',
155 'PDECIMAL' => '[float]',
156 'PDECIMAL:' => '[float]',
157 'VCHAR_UNI' => '[varchar] (255)',
158 'VCHAR_UNI:'=> '[varchar] (%d)',
159 'VCHAR_CI' => '[varchar] (255)',
160 'VARBINARY' => '[varchar] (255)',
163 'mssqlnative' => array(
171 'VCHAR' => '[varchar] (255)',
172 'VCHAR:' => '[varchar] (%d)',
173 'CHAR:' => '[char] (%d)',
174 'XSTEXT' => '[varchar] (1000)',
175 'STEXT' => '[varchar] (3000)',
176 'TEXT' => '[varchar] (8000)',
178 'XSTEXT_UNI'=> '[varchar] (100)',
179 'STEXT_UNI' => '[varchar] (255)',
180 'TEXT_UNI' => '[varchar] (4000)',
181 'MTEXT_UNI' => '[text]',
182 'TIMESTAMP' => '[int]',
183 'DECIMAL' => '[float]',
184 'DECIMAL:' => '[float]',
185 'PDECIMAL' => '[float]',
186 'PDECIMAL:' => '[float]',
187 'VCHAR_UNI' => '[varchar] (255)',
188 'VCHAR_UNI:'=> '[varchar] (%d)',
189 'VCHAR_CI' => '[varchar] (255)',
190 'VARBINARY' => '[varchar] (255)',
194 'INT:' => 'number(%d)',
195 'BINT' => 'number(20)',
196 'UINT' => 'number(8)',
197 'UINT:' => 'number(%d)',
198 'TINT:' => 'number(%d)',
199 'USINT' => 'number(4)',
200 'BOOL' => 'number(1)',
201 'VCHAR' => 'varchar2(255)',
202 'VCHAR:' => 'varchar2(%d)',
203 'CHAR:' => 'char(%d)',
204 'XSTEXT' => 'varchar2(1000)',
205 'STEXT' => 'varchar2(3000)',
208 'XSTEXT_UNI'=> 'varchar2(300)',
209 'STEXT_UNI' => 'varchar2(765)',
210 'TEXT_UNI' => 'clob',
211 'MTEXT_UNI' => 'clob',
212 'TIMESTAMP' => 'number(11)',
213 'DECIMAL' => 'number(5, 2)',
214 'DECIMAL:' => 'number(%d, 2)',
215 'PDECIMAL' => 'number(6, 3)',
216 'PDECIMAL:' => 'number(%d, 3)',
217 'VCHAR_UNI' => 'varchar2(765)',
218 'VCHAR_UNI:'=> array('varchar2(%d)', 'limit' => array('mult', 3, 765, 'clob')),
219 'VCHAR_CI' => 'varchar2(255)',
220 'VARBINARY' => 'raw(255)',
225 'BINT' => 'bigint(20)',
226 'UINT' => 'INTEGER UNSIGNED', //'mediumint(8) UNSIGNED',
227 'UINT:' => 'INTEGER UNSIGNED', // 'int(%d) UNSIGNED',
228 'TINT:' => 'tinyint(%d)',
229 'USINT' => 'INTEGER UNSIGNED', //'mediumint(4) UNSIGNED',
230 'BOOL' => 'INTEGER UNSIGNED', //'tinyint(1) UNSIGNED',
231 'VCHAR' => 'varchar(255)',
232 'VCHAR:' => 'varchar(%d)',
233 'CHAR:' => 'char(%d)',
234 'XSTEXT' => 'text(65535)',
235 'STEXT' => 'text(65535)',
236 'TEXT' => 'text(65535)',
237 'MTEXT' => 'mediumtext(16777215)',
238 'XSTEXT_UNI'=> 'text(65535)',
239 'STEXT_UNI' => 'text(65535)',
240 'TEXT_UNI' => 'text(65535)',
241 'MTEXT_UNI' => 'mediumtext(16777215)',
242 'TIMESTAMP' => 'INTEGER UNSIGNED', //'int(11) UNSIGNED',
243 'DECIMAL' => 'decimal(5,2)',
244 'DECIMAL:' => 'decimal(%d,2)',
245 'PDECIMAL' => 'decimal(6,3)',
246 'PDECIMAL:' => 'decimal(%d,3)',
247 'VCHAR_UNI' => 'varchar(255)',
248 'VCHAR_UNI:'=> 'varchar(%d)',
249 'VCHAR_CI' => 'varchar(255)',
250 'VARBINARY' => 'blob',
256 'UINT' => 'INT4', // unsigned
257 'UINT:' => 'INT4', // unsigned
258 'USINT' => 'INT2', // unsigned
259 'BOOL' => 'INT2', // unsigned
261 'VCHAR' => 'varchar(255)',
262 'VCHAR:' => 'varchar(%d)',
263 'CHAR:' => 'char(%d)',
264 'XSTEXT' => 'varchar(1000)',
265 'STEXT' => 'varchar(3000)',
266 'TEXT' => 'varchar(8000)',
268 'XSTEXT_UNI'=> 'varchar(100)',
269 'STEXT_UNI' => 'varchar(255)',
270 'TEXT_UNI' => 'varchar(4000)',
271 'MTEXT_UNI' => 'TEXT',
272 'TIMESTAMP' => 'INT4', // unsigned
273 'DECIMAL' => 'decimal(5,2)',
274 'DECIMAL:' => 'decimal(%d,2)',
275 'PDECIMAL' => 'decimal(6,3)',
276 'PDECIMAL:' => 'decimal(%d,3)',
277 'VCHAR_UNI' => 'varchar(255)',
278 'VCHAR_UNI:'=> 'varchar(%d)',
279 'VCHAR_CI' => 'varchar_ci',
280 'VARBINARY' => 'bytea',
285 * A list of types being unsigned for better reference in some db's
288 var $unsigned_types = array('UINT', 'UINT:', 'USINT', 'BOOL', 'TIMESTAMP');
291 * A list of supported DBMS. We change this class to support more DBMS, the DBMS itself only need to follow some rules.
294 var $supported_dbms = array('firebird', 'mssql', 'mssqlnative', 'mysql_40', 'mysql_41', 'oracle', 'postgres', 'sqlite');
297 * This is set to true if user only wants to return the 'to-be-executed' SQL statement(s) (as an array).
298 * This mode has no effect on some methods (inserting of data for example). This is expressed within the methods command.
300 var $return_statements = false;
303 * Constructor. Set DB Object and set {@link $return_statements return_statements}.
305 * @param phpbb_dbal $db DBAL object
306 * @param bool $return_statements True if only statements should be returned and no SQL being executed
308 function phpbb_db_tools(&$db, $return_statements = false)
311 $this->return_statements = $return_statements;
313 // Determine mapping database type
314 switch ($this->db->sql_layer)
317 $this->sql_layer = 'mysql_40';
321 if (version_compare($this->db->sql_server_info(true), '4.1.3', '>='))
323 $this->sql_layer = 'mysql_41';
327 $this->sql_layer = 'mysql_40';
332 $this->sql_layer = 'mysql_41';
337 $this->sql_layer = 'mssql';
341 $this->sql_layer = 'mssqlnative';
345 $this->sql_layer = $this->db->sql_layer;
351 * Gets a list of tables in the database.
353 * @return array Array of table names (all lower case)
355 function sql_list_tables()
357 switch ($this->db->sql_layer)
362 $sql = 'SHOW TABLES';
368 WHERE type = "table"';
380 $sql = 'SELECT relname
381 FROM pg_stat_user_tables';
385 $sql = 'SELECT rdb$relation_name
387 WHERE rdb$view_source is null
388 AND rdb$system_flag = 0';
392 $sql = 'SELECT table_name
397 $result = $this->db->sql_query($sql);
400 while ($row = $this->db->sql_fetchrow($result))
402 $name = current($row);
403 $tables[$name] = $name;
405 $this->db->sql_freeresult($result);
411 * Check if table exists
414 * @param string $table_name The table name to check for
415 * @return bool true if table exists, else false
417 function sql_table_exists($table_name)
419 $this->db->sql_return_on_error(true);
420 $result = $this->db->sql_query_limit('SELECT * FROM ' . $table_name, 1);
421 $this->db->sql_return_on_error(false);
425 $this->db->sql_freeresult($result);
435 * @param string $table_name The table name to create
436 * @param array $table_data Array containing table data.
437 * @return array Statements if $return_statements is true.
439 function sql_create_table($table_name, $table_data)
441 // holds the DDL for a column
442 $columns = $statements = array();
444 if ($this->sql_table_exists($table_name))
446 return $this->_sql_run_sql($statements);
450 $statements[] = 'begin';
452 // Determine if we have created a PRIMARY KEY in the earliest
453 $primary_key_gen = false;
455 // Determine if the table must be created with TEXTIMAGE
456 $create_textimage = false;
458 // Determine if the table requires a sequence
459 $create_sequence = false;
461 // Begin table sql statement
462 switch ($this->sql_layer)
466 $table_sql = 'CREATE TABLE [' . $table_name . '] (' . "\n";
470 $table_sql = 'CREATE TABLE ' . $table_name . ' (' . "\n";
474 // Iterate through the columns to create a table
475 foreach ($table_data['COLUMNS'] as $column_name => $column_data)
477 // here lies an array, filled with information compiled on the column's data
478 $prepared_column = $this->sql_prepare_column_data($table_name, $column_name, $column_data);
480 if (isset($prepared_column['auto_increment']) && strlen($column_name) > 26) // "${column_name}_gen"
482 trigger_error("Index name '${column_name}_gen' on table '$table_name' is too long. The maximum auto increment column length is 26 characters.", E_USER_ERROR);
485 // here we add the definition of the new column to the list of columns
486 switch ($this->sql_layer)
490 $columns[] = "\t [{$column_name}] " . $prepared_column['column_type_sql_default'];
494 $columns[] = "\t {$column_name} " . $prepared_column['column_type_sql'];
498 // see if we have found a primary key set due to a column definition if we have found it, we can stop looking
499 if (!$primary_key_gen)
501 $primary_key_gen = isset($prepared_column['primary_key_set']) && $prepared_column['primary_key_set'];
504 // create textimage DDL based off of the existance of certain column types
505 if (!$create_textimage)
507 $create_textimage = isset($prepared_column['textimage']) && $prepared_column['textimage'];
510 // create sequence DDL based off of the existance of auto incrementing columns
511 if (!$create_sequence && isset($prepared_column['auto_increment']) && $prepared_column['auto_increment'])
513 $create_sequence = $column_name;
517 // this makes up all the columns in the create table statement
518 $table_sql .= implode(",\n", $columns);
520 // Close the table for two DBMS and add to the statements
521 switch ($this->sql_layer)
524 $table_sql .= "\n);";
525 $statements[] = $table_sql;
530 $table_sql .= "\n) ON [PRIMARY]" . (($create_textimage) ? ' TEXTIMAGE_ON [PRIMARY]' : '');
531 $statements[] = $table_sql;
535 // we have yet to create a primary key for this table,
536 // this means that we can add the one we really wanted instead
537 if (!$primary_key_gen)
540 if (isset($table_data['PRIMARY_KEY']))
542 if (!is_array($table_data['PRIMARY_KEY']))
544 $table_data['PRIMARY_KEY'] = array($table_data['PRIMARY_KEY']);
547 switch ($this->sql_layer)
553 $table_sql .= ",\n\t PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')';
559 // We need the data here
560 $old_return_statements = $this->return_statements;
561 $this->return_statements = true;
563 $primary_key_stmts = $this->sql_create_primary_key($table_name, $table_data['PRIMARY_KEY']);
564 foreach ($primary_key_stmts as $pk_stmt)
566 $statements[] = $pk_stmt;
569 $this->return_statements = $old_return_statements;
573 $table_sql .= ",\n\t CONSTRAINT pk_{$table_name} PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')';
580 switch ($this->sql_layer)
583 // make sure the table is in UTF-8 mode
584 $table_sql .= "\n) CHARACTER SET `utf8` COLLATE `utf8_bin`;";
585 $statements[] = $table_sql;
590 $table_sql .= "\n);";
591 $statements[] = $table_sql;
595 // do we need to add a sequence for auto incrementing columns?
596 if ($create_sequence)
598 $statements[] = "CREATE SEQUENCE {$table_name}_seq;";
601 $table_sql .= "\n);";
602 $statements[] = $table_sql;
607 $statements[] = $table_sql;
609 // do we need to add a sequence and a tigger for auto incrementing columns?
610 if ($create_sequence)
612 // create the actual sequence
613 $statements[] = "CREATE SEQUENCE {$table_name}_seq";
615 // the trigger is the mechanism by which we increment the counter
616 $trigger = "CREATE OR REPLACE TRIGGER t_{$table_name}\n";
617 $trigger .= "BEFORE INSERT ON {$table_name}\n";
618 $trigger .= "FOR EACH ROW WHEN (\n";
619 $trigger .= "\tnew.{$create_sequence} IS NULL OR new.{$create_sequence} = 0\n";
621 $trigger .= "BEGIN\n";
622 $trigger .= "\tSELECT {$table_name}_seq.nextval\n";
623 $trigger .= "\tINTO :new.{$create_sequence}\n";
624 $trigger .= "\tFROM dual;\n";
627 $statements[] = $trigger;
632 if ($create_sequence)
634 $statements[] = "CREATE GENERATOR {$table_name}_gen;";
635 $statements[] = "SET GENERATOR {$table_name}_gen TO 0;";
637 $trigger = "CREATE TRIGGER t_$table_name FOR $table_name\n";
638 $trigger .= "BEFORE INSERT\nAS\nBEGIN\n";
639 $trigger .= "\tNEW.{$create_sequence} = GEN_ID({$table_name}_gen, 1);\nEND;";
640 $statements[] = $trigger;
646 if (isset($table_data['KEYS']))
648 foreach ($table_data['KEYS'] as $key_name => $key_data)
650 if (!is_array($key_data[1]))
652 $key_data[1] = array($key_data[1]);
655 $old_return_statements = $this->return_statements;
656 $this->return_statements = true;
658 $key_stmts = ($key_data[0] == 'UNIQUE') ? $this->sql_create_unique_index($table_name, $key_name, $key_data[1]) : $this->sql_create_index($table_name, $key_name, $key_data[1]);
660 foreach ($key_stmts as $key_stmt)
662 $statements[] = $key_stmt;
665 $this->return_statements = $old_return_statements;
669 // Commit Transaction
670 $statements[] = 'commit';
672 return $this->_sql_run_sql($statements);
676 * Handle passed database update array.
677 * Expected structure...
678 * Key being one of the following
679 * change_columns: Column changes (only type, not name)
680 * add_columns: Add columns to a table
681 * drop_keys: Dropping keys
682 * drop_columns: Removing/Dropping columns
683 * add_primary_keys: adding primary keys
684 * add_unique_index: adding an unique index
685 * add_index: adding an index (can be column:index_size if you need to provide size)
687 * The values are in this format:
688 * {TABLE NAME} => array(
689 * {COLUMN NAME} => array({COLUMN TYPE}, {DEFAULT VALUE}, {OPTIONAL VARIABLES}),
690 * {KEY/INDEX NAME} => array({COLUMN NAMES}),
693 * For more information have a look at /develop/create_schema_files.php (only available through SVN)
695 function perform_schema_changes($schema_changes)
697 if (empty($schema_changes))
702 $statements = array();
705 // For SQLite we need to perform the schema changes in a much more different way
706 if ($this->db->sql_layer == 'sqlite' && $this->return_statements)
708 $sqlite_data = array();
713 if (!empty($schema_changes['drop_tables']))
715 foreach ($schema_changes['drop_tables'] as $table)
717 // only drop table if it exists
718 if ($this->sql_table_exists($table))
720 $result = $this->sql_table_drop($table);
721 if ($this->return_statements)
723 $statements = array_merge($statements, $result);
730 if (!empty($schema_changes['add_tables']))
732 foreach ($schema_changes['add_tables'] as $table => $table_data)
734 $result = $this->sql_create_table($table, $table_data);
735 if ($this->return_statements)
737 $statements = array_merge($statements, $result);
743 if (!empty($schema_changes['change_columns']))
745 foreach ($schema_changes['change_columns'] as $table => $columns)
747 foreach ($columns as $column_name => $column_data)
749 // If the column exists we change it, else we add it ;)
750 if ($column_exists = $this->sql_column_exists($table, $column_name))
752 $result = $this->sql_column_change($table, $column_name, $column_data, true);
756 $result = $this->sql_column_add($table, $column_name, $column_data, true);
763 $sqlite_data[$table]['change_columns'][] = $result;
767 $sqlite_data[$table]['add_columns'][] = $result;
770 else if ($this->return_statements)
772 $statements = array_merge($statements, $result);
779 if (!empty($schema_changes['add_columns']))
781 foreach ($schema_changes['add_columns'] as $table => $columns)
783 foreach ($columns as $column_name => $column_data)
785 // Only add the column if it does not exist yet
786 if ($column_exists = $this->sql_column_exists($table, $column_name))
789 // This is commented out here because it can take tremendous time on updates
790 // $result = $this->sql_column_change($table, $column_name, $column_data, true);
794 $result = $this->sql_column_add($table, $column_name, $column_data, true);
802 // $sqlite_data[$table]['change_columns'][] = $result;
806 $sqlite_data[$table]['add_columns'][] = $result;
809 else if ($this->return_statements)
811 $statements = array_merge($statements, $result);
818 if (!empty($schema_changes['drop_keys']))
820 foreach ($schema_changes['drop_keys'] as $table => $indexes)
822 foreach ($indexes as $index_name)
824 if (!$this->sql_index_exists($table, $index_name))
829 $result = $this->sql_index_drop($table, $index_name);
831 if ($this->return_statements)
833 $statements = array_merge($statements, $result);
840 if (!empty($schema_changes['drop_columns']))
842 foreach ($schema_changes['drop_columns'] as $table => $columns)
844 foreach ($columns as $column)
846 // Only remove the column if it exists...
847 if ($this->sql_column_exists($table, $column))
849 $result = $this->sql_column_remove($table, $column, true);
853 $sqlite_data[$table]['drop_columns'][] = $result;
855 else if ($this->return_statements)
857 $statements = array_merge($statements, $result);
865 if (!empty($schema_changes['add_primary_keys']))
867 foreach ($schema_changes['add_primary_keys'] as $table => $columns)
869 $result = $this->sql_create_primary_key($table, $columns, true);
873 $sqlite_data[$table]['primary_key'] = $result;
875 else if ($this->return_statements)
877 $statements = array_merge($statements, $result);
882 // Add unqiue indexes?
883 if (!empty($schema_changes['add_unique_index']))
885 foreach ($schema_changes['add_unique_index'] as $table => $index_array)
887 foreach ($index_array as $index_name => $column)
889 if ($this->sql_unique_index_exists($table, $index_name))
894 $result = $this->sql_create_unique_index($table, $index_name, $column);
896 if ($this->return_statements)
898 $statements = array_merge($statements, $result);
905 if (!empty($schema_changes['add_index']))
907 foreach ($schema_changes['add_index'] as $table => $index_array)
909 foreach ($index_array as $index_name => $column)
911 if ($this->sql_index_exists($table, $index_name))
916 $result = $this->sql_create_index($table, $index_name, $column);
918 if ($this->return_statements)
920 $statements = array_merge($statements, $result);
928 foreach ($sqlite_data as $table_name => $sql_schema_changes)
930 // Create temporary table with original data
931 $statements[] = 'begin';
936 AND name = '{$table_name}'
937 ORDER BY type DESC, name;";
938 $result = $this->db->sql_query($sql);
945 $row = $this->db->sql_fetchrow($result);
946 $this->db->sql_freeresult($result);
948 // Create a backup table and populate it, destroy the existing one
949 $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
950 $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
951 $statements[] = 'DROP TABLE ' . $table_name;
953 // Get the columns...
954 preg_match('#\((.*)\)#s', $row['sql'], $matches);
956 $plain_table_cols = trim($matches[1]);
957 $new_table_cols = preg_split('/,(?![\s\w]+\))/m', $plain_table_cols);
958 $column_list = array();
960 foreach ($new_table_cols as $declaration)
962 $entities = preg_split('#\s+#', trim($declaration));
963 if ($entities[0] == 'PRIMARY')
967 $column_list[] = $entities[0];
970 // note down the primary key notation because sqlite only supports adding it to the end for the new table
971 $primary_key = false;
972 $_new_cols = array();
974 foreach ($new_table_cols as $key => $declaration)
976 $entities = preg_split('#\s+#', trim($declaration));
977 if ($entities[0] == 'PRIMARY')
979 $primary_key = $declaration;
982 $_new_cols[] = $declaration;
985 $new_table_cols = $_new_cols;
987 // First of all... change columns
988 if (!empty($sql_schema_changes['change_columns']))
990 foreach ($sql_schema_changes['change_columns'] as $column_sql)
992 foreach ($new_table_cols as $key => $declaration)
994 $entities = preg_split('#\s+#', trim($declaration));
995 if (strpos($column_sql, $entities[0] . ' ') === 0)
997 $new_table_cols[$key] = $column_sql;
1003 if (!empty($sql_schema_changes['add_columns']))
1005 foreach ($sql_schema_changes['add_columns'] as $column_sql)
1007 $new_table_cols[] = $column_sql;
1012 if (!empty($sql_schema_changes['drop_columns']))
1014 foreach ($sql_schema_changes['drop_columns'] as $column_name)
1016 // Remove from column list...
1017 $new_column_list = array();
1018 foreach ($column_list as $key => $value)
1020 if ($value === $column_name)
1025 $new_column_list[] = $value;
1028 $column_list = $new_column_list;
1030 // Remove from table...
1031 $_new_cols = array();
1032 foreach ($new_table_cols as $key => $declaration)
1034 $entities = preg_split('#\s+#', trim($declaration));
1035 if (strpos($column_name . ' ', $entities[0] . ' ') === 0)
1039 $_new_cols[] = $declaration;
1041 $new_table_cols = $_new_cols;
1046 if (!empty($sql_schema_changes['primary_key']))
1048 $new_table_cols[] = 'PRIMARY KEY (' . implode(', ', $sql_schema_changes['primary_key']) . ')';
1050 // Add a new one or the old primary key
1051 else if ($primary_key !== false)
1053 $new_table_cols[] = $primary_key;
1056 $columns = implode(',', $column_list);
1058 // create a new table and fill it up. destroy the temp one
1059 $statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $new_table_cols) . ');';
1060 $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
1061 $statements[] = 'DROP TABLE ' . $table_name . '_temp';
1063 $statements[] = 'commit';
1067 if ($this->return_statements)
1074 * Gets a list of columns of a table.
1076 * @param string $table Table name
1078 * @return array Array of column names (all lower case)
1080 function sql_list_columns($table)
1084 switch ($this->sql_layer)
1088 $sql = "SHOW COLUMNS FROM $table";
1091 // PostgreSQL has a way of doing this in a much simpler way but would
1092 // not allow us to support all versions of PostgreSQL
1094 $sql = "SELECT a.attname
1095 FROM pg_class c, pg_attribute a
1096 WHERE c.relname = '{$table}'
1098 AND a.attrelid = c.oid";
1101 // same deal with PostgreSQL, we must perform more complex operations than
1102 // we technically could
1105 $sql = "SELECT c.name
1107 LEFT JOIN sysobjects o ON c.id = o.id
1108 WHERE o.name = '{$table}'";
1112 $sql = "SELECT column_name
1113 FROM user_tab_columns
1114 WHERE LOWER(table_name) = '" . strtolower($table) . "'";
1118 $sql = "SELECT RDB\$FIELD_NAME as FNAME
1119 FROM RDB\$RELATION_FIELDS
1120 WHERE RDB\$RELATION_NAME = '" . strtoupper($table) . "'";
1126 WHERE type = 'table'
1127 AND name = '{$table}'";
1129 $result = $this->db->sql_query($sql);
1136 $row = $this->db->sql_fetchrow($result);
1137 $this->db->sql_freeresult($result);
1139 preg_match('#\((.*)\)#s', $row['sql'], $matches);
1141 $cols = trim($matches[1]);
1142 $col_array = preg_split('/,(?![\s\w]+\))/m', $cols);
1144 foreach ($col_array as $declaration)
1146 $entities = preg_split('#\s+#', trim($declaration));
1147 if ($entities[0] == 'PRIMARY')
1152 $column = strtolower($entities[0]);
1153 $columns[$column] = $column;
1160 $result = $this->db->sql_query($sql);
1162 while ($row = $this->db->sql_fetchrow($result))
1164 $column = strtolower(current($row));
1165 $columns[$column] = $column;
1167 $this->db->sql_freeresult($result);
1173 * Check whether a specified column exist in a table
1175 * @param string $table Table to check
1176 * @param string $column_name Column to check
1178 * @return bool True if column exists, false otherwise
1180 function sql_column_exists($table, $column_name)
1182 $columns = $this->sql_list_columns($table);
1184 return isset($columns[$column_name]);
1188 * Check if a specified index exists in table. Does not return PRIMARY KEY and UNIQUE indexes.
1190 * @param string $table_name Table to check the index at
1191 * @param string $index_name The index name to check
1193 * @return bool True if index exists, else false
1195 function sql_index_exists($table_name, $index_name)
1197 if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative')
1199 $sql = "EXEC sp_statistics '$table_name'";
1200 $result = $this->db->sql_query($sql);
1202 while ($row = $this->db->sql_fetchrow($result))
1204 if ($row['TYPE'] == 3)
1206 if (strtolower($row['INDEX_NAME']) == strtolower($index_name))
1208 $this->db->sql_freeresult($result);
1213 $this->db->sql_freeresult($result);
1218 switch ($this->sql_layer)
1221 $sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name
1223 WHERE RDB\$RELATION_NAME = '" . strtoupper($table_name) . "'
1224 AND RDB\$UNIQUE_FLAG IS NULL
1225 AND RDB\$FOREIGN_KEY IS NULL";
1226 $col = 'index_name';
1230 $sql = "SELECT ic.relname as index_name
1231 FROM pg_class bc, pg_class ic, pg_index i
1232 WHERE (bc.oid = i.indrelid)
1233 AND (ic.oid = i.indexrelid)
1234 AND (bc.relname = '" . $table_name . "')
1235 AND (i.indisunique != 't')
1236 AND (i.indisprimary != 't')";
1237 $col = 'index_name';
1243 FROM ' . $table_name;
1248 $sql = "SELECT index_name
1250 WHERE table_name = '" . strtoupper($table_name) . "'
1252 AND uniqueness = 'NONUNIQUE'";
1253 $col = 'index_name';
1257 $sql = "PRAGMA index_list('" . $table_name . "');";
1262 $result = $this->db->sql_query($sql);
1263 while ($row = $this->db->sql_fetchrow($result))
1265 if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && !$row['Non_unique'])
1270 // These DBMS prefix index name with the table name
1271 switch ($this->sql_layer)
1277 $row[$col] = substr($row[$col], strlen($table_name) + 1);
1281 if (strtolower($row[$col]) == strtolower($index_name))
1283 $this->db->sql_freeresult($result);
1287 $this->db->sql_freeresult($result);
1293 * Check if a specified index exists in table. Does not return PRIMARY KEY and UNIQUE indexes.
1295 * @param string $table_name Table to check the index at
1296 * @param string $index_name The index name to check
1298 * @return bool True if index exists, else false
1300 function sql_unique_index_exists($table_name, $index_name)
1302 if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative')
1304 $sql = "EXEC sp_statistics '$table_name'";
1305 $result = $this->db->sql_query($sql);
1307 while ($row = $this->db->sql_fetchrow($result))
1309 // Usually NON_UNIQUE is the column we want to check, but we allow for both
1310 if ($row['TYPE'] == 3)
1312 if (strtolower($row['INDEX_NAME']) == strtolower($index_name))
1314 $this->db->sql_freeresult($result);
1319 $this->db->sql_freeresult($result);
1323 switch ($this->sql_layer)
1326 $sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name
1328 WHERE RDB\$RELATION_NAME = '" . strtoupper($table_name) . "'
1329 AND RDB\$UNIQUE_FLAG IS NOT NULL
1330 AND RDB\$FOREIGN_KEY IS NULL";
1331 $col = 'index_name';
1335 $sql = "SELECT ic.relname as index_name, i.indisunique
1336 FROM pg_class bc, pg_class ic, pg_index i
1337 WHERE (bc.oid = i.indrelid)
1338 AND (ic.oid = i.indexrelid)
1339 AND (bc.relname = '" . $table_name . "')
1340 AND (i.indisprimary != 't')";
1341 $col = 'index_name';
1347 FROM ' . $table_name;
1352 $sql = "SELECT index_name, table_owner
1354 WHERE table_name = '" . strtoupper($table_name) . "'
1356 AND uniqueness = 'UNIQUE'";
1357 $col = 'index_name';
1361 $sql = "PRAGMA index_list('" . $table_name . "');";
1366 $result = $this->db->sql_query($sql);
1367 while ($row = $this->db->sql_fetchrow($result))
1369 if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && ($row['Non_unique'] || $row[$col] == 'PRIMARY'))
1374 if ($this->sql_layer == 'sqlite' && !$row['unique'])
1379 if ($this->sql_layer == 'postgres' && $row['indisunique'] != 't')
1384 // These DBMS prefix index name with the table name
1385 switch ($this->sql_layer)
1388 // Two cases here... prefixed with U_[table_owner] and not prefixed with table_name
1389 if (strpos($row[$col], 'U_') === 0)
1391 $row[$col] = substr($row[$col], strlen('U_' . $row['table_owner']) + 1);
1393 else if (strpos($row[$col], strtoupper($table_name)) === 0)
1395 $row[$col] = substr($row[$col], strlen($table_name) + 1);
1402 $row[$col] = substr($row[$col], strlen($table_name) + 1);
1406 if (strtolower($row[$col]) == strtolower($index_name))
1408 $this->db->sql_freeresult($result);
1412 $this->db->sql_freeresult($result);
1418 * Private method for performing sql statements (either execute them or return them)
1421 function _sql_run_sql($statements)
1423 if ($this->return_statements)
1428 // We could add error handling here...
1429 foreach ($statements as $sql)
1431 if ($sql === 'begin')
1433 $this->db->sql_transaction('begin');
1435 else if ($sql === 'commit')
1437 $this->db->sql_transaction('commit');
1441 $this->db->sql_query($sql);
1449 * Function to prepare some column information for better usage
1452 function sql_prepare_column_data($table_name, $column_name, $column_data)
1454 if (strlen($column_name) > 30)
1456 trigger_error("Column name '$column_name' on table '$table_name' is too long. The maximum is 30 characters.", E_USER_ERROR);
1460 if (strpos($column_data[0], ':') !== false)
1462 list($orig_column_type, $column_length) = explode(':', $column_data[0]);
1463 if (!is_array($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']))
1465 $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'], $column_length);
1469 if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule']))
1471 switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][0])
1474 $column_length /= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['rule'][1];
1475 $column_length = ceil($column_length);
1476 $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length);
1481 if (isset($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit']))
1483 switch ($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][0])
1486 $column_length *= $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][1];
1487 if ($column_length > $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][2])
1489 $column_type = $this->dbms_type_map[$this->sql_layer][$orig_column_type . ':']['limit'][3];
1493 $column_type = sprintf($this->dbms_type_map[$this->sql_layer][$orig_column_type . ':'][0], $column_length);
1499 $orig_column_type .= ':';
1503 $orig_column_type = $column_data[0];
1504 $column_type = $this->dbms_type_map[$this->sql_layer][$column_data[0]];
1507 // Adjust default value if db-dependant specified
1508 if (is_array($column_data[1]))
1510 $column_data[1] = (isset($column_data[1][$this->sql_layer])) ? $column_data[1][$this->sql_layer] : $column_data[1]['default'];
1515 $return_array = array();
1517 switch ($this->sql_layer)
1520 $sql .= " {$column_type} ";
1521 $return_array['column_type_sql_type'] = " {$column_type} ";
1523 if (!is_null($column_data[1]))
1525 $sql .= 'DEFAULT ' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' ';
1526 $return_array['column_type_sql_default'] = ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' ';
1531 // This is a UNICODE column and thus should be given it's fair share
1532 if (preg_match('/^X?STEXT_UNI|VCHAR_(CI|UNI:?)/', $column_data[0]))
1534 $sql .= ' COLLATE UNICODE';
1537 $return_array['auto_increment'] = false;
1538 if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
1540 $return_array['auto_increment'] = true;
1547 $sql .= " {$column_type} ";
1548 $sql_default = " {$column_type} ";
1550 // For adding columns we need the default definition
1551 if (!is_null($column_data[1]))
1553 // For hexadecimal values do not use single quotes
1554 if (strpos($column_data[1], '0x') === 0)
1556 $return_array['default'] = 'DEFAULT (' . $column_data[1] . ') ';
1557 $sql_default .= $return_array['default'];
1561 $return_array['default'] = 'DEFAULT (' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ') ';
1562 $sql_default .= $return_array['default'];
1566 if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
1568 // $sql .= 'IDENTITY (1, 1) ';
1569 $sql_default .= 'IDENTITY (1, 1) ';
1572 $return_array['textimage'] = $column_type === '[text]';
1575 $sql_default .= 'NOT NULL';
1577 $return_array['column_type_sql_default'] = $sql_default;
1583 $sql .= " {$column_type} ";
1585 // For hexadecimal values do not use single quotes
1586 if (!is_null($column_data[1]) && substr($column_type, -4) !== 'text' && substr($column_type, -4) !== 'blob')
1588 $sql .= (strpos($column_data[1], '0x') === 0) ? "DEFAULT {$column_data[1]} " : "DEFAULT '{$column_data[1]}' ";
1592 if (isset($column_data[2]))
1594 if ($column_data[2] == 'auto_increment')
1596 $sql .= ' auto_increment';
1598 else if ($this->sql_layer === 'mysql_41' && $column_data[2] == 'true_sort')
1600 $sql .= ' COLLATE utf8_unicode_ci';
1607 $sql .= " {$column_type} ";
1608 $sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : '';
1610 // In Oracle empty strings ('') are treated as NULL.
1611 // Therefore in oracle we allow NULL's for all DEFAULT '' entries
1612 // Oracle does not like setting NOT NULL on a column that is already NOT NULL (this happens only on number fields)
1613 if (!preg_match('/number/i', $column_type))
1615 $sql .= ($column_data[1] === '') ? '' : 'NOT NULL';
1618 $return_array['auto_increment'] = false;
1619 if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
1621 $return_array['auto_increment'] = true;
1627 $return_array['column_type'] = $column_type;
1629 $sql .= " {$column_type} ";
1631 $return_array['auto_increment'] = false;
1632 if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
1634 $default_val = "nextval('{$table_name}_seq')";
1635 $return_array['auto_increment'] = true;
1637 else if (!is_null($column_data[1]))
1639 $default_val = "'" . $column_data[1] . "'";
1640 $return_array['null'] = 'NOT NULL';
1641 $sql .= 'NOT NULL ';
1644 $return_array['default'] = $default_val;
1646 $sql .= "DEFAULT {$default_val}";
1648 // Unsigned? Then add a CHECK contraint
1649 if (in_array($orig_column_type, $this->unsigned_types))
1651 $return_array['constraint'] = "CHECK ({$column_name} >= 0)";
1652 $sql .= " CHECK ({$column_name} >= 0)";
1658 $return_array['primary_key_set'] = false;
1659 if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
1661 $sql .= ' INTEGER PRIMARY KEY';
1662 $return_array['primary_key_set'] = true;
1666 $sql .= ' ' . $column_type;
1669 $sql .= ' NOT NULL ';
1670 $sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}'" : '';
1675 $return_array['column_type_sql'] = $sql;
1677 return $return_array;
1683 function sql_column_add($table_name, $column_name, $column_data, $inline = false)
1685 $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data);
1686 $statements = array();
1688 switch ($this->sql_layer)
1691 // Does not support AFTER statement, only POSITION (and there you need the column position)
1692 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD "' . strtoupper($column_name) . '" ' . $column_data['column_type_sql'];
1697 // Does not support AFTER, only through temporary table
1698 $statements[] = 'ALTER TABLE [' . $table_name . '] ADD [' . $column_name . '] ' . $column_data['column_type_sql_default'];
1703 $after = (!empty($column_data['after'])) ? ' AFTER ' . $column_data['after'] : '';
1704 $statements[] = 'ALTER TABLE `' . $table_name . '` ADD COLUMN `' . $column_name . '` ' . $column_data['column_type_sql'] . $after;
1708 // Does not support AFTER, only through temporary table
1709 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql'];
1713 // Does not support AFTER, only through temporary table
1714 if (version_compare($this->db->sql_server_info(true), '8.0', '>='))
1716 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type_sql'];
1720 // old versions cannot add columns with default and null information
1721 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type'] . ' ' . $column_data['constraint'];
1723 if (isset($column_data['null']))
1725 if ($column_data['null'] == 'NOT NULL')
1727 $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET NOT NULL';
1731 if (isset($column_data['default']))
1733 $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default'];
1741 if ($inline && $this->return_statements)
1743 return $column_name . ' ' . $column_data['column_type_sql'];
1746 if (version_compare(sqlite_libversion(), '3.0') == -1)
1750 WHERE type = 'table'
1751 AND name = '{$table_name}'
1752 ORDER BY type DESC, name;";
1753 $result = $this->db->sql_query($sql);
1760 $row = $this->db->sql_fetchrow($result);
1761 $this->db->sql_freeresult($result);
1763 $statements[] = 'begin';
1765 // Create a backup table and populate it, destroy the existing one
1766 $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
1767 $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
1768 $statements[] = 'DROP TABLE ' . $table_name;
1770 preg_match('#\((.*)\)#s', $row['sql'], $matches);
1772 $new_table_cols = trim($matches[1]);
1773 $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
1774 $column_list = array();
1776 foreach ($old_table_cols as $declaration)
1778 $entities = preg_split('#\s+#', trim($declaration));
1779 if ($entities[0] == 'PRIMARY')
1783 $column_list[] = $entities[0];
1786 $columns = implode(',', $column_list);
1788 $new_table_cols = $column_name . ' ' . $column_data['column_type_sql'] . ',' . $new_table_cols;
1790 // create a new table and fill it up. destroy the temp one
1791 $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');';
1792 $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
1793 $statements[] = 'DROP TABLE ' . $table_name . '_temp';
1795 $statements[] = 'commit';
1799 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' [' . $column_data['column_type_sql'] . ']';
1804 return $this->_sql_run_sql($statements);
1810 function sql_column_remove($table_name, $column_name, $inline = false)
1812 $statements = array();
1814 switch ($this->sql_layer)
1817 $statements[] = 'ALTER TABLE ' . $table_name . ' DROP "' . strtoupper($column_name) . '"';
1822 $statements[] = 'ALTER TABLE [' . $table_name . '] DROP COLUMN [' . $column_name . ']';
1827 $statements[] = 'ALTER TABLE `' . $table_name . '` DROP COLUMN `' . $column_name . '`';
1831 $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN ' . $column_name;
1835 $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN "' . $column_name . '"';
1840 if ($inline && $this->return_statements)
1842 return $column_name;
1845 if (version_compare(sqlite_libversion(), '3.0') == -1)
1849 WHERE type = 'table'
1850 AND name = '{$table_name}'
1851 ORDER BY type DESC, name;";
1852 $result = $this->db->sql_query($sql);
1859 $row = $this->db->sql_fetchrow($result);
1860 $this->db->sql_freeresult($result);
1862 $statements[] = 'begin';
1864 // Create a backup table and populate it, destroy the existing one
1865 $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
1866 $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
1867 $statements[] = 'DROP TABLE ' . $table_name;
1869 preg_match('#\((.*)\)#s', $row['sql'], $matches);
1871 $new_table_cols = trim($matches[1]);
1872 $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
1873 $column_list = array();
1875 foreach ($old_table_cols as $declaration)
1877 $entities = preg_split('#\s+#', trim($declaration));
1878 if ($entities[0] == 'PRIMARY' || $entities[0] === $column_name)
1882 $column_list[] = $entities[0];
1885 $columns = implode(',', $column_list);
1887 $new_table_cols = preg_replace('/' . $column_name . '[^,]+(?:,|$)/m', '', $new_table_cols);
1889 // create a new table and fill it up. destroy the temp one
1890 $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');';
1891 $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
1892 $statements[] = 'DROP TABLE ' . $table_name . '_temp';
1894 $statements[] = 'commit';
1898 $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN ' . $column_name;
1903 return $this->_sql_run_sql($statements);
1909 function sql_index_drop($table_name, $index_name)
1911 $statements = array();
1913 switch ($this->sql_layer)
1917 $statements[] = 'DROP INDEX ' . $table_name . '.' . $index_name;
1922 $statements[] = 'DROP INDEX ' . $index_name . ' ON ' . $table_name;
1929 $statements[] = 'DROP INDEX ' . $table_name . '_' . $index_name;
1933 return $this->_sql_run_sql($statements);
1939 function sql_table_drop($table_name)
1941 $statements = array();
1943 if (!$this->sql_table_exists($table_name))
1945 return $this->_sql_run_sql($statements);
1948 // the most basic operation, get rid of the table
1949 $statements[] = 'DROP TABLE ' . $table_name;
1951 switch ($this->sql_layer)
1954 $sql = 'SELECT RDB$GENERATOR_NAME as gen
1956 WHERE RDB$SYSTEM_FLAG = 0
1957 AND RDB$GENERATOR_NAME = \'' . strtoupper($table_name) . "_GEN'";
1958 $result = $this->db->sql_query($sql);
1960 // does a generator exist?
1961 if ($row = $this->db->sql_fetchrow($result))
1963 $statements[] = "DROP GENERATOR {$row['gen']};";
1965 $this->db->sql_freeresult($result);
1969 $sql = 'SELECT A.REFERENCED_NAME
1970 FROM USER_DEPENDENCIES A, USER_TRIGGERS B
1971 WHERE A.REFERENCED_TYPE = \'SEQUENCE\'
1972 AND A.NAME = B.TRIGGER_NAME
1973 AND B.TABLE_NAME = \'' . strtoupper($table_name) . "'";
1974 $result = $this->db->sql_query($sql);
1976 // any sequences ref'd to this table's triggers?
1977 while ($row = $this->db->sql_fetchrow($result))
1979 $statements[] = "DROP SEQUENCE {$row['referenced_name']}";
1981 $this->db->sql_freeresult($result);
1985 // PGSQL does not "tightly" bind sequences and tables, we must guess...
1986 $sql = "SELECT relname
1989 AND relname = '{$table_name}_seq'";
1990 $result = $this->db->sql_query($sql);
1992 // We don't even care about storing the results. We already know the answer if we get rows back.
1993 if ($this->db->sql_fetchrow($result))
1995 $statements[] = "DROP SEQUENCE {$table_name}_seq;\n";
1997 $this->db->sql_freeresult($result);
2001 return $this->_sql_run_sql($statements);
2007 function sql_create_primary_key($table_name, $column, $inline = false)
2009 $statements = array();
2011 switch ($this->sql_layer)
2017 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD PRIMARY KEY (' . implode(', ', $column) . ')';
2022 $sql = "ALTER TABLE [{$table_name}] WITH NOCHECK ADD ";
2023 $sql .= "CONSTRAINT [PK_{$table_name}] PRIMARY KEY CLUSTERED (";
2024 $sql .= '[' . implode("],\n\t\t[", $column) . ']';
2025 $sql .= ') ON [PRIMARY]';
2027 $statements[] = $sql;
2031 $statements[] = 'ALTER TABLE ' . $table_name . 'add CONSTRAINT pk_' . $table_name . ' PRIMARY KEY (' . implode(', ', $column) . ')';
2036 if ($inline && $this->return_statements)
2043 WHERE type = 'table'
2044 AND name = '{$table_name}'
2045 ORDER BY type DESC, name;";
2046 $result = $this->db->sql_query($sql);
2053 $row = $this->db->sql_fetchrow($result);
2054 $this->db->sql_freeresult($result);
2056 $statements[] = 'begin';
2058 // Create a backup table and populate it, destroy the existing one
2059 $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
2060 $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
2061 $statements[] = 'DROP TABLE ' . $table_name;
2063 preg_match('#\((.*)\)#s', $row['sql'], $matches);
2065 $new_table_cols = trim($matches[1]);
2066 $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
2067 $column_list = array();
2069 foreach ($old_table_cols as $declaration)
2071 $entities = preg_split('#\s+#', trim($declaration));
2072 if ($entities[0] == 'PRIMARY')
2076 $column_list[] = $entities[0];
2079 $columns = implode(',', $column_list);
2081 // create a new table and fill it up. destroy the temp one
2082 $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ', PRIMARY KEY (' . implode(', ', $column) . '));';
2083 $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
2084 $statements[] = 'DROP TABLE ' . $table_name . '_temp';
2086 $statements[] = 'commit';
2090 return $this->_sql_run_sql($statements);
2096 function sql_create_unique_index($table_name, $index_name, $column)
2098 $statements = array();
2100 $table_prefix = substr(CONFIG_TABLE, 0, -6); // strlen(config)
2101 if (strlen($table_name . $index_name) - strlen($table_prefix) > 24)
2103 $max_length = strlen($table_prefix) + 24;
2104 trigger_error("Index name '{$table_name}_$index_name' on table '$table_name' is too long. The maximum is $max_length characters.", E_USER_ERROR);
2107 switch ($this->sql_layer)
2113 $statements[] = 'CREATE UNIQUE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
2118 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD UNIQUE INDEX (' . implode(', ', $column) . ')';
2123 $statements[] = 'CREATE UNIQUE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]';
2127 return $this->_sql_run_sql($statements);
2133 function sql_create_index($table_name, $index_name, $column)
2135 $statements = array();
2137 $table_prefix = substr(CONFIG_TABLE, 0, -6); // strlen(config)
2138 if (strlen($table_name . $index_name) - strlen($table_prefix) > 24)
2140 $max_length = strlen($table_prefix) + 24;
2141 trigger_error("Index name '{$table_name}_$index_name' on table '$table_name' is too long. The maximum is $max_length characters.", E_USER_ERROR);
2144 // remove index length unless MySQL4
2145 if ('mysql_40' != $this->sql_layer)
2147 $column = preg_replace('#:.*$#', '', $column);
2150 switch ($this->sql_layer)
2156 $statements[] = 'CREATE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')';
2160 // add index size to definition as required by MySQL4
2161 foreach ($column as $i => $col)
2163 if (false !== strpos($col, ':'))
2165 list($col, $index_size) = explode(':', $col);
2166 $column[$i] = "$col($index_size)";
2171 $statements[] = 'ALTER TABLE ' . $table_name . ' ADD INDEX ' . $index_name . '(' . implode(', ', $column) . ')';
2176 $statements[] = 'CREATE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]';
2180 return $this->_sql_run_sql($statements);
2184 * List all of the indices that belong to a table,
2189 function sql_list_index($table_name)
2191 $index_array = array();
2193 if ($this->sql_layer == 'mssql' || $this->sql_layer == 'mssqlnative')
2195 $sql = "EXEC sp_statistics '$table_name'";
2196 $result = $this->db->sql_query($sql);
2197 while ($row = $this->db->sql_fetchrow($result))
2199 if ($row['TYPE'] == 3)
2201 $index_array[] = $row['INDEX_NAME'];
2204 $this->db->sql_freeresult($result);
2208 switch ($this->sql_layer)
2211 $sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name
2213 WHERE RDB\$RELATION_NAME = '" . strtoupper($table_name) . "'
2214 AND RDB\$UNIQUE_FLAG IS NULL
2215 AND RDB\$FOREIGN_KEY IS NULL";
2216 $col = 'index_name';
2220 $sql = "SELECT ic.relname as index_name
2221 FROM pg_class bc, pg_class ic, pg_index i
2222 WHERE (bc.oid = i.indrelid)
2223 AND (ic.oid = i.indexrelid)
2224 AND (bc.relname = '" . $table_name . "')
2225 AND (i.indisunique != 't')
2226 AND (i.indisprimary != 't')";
2227 $col = 'index_name';
2233 FROM ' . $table_name;
2238 $sql = "SELECT index_name
2240 WHERE table_name = '" . strtoupper($table_name) . "'
2242 AND uniqueness = 'NONUNIQUE'";
2243 $col = 'index_name';
2247 $sql = "PRAGMA index_info('" . $table_name . "');";
2252 $result = $this->db->sql_query($sql);
2253 while ($row = $this->db->sql_fetchrow($result))
2255 if (($this->sql_layer == 'mysql_40' || $this->sql_layer == 'mysql_41') && !$row['Non_unique'])
2260 switch ($this->sql_layer)
2266 $row[$col] = substr($row[$col], strlen($table_name) + 1);
2270 $index_array[] = $row[$col];
2272 $this->db->sql_freeresult($result);
2275 return array_map('strtolower', $index_array);
2279 * Change column type (not name!)
2281 function sql_column_change($table_name, $column_name, $column_data, $inline = false)
2283 $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data);
2284 $statements = array();
2286 switch ($this->sql_layer)
2290 if (!empty($column_data['column_type_sql_default']))
2292 $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" TYPE ' . ' ' . $column_data['column_type_sql_type'];
2293 $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" SET DEFAULT ' . ' ' . $column_data['column_type_sql_default'];
2297 // TODO: try to change pkey without removing trigger, generator or constraints. ATM this query may fail.
2298 $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN "' . strtoupper($column_name) . '" TYPE ' . ' ' . $column_data['column_type_sql_type'];
2304 $statements[] = 'ALTER TABLE [' . $table_name . '] ALTER COLUMN [' . $column_name . '] ' . $column_data['column_type_sql'];
2306 if (!empty($column_data['default']))
2308 // Using TRANSACT-SQL for this statement because we do not want to have colliding data if statements are executed at a later stage
2309 $statements[] = "DECLARE @drop_default_name VARCHAR(100), @cmd VARCHAR(1000)
2310 SET @drop_default_name =
2311 (SELECT so.name FROM sysobjects so
2312 JOIN sysconstraints sc ON so.id = sc.constid
2313 WHERE object_name(so.parent_obj) = '{$table_name}'
2315 AND sc.colid = (SELECT colid FROM syscolumns
2316 WHERE id = object_id('{$table_name}')
2317 AND name = '{$column_name}'))
2318 IF @drop_default_name <> ''
2320 SET @cmd = 'ALTER TABLE [{$table_name}] DROP CONSTRAINT [' + @drop_default_name + ']'
2323 SET @cmd = 'ALTER TABLE [{$table_name}] ADD CONSTRAINT [DF_{$table_name}_{$column_name}_1] {$column_data['default']} FOR [{$column_name}]'
2330 $statements[] = 'ALTER TABLE `' . $table_name . '` CHANGE `' . $column_name . '` `' . $column_name . '` ' . $column_data['column_type_sql'];
2334 $statements[] = 'ALTER TABLE ' . $table_name . ' MODIFY ' . $column_name . ' ' . $column_data['column_type_sql'];
2338 $sql = 'ALTER TABLE ' . $table_name . ' ';
2340 $sql_array = array();
2341 $sql_array[] = 'ALTER COLUMN ' . $column_name . ' TYPE ' . $column_data['column_type'];
2343 if (isset($column_data['null']))
2345 if ($column_data['null'] == 'NOT NULL')
2347 $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET NOT NULL';
2349 else if ($column_data['null'] == 'NULL')
2351 $sql_array[] = 'ALTER COLUMN ' . $column_name . ' DROP NOT NULL';
2355 if (isset($column_data['default']))
2357 $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default'];
2360 // we don't want to double up on constraints if we change different number data types
2361 if (isset($column_data['constraint']))
2363 $constraint_sql = "SELECT consrc as constraint_data
2364 FROM pg_constraint, pg_class bc
2365 WHERE conrelid = bc.oid
2366 AND bc.relname = '{$table_name}'
2369 FROM pg_constraint as c, pg_inherits as i
2370 WHERE i.inhrelid = pg_constraint.conrelid
2371 AND c.conname = pg_constraint.conname
2372 AND c.consrc = pg_constraint.consrc
2373 AND c.conrelid = i.inhparent
2376 $constraint_exists = false;
2378 $result = $this->db->sql_query($constraint_sql);
2379 while ($row = $this->db->sql_fetchrow($result))
2381 if (trim($row['constraint_data']) == trim($column_data['constraint']))
2383 $constraint_exists = true;
2387 $this->db->sql_freeresult($result);
2389 if (!$constraint_exists)
2391 $sql_array[] = 'ADD ' . $column_data['constraint'];
2395 $sql .= implode(', ', $sql_array);
2397 $statements[] = $sql;
2402 if ($inline && $this->return_statements)
2404 return $column_name . ' ' . $column_data['column_type_sql'];
2409 WHERE type = 'table'
2410 AND name = '{$table_name}'
2411 ORDER BY type DESC, name;";
2412 $result = $this->db->sql_query($sql);
2419 $row = $this->db->sql_fetchrow($result);
2420 $this->db->sql_freeresult($result);
2422 $statements[] = 'begin';
2424 // Create a temp table and populate it, destroy the existing one
2425 $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']);
2426 $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name;
2427 $statements[] = 'DROP TABLE ' . $table_name;
2429 preg_match('#\((.*)\)#s', $row['sql'], $matches);
2431 $new_table_cols = trim($matches[1]);
2432 $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
2433 $column_list = array();
2435 foreach ($old_table_cols as $key => $declaration)
2437 $entities = preg_split('#\s+#', trim($declaration));
2438 $column_list[] = $entities[0];
2439 if ($entities[0] == $column_name)
2441 $old_table_cols[$key] = $column_name . ' ' . $column_data['column_type_sql'];
2445 $columns = implode(',', $column_list);
2447 // create a new table and fill it up. destroy the temp one
2448 $statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $old_table_cols) . ');';
2449 $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;';
2450 $statements[] = 'DROP TABLE ' . $table_name . '_temp';
2452 $statements[] = 'commit';
2457 return $this->_sql_run_sql($statements);