1
|
<?php
|
2
|
|
3
|
/**
|
4
|
* @file
|
5
|
* Generic Database schema code.
|
6
|
*/
|
7
|
|
8
|
require_once dirname(__FILE__) . '/query.inc';
|
9
|
|
10
|
/**
|
11
|
* @defgroup schemaapi Schema API
|
12
|
* @{
|
13
|
* API to handle database schemas.
|
14
|
*
|
15
|
* A Drupal schema definition is an array structure representing one or
|
16
|
* more tables and their related keys and indexes. A schema is defined by
|
17
|
* hook_schema(), which usually lives in a modulename.install file.
|
18
|
*
|
19
|
* By implementing hook_schema() and specifying the tables your module
|
20
|
* declares, you can easily create and drop these tables on all
|
21
|
* supported database engines. You don't have to deal with the
|
22
|
* different SQL dialects for table creation and alteration of the
|
23
|
* supported database engines.
|
24
|
*
|
25
|
* hook_schema() should return an array with a key for each table that
|
26
|
* the module defines.
|
27
|
*
|
28
|
* The following keys are defined:
|
29
|
* - 'description': A string in non-markup plain text describing this table
|
30
|
* and its purpose. References to other tables should be enclosed in
|
31
|
* curly-brackets. For example, the node_revisions table
|
32
|
* description field might contain "Stores per-revision title and
|
33
|
* body data for each {node}."
|
34
|
* - 'fields': An associative array ('fieldname' => specification)
|
35
|
* that describes the table's database columns. The specification
|
36
|
* is also an array. The following specification parameters are defined:
|
37
|
* - 'description': A string in non-markup plain text describing this field
|
38
|
* and its purpose. References to other tables should be enclosed in
|
39
|
* curly-brackets. For example, the node table vid field
|
40
|
* description might contain "Always holds the largest (most
|
41
|
* recent) {node_revision}.vid value for this nid."
|
42
|
* - 'type': The generic datatype: 'char', 'varchar', 'text', 'blob', 'int',
|
43
|
* 'float', 'numeric', or 'serial'. Most types just map to the according
|
44
|
* database engine specific datatypes. Use 'serial' for auto incrementing
|
45
|
* fields. This will expand to 'INT auto_increment' on MySQL.
|
46
|
* - 'mysql_type', 'pgsql_type', 'sqlite_type', etc.: If you need to
|
47
|
* use a record type not included in the officially supported list
|
48
|
* of types above, you can specify a type for each database
|
49
|
* backend. In this case, you can leave out the type parameter,
|
50
|
* but be advised that your schema will fail to load on backends that
|
51
|
* do not have a type specified. A possible solution can be to
|
52
|
* use the "text" type as a fallback.
|
53
|
* - 'serialize': A boolean indicating whether the field will be stored as
|
54
|
* a serialized string.
|
55
|
* - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
|
56
|
* 'big'. This is a hint about the largest value the field will
|
57
|
* store and determines which of the database engine specific
|
58
|
* datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT).
|
59
|
* 'normal', the default, selects the base type (e.g. on MySQL,
|
60
|
* INT, VARCHAR, BLOB, etc.).
|
61
|
* Not all sizes are available for all data types. See
|
62
|
* DatabaseSchema::getFieldTypeMap() for possible combinations.
|
63
|
* - 'not null': If true, no NULL values will be allowed in this
|
64
|
* database column. Defaults to false.
|
65
|
* - 'default': The field's default value. The PHP type of the
|
66
|
* value matters: '', '0', and 0 are all different. If you
|
67
|
* specify '0' as the default value for a type 'int' field it
|
68
|
* will not work because '0' is a string containing the
|
69
|
* character "zero", not an integer.
|
70
|
* - 'length': The maximal length of a type 'char', 'varchar' or 'text'
|
71
|
* field. Ignored for other field types.
|
72
|
* - 'unsigned': A boolean indicating whether a type 'int', 'float'
|
73
|
* and 'numeric' only is signed or unsigned. Defaults to
|
74
|
* FALSE. Ignored for other field types.
|
75
|
* - 'precision', 'scale': For type 'numeric' fields, indicates
|
76
|
* the precision (total number of significant digits) and scale
|
77
|
* (decimal digits right of the decimal point). Both values are
|
78
|
* mandatory. Ignored for other field types.
|
79
|
* - 'binary': A boolean indicating that MySQL should force 'char',
|
80
|
* 'varchar' or 'text' fields to use case-sensitive binary collation.
|
81
|
* This has no effect on other database types for which case sensitivity
|
82
|
* is already the default behavior.
|
83
|
* All parameters apart from 'type' are optional except that type
|
84
|
* 'numeric' columns must specify 'precision' and 'scale', and type
|
85
|
* 'varchar' must specify the 'length' parameter.
|
86
|
* - 'primary key': An array of one or more key column specifiers (see below)
|
87
|
* that form the primary key.
|
88
|
* - 'unique keys': An associative array of unique keys ('keyname' =>
|
89
|
* specification). Each specification is an array of one or more
|
90
|
* key column specifiers (see below) that form a unique key on the table.
|
91
|
* - 'foreign keys': An associative array of relations ('my_relation' =>
|
92
|
* specification). Each specification is an array containing the name of
|
93
|
* the referenced table ('table'), and an array of column mappings
|
94
|
* ('columns'). Column mappings are defined by key pairs ('source_column' =>
|
95
|
* 'referenced_column'). This key is for documentation purposes only; foreign
|
96
|
* keys are not created in the database, nor are they enforced by Drupal.
|
97
|
* - 'indexes': An associative array of indexes ('indexname' =>
|
98
|
* specification). Each specification is an array of one or more
|
99
|
* key column specifiers (see below) that form an index on the
|
100
|
* table.
|
101
|
*
|
102
|
* A key column specifier is either a string naming a column or an
|
103
|
* array of two elements, column name and length, specifying a prefix
|
104
|
* of the named column.
|
105
|
*
|
106
|
* As an example, here is a SUBSET of the schema definition for
|
107
|
* Drupal's 'node' table. It show four fields (nid, vid, type, and
|
108
|
* title), the primary key on field 'nid', a unique key named 'vid' on
|
109
|
* field 'vid', and two indexes, one named 'nid' on field 'nid' and
|
110
|
* one named 'node_title_type' on the field 'title' and the first four
|
111
|
* bytes of the field 'type':
|
112
|
*
|
113
|
* @code
|
114
|
* $schema['node'] = array(
|
115
|
* 'description' => 'The base table for nodes.',
|
116
|
* 'fields' => array(
|
117
|
* 'nid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
|
118
|
* 'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE,'default' => 0),
|
119
|
* 'type' => array('type' => 'varchar','length' => 32,'not null' => TRUE, 'default' => ''),
|
120
|
* 'language' => array('type' => 'varchar','length' => 12,'not null' => TRUE,'default' => ''),
|
121
|
* 'title' => array('type' => 'varchar','length' => 255,'not null' => TRUE, 'default' => ''),
|
122
|
* 'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
123
|
* 'status' => array('type' => 'int', 'not null' => TRUE, 'default' => 1),
|
124
|
* 'created' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
125
|
* 'changed' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
126
|
* 'comment' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
127
|
* 'promote' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
128
|
* 'moderate' => array('type' => 'int', 'not null' => TRUE,'default' => 0),
|
129
|
* 'sticky' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
130
|
* 'tnid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
|
131
|
* 'translate' => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
|
132
|
* ),
|
133
|
* 'indexes' => array(
|
134
|
* 'node_changed' => array('changed'),
|
135
|
* 'node_created' => array('created'),
|
136
|
* 'node_moderate' => array('moderate'),
|
137
|
* 'node_frontpage' => array('promote', 'status', 'sticky', 'created'),
|
138
|
* 'node_status_type' => array('status', 'type', 'nid'),
|
139
|
* 'node_title_type' => array('title', array('type', 4)),
|
140
|
* 'node_type' => array(array('type', 4)),
|
141
|
* 'uid' => array('uid'),
|
142
|
* 'tnid' => array('tnid'),
|
143
|
* 'translate' => array('translate'),
|
144
|
* ),
|
145
|
* 'unique keys' => array(
|
146
|
* 'vid' => array('vid'),
|
147
|
* ),
|
148
|
* // For documentation purposes only; foreign keys are not created in the
|
149
|
* // database.
|
150
|
* 'foreign keys' => array(
|
151
|
* 'node_revision' => array(
|
152
|
* 'table' => 'node_revision',
|
153
|
* 'columns' => array('vid' => 'vid'),
|
154
|
* ),
|
155
|
* 'node_author' => array(
|
156
|
* 'table' => 'users',
|
157
|
* 'columns' => array('uid' => 'uid'),
|
158
|
* ),
|
159
|
* ),
|
160
|
* 'primary key' => array('nid'),
|
161
|
* );
|
162
|
* @endcode
|
163
|
*
|
164
|
* @see drupal_install_schema()
|
165
|
*/
|
166
|
|
167
|
/**
|
168
|
* Base class for database schema definitions.
|
169
|
*/
|
170
|
abstract class DatabaseSchema implements QueryPlaceholderInterface {
|
171
|
|
172
|
/**
|
173
|
* The database connection.
|
174
|
*
|
175
|
* @var DatabaseConnection
|
176
|
*/
|
177
|
protected $connection;
|
178
|
|
179
|
/**
|
180
|
* The placeholder counter.
|
181
|
*/
|
182
|
protected $placeholder = 0;
|
183
|
|
184
|
/**
|
185
|
* Definition of prefixInfo array structure.
|
186
|
*
|
187
|
* Rather than redefining DatabaseSchema::getPrefixInfo() for each driver,
|
188
|
* by defining the defaultSchema variable only MySQL has to re-write the
|
189
|
* method.
|
190
|
*
|
191
|
* @see DatabaseSchema::getPrefixInfo()
|
192
|
*/
|
193
|
protected $defaultSchema = 'public';
|
194
|
|
195
|
/**
|
196
|
* A unique identifier for this query object.
|
197
|
*/
|
198
|
protected $uniqueIdentifier;
|
199
|
|
200
|
public function __construct($connection) {
|
201
|
$this->uniqueIdentifier = uniqid('', TRUE);
|
202
|
$this->connection = $connection;
|
203
|
}
|
204
|
|
205
|
/**
|
206
|
* Implements the magic __clone function.
|
207
|
*/
|
208
|
public function __clone() {
|
209
|
$this->uniqueIdentifier = uniqid('', TRUE);
|
210
|
}
|
211
|
|
212
|
/**
|
213
|
* Implements QueryPlaceHolderInterface::uniqueIdentifier().
|
214
|
*/
|
215
|
public function uniqueIdentifier() {
|
216
|
return $this->uniqueIdentifier;
|
217
|
}
|
218
|
|
219
|
/**
|
220
|
* Implements QueryPlaceHolderInterface::nextPlaceholder().
|
221
|
*/
|
222
|
public function nextPlaceholder() {
|
223
|
return $this->placeholder++;
|
224
|
}
|
225
|
|
226
|
/**
|
227
|
* Get information about the table name and schema from the prefix.
|
228
|
*
|
229
|
* @param
|
230
|
* Name of table to look prefix up for. Defaults to 'default' because thats
|
231
|
* default key for prefix.
|
232
|
* @param $add_prefix
|
233
|
* Boolean that indicates whether the given table name should be prefixed.
|
234
|
*
|
235
|
* @return
|
236
|
* A keyed array with information about the schema, table name and prefix.
|
237
|
*/
|
238
|
protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
|
239
|
$info = array(
|
240
|
'schema' => $this->defaultSchema,
|
241
|
'prefix' => $this->connection->tablePrefix($table),
|
242
|
);
|
243
|
if ($add_prefix) {
|
244
|
$table = $info['prefix'] . $table;
|
245
|
}
|
246
|
// If the prefix contains a period in it, then that means the prefix also
|
247
|
// contains a schema reference in which case we will change the schema key
|
248
|
// to the value before the period in the prefix. Everything after the dot
|
249
|
// will be prefixed onto the front of the table.
|
250
|
if (($pos = strpos($table, '.')) !== FALSE) {
|
251
|
// Grab everything before the period.
|
252
|
$info['schema'] = substr($table, 0, $pos);
|
253
|
// Grab everything after the dot.
|
254
|
$info['table'] = substr($table, ++$pos);
|
255
|
}
|
256
|
else {
|
257
|
$info['table'] = $table;
|
258
|
}
|
259
|
return $info;
|
260
|
}
|
261
|
|
262
|
/**
|
263
|
* Create names for indexes, primary keys and constraints.
|
264
|
*
|
265
|
* This prevents using {} around non-table names like indexes and keys.
|
266
|
*/
|
267
|
function prefixNonTable($table) {
|
268
|
$args = func_get_args();
|
269
|
$info = $this->getPrefixInfo($table);
|
270
|
$args[0] = $info['table'];
|
271
|
return implode('_', $args);
|
272
|
}
|
273
|
|
274
|
/**
|
275
|
* Build a condition to match a table name against a standard information_schema.
|
276
|
*
|
277
|
* The information_schema is a SQL standard that provides information about the
|
278
|
* database server and the databases, schemas, tables, columns and users within
|
279
|
* it. This makes information_schema a useful tool to use across the drupal
|
280
|
* database drivers and is used by a few different functions. The function below
|
281
|
* describes the conditions to be meet when querying information_schema.tables
|
282
|
* for drupal tables or information associated with drupal tables. Even though
|
283
|
* this is the standard method, not all databases follow standards and so this
|
284
|
* method should be overwritten by a database driver if the database provider
|
285
|
* uses alternate methods. Because information_schema.tables is used in a few
|
286
|
* different functions, a database driver will only need to override this function
|
287
|
* to make all the others work. For example see includes/databases/mysql/schema.inc.
|
288
|
*
|
289
|
* @param $table_name
|
290
|
* The name of the table in question.
|
291
|
* @param $operator
|
292
|
* The operator to apply on the 'table' part of the condition.
|
293
|
* @param $add_prefix
|
294
|
* Boolean to indicate whether the table name needs to be prefixed.
|
295
|
*
|
296
|
* @return QueryConditionInterface
|
297
|
* A DatabaseCondition object.
|
298
|
*/
|
299
|
protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
|
300
|
$info = $this->connection->getConnectionOptions();
|
301
|
|
302
|
// Retrieve the table name and schema
|
303
|
$table_info = $this->getPrefixInfo($table_name, $add_prefix);
|
304
|
|
305
|
$condition = new DatabaseCondition('AND');
|
306
|
$condition->condition('table_catalog', $info['database']);
|
307
|
$condition->condition('table_schema', $table_info['schema']);
|
308
|
$condition->condition('table_name', $table_info['table'], $operator);
|
309
|
return $condition;
|
310
|
}
|
311
|
|
312
|
/**
|
313
|
* Check if a table exists.
|
314
|
*
|
315
|
* @param $table
|
316
|
* The name of the table in drupal (no prefixing).
|
317
|
*
|
318
|
* @return
|
319
|
* TRUE if the given table exists, otherwise FALSE.
|
320
|
*/
|
321
|
public function tableExists($table) {
|
322
|
$condition = $this->buildTableNameCondition($table);
|
323
|
$condition->compile($this->connection, $this);
|
324
|
// Normally, we would heartily discourage the use of string
|
325
|
// concatenation for conditionals like this however, we
|
326
|
// couldn't use db_select() here because it would prefix
|
327
|
// information_schema.tables and the query would fail.
|
328
|
// Don't use {} around information_schema.tables table.
|
329
|
return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
|
330
|
}
|
331
|
|
332
|
/**
|
333
|
* Find all tables that are like the specified base table name.
|
334
|
*
|
335
|
* @param $table_expression
|
336
|
* An SQL expression, for example "simpletest%" (without the quotes).
|
337
|
* BEWARE: this is not prefixed, the caller should take care of that.
|
338
|
*
|
339
|
* @return
|
340
|
* Array, both the keys and the values are the matching tables.
|
341
|
*/
|
342
|
public function findTables($table_expression) {
|
343
|
$condition = $this->buildTableNameCondition($table_expression, 'LIKE', FALSE);
|
344
|
|
345
|
$condition->compile($this->connection, $this);
|
346
|
// Normally, we would heartily discourage the use of string
|
347
|
// concatenation for conditionals like this however, we
|
348
|
// couldn't use db_select() here because it would prefix
|
349
|
// information_schema.tables and the query would fail.
|
350
|
// Don't use {} around information_schema.tables table.
|
351
|
return $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchAllKeyed(0, 0);
|
352
|
}
|
353
|
|
354
|
/**
|
355
|
* Finds all tables that are like the specified base table name. This is a
|
356
|
* backport of the change made to findTables in Drupal 8 to work with virtual,
|
357
|
* un-prefixed table names. The original function is retained for Backwards
|
358
|
* Compatibility.
|
359
|
* @see https://www.drupal.org/node/2552435
|
360
|
*
|
361
|
* @param string $table_expression
|
362
|
* An SQL expression, for example "cache_%" (without the quotes).
|
363
|
*
|
364
|
* @return array
|
365
|
* Both the keys and the values are the matching tables.
|
366
|
*/
|
367
|
public function findTablesD8($table_expression) {
|
368
|
// Load all the tables up front in order to take into account per-table
|
369
|
// prefixes. The actual matching is done at the bottom of the method.
|
370
|
$condition = $this->buildTableNameCondition('%', 'LIKE');
|
371
|
$condition->compile($this->connection, $this);
|
372
|
|
373
|
$individually_prefixed_tables = $this->connection->getUnprefixedTablesMap();
|
374
|
$default_prefix = $this->connection->tablePrefix();
|
375
|
$default_prefix_length = strlen($default_prefix);
|
376
|
$tables = array();
|
377
|
// Normally, we would heartily discourage the use of string
|
378
|
// concatenation for conditionals like this however, we
|
379
|
// couldn't use db_select() here because it would prefix
|
380
|
// information_schema.tables and the query would fail.
|
381
|
// Don't use {} around information_schema.tables table.
|
382
|
$results = $this->connection->query("SELECT table_name AS table_name FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments());
|
383
|
foreach ($results as $table) {
|
384
|
// Take into account tables that have an individual prefix.
|
385
|
if (isset($individually_prefixed_tables[$table->table_name])) {
|
386
|
$prefix_length = strlen($this->connection->tablePrefix($individually_prefixed_tables[$table->table_name]));
|
387
|
}
|
388
|
elseif ($default_prefix && substr($table->table_name, 0, $default_prefix_length) !== $default_prefix) {
|
389
|
// This table name does not start the default prefix, which means that
|
390
|
// it is not managed by Drupal so it should be excluded from the result.
|
391
|
continue;
|
392
|
}
|
393
|
else {
|
394
|
$prefix_length = $default_prefix_length;
|
395
|
}
|
396
|
|
397
|
// Remove the prefix from the returned tables.
|
398
|
$unprefixed_table_name = substr($table->table_name, $prefix_length);
|
399
|
|
400
|
// The pattern can match a table which is the same as the prefix. That
|
401
|
// will become an empty string when we remove the prefix, which will
|
402
|
// probably surprise the caller, besides not being a prefixed table. So
|
403
|
// remove it.
|
404
|
if (!empty($unprefixed_table_name)) {
|
405
|
$tables[$unprefixed_table_name] = $unprefixed_table_name;
|
406
|
}
|
407
|
}
|
408
|
|
409
|
// Convert the table expression from its SQL LIKE syntax to a regular
|
410
|
// expression and escape the delimiter that will be used for matching.
|
411
|
$table_expression = str_replace(array('%', '_'), array('.*?', '.'), preg_quote($table_expression, '/'));
|
412
|
$tables = preg_grep('/^' . $table_expression . '$/i', $tables);
|
413
|
|
414
|
return $tables;
|
415
|
}
|
416
|
|
417
|
/**
|
418
|
* Check if a column exists in the given table.
|
419
|
*
|
420
|
* @param $table
|
421
|
* The name of the table in drupal (no prefixing).
|
422
|
* @param $name
|
423
|
* The name of the column.
|
424
|
*
|
425
|
* @return
|
426
|
* TRUE if the given column exists, otherwise FALSE.
|
427
|
*/
|
428
|
public function fieldExists($table, $column) {
|
429
|
$condition = $this->buildTableNameCondition($table);
|
430
|
$condition->condition('column_name', $column);
|
431
|
$condition->compile($this->connection, $this);
|
432
|
// Normally, we would heartily discourage the use of string
|
433
|
// concatenation for conditionals like this however, we
|
434
|
// couldn't use db_select() here because it would prefix
|
435
|
// information_schema.tables and the query would fail.
|
436
|
// Don't use {} around information_schema.columns table.
|
437
|
return (bool) $this->connection->query("SELECT 1 FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
|
438
|
}
|
439
|
|
440
|
/**
|
441
|
* Returns a mapping of Drupal schema field names to DB-native field types.
|
442
|
*
|
443
|
* Because different field types do not map 1:1 between databases, Drupal has
|
444
|
* its own normalized field type names. This function returns a driver-specific
|
445
|
* mapping table from Drupal names to the native names for each database.
|
446
|
*
|
447
|
* @return array
|
448
|
* An array of Schema API field types to driver-specific field types.
|
449
|
*/
|
450
|
abstract public function getFieldTypeMap();
|
451
|
|
452
|
/**
|
453
|
* Rename a table.
|
454
|
*
|
455
|
* @param $table
|
456
|
* The table to be renamed.
|
457
|
* @param $new_name
|
458
|
* The new name for the table.
|
459
|
*
|
460
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
461
|
* If the specified table doesn't exist.
|
462
|
* @throws DatabaseSchemaObjectExistsException
|
463
|
* If a table with the specified new name already exists.
|
464
|
*/
|
465
|
abstract public function renameTable($table, $new_name);
|
466
|
|
467
|
/**
|
468
|
* Drop a table.
|
469
|
*
|
470
|
* @param $table
|
471
|
* The table to be dropped.
|
472
|
*
|
473
|
* @return
|
474
|
* TRUE if the table was successfully dropped, FALSE if there was no table
|
475
|
* by that name to begin with.
|
476
|
*/
|
477
|
abstract public function dropTable($table);
|
478
|
|
479
|
/**
|
480
|
* Add a new field to a table.
|
481
|
*
|
482
|
* @param $table
|
483
|
* Name of the table to be altered.
|
484
|
* @param $field
|
485
|
* Name of the field to be added.
|
486
|
* @param $spec
|
487
|
* The field specification array, as taken from a schema definition.
|
488
|
* The specification may also contain the key 'initial', the newly
|
489
|
* created field will be set to the value of the key in all rows.
|
490
|
* This is most useful for creating NOT NULL columns with no default
|
491
|
* value in existing tables.
|
492
|
* @param $keys_new
|
493
|
* (optional) Keys and indexes specification to be created on the
|
494
|
* table along with adding the field. The format is the same as a
|
495
|
* table specification but without the 'fields' element. If you are
|
496
|
* adding a type 'serial' field, you MUST specify at least one key
|
497
|
* or index including it in this array. See db_change_field() for more
|
498
|
* explanation why.
|
499
|
*
|
500
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
501
|
* If the specified table doesn't exist.
|
502
|
* @throws DatabaseSchemaObjectExistsException
|
503
|
* If the specified table already has a field by that name.
|
504
|
*/
|
505
|
abstract public function addField($table, $field, $spec, $keys_new = array());
|
506
|
|
507
|
/**
|
508
|
* Drop a field.
|
509
|
*
|
510
|
* @param $table
|
511
|
* The table to be altered.
|
512
|
* @param $field
|
513
|
* The field to be dropped.
|
514
|
*
|
515
|
* @return
|
516
|
* TRUE if the field was successfully dropped, FALSE if there was no field
|
517
|
* by that name to begin with.
|
518
|
*/
|
519
|
abstract public function dropField($table, $field);
|
520
|
|
521
|
/**
|
522
|
* Set the default value for a field.
|
523
|
*
|
524
|
* @param $table
|
525
|
* The table to be altered.
|
526
|
* @param $field
|
527
|
* The field to be altered.
|
528
|
* @param $default
|
529
|
* Default value to be set. NULL for 'default NULL'.
|
530
|
*
|
531
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
532
|
* If the specified table or field doesn't exist.
|
533
|
*/
|
534
|
abstract public function fieldSetDefault($table, $field, $default);
|
535
|
|
536
|
/**
|
537
|
* Set a field to have no default value.
|
538
|
*
|
539
|
* @param $table
|
540
|
* The table to be altered.
|
541
|
* @param $field
|
542
|
* The field to be altered.
|
543
|
*
|
544
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
545
|
* If the specified table or field doesn't exist.
|
546
|
*/
|
547
|
abstract public function fieldSetNoDefault($table, $field);
|
548
|
|
549
|
/**
|
550
|
* Checks if an index exists in the given table.
|
551
|
*
|
552
|
* @param $table
|
553
|
* The name of the table in drupal (no prefixing).
|
554
|
* @param $name
|
555
|
* The name of the index in drupal (no prefixing).
|
556
|
*
|
557
|
* @return
|
558
|
* TRUE if the given index exists, otherwise FALSE.
|
559
|
*/
|
560
|
abstract public function indexExists($table, $name);
|
561
|
|
562
|
/**
|
563
|
* Add a primary key.
|
564
|
*
|
565
|
* @param $table
|
566
|
* The table to be altered.
|
567
|
* @param $fields
|
568
|
* Fields for the primary key.
|
569
|
*
|
570
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
571
|
* If the specified table doesn't exist.
|
572
|
* @throws DatabaseSchemaObjectExistsException
|
573
|
* If the specified table already has a primary key.
|
574
|
*/
|
575
|
abstract public function addPrimaryKey($table, $fields);
|
576
|
|
577
|
/**
|
578
|
* Drop the primary key.
|
579
|
*
|
580
|
* @param $table
|
581
|
* The table to be altered.
|
582
|
*
|
583
|
* @return
|
584
|
* TRUE if the primary key was successfully dropped, FALSE if there was no
|
585
|
* primary key on this table to begin with.
|
586
|
*/
|
587
|
abstract public function dropPrimaryKey($table);
|
588
|
|
589
|
/**
|
590
|
* Add a unique key.
|
591
|
*
|
592
|
* @param $table
|
593
|
* The table to be altered.
|
594
|
* @param $name
|
595
|
* The name of the key.
|
596
|
* @param $fields
|
597
|
* An array of field names.
|
598
|
*
|
599
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
600
|
* If the specified table doesn't exist.
|
601
|
* @throws DatabaseSchemaObjectExistsException
|
602
|
* If the specified table already has a key by that name.
|
603
|
*/
|
604
|
abstract public function addUniqueKey($table, $name, $fields);
|
605
|
|
606
|
/**
|
607
|
* Drop a unique key.
|
608
|
*
|
609
|
* @param $table
|
610
|
* The table to be altered.
|
611
|
* @param $name
|
612
|
* The name of the key.
|
613
|
*
|
614
|
* @return
|
615
|
* TRUE if the key was successfully dropped, FALSE if there was no key by
|
616
|
* that name to begin with.
|
617
|
*/
|
618
|
abstract public function dropUniqueKey($table, $name);
|
619
|
|
620
|
/**
|
621
|
* Add an index.
|
622
|
*
|
623
|
* @param $table
|
624
|
* The table to be altered.
|
625
|
* @param $name
|
626
|
* The name of the index.
|
627
|
* @param $fields
|
628
|
* An array of field names.
|
629
|
*
|
630
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
631
|
* If the specified table doesn't exist.
|
632
|
* @throws DatabaseSchemaObjectExistsException
|
633
|
* If the specified table already has an index by that name.
|
634
|
*/
|
635
|
abstract public function addIndex($table, $name, $fields);
|
636
|
|
637
|
/**
|
638
|
* Drop an index.
|
639
|
*
|
640
|
* @param $table
|
641
|
* The table to be altered.
|
642
|
* @param $name
|
643
|
* The name of the index.
|
644
|
*
|
645
|
* @return
|
646
|
* TRUE if the index was successfully dropped, FALSE if there was no index
|
647
|
* by that name to begin with.
|
648
|
*/
|
649
|
abstract public function dropIndex($table, $name);
|
650
|
|
651
|
/**
|
652
|
* Change a field definition.
|
653
|
*
|
654
|
* IMPORTANT NOTE: To maintain database portability, you have to explicitly
|
655
|
* recreate all indices and primary keys that are using the changed field.
|
656
|
*
|
657
|
* That means that you have to drop all affected keys and indexes with
|
658
|
* db_drop_{primary_key,unique_key,index}() before calling db_change_field().
|
659
|
* To recreate the keys and indices, pass the key definitions as the
|
660
|
* optional $keys_new argument directly to db_change_field().
|
661
|
*
|
662
|
* For example, suppose you have:
|
663
|
* @code
|
664
|
* $schema['foo'] = array(
|
665
|
* 'fields' => array(
|
666
|
* 'bar' => array('type' => 'int', 'not null' => TRUE)
|
667
|
* ),
|
668
|
* 'primary key' => array('bar')
|
669
|
* );
|
670
|
* @endcode
|
671
|
* and you want to change foo.bar to be type serial, leaving it as the
|
672
|
* primary key. The correct sequence is:
|
673
|
* @code
|
674
|
* db_drop_primary_key('foo');
|
675
|
* db_change_field('foo', 'bar', 'bar',
|
676
|
* array('type' => 'serial', 'not null' => TRUE),
|
677
|
* array('primary key' => array('bar')));
|
678
|
* @endcode
|
679
|
*
|
680
|
* The reasons for this are due to the different database engines:
|
681
|
*
|
682
|
* On PostgreSQL, changing a field definition involves adding a new field
|
683
|
* and dropping an old one which* causes any indices, primary keys and
|
684
|
* sequences (from serial-type fields) that use the changed field to be dropped.
|
685
|
*
|
686
|
* On MySQL, all type 'serial' fields must be part of at least one key
|
687
|
* or index as soon as they are created. You cannot use
|
688
|
* db_add_{primary_key,unique_key,index}() for this purpose because
|
689
|
* the ALTER TABLE command will fail to add the column without a key
|
690
|
* or index specification. The solution is to use the optional
|
691
|
* $keys_new argument to create the key or index at the same time as
|
692
|
* field.
|
693
|
*
|
694
|
* You could use db_add_{primary_key,unique_key,index}() in all cases
|
695
|
* unless you are converting a field to be type serial. You can use
|
696
|
* the $keys_new argument in all cases.
|
697
|
*
|
698
|
* @param $table
|
699
|
* Name of the table.
|
700
|
* @param $field
|
701
|
* Name of the field to change.
|
702
|
* @param $field_new
|
703
|
* New name for the field (set to the same as $field if you don't want to change the name).
|
704
|
* @param $spec
|
705
|
* The field specification for the new field.
|
706
|
* @param $keys_new
|
707
|
* (optional) Keys and indexes specification to be created on the
|
708
|
* table along with changing the field. The format is the same as a
|
709
|
* table specification but without the 'fields' element.
|
710
|
*
|
711
|
* @throws DatabaseSchemaObjectDoesNotExistException
|
712
|
* If the specified table or source field doesn't exist.
|
713
|
* @throws DatabaseSchemaObjectExistsException
|
714
|
* If the specified destination field already exists.
|
715
|
*/
|
716
|
abstract public function changeField($table, $field, $field_new, $spec, $keys_new = array());
|
717
|
|
718
|
/**
|
719
|
* Create a new table from a Drupal table definition.
|
720
|
*
|
721
|
* @param $name
|
722
|
* The name of the table to create.
|
723
|
* @param $table
|
724
|
* A Schema API table definition array.
|
725
|
*
|
726
|
* @throws DatabaseSchemaObjectExistsException
|
727
|
* If the specified table already exists.
|
728
|
*/
|
729
|
public function createTable($name, $table) {
|
730
|
if ($this->tableExists($name)) {
|
731
|
throw new DatabaseSchemaObjectExistsException(t('Table @name already exists.', array('@name' => $name)));
|
732
|
}
|
733
|
$statements = $this->createTableSql($name, $table);
|
734
|
foreach ($statements as $statement) {
|
735
|
$this->connection->query($statement);
|
736
|
}
|
737
|
}
|
738
|
|
739
|
/**
|
740
|
* Return an array of field names from an array of key/index column specifiers.
|
741
|
*
|
742
|
* This is usually an identity function but if a key/index uses a column prefix
|
743
|
* specification, this function extracts just the name.
|
744
|
*
|
745
|
* @param $fields
|
746
|
* An array of key/index column specifiers.
|
747
|
*
|
748
|
* @return
|
749
|
* An array of field names.
|
750
|
*/
|
751
|
public function fieldNames($fields) {
|
752
|
$return = array();
|
753
|
foreach ($fields as $field) {
|
754
|
if (is_array($field)) {
|
755
|
$return[] = $field[0];
|
756
|
}
|
757
|
else {
|
758
|
$return[] = $field;
|
759
|
}
|
760
|
}
|
761
|
return $return;
|
762
|
}
|
763
|
|
764
|
/**
|
765
|
* Prepare a table or column comment for database query.
|
766
|
*
|
767
|
* @param $comment
|
768
|
* The comment string to prepare.
|
769
|
* @param $length
|
770
|
* Optional upper limit on the returned string length.
|
771
|
*
|
772
|
* @return
|
773
|
* The prepared comment.
|
774
|
*/
|
775
|
public function prepareComment($comment, $length = NULL) {
|
776
|
return $this->connection->quote($comment);
|
777
|
}
|
778
|
}
|
779
|
|
780
|
/**
|
781
|
* Exception thrown if an object being created already exists.
|
782
|
*
|
783
|
* For example, this exception should be thrown whenever there is an attempt to
|
784
|
* create a new database table, field, or index that already exists in the
|
785
|
* database schema.
|
786
|
*/
|
787
|
class DatabaseSchemaObjectExistsException extends Exception {}
|
788
|
|
789
|
/**
|
790
|
* Exception thrown if an object being modified doesn't exist yet.
|
791
|
*
|
792
|
* For example, this exception should be thrown whenever there is an attempt to
|
793
|
* modify a database table, field, or index that does not currently exist in
|
794
|
* the database schema.
|
795
|
*/
|
796
|
class DatabaseSchemaObjectDoesNotExistException extends Exception {}
|
797
|
|
798
|
/**
|
799
|
* @} End of "defgroup schemaapi".
|
800
|
*/
|
801
|
|