/
Table.php
1979 lines (1748 loc) · 56 KB
/
Table.php
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
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
require_once dirname(__FILE__) . '/ScopedElement.php';
require_once dirname(__FILE__) . '/../exception/EngineException.php';
require_once dirname(__FILE__) . '/IDMethod.php';
require_once dirname(__FILE__) . '/NameFactory.php';
require_once dirname(__FILE__) . '/Column.php';
require_once dirname(__FILE__) . '/Unique.php';
require_once dirname(__FILE__) . '/ForeignKey.php';
require_once dirname(__FILE__) . '/IdMethodParameter.php';
require_once dirname(__FILE__) . '/Validator.php';
require_once dirname(__FILE__) . '/Behavior.php';
/**
* Data about a table used in an application.
*
* @author Hans Lellelid <hans@xmpl.org> (Propel)
* @author Leon Messerschmidt <leon@opticode.co.za> (Torque)
* @author Jason van Zyl <jvanzyl@apache.org> (Torque)
* @author Martin Poeschl <mpoeschl@marmot.at> (Torque)
* @author John McNally <jmcnally@collab.net> (Torque)
* @author Daniel Rall <dlr@collab.net> (Torque)
* @author Byron Foster <byron_foster@yahoo.com> (Torque)
* @version $Revision$
* @package propel.generator.model
*/
class Table extends ScopedElement implements IDMethod
{
/**
* Enables some debug printing.
*/
const DEBUG = false;
/**
* Columns for this table.
*
* @var array Column[]
*/
private $columnList = array();
/**
* Validators for this table.
*
* @var array Validator[]
*/
private $validatorList = array();
/**
* Foreign keys for this table.
*
* @var array ForeignKey[]
*/
private $foreignKeys = array();
/**
* Indexes for this table.
*
* @var array Index[]
*/
private $indices = array();
/**
* Unique indexes for this table.
*
* @var array Unique[]
*/
private $unices = array();
/**
* Any parameters for the ID method (currently supports changing sequence name).
*
* @var array
*/
private $idMethodParameters = array();
/**
* Table name (with prefix if it has one).
*
* @var string
*/
private $commonName;
/**
* Table name without prefix. Only used for phpName generation.
*
* @var string
*/
private $nonPrefixedName;
/**
* Table description.
*
* @var string
*/
private $description;
/**
* phpName for the table.
*
* @var string
*/
private $phpName;
/**
* ID method for the table (e.g. IDMethod::NATIVE, IDMethod::NONE).
*
* @var string
*/
private $idMethod;
/**
* Wether an INSERT with set PK is allowed on tables with IDMethod::NATIVE
*
* @var boolean
*/
private $allowPkInsert;
/**
* Strategry to use for converting column name to phpName.
*
* @var string
*/
private $phpNamingMethod;
/**
* The Database that this table belongs to.
*
* @var Database
*/
private $database;
/**
* Foreign Keys that refer to this table.
*
* @var array ForeignKey[]
*/
private $referrers = array();
/**
* Names of foreign tables.
*
* @var array string[]
*/
private $foreignTableNames;
/**
* Whether this table contains a foreign primary key.
*
* @var boolean
*/
private $containsForeignPK;
/**
* The inheritance column for this table (if any).
*
* @var Column
*/
private $inheritanceColumn;
/**
* Whether to skip generation of SQL for this table.
*
* @var boolean
*/
private $skipSql;
/**
* Whether this table is "read-only".
*
* @var boolean
*/
private $readOnly;
/**
* Whether this table should result in abstract OM classes.
*
* @var boolean
*/
private $abstractValue;
/**
* Whether this table is an alias for another table.
*
* @var string
*/
private $alias;
/**
* The interface that the generated "object" class should implement.
*
* @var string
*/
private $interface;
/**
* The base class to extend for the generated "object" class.
*
* @var string
*/
private $baseClass;
/**
* The base peer class to extend for generated "peer" class.
*
* @var string
*/
private $basePeer;
/**
* Map of columns by name.
*
* @var array
*/
private $columnsByName = array();
/**
* Map of columns by lowercase name.
*
* @var array
*/
private $columnsByLowercaseName = array();
/**
* Map of columns by phpName.
*
* @var array
*/
private $columnsByPhpName = array();
/**
* Whether this table needs to use transactions in Postgres.
*
* @var string
* @deprecated
*/
private $needsTransactionInPostgres;
/**
* Whether to perform additional indexing on this table.
*
* @var boolean
*/
private $heavyIndexing;
/**
* Whether this table is for reference only.
*
* @var boolean
*/
private $forReferenceOnly;
/**
* The tree mode (nested set, etc.) implemented by this table.
*
* @var string
*/
private $treeMode;
/**
* Whether to reload the rows in this table after insert.
*
* @var boolean
*/
private $reloadOnInsert;
/**
* Whether to reload the rows in this table after update.
*
* @var boolean
*/
private $reloadOnUpdate;
/**
* List of behaviors registered for this table
*
* @var array
*/
protected $behaviors = array();
/**
* Whether this table is a cross-reference table for a many-to-many relationship
*
* @var boolean
*/
protected $isCrossRef = false;
/**
* The default string format for objects based on this table
* (e.g. 'XML', 'YAML', 'CSV', 'JSON')
*
* @var string
*/
protected $defaultStringFormat;
/**
* Constructs a table object with a name
*
* @param string $name table name
*/
public function __construct($name = null)
{
$this->commonName = $name;
$this->nonPrefixedName = $name;
}
/**
* get a qualified name of this table with scheme and common name separated by '_'
* if schemaAutoPrefix is set. Otherwise get the common name.
* @return string
*/
private function getStdSeparatedName()
{
if ($this->schema && $this->getBuildProperty('schemaAutoPrefix')) {
return $this->schema . NameGenerator::STD_SEPARATOR_CHAR . $this->nonPrefixedName;
} else {
return $this->nonPrefixedName;
}
}
/**
* Sets up the Rule object based on the attributes that were passed to loadFromXML().
* @see parent::loadFromXML()
*/
public function setupObject()
{
parent::setupObject();
$this->commonName = $this->getDatabase()->getTablePrefix() . $this->getAttribute("name");
$this->nonPrefixedName = $this->getAttribute('name');
// retrieves the method for converting from specified name to a PHP name.
$this->phpNamingMethod = $this->getAttribute("phpNamingMethod", $this->getDatabase()->getDefaultPhpNamingMethod());
$this->phpName = $this->getAttribute("phpName", $this->buildPhpName($this->getStdSeparatedName()));
$this->idMethod = $this->getAttribute("idMethod", $this->getDatabase()->getDefaultIdMethod());
$this->allowPkInsert = $this->booleanValue($this->getAttribute("allowPkInsert"));
$this->skipSql = $this->booleanValue($this->getAttribute("skipSql"));
$this->readOnly = $this->booleanValue($this->getAttribute("readOnly"));
$this->abstractValue = $this->booleanValue($this->getAttribute("abstract"));
$this->baseClass = $this->getAttribute("baseClass");
$this->basePeer = $this->getAttribute("basePeer");
$this->alias = $this->getAttribute("alias");
$this->heavyIndexing = ( $this->booleanValue($this->getAttribute("heavyIndexing"))
|| ("false" !== $this->getAttribute("heavyIndexing")
&& $this->getDatabase()->isHeavyIndexing() ) );
$this->description = $this->getAttribute("description");
$this->interface = $this->getAttribute("interface"); // sic ('interface' is reserved word)
$this->treeMode = $this->getAttribute("treeMode");
$this->reloadOnInsert = $this->booleanValue($this->getAttribute("reloadOnInsert"));
$this->reloadOnUpdate = $this->booleanValue($this->getAttribute("reloadOnUpdate"));
$this->isCrossRef = $this->booleanValue($this->getAttribute("isCrossRef", false));
$this->defaultStringFormat = $this->getAttribute('defaultStringFormat');
}
/**
* get a build property for the database this table belongs to
*
* @param string $key key of the build property
* @return string value of the property
*/
public function getBuildProperty($key)
{
return $this->getDatabase() ? $this->getDatabase()->getBuildProperty($key) : '';
}
/**
* Execute behavior table modifiers
*/
public function applyBehaviors()
{
foreach ($this->getBehaviors() as $behavior) {
if (!$behavior->isTableModified()) {
$behavior->getTableModifier()->modifyTable();
$behavior->setTableModified(true);
}
}
}
/**
* <p>A hook for the SAX XML parser to call when this table has
* been fully loaded from the XML, and all nested elements have
* been processed.</p>
*
* <p>Performs heavy indexing and naming of elements which weren't
* provided with a name.</p>
*/
public function doFinalInitialization()
{
// Heavy indexing must wait until after all columns composing
// a table's primary key have been parsed.
if ($this->heavyIndexing) {
$this->doHeavyIndexing();
}
// Name any indices which are missing a name using the
// appropriate algorithm.
$this->doNaming();
// if idMethod is "native" and in fact there are no autoIncrement
// columns in the table, then change it to "none"
$anyAutoInc = false;
foreach ($this->getColumns() as $col) {
if ($col->isAutoIncrement()) {
$anyAutoInc = true;
}
}
if ($this->getIdMethod() === IDMethod::NATIVE && !$anyAutoInc) {
$this->setIdMethod(IDMethod::NO_ID_METHOD);
}
}
/**
* Adds extra indices for multi-part primary key columns.
*
* For databases like MySQL, values in a where clause much
* match key part order from the left to right. So, in the key
* definition <code>PRIMARY KEY (FOO_ID, BAR_ID)</code>,
* <code>FOO_ID</code> <i>must</i> be the first element used in
* the <code>where</code> clause of the SQL query used against
* this table for the primary key index to be used. This feature
* could cause problems under MySQL with heavily indexed tables,
* as MySQL currently only supports 16 indices per table (i.e. it
* might cause too many indices to be created).
*
* See the mysqm manual http://www.mysql.com/doc/E/X/EXPLAIN.html
* for a better description of why heavy indexing is useful for
* quickly searchable database tables.
*/
private function doHeavyIndexing()
{
if (self::DEBUG) {
print("doHeavyIndex() called on table " . $this->getName()."\n");
}
$pk = $this->getPrimaryKey();
$size = count($pk);
// We start at an offset of 1 because the entire column
// list is generally implicitly indexed by the fact that
// it's a primary key.
for ($i=1; $i < $size; $i++) {
$idx = new Index();
$idx->setColumns(array_slice($pk, $i, $size));
$this->addIndex($idx);
}
}
/**
* Adds extra indices for reverse foreign keys
* This is required for MySQL databases,
* and is called from Database::doFinalInitialization()
*/
public function addExtraIndices()
{
/**
* A collection of indexed columns. The keys is the column name
* (concatenated with a comma in the case of multi-col index), the value is
* an array with the names of the indexes that index these columns. We use
* it to determine which additional indexes must be created for foreign
* keys. It could also be used to detect duplicate indexes, but this is not
* implemented yet.
* @var array
*/
$_indices = array();
$this->collectIndexedColumns('PRIMARY', $this->getPrimaryKey(), $_indices);
$_tableIndices = array_merge($this->getIndices(), $this->getUnices());
foreach ($_tableIndices as $_index) {
$this->collectIndexedColumns($_index->getName(), $_index->getColumns(), $_indices);
}
// we're determining which tables have foreign keys that point to this table,
// since MySQL needs an index on any column that is referenced by another table
// (yep, MySQL _is_ a PITA)
$counter = 0;
foreach ($this->getReferrers() as $foreignKey) {
$referencedColumns = $foreignKey->getForeignColumnObjects();
$referencedColumnsHash = $this->getColumnList($referencedColumns);
if (!array_key_exists($referencedColumnsHash, $_indices)) {
// no matching index defined in the schema, so we have to create one
$index = new Index();
$index->setName(sprintf('I_referenced_%s_%s', $foreignKey->getName(), ++$counter));
$index->setColumns($referencedColumns);
$index->resetColumnSize();
$this->addIndex($index);
// Add this new index to our collection, otherwise we might add it again (bug #725)
$this->collectIndexedColumns($index->getName(), $referencedColumns, $_indices);
}
}
// we're adding indices for this table foreign keys
foreach ($this->getForeignKeys() as $foreignKey) {
$localColumns = $foreignKey->getLocalColumnObjects();
$localColumnsHash = $this->getColumnList($localColumns);
if (!array_key_exists($localColumnsHash, $_indices)) {
// no matching index defined in the schema, so we have to create one. MySQL needs indices on any columns that serve as foreign keys. these are not auto-created prior to 4.1.2
$index = new Index();
$index->setName(substr_replace($foreignKey->getName(), 'FI_', strrpos($foreignKey->getName(), 'FK_'), 3));
$index->setColumns($localColumns);
$index->resetColumnSize();
$this->addIndex($index);
$this->collectIndexedColumns($index->getName(), $localColumns, $_indices);
}
}
}
/**
* Helper function to collect indexed columns.
*
* @param string $indexName The name of the index
* @param array $columns The column names or objects
* @param array $collectedIndexes The collected indexes
*/
protected function collectIndexedColumns($indexName, $columns, &$collectedIndexes)
{
/**
* "If the table has a multiple-column index, any leftmost prefix of the
* index can be used by the optimizer to find rows. For example, if you
* have a three-column index on (col1, col2, col3), you have indexed search
* capabilities on (col1), (col1, col2), and (col1, col2, col3)."
* @link http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html
*/
$indexedColumns = array();
foreach ($columns as $column) {
$indexedColumns[] = $column;
$indexedColumnsHash = $this->getColumnList($indexedColumns);
if (!array_key_exists($indexedColumnsHash, $collectedIndexes)) {
$collectedIndexes[$indexedColumnsHash] = array();
}
$collectedIndexes[$indexedColumnsHash][] = $indexName;
}
}
/**
* Creates a delimiter-delimited string list of column names
*
* @see Platform::getColumnList() if quoting is required
* @param array Column[] or string[]
* @param string $delim The delimiter to use in separating the column names.
* @return string
*/
public function getColumnList($columns, $delim = ',')
{
$list = array();
foreach ($columns as $col) {
if ($col instanceof Column) {
$col = $col->getName();
}
$list[] = $col;
}
return implode($delim, $list);
}
/**
* Names composing objects which haven't yet been named. This
* currently consists of foreign-key and index entities.
*/
public function doNaming()
{
// Assure names are unique across all databases.
try {
for ($i=0, $size = count($this->foreignKeys); $i < $size; $i++) {
$fk = $this->foreignKeys[$i];
$name = $fk->getName();
if (empty($name)) {
$name = $this->acquireConstraintName("FK", $i + 1);
$fk->setName($name);
}
}
for ($i = 0, $size = count($this->indices); $i < $size; $i++) {
$index = $this->indices[$i];
$name = $index->getName();
if (empty($name)) {
$name = $this->acquireConstraintName("I", $i + 1);
$index->setName($name);
}
}
for ($i = 0, $size = count($this->unices); $i < $size; $i++) {
$index = $this->unices[$i];
$name = $index->getName();
if (empty($name)) {
$name = $this->acquireConstraintName("U", $i + 1);
$index->setName($name);
}
}
// NOTE: Most RDBMSes can apparently name unique column
// constraints/indices themselves (using MySQL and Oracle
// as test cases), so we'll assume that we needn't add an
// entry to the system name list for these.
} catch (EngineException $nameAlreadyInUse) {
print $nameAlreadyInUse->getMessage() . "\n";
print $nameAlreadyInUse->getTraceAsString();
}
}
/**
* Macro to a constraint name.
*
* @param nameType constraint type
* @param nbr unique number for this constraint type
* @return unique name for constraint
* @throws EngineException
*/
private function acquireConstraintName($nameType, $nbr)
{
$inputs = array();
$inputs[] = $this->getDatabase();
$inputs[] = $this->getCommonName();
$inputs[] = $nameType;
$inputs[] = $nbr;
return NameFactory::generateName(NameFactory::CONSTRAINT_GENERATOR, $inputs);
}
/**
* Gets the value of base class for classes produced from this table.
*
* @return The base class for classes produced from this table.
*/
public function getBaseClass()
{
if ($this->isAlias() && $this->baseClass === null) {
return $this->alias;
} elseif ($this->baseClass === null) {
return $this->getDatabase()->getBaseClass();
} else {
return $this->baseClass;
}
}
/**
* Set the value of baseClass.
* @param v Value to assign to baseClass.
*/
public function setBaseClass($v)
{
$this->baseClass = $v;
}
/**
* Get the value of basePeer.
* @return value of basePeer.
*/
public function getBasePeer()
{
if ($this->isAlias() && $this->basePeer === null) {
return $this->alias . "Peer";
} elseif ($this->basePeer === null) {
return $this->getDatabase()->getBasePeer();
} else {
return $this->basePeer;
}
}
/**
* Set the value of basePeer.
* @param v Value to assign to basePeer.
*/
public function setBasePeer($v)
{
$this->basePeer = $v;
}
/**
* A utility function to create a new column from attrib and add it to this
* table.
*
* @param Column|string $coldata xml attributes or Column class for the column to add
* @return Column the added column
* @throws EngineException
*/
public function addColumn($data)
{
if ($data instanceof Column) {
$col = $data;
if (isset($this->columnsByName[$col->getName()])) {
throw new EngineException(sprintf('Column "%s" declared twice in table "%s"', $col->getName(), $this->getName()));
}
$col->setTable($this);
if ($col->isInheritance()) {
$this->inheritanceColumn = $col;
}
if (isset($this->columnsByName[$col->getName()])) {
throw new EngineException('Duplicate column declared: ' . $col->getName());
}
$this->columnList[] = $col;
$this->columnsByName[$col->getName()] = $col;
$this->columnsByLowercaseName[strtolower($col->getName())] = $col;
$this->columnsByPhpName[$col->getPhpName()] = $col;
$col->setPosition(count($this->columnList));
$this->needsTransactionInPostgres |= $col->requiresTransactionInPostgres();
return $col;
} else {
$col = new Column();
$col->setTable($this);
$col->loadFromXML($data);
return $this->addColumn($col); // call self w/ different param
}
}
/**
* Removed a column from the table
* @param Column|string $col the column to remove
* @throws EngineException
*/
public function removeColumn($col)
{
if (is_string($col)) {
$col = $this->getColumn($col);
}
$pos = array_search($col, $this->columnList);
if (false === $pos) {
throw new EngineException(sprintf('No column named %s found in table %s', $col->getName(), $table->getName()));
}
unset($this->columnList[$pos]);
unset($this->columnsByName[$col->getName()]);
unset($this->columnsByLowercaseName[strtolower($col->getName())]);
unset($this->columnsByPhpName[$col->getPhpName()]);
$this->adjustColumnPositions();
// FIXME: also remove indexes and validators on this column?
}
public function adjustColumnPositions()
{
$this->columnList = array_values($this->columnList);
$columnCount = $this->getNumColumns();
for ($i=0; $i < $columnCount; $i++) {
$this->columnList[$i]->setPosition($i + 1);
}
}
/**
* Add a validator to this table.
*
* Supports two signatures:
* - addValidator(Validator $validator)
* - addValidator(array $attribs)
*
* @param mixed $data Validator object or XML attribs (array) from <validator /> element.
* @return Validator The added Validator.
* @throws EngineException
*/
public function addValidator($data)
{
if ($data instanceof Validator) {
$validator = $data;
$col = $this->getColumn($validator->getColumnName());
if ($col == null) {
throw new EngineException("Failed adding validator to table '" . $this->getName() .
"': column '" . $validator->getColumnName() . "' does not exist !");
}
$validator->setColumn($col);
$validator->setTable($this);
$this->validatorList[] = $validator;
return $validator;
} else {
$validator = new Validator();
$validator->setTable($this);
$validator->loadFromXML($data);
return $this->addValidator($validator);
}
}
/**
* Removes validators based on a column name
*
* @param string the name of the column bearing a validator
*/
public function removeValidatorForColumn($columnName)
{
foreach ($this->validatorList as $key => $validator) {
if ($validator->getColumnName() == $columnName) {
unset($this->validatorList[$key]);
}
}
}
/**
* A utility function to create a new foreign key
* from attrib and add it to this table.
*/
public function addForeignKey($fkdata)
{
if ($fkdata instanceof ForeignKey) {
$fk = $fkdata;
$fk->setTable($this);
$this->foreignKeys[] = $fk;
if ($this->foreignTableNames === null) {
$this->foreignTableNames = array();
}
if (!in_array($fk->getForeignTableName(), $this->foreignTableNames)) {
$this->foreignTableNames[] = $fk->getForeignTableName();
}
return $fk;
} else {
$fk = new ForeignKey();
$fk->setTable($this);
$fk->loadFromXML($fkdata);
return $this->addForeignKey($fk);
}
}
/**
* Gets the column that subclasses of the class representing this
* table can be produced from.
* @return Column
*/
public function getChildrenColumn()
{
return $this->inheritanceColumn;
}
/**
* Get the subclasses that can be created from this table.
* @return array string[] Class names
*/
public function getChildrenNames()
{
if ($this->inheritanceColumn === null
|| !$this->inheritanceColumn->isEnumeratedClasses()) {
return null;
}
$children = $this->inheritanceColumn->getChildren();
$names = array();
for ($i = 0, $size=count($children); $i < $size; $i++) {
$names[] = get_class($children[$i]);
}
return $names;
}
/**
* Adds the foreign key from another table that refers to this table.
*/
public function addReferrer(ForeignKey $fk)
{
if ($this->referrers === null) {
$this->referrers = array();
}
$this->referrers[] = $fk;
}
/**
* Get list of references to this table.
*/
public function getReferrers()
{
return $this->referrers;
}
/**
* Browses the foreign keys and creates referrers for the foreign table.
* This method can be called several times on the same table. It only
* adds the missing referrers and is non-destructive.
* Warning: only use when all the tables were created.
*/
public function setupReferrers($throwErrors = false)
{
foreach ($this->getForeignKeys() as $foreignKey) {
// table referrers
$foreignTable = $this->getDatabase()->getTable($foreignKey->getForeignTableName());
if ($foreignTable !== null) {
$referrers = $foreignTable->getReferrers();
if ($referrers === null || !in_array($foreignKey, $referrers, true) ) {
$foreignTable->addReferrer($foreignKey);
}
} elseif ($throwErrors) {
throw new BuildException(sprintf(
'Table "%s" contains a foreign key to nonexistent table "%s"',
$this->getName(),
$foreignKey->getForeignTableName()
));
}
// foreign pk's
$localColumnNames = $foreignKey->getLocalColumns();
foreach ($localColumnNames as $localColumnName) {
$localColumn = $this->getColumn($localColumnName);
if ($localColumn !== null) {
if ($localColumn->isPrimaryKey() && !$this->getContainsForeignPK()) {
$this->setContainsForeignPK(true);
}
} elseif ($throwErrors) {
// give notice of a schema inconsistency.
// note we do not prevent the npe as there is nothing
// that we can do, if it is to occur.
throw new BuildException(sprintf(
'Table "%s" contains a foreign key with nonexistent local column "%s"',
$this->getName(),
$localColumnName
));
}
}
// foreign column references
$foreignColumnNames = $foreignKey->getForeignColumns();
foreach ($foreignColumnNames as $foreignColumnName) {
if ($foreignTable === null) {
continue;
}
$foreignColumn = $foreignTable->getColumn($foreignColumnName);
if ($foreignColumn !== null) {
if (!$foreignColumn->hasReferrer($foreignKey)) {
$foreignColumn->addReferrer($foreignKey);
}
} elseif ($throwErrors) {
// if the foreign column does not exist, we may have an
// external reference or a misspelling
throw new BuildException(sprintf(
'Table "%s" contains a foreign key to table "%s" with nonexistent column "%s"',
$this->getName(),
$foreignTable->getName(),
$foreignColumnName
));
}
}
if ($this->getDatabase()->getPlatform() instanceof MysqlPLatform) {
$this->addExtraIndices();
}
} // foreach foreign keys
}
public function getCrossFks()
{
$crossFks = array();
foreach ($this->getReferrers() as $refFK) {
if ($refFK->getTable()->getIsCrossRef()) {
foreach ($refFK->getOtherFks() as $crossFK) {
$crossFks[]= array($refFK, $crossFK);
}
}
}
return $crossFks;
}
/**
* Set whether this table contains a foreign PK
*/
public function setContainsForeignPK($b)
{
$this->containsForeignPK = (boolean) $b;
}
/**
* Determine if this table contains a foreign PK
*/
public function getContainsForeignPK()
{
return $this->containsForeignPK;
}
/**
* A list of tables referenced by foreign keys in this table
*/
public function getForeignTableNames()
{
if ($this->foreignTableNames === null) {
$this->foreignTableNames = array();
}
return $this->foreignTableNames;
}
/**
* Return true if the column requires a transaction in Postgres
*/
public function requiresTransactionInPostgres()
{
return $this->needsTransactionInPostgres;
}