-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSchema.php
More file actions
2181 lines (1969 loc) · 73.7 KB
/
Schema.php
File metadata and controls
2181 lines (1969 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace DreamFactory\Core\Database\Components;
use DreamFactory\Core\Contracts\DbSchemaInterface;
use DreamFactory\Core\Database\Schema\ColumnSchema;
use DreamFactory\Core\Database\Schema\FunctionSchema;
use DreamFactory\Core\Database\Schema\NamedResourceSchema;
use DreamFactory\Core\Database\Schema\ParameterSchema;
use DreamFactory\Core\Database\Schema\ProcedureSchema;
use DreamFactory\Core\Database\Schema\RoutineSchema;
use DreamFactory\Core\Database\Schema\TableSchema;
use DreamFactory\Core\Enums\DbResourceTypes;
use DreamFactory\Core\Enums\DbSimpleTypes;
use DreamFactory\Core\Exceptions\BadRequestException;
use DreamFactory\Core\Exceptions\InternalServerErrorException;
use DreamFactory\Core\Exceptions\NotImplementedException;
use Illuminate\Database\Connection;
use Illuminate\Database\ConnectionInterface;
/**
* Schema is the base class for retrieving metadata information.
*
*/
class Schema implements DbSchemaInterface
{
/**
* @const integer Maximum size of a string
*/
const DEFAULT_STRING_MAX_SIZE = 255;
/**
* @const string Quoting characters
*/
const LEFT_QUOTE_CHARACTER = '';
/**
* @const string Quoting characters
*/
const RIGHT_QUOTE_CHARACTER = '';
/**
* Default fetch mode for procedures and functions
*/
const ROUTINE_FETCH_MODE = \PDO::FETCH_NAMED;
/**
* @var Connection
*/
protected $connection;
/**
* Constructor.
*
* @param ConnectionInterface $conn database connection.
*/
public function __construct($conn)
{
$this->connection = $conn;
}
/**
* @return ConnectionInterface database connection. The connection is active.
*/
public function getDbConnection()
{
return $this->connection;
}
/**
* @return mixed
*/
public function getUserName()
{
return $this->connection->getConfig('username');
}
/**
* @param $query
* @param array $bindings
* @param null $column
*
* @return array
*/
public function selectColumn($query, $bindings = [], $column = null)
{
$rows = $this->connection->select($query, $bindings);
foreach ($rows as $key => $row) {
if (!empty($column)) {
$rows[$key] = data_get($row, $column);
} else {
$row = (array)$row;
$rows[$key] = reset($row);
}
}
return $rows;
}
/**
* @param $query
* @param array $bindings
* @param null $column
*
* @return mixed|null
*/
public function selectValue($query, $bindings = [], $column = null)
{
if (null !== $row = $this->connection->selectOne($query, $bindings)) {
if (!empty($column)) {
return data_get($row, $column);
} else {
$row = (array)$row;
return reset($row);
}
}
return null;
}
/**
* Quotes a string value for use in a query.
*
* @param string $str string to be quoted
*
* @return string the properly quoted string
* @see http://www.php.net/manual/en/function.PDO-quote.php
*/
public function quoteValue($str)
{
if (is_int($str) || is_float($str)) {
return $str;
}
if (($value = $this->connection->getPdo()->quote($str)) !== false) {
return $value;
} else // the driver doesn't support quote (e.g. oci)
{
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
}
}
/**
* Returns the default schema name for the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply returns null.
*
* @throws \Exception
* @return string Default schema name for this connection
*/
public function getDefaultSchema()
{
return null;
}
/**
* Returns all schema names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
*
* @throws \Exception
* @return array all schema names in the database.
*/
public function getSchemas()
{
// throw new \Exception( "{get_class( $this )} does not support fetching all schema names." );
return [''];
}
/**
* Return an array of supported schema resource types.
* @return array
*/
public function getSupportedResourceTypes()
{
return [DbResourceTypes::TYPE_TABLE];
}
/**
* @param string $type Resource type
*
* @return boolean
*/
public function supportsResourceType($type)
{
return in_array($type, $this->getSupportedResourceTypes());
}
/**
* @param string $type Resource type
* @param string $name
* @param bool $returnName
*
* @return mixed
* @throws \Exception
*/
public function doesResourceExist($type, $name, $returnName = false)
{
if (empty($name)) {
throw new \InvalidArgumentException('Resource name cannot be empty.');
}
// Build the lower-cased resource array
$names = $this->getResourceNames($type);
// Search normal, return real name
$ndx = strtolower($name);
if (false !== array_key_exists($ndx, $names)) {
return $returnName ? $names[$ndx]->name : true;
}
return false;
}
/**
* Return an array of names of a particular type of resource.
*
* @param string $type Resource type
* @param string $schema Schema name if any specific requested
*
* @return array
* @throws \Exception
*/
public function getResourceNames($type, $schema = '')
{
switch ($type) {
case DbResourceTypes::TYPE_SCHEMA:
return $this->getSchemas();
case DbResourceTypes::TYPE_TABLE:
return $this->getTableNames($schema);
case DbResourceTypes::TYPE_VIEW:
return $this->getViewNames($schema);
case DbResourceTypes::TYPE_TABLE_CONSTRAINT:
return $this->getTableConstraints($schema);
case DbResourceTypes::TYPE_PROCEDURE:
return $this->getProcedureNames($schema);
case DbResourceTypes::TYPE_FUNCTION:
return $this->getFunctionNames($schema);
default:
return [];
}
}
/**
* Return the metadata about a particular schema resource.
*
* @param string $type Resource type
* @param string|NamedResourceSchema $name Resource name
*
* @return null|mixed
* @throws \Exception
*/
public function getResource($type, &$name)
{
switch ($type) {
case DbResourceTypes::TYPE_SCHEMA:
return $name;
case DbResourceTypes::TYPE_TABLE:
$this->loadTable($name);
return $name;
case DbResourceTypes::TYPE_VIEW:
$this->loadView($name);
return $name;
case DbResourceTypes::TYPE_PROCEDURE:
$this->loadProcedure($name);
return $name;
case DbResourceTypes::TYPE_FUNCTION:
$this->loadFunction($name);
return $name;
default:
return null;
}
}
/**
* @param string $type Resource type
* @param string $name Resource name
* @return mixed
* @throws \Exception
*/
public function dropResource($type, $name)
{
switch ($type) {
case DbResourceTypes::TYPE_SCHEMA:
throw new \Exception('Dropping the schema resource is not currently supported.');
break;
case DbResourceTypes::TYPE_TABLE:
$this->dropTable($name);
break;
case DbResourceTypes::TYPE_TABLE_FIELD:
if (!is_array($name) || (2 > count($name))) {
throw new \InvalidArgumentException('Invalid resource name for type.');
}
$this->dropColumns($name[0], $name[1]);
break;
case DbResourceTypes::TYPE_TABLE_CONSTRAINT:
if (!is_array($name) || (2 > count($name))) {
throw new \InvalidArgumentException('Invalid resource name for type.');
}
$this->dropRelationship($name[0], $name[1]);
break;
case DbResourceTypes::TYPE_PROCEDURE:
throw new \Exception('Dropping the stored procedure resource is not currently supported.');
break;
case DbResourceTypes::TYPE_FUNCTION:
throw new \Exception('Dropping the stored function resource is not currently supported.');
break;
default:
return false;
}
return true;
}
/**
* Loads the metadata for the specified table.
*
* @param TableSchema $table Any already known info about the table
*/
protected function loadTable(TableSchema $table)
{
$this->loadTableColumns($table);
}
/**
* Loads the metadata for the specified view.
*
* @param TableSchema $table Any already known info about the view
*/
protected function loadView(TableSchema $table)
{
$this->loadTableColumns($table);
}
/**
* Finds the column metadata from the database for the specified table.
*
* @param TableSchema $table Any already known info about the table
*/
protected function loadTableColumns(
/** @noinspection PhpUnusedParameterInspection */
TableSchema $table
) {
}
/**
* Returns all table constraints in the database for the specified schemas.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply returns empty array.
*
* @param string $schema the schema of the tables. Defaults to empty string, meaning all schemas.
* @return array All table constraints in the database
*/
protected function getTableConstraints($schema = '')
{
return [];
}
/**
* Returns all table names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
*
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
* If not empty, the returned table names will be prefixed with the schema name.
*
* @return TableSchema[] all table names in the database.
* @throws \Exception
*/
protected function getTableNames(
/** @noinspection PhpUnusedParameterInspection */
$schema = ''
) {
throw new NotImplementedException("Database or driver does not support fetching all table names.");
}
/**
* Returns all view names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
*
* @param string $schema the schema of the views. Defaults to empty string, meaning the current or default schema.
* If not empty, the returned view names will be prefixed with the schema name.
*
* @return TableSchema[] all view names in the database.
* @throws \Exception
*/
protected function getViewNames(
/** @noinspection PhpUnusedParameterInspection */
$schema = ''
) {
throw new NotImplementedException("Database or driver does not support fetching all view names.");
}
/**
* Returns all stored procedure names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
*
* @param string $schema the schema of the procedures. Defaults to empty string, meaning the current or default
* schema. If not empty, the returned procedure names will be prefixed with the schema name.
*
* @return array all procedure names in the database.
*/
public function getProcedureNames($schema = '')
{
return $this->getRoutineNames('PROCEDURE', $schema);
}
/**
* Returns all stored functions names in the database.
* This method should be overridden by child classes in order to support this feature
* because the default implementation simply throws an exception.
*
* @param string $schema the schema of the functions. Defaults to empty string, meaning the current or default
* schema. If not empty, the returned functions names will be prefixed with the schema name.
*
* @return array all stored functions names in the database.
*/
public function getFunctionNames($schema = '')
{
return $this->getRoutineNames('FUNCTION', $schema);
// throw new NotImplementedException("Database or driver does not support fetching all stored function names.");
}
/**
* Returns all routines in the database.
*
* @param string $type "procedure" or "function"
* @param string $schema the schema of the routine. Defaults to empty string, meaning the current or
* default schema. If not empty, the returned stored function names will be prefixed with the
* schema name.
*
* @throws \InvalidArgumentException
* @return array all stored function names in the database.
*/
protected function getRoutineNames($type, $schema = '')
{
return [];
}
/**
* Loads the metadata for the specified stored procedure.
*
* @param ProcedureSchema $procedure procedure
*
* @throws \Exception
*/
protected function loadProcedure(ProcedureSchema $procedure)
{
$this->loadParameters($procedure);
}
/**
* Loads the metadata for the specified stored function.
*
* @param FunctionSchema $function
*/
protected function loadFunction(FunctionSchema $function)
{
$this->loadParameters($function);
}
/**
* Loads the parameter metadata for the specified stored procedure or function.
*
* @param RoutineSchema $holder
*/
protected function loadParameters(RoutineSchema $holder)
{
}
/**
* Quotes a table name for use in a query.
* If the table name contains schema prefix, the prefix will also be properly quoted.
*
* @param string $name table name
*
* @return string the properly quoted table name
* @see quoteSimpleTableName
*/
public function quoteTableName($name)
{
if (strpos($name, '.') === false) {
return $this->quoteSimpleTableName($name);
}
$parts = explode('.', $name);
foreach ($parts as $i => $part) {
$parts[$i] = $this->quoteSimpleTableName($part);
}
return implode('.', $parts);
}
/**
* Quotes a simple table name for use in a query.
* A simple table name does not schema prefix.
*
* @param string $name table name
*
* @return string the properly quoted table name
*/
public function quoteSimpleTableName($name)
{
return static::LEFT_QUOTE_CHARACTER . $name . static::RIGHT_QUOTE_CHARACTER;
}
/**
* Quotes a column name for use in a query.
* If the column name contains prefix, the prefix will also be properly quoted.
*
* @param string $name column name
*
* @return string the properly quoted column name
* @see quoteSimpleColumnName
*/
public function quoteColumnName($name)
{
if (($pos = strrpos($name, '.')) !== false) {
$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1);
} else {
$prefix = '';
}
if ('*' !== $name) {
$name = $this->quoteSimpleColumnName($name);
}
return $prefix . $name;
}
/**
* Quotes a simple column name for use in a query.
* A simple column name does not contain prefix.
*
* @param string $name column name
*
* @return string the properly quoted column name
*/
public function quoteSimpleColumnName($name)
{
return static::LEFT_QUOTE_CHARACTER . $name . static::RIGHT_QUOTE_CHARACTER;
}
/**
* Compares two table names.
* The table names can be either quoted or unquoted. This method
* will consider both cases.
*
* @param string $name1 table name 1
* @param string $name2 table name 2
*
* @return boolean whether the two table names refer to the same table.
*/
public function compareTableNames($name1, $name2)
{
$name1 = str_replace(['"', '`', "'"], '', $name1);
$name2 = str_replace(['"', '`', "'"], '', $name2);
if (($pos = strrpos($name1, '.')) !== false) {
$name1 = substr($name1, $pos + 1);
}
if (($pos = strrpos($name2, '.')) !== false) {
$name2 = substr($name2, $pos + 1);
}
if ($this->connection->getTablePrefix() !== null) {
if (strpos($name1, '{') !== false) {
$name1 = $this->connection->getTablePrefix() . str_replace(['{', '}'], '', $name1);
}
if (strpos($name2, '{') !== false) {
$name2 = $this->connection->getTablePrefix() . str_replace(['{', '}'], '', $name2);
}
}
return $name1 === $name2;
}
/**
* Resets the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted
* will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
*
* @param TableSchema $table the table schema whose primary key sequence will be reset
* @param integer|null $value the value for the primary key of the next new row inserted.
* If this is not set, the next new row's primary key will have the max value of a
* primary key plus one (i.e. sequence trimming).
*/
public function resetSequence($table, $value = null)
{
}
public static function isUndiscoverableType($type)
{
switch ($type) {
// keep our type extensions
case DbSimpleTypes::TYPE_USER_ID:
case DbSimpleTypes::TYPE_USER_ID_ON_CREATE:
case DbSimpleTypes::TYPE_USER_ID_ON_UPDATE:
case DbSimpleTypes::TYPE_TIMESTAMP_ON_CREATE:
case DbSimpleTypes::TYPE_TIMESTAMP_ON_UPDATE:
return true;
}
return false;
}
/**
* @param array $info
*/
protected function translateSimpleColumnTypes(array &$info)
{
}
/**
* @param array $info
*/
protected function validateColumnSettings(array &$info)
{
}
/**
* @param array $info
*
* @return string
* @throws \Exception
*/
protected function buildColumnDefinition(array $info)
{
// This works for most except Oracle
$type = (isset($info['type'])) ? $info['type'] : null;
$typeExtras = (isset($info['type_extras'])) ? $info['type_extras'] : null;
$definition = $type . $typeExtras;
$allowNull = (isset($info['allow_null'])) ? $info['allow_null'] : null;
$definition .= ($allowNull) ? ' NULL' : ' NOT NULL';
$default = (isset($info['db_type'])) ? $info['db_type'] : null;
if (isset($default)) {
if (is_array($default)) {
$expression = (isset($default['expression'])) ? $default['expression'] : null;
if (null !== $expression) {
$definition .= ' DEFAULT ' . $expression;
}
} else {
$default = $this->quoteValue($default);
$definition .= ' DEFAULT ' . $default;
}
}
if (isset($info['is_primary_key']) && filter_var($info['is_primary_key'], FILTER_VALIDATE_BOOLEAN)) {
$definition .= ' PRIMARY KEY';
} elseif (isset($info['is_unique']) && filter_var($info['is_unique'], FILTER_VALIDATE_BOOLEAN)) {
$definition .= ' UNIQUE KEY';
}
return $definition;
}
/**
* Converts an abstract column type into a physical column type.
* The conversion is done using the type map specified in {@link columnTypes}.
* These abstract column types are supported (using MySQL as example to explain the corresponding
* physical types):
* <ul>
* <li>pk: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY
* KEY"</li>
* <li>string: string type, will be converted into "varchar(255)"</li>
* <li>text: a long string type, will be converted into "text"</li>
* <li>integer: integer type, will be converted into "int(11)"</li>
* <li>boolean: boolean type, will be converted into "tinyint(1)"</li>
* <li>float: float number type, will be converted into "float"</li>
* <li>decimal: decimal number type, will be converted into "decimal"</li>
* <li>datetime: datetime type, will be converted into "datetime"</li>
* <li>timestamp: timestamp type, will be converted into "timestamp"</li>
* <li>time: time type, will be converted into "time"</li>
* <li>date: date type, will be converted into "date"</li>
* <li>binary: binary data type, will be converted into "blob"</li>
* </ul>
*
* If the abstract type contains two or more parts separated by spaces or '(' (e.g. "string NOT NULL" or
* "decimal(10,2)"), then only the first part will be converted, and the rest of the parts will be appended to the
* conversion result. For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
*
* @param string $info abstract column type
*
* @return string physical column type including arguments, null designation and defaults.
* @throws \Exception
*/
protected function getColumnType($info)
{
$out = [];
$type = '';
if (is_string($info)) {
$type = trim($info); // cleanup
} elseif (is_array($info)) {
$sql = (isset($info['sql'])) ? $info['sql'] : null;
if (!empty($sql)) {
return $sql; // raw SQL statement given, pass it on.
}
$out = $info;
$type = (isset($info['type'])) ? $info['type'] : null;
if (empty($type)) {
$type = (isset($info['db_type'])) ? $info['db_type'] : null;
if (empty($type)) {
throw new \Exception("Invalid schema detected - no type or db_type element.");
}
}
$type = trim($type); // cleanup
}
if (empty($type)) {
throw new \Exception("Invalid schema detected - no type definition.");
}
// If there are extras, then pass it on through
if ((false !== strpos($type, ' ')) || (false !== strpos($type, '('))) {
return $type;
}
$out['type'] = $type;
$this->translateSimpleColumnTypes($out);
$this->validateColumnSettings($out);
return $this->buildColumnDefinition($out);
}
/**
* Builds a SQL statement for renaming a DB table.
*
* @param string $table the table to be renamed. The name will be properly quoted by the method.
* @param string $newName the new table name. The name will be properly quoted by the method.
*
* @return string the SQL statement for renaming a DB table.
*/
public function renameTable($table, $newName)
{
return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
}
/**
* Builds a SQL statement for truncating a DB table.
*
* @param string $table the table to be truncated. The name will be properly quoted by the method.
*
* @return string the SQL statement for truncating a DB table.
*/
public function truncateTable($table)
{
return "TRUNCATE TABLE " . $this->quoteTableName($table);
}
/**
* Builds a SQL statement for adding a new DB column.
*
* @param string $table The quoted table that the new column will be added to.
* @param string $column The name of the new column. The name will be properly quoted by the method.
* @param string $type The column type. The {@link getColumnType} method will be invoked to convert abstract
* column type (if any) into the physical one. Anything that is not recognized as abstract
* type will be kept in the generated SQL. For example, 'string' will be turned into
* 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
*
* @return string the SQL statement for adding a new column.
*/
public function addColumn($table, $column, $type)
{
return <<<MYSQL
ALTER TABLE $table ADD COLUMN {$this->quoteColumnName($column)} {$this->getColumnType($type)};
MYSQL;
}
/**
* Builds a SQL statement for renaming a column.
*
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
* @param string $name the old name of the column. The name will be properly quoted by the method.
* @param string $newName the new name of the column. The name will be properly quoted by the method.
*
* @return string the SQL statement for renaming a DB column.
*/
public function renameColumn($table, $name, $newName)
{
return <<<MYSQL
ALTER TABLE $table RENAME COLUMN {$this->quoteColumnName($name)} TO {$this->quoteColumnName($newName)};
MYSQL;
}
/**
* Builds a SQL statement for changing the definition of a column.
*
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the
* method.
* @param string $column the name of the column to be changed. The name will be properly quoted by the method.
* @param string $definition the new column type. The {@link getColumnType} method will be invoked to convert
* abstract column type (if any) into the physical one. Anything that is not recognized
* as abstract type will be kept in the generated SQL. For example, 'string' will be
* turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not
* null'.
*
* @return string the SQL statement for changing the definition of a column.
*/
public function alterColumn($table, $column, $definition)
{
return <<<MYSQL
ALTER TABLE $table CHANGE {$this->quoteColumnName($column)} {$this->quoteColumnName($column)} {$this->getColumnType($definition)};
MYSQL;
}
/**
* @param string $prefix
* @param string $table
* @param string|null $column
*
* @return string
*/
public function makeConstraintName($prefix, $table, $column = null)
{
$temp = $prefix . '_' . str_replace('.', '_', $table);
if (!empty($column)) {
$temp .= '_' . $column;
}
return $temp;
}
/**
* Builds a SQL statement for adding a foreign key constraint to an existing table.
* The method will properly quote the table and column names.
*
* @param string $name the name of the foreign key constraint.
* @param string $table the table that the foreign key constraint will be added to.
* @param string $columns the name of the column to that the constraint will be added on. If there are multiple
* columns, separate them with commas.
* @param string $refTable the table that the foreign key references to.
* @param string $refColumns the name of the column that the foreign key references to. If there are multiple
* columns, separate them with commas.
* @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
* SET DEFAULT, SET NULL
* @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION,
* SET DEFAULT, SET NULL
*
* @return string the SQL statement for adding a foreign key constraint to an existing table.
*/
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
foreach ($columns as $i => $col) {
$columns[$i] = $this->quoteColumnName($col);
}
$refColumns = preg_split('/\s*,\s*/', $refColumns, -1, PREG_SPLIT_NO_EMPTY);
foreach ($refColumns as $i => $col) {
$refColumns[$i] = $this->quoteColumnName($col);
}
$sql =
'ALTER TABLE ' .
$this->quoteTableName($table) .
' ADD CONSTRAINT ' .
$this->quoteColumnName($name) .
' FOREIGN KEY (' .
implode(', ', $columns) .
')' .
' REFERENCES ' .
$this->quoteTableName($refTable) .
' (' .
implode(', ', $refColumns) .
')';
if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete;
}
if ($update !== null) {
$sql .= ' ON UPDATE ' . $update;
}
return $sql;
}
/**
* Builds a SQL statement for dropping a foreign key constraint.
*
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by
* the method.
* @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
*
* @return string the SQL statement for dropping a foreign key constraint.
*/
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP CONSTRAINT ' . $this->quoteColumnName($name);
}
/**
* @param bool $unique
* @param bool $on_create_table
*
* @return bool
*/
public function requiresCreateIndex($unique = false, $on_create_table = false)
{
return true;
}
/**
* @return bool
*/
public function allowsSeparateForeignConstraint()
{
return true;
}
/**
* Builds a SQL statement for creating a new index.
*
* @param string $name the name of the index. The name will be properly quoted by the method.
* @param string $table the table that the new index will be created for. The table name will be properly quoted
* by the method.
* @param string $column the column(s) that should be included in the index. If there are multiple columns, please
* separate them by commas. Each column name will be properly quoted by the method, unless a
* parenthesis is found in the name.
* @param boolean $unique whether to add UNIQUE constraint on the created index.
*
* @return string the SQL statement for creating a new index.
*/
public function createIndex($name, $table, $column, $unique = false)
{
$cols = [];
$columns = preg_split('/\s*,\s*/', $column, -1, PREG_SPLIT_NO_EMPTY);
foreach ($columns as $col) {
if (strpos($col, '(') !== false) {
$cols[] = $col;
} else {
$cols[] = $this->quoteColumnName($col);
}
}
return
($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
$this->quoteTableName($name) .
' ON ' .
$this->quoteTableName($table) .
' (' .
implode(', ', $cols) .
')';
}
/**
* Builds a SQL statement for dropping an index.
*
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
*
* @return string the SQL statement for dropping an index.
*/
public function dropIndex($name, $table)
{
return 'DROP INDEX ' . $this->quoteTableName($name) . ' ON ' . $this->quoteTableName($table);
}
/**
* Builds a SQL statement for adding a primary key constraint to an existing table.
*
* @param string $name the name of the primary key constraint.
* @param string $table the table that the primary key constraint will be added to.
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
* Array value can be passed.
*
* @return string the SQL statement for adding a primary key constraint to an existing table.
*/
public function addPrimaryKey($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->quoteColumnName($col);
}
return
'ALTER TABLE ' .
$this->quoteTableName($table) .
' ADD CONSTRAINT ' .
$this->quoteColumnName($name) .
' PRIMARY KEY (' .
implode(', ', $columns) .
' )';
}
/**
* Builds a SQL statement for removing a primary key constraint to an existing table.
*
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
*
* @return string the SQL statement for removing a primary key constraint from an existing table.
*/