-
Notifications
You must be signed in to change notification settings - Fork 25
/
TDBMService.php
1544 lines (1348 loc) · 61.7 KB
/
TDBMService.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
/*
Copyright (C) 2006-2016 David Négrier - THE CODING MACHINE
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
namespace Mouf\Database\TDBM;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\VoidCache;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
use Mouf\Database\MagicQuery;
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
use Mouf\Database\TDBM\Utils\TDBMDaoGenerator;
/**
* The TDBMService class is the main TDBM class. It provides methods to retrieve TDBMObject instances
* from the database.
*
* @author David Negrier
* @ExtendedAction {"name":"Generate DAOs", "url":"tdbmadmin/", "default":false}
*/
class TDBMService
{
const MODE_CURSOR = 1;
const MODE_ARRAY = 2;
/**
* The database connection.
*
* @var Connection
*/
private $connection;
/**
* @var SchemaAnalyzer
*/
private $schemaAnalyzer;
/**
* @var MagicQuery
*/
private $magicQuery;
/**
* @var TDBMSchemaAnalyzer
*/
private $tdbmSchemaAnalyzer;
/**
* @var string
*/
private $cachePrefix;
/**
* Cache of table of primary keys.
* Primary keys are stored by tables, as an array of column.
* For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
*
* @var string[]
*/
private $primaryKeysColumns;
/**
* Service storing objects in memory.
* Access is done by table name and then by primary key.
* If the primary key is split on several columns, access is done by an array of columns, serialized.
*
* @var StandardObjectStorage|WeakrefObjectStorage
*/
private $objectStorage;
/**
* The fetch mode of the result sets returned by `getObjects`.
* Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
*
* In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
* In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
* and it cannot be accessed via key. Use this mode for large datasets processed by batch.
* In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
* You can access the array by key, or using foreach, several times.
*
* @var int
*/
private $mode = self::MODE_ARRAY;
/**
* Table of new objects not yet inserted in database or objects modified that must be saved.
*
* @var \SplObjectStorage of DbRow objects
*/
private $toSaveObjects;
/**
* The content of the cache variable.
*
* @var array<string, mixed>
*/
private $cache;
/**
* Map associating a table name to a fully qualified Bean class name.
*
* @var array
*/
private $tableToBeanMap = [];
/**
* @var \ReflectionClass[]
*/
private $reflectionClassCache = array();
/**
* @param Connection $connection The DBAL DB connection to use
* @param Cache|null $cache A cache service to be used
* @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
* Will be automatically created if not passed.
*/
public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null)
{
if (extension_loaded('weakref')) {
$this->objectStorage = new WeakrefObjectStorage();
} else {
$this->objectStorage = new StandardObjectStorage();
}
$this->connection = $connection;
if ($cache !== null) {
$this->cache = $cache;
} else {
$this->cache = new VoidCache();
}
if ($schemaAnalyzer) {
$this->schemaAnalyzer = $schemaAnalyzer;
} else {
$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
}
$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
$this->toSaveObjects = new \SplObjectStorage();
}
/**
* Returns the object used to connect to the database.
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Creates a unique cache key for the current connection.
*
* @return string
*/
private function getConnectionUniqueId()
{
return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
}
/**
* Sets the default fetch mode of the result sets returned by `findObjects`.
* Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
*
* In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
* In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
* several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
*
* @param int $mode
*
* @return $this
*
* @throws TDBMException
*/
public function setFetchMode($mode)
{
if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
}
$this->mode = $mode;
return $this;
}
/**
* Returns a TDBMObject associated from table "$table_name".
* If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
* $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
*
* For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
* $user = $tdbmService->getObject('users',1);
* echo $user->name;
* will return the name of the user whose user_id is one.
*
* If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
* For instance:
* $group = $tdbmService->getObject('groups',array(1,2));
*
* Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
* will be the same.
*
* For instance:
* $user1 = $tdbmService->getObject('users',1);
* $user2 = $tdbmService->getObject('users',1);
* $user1->name = 'John Doe';
* echo $user2->name;
* will return 'John Doe'.
*
* You can use filters instead of passing the primary key. For instance:
* $user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
* This will return the user whose login is 'jdoe'.
* Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
*
* Also, you can specify the return class for the object (provided the return class extends TDBMObject).
* For instance:
* $user = $tdbmService->getObject('users',1,'User');
* will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
* Please be sure not to override any method or any property unless you perfectly know what you are doing!
*
* @param string $table_name The name of the table we retrieve an object from.
* @param mixed $filters If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
* @param string $className Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned.
* @param bool $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown.
*
* @return TDBMObject
*/
/* public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
if (is_array($filters) || $filters instanceof FilterInterface) {
$isFilterBag = false;
if (is_array($filters)) {
// Is this a multiple primary key or a filter bag?
// Let's have a look at the first item of the array to decide.
foreach ($filters as $filter) {
if (is_array($filter) || $filter instanceof FilterInterface) {
$isFilterBag = true;
}
break;
}
} else {
$isFilterBag = true;
}
if ($isFilterBag == true) {
// If a filter bag was passer in parameter, let's perform a findObjects.
$objects = $this->findObjects($table_name, $filters, null, null, null, $className);
if (count($objects) == 0) {
return null;
} elseif (count($objects) > 1) {
throw new DuplicateRowException("Error while querying an object for table '$table_name': ".count($objects)." rows have been returned, but we should have received at most one.");
}
// Return the first and only object.
if ($objects instanceof \Generator) {
return $objects->current();
} else {
return $objects[0];
}
}
}
$id = $filters;
if ($this->connection == null) {
throw new TDBMException("Error while calling TdbmService->getObject(): No connection has been established on the database!");
}
$table_name = $this->connection->toStandardcase($table_name);
// If the ID is null, let's throw an exception
if ($id === null) {
throw new TDBMException("The ID you passed to TdbmService->getObject is null for the object of type '$table_name'. Objects primary keys cannot be null.");
}
// If the primary key is split over many columns, the IDs are passed in an array. Let's serialize this array to store it.
if (is_array($id)) {
$id = serialize($id);
}
if ($className === null) {
if (isset($this->tableToBeanMap[$table_name])) {
$className = $this->tableToBeanMap[$table_name];
} else {
$className = "Mouf\\Database\\TDBM\\TDBMObject";
}
}
if ($this->objectStorage->has($table_name, $id)) {
$obj = $this->objectStorage->get($table_name, $id);
if (is_a($obj, $className)) {
return $obj;
} else {
throw new TDBMException("Error! The object with ID '$id' for table '$table_name' has already been retrieved. The type for this object is '".get_class($obj)."'' which is not a subtype of '$className'");
}
}
if ($className != "Mouf\\Database\\TDBM\\TDBMObject" && !is_subclass_of($className, "Mouf\\Database\\TDBM\\TDBMObject")) {
if (!class_exists($className)) {
throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." does not exist.");
} else {
throw new TDBMException("Error while calling TDBMService->getObject: The class ".$className." should extend TDBMObject.");
}
}
$obj = new $className($this, $table_name, $id);
if ($lazy_loading == false) {
// If we are not doing lazy loading, let's load the object:
$obj->_dbLoadIfNotLoaded();
}
$this->objectStorage->set($table_name, $id, $obj);
return $obj;
}*/
/**
* Removes the given object from database.
* This cannot be called on an object that is not attached to this TDBMService
* (will throw a TDBMInvalidOperationException).
*
* @param AbstractTDBMObject $object the object to delete.
*
* @throws TDBMException
* @throws TDBMInvalidOperationException
*/
public function delete(AbstractTDBMObject $object)
{
switch ($object->_getStatus()) {
case TDBMObjectStateEnum::STATE_DELETED:
// Nothing to do, object already deleted.
return;
case TDBMObjectStateEnum::STATE_DETACHED:
throw new TDBMInvalidOperationException('Cannot delete a detached object');
case TDBMObjectStateEnum::STATE_NEW:
$this->deleteManyToManyRelationships($object);
foreach ($object->_getDbRows() as $dbRow) {
$this->removeFromToSaveObjectList($dbRow);
}
break;
case TDBMObjectStateEnum::STATE_DIRTY:
foreach ($object->_getDbRows() as $dbRow) {
$this->removeFromToSaveObjectList($dbRow);
}
// And continue deleting...
case TDBMObjectStateEnum::STATE_NOT_LOADED:
case TDBMObjectStateEnum::STATE_LOADED:
$this->deleteManyToManyRelationships($object);
// Let's delete db rows, in reverse order.
foreach (array_reverse($object->_getDbRows()) as $dbRow) {
$tableName = $dbRow->_getDbTableName();
$primaryKeys = $dbRow->_getPrimaryKeys();
$this->connection->delete($tableName, $primaryKeys);
$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
}
break;
// @codeCoverageIgnoreStart
default:
throw new TDBMInvalidOperationException('Unexpected status for bean');
// @codeCoverageIgnoreEnd
}
$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
}
/**
* Removes all many to many relationships for this object.
*
* @param AbstractTDBMObject $object
*/
private function deleteManyToManyRelationships(AbstractTDBMObject $object)
{
foreach ($object->_getDbRows() as $tableName => $dbRow) {
$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
foreach ($pivotTables as $pivotTable) {
$remoteBeans = $object->_getRelationships($pivotTable);
foreach ($remoteBeans as $remoteBean) {
$object->_removeRelationship($pivotTable, $remoteBean);
}
}
}
$this->persistManyToManyRelationships($object);
}
/**
* This function removes the given object from the database. It will also remove all objects relied to the one given
* by parameter before all.
*
* Notice: if the object has a multiple primary key, the function will not work.
*
* @param AbstractTDBMObject $objToDelete
*/
public function deleteCascade(AbstractTDBMObject $objToDelete)
{
$this->deleteAllConstraintWithThisObject($objToDelete);
$this->delete($objToDelete);
}
/**
* This function is used only in TDBMService (private function)
* It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
*
* @param AbstractTDBMObject $obj
*/
private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
{
$dbRows = $obj->_getDbRows();
foreach ($dbRows as $dbRow) {
$tableName = $dbRow->_getDbTableName();
$pks = array_values($dbRow->_getPrimaryKeys());
if (!empty($pks)) {
$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
foreach ($incomingFks as $incomingFk) {
$filter = array_combine($incomingFk->getLocalColumns(), $pks);
$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
foreach ($results as $bean) {
$this->deleteCascade($bean);
}
}
}
}
}
/**
* This function performs a save() of all the objects that have been modified.
*/
public function completeSave()
{
foreach ($this->toSaveObjects as $dbRow) {
$this->save($dbRow->getTDBMObject());
}
}
/**
* Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
* and gives back a proper Filter object.
*
* @param mixed $filter_bag
* @param int $counter
*
* @return array First item: filter string, second item: parameters.
*
* @throws TDBMException
*/
public function buildFilterFromFilterBag($filter_bag, $counter = 1)
{
if ($filter_bag === null) {
return ['', []];
} elseif (is_string($filter_bag)) {
return [$filter_bag, []];
} elseif (is_array($filter_bag)) {
$sqlParts = [];
$parameters = [];
foreach ($filter_bag as $column => $value) {
if (is_int($column)) {
list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
$sqlParts[] = $subSqlPart;
$parameters += $subParameters;
} else {
$paramName = 'tdbmparam'.$counter;
if (is_array($value)) {
$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
} else {
$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
}
$parameters[$paramName] = $value;
++$counter;
}
}
return [implode(' AND ', $sqlParts), $parameters];
} elseif ($filter_bag instanceof AbstractTDBMObject) {
$sqlParts = [];
$parameters = [];
$dbRows = $filter_bag->_getDbRows();
$dbRow = reset($dbRows);
$primaryKeys = $dbRow->_getPrimaryKeys();
foreach ($primaryKeys as $column => $value) {
$paramName = 'tdbmparam'.$counter;
$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
$parameters[$paramName] = $value;
++$counter;
}
return [implode(' AND ', $sqlParts), $parameters];
} elseif ($filter_bag instanceof \Iterator) {
return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
} else {
throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
}
}
/**
* @param string $table
*
* @return string[]
*/
public function getPrimaryKeyColumns($table)
{
if (!isset($this->primaryKeysColumns[$table])) {
$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
/*$arr = array();
foreach ($this->connection->getPrimaryKey($table) as $col) {
$arr[] = $col->name;
}
// The primaryKeysColumns contains only the column's name, not the DB_Column object.
$this->primaryKeysColumns[$table] = $arr;
if (empty($this->primaryKeysColumns[$table]))
{
// Unable to find primary key.... this is an error
// Let's try to be precise in error reporting. Let's try to find the table.
$tables = $this->connection->checkTableExist($table);
if ($tables === true)
throw new TDBMException("Could not find table primary key for table '$table'. Please define a primary key for this table.");
elseif ($tables !== null) {
if (count($tables)==1)
$str = "Could not find table '$table'. Maybe you meant this table: '".$tables[0]."'";
else
$str = "Could not find table '$table'. Maybe you meant one of those tables: '".implode("', '",$tables)."'";
throw new TDBMException($str);
}
}*/
}
return $this->primaryKeysColumns[$table];
}
/**
* This is an internal function, you should not use it in your application.
* This is used internally by TDBM to add an object to the object cache.
*
* @param DbRow $dbRow
*/
public function _addToCache(DbRow $dbRow)
{
$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
$hash = $this->getObjectHash($primaryKey);
$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
}
/**
* This is an internal function, you should not use it in your application.
* This is used internally by TDBM to remove the object from the list of objects that have been
* created/updated but not saved yet.
*
* @param DbRow $myObject
*/
private function removeFromToSaveObjectList(DbRow $myObject)
{
unset($this->toSaveObjects[$myObject]);
}
/**
* This is an internal function, you should not use it in your application.
* This is used internally by TDBM to add an object to the list of objects that have been
* created/updated but not saved yet.
*
* @param AbstractTDBMObject $myObject
*/
public function _addToToSaveObjectList(DbRow $myObject)
{
$this->toSaveObjects[$myObject] = true;
}
/**
* Generates all the daos and beans.
*
* @param string $daoFactoryClassName The classe name of the DAO factory
* @param string $daonamespace The namespace for the DAOs, without trailing \
* @param string $beannamespace The Namespace for the beans, without trailing \
* @param bool $storeInUtc If the generated daos should store the date in UTC timezone instead of user's timezone.
* @param string $composerFile If it's set, location of custom Composer file. Relative to project root.
*
* @return \string[] the list of tables
*/
public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
{
// Purge cache before generating anything.
$this->cache->deleteAll();
$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
if (null !== $composerFile) {
$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
}
return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
}
/**
* @param array<string, string> $tableToBeanMap
*/
public function setTableToBeanMap(array $tableToBeanMap)
{
$this->tableToBeanMap = $tableToBeanMap;
}
/**
* Saves $object by INSERTing or UPDAT(E)ing it in the database.
*
* @param AbstractTDBMObject $object
*
* @throws TDBMException
*/
public function save(AbstractTDBMObject $object)
{
$status = $object->_getStatus();
// Let's attach this object if it is in detached state.
if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
$object->_attach($this);
$status = $object->_getStatus();
}
if ($status === TDBMObjectStateEnum::STATE_NEW) {
$dbRows = $object->_getDbRows();
$unindexedPrimaryKeys = array();
foreach ($dbRows as $dbRow) {
$tableName = $dbRow->_getDbTableName();
$schema = $this->tdbmSchemaAnalyzer->getSchema();
$tableDescriptor = $schema->getTable($tableName);
$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
if (empty($unindexedPrimaryKeys)) {
$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
} else {
// First insert, the children must have the same primary key as the parent.
$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
$dbRow->_setPrimaryKeys($primaryKeys);
}
$references = $dbRow->_getReferences();
// Let's save all references in NEW or DETACHED state (we need their primary key)
foreach ($references as $fkName => $reference) {
$refStatus = $reference->_getStatus();
if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
$this->save($reference);
}
}
$dbRowData = $dbRow->_getDbRow();
// Let's see if the columns for primary key have been set before inserting.
// We assume that if one of the value of the PK has been set, the PK is set.
$isPkSet = !empty($primaryKeys);
/*if (!$isPkSet) {
// if there is no autoincrement and no pk set, let's go in error.
$isAutoIncrement = true;
foreach ($primaryKeyColumns as $pkColumnName) {
$pkColumn = $tableDescriptor->getColumn($pkColumnName);
if (!$pkColumn->getAutoincrement()) {
$isAutoIncrement = false;
}
}
if (!$isAutoIncrement) {
$msg = "Error! You did not set the primary key(s) for the new object of type '$tableName'. The primary key is not set to 'autoincrement' so you must either set the primary key in the object or modify the DB model to create an primary key with auto-increment.";
throw new TDBMException($msg);
}
}*/
$types = [];
foreach ($dbRowData as $columnName => $value) {
$columnDescriptor = $tableDescriptor->getColumn($columnName);
$types[] = $columnDescriptor->getType();
}
$this->connection->insert($tableName, $dbRowData, $types);
if (!$isPkSet && count($primaryKeyColumns) == 1) {
$id = $this->connection->lastInsertId();
$primaryKeys[$primaryKeyColumns[0]] = $id;
}
// TODO: change this to some private magic accessor in future
$dbRow->_setPrimaryKeys($primaryKeys);
$unindexedPrimaryKeys = array_values($primaryKeys);
/*
* When attached, on "save", we check if the column updated is part of a primary key
* If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
* This method should first verify that the id is not already used (and is not auto-incremented)
*
* In the object, the key is stored in an array of (column => value), that can be directly used to update the record.
*
*
*/
/*try {
$this->db_connection->exec($sql);
} catch (TDBMException $e) {
$this->db_onerror = true;
// Strange..... if we do not have the line below, bad inserts are not catched.
// It seems that destructors are called before the registered shutdown function (PHP >=5.0.5)
//if ($this->tdbmService->isProgramExiting())
// trigger_error("program exiting");
trigger_error($e->getMessage(), E_USER_ERROR);
if (!$this->tdbmService->isProgramExiting())
throw $e;
else
{
trigger_error($e->getMessage(), E_USER_ERROR);
}
}*/
// Let's remove this object from the $new_objects static table.
$this->removeFromToSaveObjectList($dbRow);
// TODO: change this behaviour to something more sensible performance-wise
// Maybe a setting to trigger this globally?
//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
//$this->db_modified_state = false;
//$dbRow = array();
// Let's add this object to the list of objects in cache.
$this->_addToCache($dbRow);
}
$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
$dbRows = $object->_getDbRows();
foreach ($dbRows as $dbRow) {
$references = $dbRow->_getReferences();
// Let's save all references in NEW state (we need their primary key)
foreach ($references as $fkName => $reference) {
if ($reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
$this->save($reference);
}
}
// Let's first get the primary keys
$tableName = $dbRow->_getDbTableName();
$dbRowData = $dbRow->_getDbRow();
$schema = $this->tdbmSchemaAnalyzer->getSchema();
$tableDescriptor = $schema->getTable($tableName);
$primaryKeys = $dbRow->_getPrimaryKeys();
$types = [];
foreach ($dbRowData as $columnName => $value) {
$columnDescriptor = $tableDescriptor->getColumn($columnName);
$types[] = $columnDescriptor->getType();
}
foreach ($primaryKeys as $columnName => $value) {
$columnDescriptor = $tableDescriptor->getColumn($columnName);
$types[] = $columnDescriptor->getType();
}
$this->connection->update($tableName, $dbRowData, $primaryKeys, $types);
// Let's check if the primary key has been updated...
$needsUpdatePk = false;
foreach ($primaryKeys as $column => $value) {
if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
$needsUpdatePk = true;
break;
}
}
if ($needsUpdatePk) {
$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
$dbRow->_setPrimaryKeys($newPrimaryKeys);
$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
}
// Let's remove this object from the list of objects to save.
$this->removeFromToSaveObjectList($dbRow);
}
$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
}
// Finally, let's save all the many to many relationships to this bean.
$this->persistManyToManyRelationships($object);
}
private function persistManyToManyRelationships(AbstractTDBMObject $object)
{
foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
foreach ($storage as $remoteBean) {
/* @var $remoteBean AbstractTDBMObject */
$statusArr = $storage[$remoteBean];
$status = $statusArr['status'];
$reverse = $statusArr['reverse'];
if ($reverse) {
continue;
}
if ($status === 'new') {
$remoteBeanStatus = $remoteBean->_getStatus();
if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
// Let's save remote bean if needed.
$this->save($remoteBean);
}
$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
$types = [];
foreach ($filters as $columnName => $value) {
$columnDescriptor = $tableDescriptor->getColumn($columnName);
$types[] = $columnDescriptor->getType();
}
$this->connection->insert($pivotTableName, $filters, $types);
// Finally, let's mark relationships as saved.
$statusArr['status'] = 'loaded';
$storage[$remoteBean] = $statusArr;
$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
$remoteStatusArr = $remoteStorage[$object];
$remoteStatusArr['status'] = 'loaded';
$remoteStorage[$object] = $remoteStatusArr;
} elseif ($status === 'delete') {
$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
$types = [];
foreach ($filters as $columnName => $value) {
$columnDescriptor = $tableDescriptor->getColumn($columnName);
$types[] = $columnDescriptor->getType();
}
$this->connection->delete($pivotTableName, $filters, $types);
// Finally, let's remove relationships completely from bean.
$storage->detach($remoteBean);
$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
}
}
}
}
private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
{
$localBeanPk = $this->getPrimaryKeyValues($localBean);
$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
$localColumns = $localFk->getLocalColumns();
$remoteColumns = $remoteFk->getLocalColumns();
$localFilters = array_combine($localColumns, $localBeanPk);
$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
return array_merge($localFilters, $remoteFilters);
}
/**
* Returns the "values" of the primary key.
* This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
*
* @param AbstractTDBMObject $bean
*
* @return array numerically indexed array of values.
*/
private function getPrimaryKeyValues(AbstractTDBMObject $bean)
{
$dbRows = $bean->_getDbRows();
$dbRow = reset($dbRows);
return array_values($dbRow->_getPrimaryKeys());
}
/**
* Returns a unique hash used to store the object based on its primary key.
* If the array contains only one value, then the value is returned.
* Otherwise, a hash representing the array is returned.
*
* @param array $primaryKeys An array of columns => values forming the primary key
*
* @return string
*/
public function getObjectHash(array $primaryKeys)
{
if (count($primaryKeys) === 1) {
return reset($primaryKeys);
} else {
ksort($primaryKeys);
return md5(json_encode($primaryKeys));
}
}
/**
* Returns an array of primary keys from the object.
* The primary keys are extracted from the object columns and not from the primary keys stored in the
* $primaryKeys variable of the object.
*
* @param DbRow $dbRow
*
* @return array Returns an array of column => value
*/
public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
{
$table = $dbRow->_getDbTableName();
$dbRowData = $dbRow->_getDbRow();
return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
}
/**
* Returns an array of primary keys for the given row.
* The primary keys are extracted from the object columns.
*
* @param $table
* @param array $columns
*
* @return array
*/
public function _getPrimaryKeysFromObjectData($table, array $columns)
{
$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
$values = array();
foreach ($primaryKeyColumns as $column) {
if (isset($columns[$column])) {
$values[$column] = $columns[$column];
}
}
return $values;
}
/**
* Attaches $object to this TDBMService.
* The $object must be in DETACHED state and will pass in NEW state.
*
* @param AbstractTDBMObject $object
*
* @throws TDBMInvalidOperationException
*/
public function attach(AbstractTDBMObject $object)
{
$object->_attach($this);
}
/**
* Returns an associative array (column => value) for the primary keys from the table name and an
* indexed array of primary key values.
*
* @param string $tableName
* @param array $indexedPrimaryKeys
*/
public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
{
$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
}
return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
}
/**
* Return the list of tables (from child to parent) joining the tables passed in parameter.