-
Notifications
You must be signed in to change notification settings - Fork 25
/
TDBMService.php
1871 lines (1664 loc) · 72.5 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-2014 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 Mouf\Database\TDBM\Filters\InFilter;
use Mouf\Database\TDBM\Filters\OrderBySQLString;
use Mouf\Database\TDBM\Filters\EqualFilter;
use Mouf\Database\TDBM\Filters\SqlStringFilter;
use Mouf\Database\TDBM\Filters\AndFilter;
use Mouf\Database\DBConnection\CachedConnection;
use Mouf\Utils\Cache\CacheInterface;
use Mouf\Database\TDBM\Filters\FilterInterface;
use Mouf\Database\DBConnection\ConnectionInterface;
use Mouf\Database\DBConnection\DBConnectionException;
use Mouf\Database\TDBM\Filters\OrFilter;
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;
const MODE_COMPATIBLE_ARRAY = 3;
/**
* The database connection.
*
* @var ConnectionInterface
*/
public $dbConnection;
/**
* The cache service to cache data.
*
* @var CacheInterface
*/
public $cacheService;
/**
* The default autosave mode for the objects
* True to automatically save the object.
* If false, the user must explicitly call the save() method to save the object.
*
* @var boolean
*/
private $autosave_default = false;
/**
* If TDBM objects are modified, and if they are not saved, they will automatically be saved at the end of the script.
* Of course, if a transaction has been started, and is not ended, at the end of the script, it is likely that the
* transaction will roll-back and that the changes will be lost.
* If commitOnQuit is set to "true", a commit will always be performed at the end of the script.
* This is a dangerous parameter. Indeed, in case of error, it might commit data that would have otherwised been roll-back.
* Use it sparesly.
*
* @var boolean
*/
private $commitOnQuit = false;
/**
* 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 array
*/
private $primary_keys;
/**
* Whether we should track execution time or not.
* If true, if the execution time reaches 90% of the allowed execution time, the request will stop with an exception.
*
* @var bool
*/
private $trackExecutionTime = true;
/**
* 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.
private $tosave_objects;
/// Table of constraints that that table applies on another table n the form [this table][this column]=XXX
//private $external_constraint;
/// The timestamp of the script startup. Useful to stop execution before time limit is reached and display useful error message.
public static $script_start_up_time;
/// True if the program is exiting (we are in the "exit" statement). False otherwise.
private $is_program_exiting = false;
/**
* The content of the cache variable.
*
* @var array<string, mixed>
*/
private $cache;
private $cacheKey = "__TDBM_Cache__";
/**
* Map associating a table name to a fully qualified Bean class name
* @var array
*/
private $tableToBeanMap = [];
public function __construct() {
register_shutdown_function(array($this,"completeSaveOnExit"));
if (extension_loaded('weakref')) {
$this->objectStorage = new WeakrefObjectStorage();
} else {
$this->objectStorage = new StandardObjectStorage();
}
}
/**
* Sets up the default connection to the database.
* The parameters of TDBMService::setConnection are similar to the parameters used by PEAR DB (since TDBMObject relies on PEAR DB).
* TODO: CORRECT THE DOC!!!!
* For instance:
* TDBMObject::setConnection(array(
* 'phptype' => 'pgsql',
* 'username' => 'my_user',
* 'password' => 'my_password',
* 'hostspec' => 'ip_of_my_database_server',
* 'database' => 'name_of_my_base'
* ));
*
* where phptype is the type of database supported (currently can be only 'pgsql' for PostGreSQL)
* username is the name of your database user
* password is the password of your rdatabase user
* hostspec is the IP of your database server (very likely, it will be 'localhost' for you)
* database is the name of your database
*
* @Compulsory
* @param ConnectionInterface $connection
*/
public function setConnection(ConnectionInterface $connection) {
if ($this->cacheService != null && !($connection instanceof CachedConnection)) {
$cachedConnection = new CachedConnection();
$cachedConnection->dbConnection = $connection;
$cachedConnection->cacheService = $this->cacheService;
$this->dbConnection = $cachedConnection;
} else {
$this->dbConnection = $connection;
}
}
/**
* Returns the object used to connect to the database.
*
* @return ConnectionInterface
*/
public function getConnection() {
return $this->dbConnection;
}
/**
* Sets the cache service.
* The cache service is used to store the structure of the database in cache, which will dramatically improve performances.
* The cache service will also wrap the database connection into a cached connection.
*
* @Compulsory
* @param CacheInterface $cacheService
*/
public function setCacheService(CacheInterface $cacheService) {
$this->cacheService = $cacheService;
if ($this->dbConnection != null && !($this->dbConnection instanceof CachedConnection)) {
$cachedConnection = new CachedConnection();
$cachedConnection->dbConnection = $this->dbConnection;
$cachedConnection->cacheService = $this->cacheService;
$this->dbConnection = $cachedConnection;
}
}
/**
* Returns true if the objects will save automatically by default,
* false if an explicit call to save() is required.
*
* The behaviour can be overloaded by setAutoSaveMode on each object.
*
* @return boolean
*/
public function getDefaultAutoSaveMode() {
return $this->autosave_default;
}
/**
* Sets the autosave mode:
* true if the object will save automatically,
* false if an explicit call to save() is required.
*
* @Compulsory
* @param boolean $autoSave
*/
public function setDefaultAutoSaveMode($autoSave = true) {
$this->autosave_default = $autoSave;
}
/**
* If TDBM objects are modified, and if they are not saved, they will automatically be saved at the end of the script.
* Of course, if a transaction has been started, and is not ended, at the end of the script, it is likely that the
* transaction will roll-back and that the changes will be lost.
* If commitOnQuit is set to "true", a commit will always be performed at the end of the script.
* This is a dangerous parameter. Indeed, in case of error, it might commit data that would have otherwised been roll-back.
* Use it sparesly.
*
* @Compulsory
* @param boolean $commitOnQuit
*/
public function setCommitOnQuit($commitOnQuit) {
$this->commitOnQuit = $commitOnQuit;
}
/**
* Sets 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 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.
*
* @param int $mode
*/
public function setFetchMode($mode) {
$this->mode = $mode;
return $this;
}
/**
* Whether we should track execution time or not.
* If true, if the execution time reaches 90% of the allowed execution time, the request will stop with an exception.
*
* @param boolean $trackExecutionTime
*/
public function setTrackExecutionTime($trackExecutionTime = true) {
$this->trackExecutionTime = $trackExecutionTime;
}
/**
* Loads the cache and stores it (to be reused in this instance).
* Note: the cache is not returned. It is stored in the $cache instance variable.
*/
private function loadCache() {
if ($this->cache == null) {
if ($this->cacheService == null) {
throw new TDBMException("A cache service must be explicitly bound to the TDBM Service. Please configure your instance of TDBM Service.");
}
$this->cache = $this->cacheService->get($this->cacheKey);
}
}
/**
* Saves the cache.
*
*/
private function saveCache() {
$this->cacheService->set($this->cacheKey, $this->cache);
}
/**
* 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 getObjects 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 getObjects 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 boolean $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 getObjects.
$objects = $this->getObjects($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->dbConnection == null) {
throw new TDBMException("Error while calling TdbmService->getObject(): No connection has been established on the database!");
}
$table_name = $this->dbConnection->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;
}
/**
* Creates a new object that will be stored in table "table_name".
* If $auto_assign_id is true, the primary key of the object will be automatically be filled.
* Otherwise, the database system or the user will have to fill it itself (for exemple with
* AUTOINCREMENT in MySQL or with a sequence in POSTGRESQL).
* Please note that $auto_assign_id parameter is ignored if the primary key is autoincremented (MySQL only)
* Also, please note that $auto_assign_id does not work on tables that have primary keys on multiple
* columns.
*
* @param string $table_name
* @param boolean $auto_assign_id
* @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.
* @return TDBMObject
*/
public function getNewObject($table_name, $auto_assign_id=true, $className = null) {
if ($this->dbConnection == null) {
throw new TDBMException("Error while calling TDBMObject::getNewObject(): No connection has been established on the database!");
}
$table_name = $this->dbConnection->toStandardcase($table_name);
// Ok, let's verify that the table does exist:
try {
/*$data =*/ $this->dbConnection->getTableInfo($table_name);
} catch (TDBMException $exception) {
$probable_table_name = $this->dbConnection->checkTableExist($table_name);
if ($probable_table_name == null)
throw new TDBMException("Error while calling TDBMObject::getNewObject(): The table named '$table_name' does not exist.");
else
throw new TDBMException("Error while calling TDBMObject::getNewObject(): The table named '$table_name' does not exist. Maybe you meant the table '$probable_table_name'.");
}
if ($className === null) {
if (isset($this->tableToBeanMap[$table_name])) {
$className = $this->tableToBeanMap[$table_name];
} else {
$className = "Mouf\\Database\\TDBM\\TDBMObject";
}
}
if (!is_string($className)) {
throw new TDBMException("Error while calling TDBMObject::getNewObject(): The third parameter should be a string representing a class name to instantiate.");
}
if (!is_a($className, "Mouf\\Database\\TDBM\\TDBMObject", true)) {
throw new TDBMException("Error while calling TDBMObject::getNewObject(): The class ".$className." should extend TDBMObject.");
}
$object = new $className($this, $table_name);
if ($auto_assign_id && !$this->isPrimaryKeyAutoIncrement($table_name)) {
$pk_table = $this->getPrimaryKeyStatic($table_name);
if (count($pk_table)==1)
{
$root_table = $this->dbConnection->findRootSequenceTable($table_name);
$id = $this->dbConnection->nextId($root_table);
// If $id == 1, it is likely that the sequence was just created.
// However, there might be already some data in the database. We will check the biggest ID in the table.
if ($id == 1) {
$sql = "SELECT MAX(".$this->dbConnection->escapeDBItem($pk_table[0]).") AS maxkey FROM ".$root_table;
$res = $this->dbConnection->getAll($sql);
// NOTE: this will work only if the ID is an integer!
$newid = $res[0]['maxkey'] + 1;
if ($newid>$id) {
$id = $newid;
}
$this->dbConnection->setSequenceId($root_table, $id);
}
$object->TDBMObject_id = $id;
$object->db_row[$pk_table[0]] = $object->TDBMObject_id;
}
}
$this->_addToToSaveObjectList($object);
return $object;
}
/**
* Removes the given object from database.
*
* @param TDBMObject $object the object to delete.
*/
public function deleteObject(TDBMObject $object) {
if ($object->getTDBMObjectState() != "new" && $object->getTDBMObjectState() != "deleted")
{
$pk_table = $object->getPrimaryKey();
// Now for the object_id
$object_id = $object->TDBMObject_id;
// If there is only one primary key:
if (count($pk_table)==1) {
$sql_where = $this->dbConnection->escapeDBItem($pk_table[0])."=".$this->dbConnection->quoteSmart($object->TDBMObject_id);
} else {
$ids = unserialize($object_id);
$i=0;
$sql_where_array = array();
foreach ($pk_table as $pk) {
$sql_where_array[] = $this->dbConnection->escapeDBItem($pk)."=".$this->dbConnection->quoteSmart($ids[$i]);
$i++;
}
$sql_where = implode(" AND ",$sql_where_array);
}
$sql = 'DELETE FROM '.$this->dbConnection->escapeDBItem($object->_getDbTableName()).' WHERE '.$sql_where;
$result = $this->dbConnection->exec($sql);
if ($result != 1)
throw new TDBMException("Error while deleting object from table ".$object->_getDbTableName().": ".$result." have been affected.");
$this->objectStorage->remove($object->_getDbTableName(), $object_id);
$object->setTDBMObjectState("deleted");
}
}
/**
* 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 TDBMObject $objToDelete
*/
public function deleteCascade(TDBMObject $objToDelete) {
$this->deleteAllConstraintWithThisObject($objToDelete);
$this->deleteObject($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 TDBMObject $obj
* @return TDBMObjectArray
*/
private function deleteAllConstraintWithThisObject(TDBMObject $obj) {
$tableFrom = $this->dbConnection->escapeDBItem($obj->_getDbTableName());
$constraints = $this->dbConnection->getConstraintsFromTable($tableFrom);
foreach ($constraints as $constraint) {
$tableTo = $this->dbConnection->escapeDBItem($constraint["table1"]);
$colFrom = $this->dbConnection->escapeDBItem($constraint["col2"]);
$colTo = $this->dbConnection->escapeDBItem($constraint["col1"]);
$idVarName = $this->dbConnection->escapeDBItem($obj->getPrimaryKey()[0]);
$idValue = $this->dbConnection->quoteSmart($obj->TDBMObject_id);
$sql = "SELECT DISTINCT ".$tableTo.".*"
." FROM ".$tableFrom
." LEFT JOIN ".$tableTo." ON ".$tableFrom.".".$colFrom." = ".$tableTo.".".$colTo
." WHERE ".$tableFrom.".".$idVarName."=".$idValue;
$result = $this->getObjectsFromSQL($constraint["table1"], $sql);
foreach ($result as $tdbmObj) {
$this->deleteCascade($tdbmObj);
}
}
}
/**
* The getObjectsFromSQL is used to retrieve objects from the database using a full SQL query.
* The TDBM library is designed to make the SQL query instead of you.
* So in 80% of the cases, you should use the getObjects method, which does the work for you.
* The getObjectsFromSQL method should be used in those 20% cases where getObjects cannot be used.
* Please refer to the section "What you cannot do with TDBM" of the manual for more information.
*
* The getObjectsFromSQL method is passed the kind of objects you want to retrieve, the SQL of the query,
* and it returns a TDBMObjectArray which is basically an array of TDBMObjects.
*
* Note that a TDBMObject always map a row in a database. Therefore, your SQL query should return all the columns
* of the mapped table, and only those columns. A simple way of doing this is to use the "table.*" notation.
*
* For instance, is you have a "users" table with a "boss_id" column referencing your "user_id" primary key
* (to handle the hierarchy in an organization), and if you want to retrieve the employees that directly work
* for "John Doe", you would write:
* $users = getObjectsBySQL("SELECT u1.* FROM users u1 JOIN users u2 ON u1.boss_id = u2.user_id WHERE u2.user_name='John Doe'");
*
* Finally, you can specify the offset and the maximum number of objects returned to you using
* the from and the limit parameters.
*
* @param string $table_name The kind of objects that will be returned
* @param string $sql The SQL of the query
* @param integer $from The offset
* @param integer $limit The maximum number of objects returned
* @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.
* @return array|\Generator|TDBMObjectArray The result set of the query as a TDBMObjectArray (an array of TDBMObjects with special properties)
*/
public function getObjectsFromSQL($table_name, $sql, $from=null, $limit=null, $className=null) {
if ($this->dbConnection == null) {
throw new TDBMException("Error while calling TDBMObject::getObject(): No connection has been established on the database!");
}
$table_name = $this->dbConnection->toStandardcase($table_name);
$this->getPrimaryKeyStatic($table_name);
$result = $this->dbConnection->query($sql, $from, $limit);
if ($className === null) {
if (isset($this->tableToBeanMap[$table_name])) {
$className = $this->tableToBeanMap[$table_name];
} else {
$className = "Mouf\\Database\\TDBM\\TDBMObject";
}
}
if (!is_string($className)) {
throw new TDBMException("Error while casting TDBMObject to class, the parameter passed is not a string. Value passed: ".$className);
}
if ($this->mode == self::MODE_COMPATIBLE_ARRAY || $this->mode == self::MODE_ARRAY) {
if ($this->mode == self::MODE_COMPATIBLE_ARRAY) {
$returned_objects = new TDBMObjectArray();
} else {
$returned_objects = [];
}
$keysStandardCased = array();
$firstLine = true;
$colsArray = null;
while ($fullCaseRow = $result->fetch(\PDO::FETCH_ASSOC))
{
$row = array();
if ($firstLine) {
// $keysStandardCased is an optimization to avoid calling toStandardCaseColumn on every cell of every row.
foreach ($fullCaseRow as $key=>$value) {
$keysStandardCased[$key] = $this->dbConnection->toStandardCaseColumn($key);
}
$firstLine = false;
}
foreach ($fullCaseRow as $key=>$value) {
$row[$keysStandardCased[$key]]=$value;
}
$pk_table = $this->primary_keys[$table_name];
if (count($pk_table)==1)
{
if (!isset($keysStandardCased[$pk_table[0]])) {
throw new TDBMException("Bad SQL request passed to getObjectsFromSQL. The SQL request should return all the rows from the '$table_name' table. Could not find primary key in this set of rows. SQL request passed: ".$sql);
}
$id = $row[$keysStandardCased[$pk_table[0]]];
}
else
{
// Let's generate the serialized primary key from the columns!
$ids = array();
foreach ($pk_table as $pk) {
$ids[] = $row[$keysStandardCased[$pk]];
}
$id = serialize($ids);
}
$obj = $this->objectStorage->get($table_name,$id);
if ($obj === null)
{
if (!is_a($className, "Mouf\\Database\\TDBM\\TDBMObject", true)) {
throw new TDBMException("Error while calling TDBM: The class ".$className." should extend TDBMObject.");
}
$obj = new $className($this, $table_name, $id);
$obj->loadFromRow($row, $colsArray);
$this->objectStorage->set($table_name, $id, $obj);
} elseif ($obj->_getStatus() == "not loaded") {
$obj->loadFromRow($row, $colsArray);
// Check that the object fetched from cache is from the requested class.
if (!is_a($obj, $className)) {
throw new TDBMException("Error while calling TDBM: An object fetched from database is already present in TDBM cache and they do not share the same class. You requested the object to be of the class ".$className." but the object available locally is of the class ".get_class($obj).".");
}
} else {
// Check that the object fetched from cache is from the requested class.
$className = ltrim($className, '\\');
if (!is_a($obj, $className)) {
throw new TDBMException("Error while calling TDBM: An object fetched from database is already present in TDBM cache and they do not share the same class. You requested the object to be of the class ".$className." but the object available locally is of the class ".get_class($obj).".");
}
}
$returned_objects[] = $obj;
}
$result->closeCursor();
return $returned_objects;
} elseif ($this->mode == self::MODE_CURSOR) {
return $this->getObjectsFromSQLGenerator($result, $table_name, $className, $sql);
} else {
throw new TDBMException("Unknown mode: ".$this->mode);
}
}
/**
* Returns a generator for the database.
* @param unknown $result
* @param unknown $table_name
* @param unknown $className
* @param unknown $sql
*/
private function getObjectsFromSQLGenerator($result, $table_name, $className, $sql) {
$keysStandardCased = array();
$firstLine = true;
$colsArray = null;
while ($fullCaseRow = $result->fetch(\PDO::FETCH_ASSOC))
{
$row = array();
if ($firstLine) {
// $keysStandardCased is an optimization to avoid calling toStandardCaseColumn on every cell of every row.
foreach ($fullCaseRow as $key=>$value) {
$keysStandardCased[$key] = $this->dbConnection->toStandardCaseColumn($key);
}
$firstLine = false;
}
foreach ($fullCaseRow as $key=>$value) {
$row[$keysStandardCased[$key]]=$value;
}
$pk_table = $this->primary_keys[$table_name];
if (count($pk_table)==1)
{
if (!isset($keysStandardCased[$pk_table[0]])) {
throw new TDBMException("Bad SQL request passed to getObjectsFromSQL. The SQL request should return all the rows from the '$table_name' table. Could not find primary key in this set of rows. SQL request passed: ".$sql);
}
$id = $row[$keysStandardCased[$pk_table[0]]];
}
else
{
// Let's generate the serialized primary key from the columns!
$ids = array();
foreach ($pk_table as $pk) {
$ids[] = $row[$keysStandardCased[$pk]];
}
$id = serialize($ids);
}
$obj = $this->objectStorage->get($table_name, $id);
if ($obj === null)
{
if ($className == null) {
$obj = new TDBMObject($this, $table_name, $id);
} elseif (is_string($className)) {
if (!is_subclass_of($className, "Mouf\\Database\\TDBM\\TDBMObject") && $className != "Mouf\\Database\\TDBM\\TDBMObject") {
throw new TDBMException("Error while calling TDBM: The class ".$className." should extend TDBMObject.");
}
$obj = new $className($this, $table_name, $id);
} else {
throw new TDBMException("Error while casting TDBMObject to class, the parameter passed is not a string. Value passed: ".$className);
}
$obj->loadFromRow($row, $colsArray);
$this->objectStorage->set($table_name, $id, $obj);
} elseif ($obj->_getStatus() == "not loaded") {
$obj->loadFromRow($row, $colsArray);
// Check that the object fetched from cache is from the requested class.
if ($className != null) {
if (!is_subclass_of(get_class($obj), $className) && get_class($obj) != $className) {
throw new TDBMException("Error while calling TDBM: An object fetched from database is already present in TDBM cache and they do not share the same class. You requested the object to be of the class ".$className." but the object available locally is of the class ".get_class($obj).".");
}
}
} else {
// Check that the object fetched from cache is from the requested class.
if ($className != null) {
$className = ltrim($className, '\\');
if (!is_subclass_of(get_class($obj), $className) && get_class($obj) != $className) {
throw new TDBMException("Error while calling TDBM: An object fetched from database is already present in TDBM cache and they do not share the same class. You requested the object to be of the class ".$className." but the object available locally is of the class ".get_class($obj).".");
}
}
}
yield $obj;
}
$result->closeCursor();
$result = null;
}
/**
* This function performs a save() of all the objects that have been modified.
* This function is automatically called at the end of your script, so you don't have to call it yourself.
*
* Note: if you want to catch or display efficiently any error that might happen, you might want to call this
* method explicitly and to catch any TDBMException that it might throw like this:
*
* try {
* TDBMObject::completeSave();
* } catch (TDBMException e) {
* // Do something here.
* }
*
*/
public function completeSave() {
if (is_array($this->tosave_objects))
{
foreach ($this->tosave_objects as $object)
{
if (!$object->db_onerror && $object->db_autosave)
{
$object->save();
}
}
}
}
/**
* This function performs a save() of all the objects that have been modified just before the program exits.
* It should never be called by the user, the program will call it directly.
*
*/
public function completeSaveOnExit() {
$this->is_program_exiting = true;
$this->completeSave();
// Now, let's commit or rollback if needed.
if ($this->dbConnection != null && $this->dbConnection->hasActiveTransaction()) {
if ($this->commitOnQuit) {
try {
$this->dbConnection->commit();
} catch (Exception $e) {
echo $e->getMessage()."<br/>";
echo $e->getTraceAsString();
}
} else {
try {
$this->dbConnection->rollback();
} catch (Exception $e) {
echo $e->getMessage()."<br/>";
echo $e->getTraceAsString();
}
}
}
}
/**
* Function used internally by TDBM.
* Returns true if the program is exiting.
*
* @return bool
*/
public function isProgramExiting() {
return $this->is_program_exiting;
}
/**
* This function performs a save() of all the objects that have been modified, then it sets all the data to a not loaded state.
* Therefore, the database will be queried again next time we access the object. Meanwhile, if another process modifies the database,
* the changes will be retrieved when we access the object again.
*
*/
public function completeSaveAndFlush() {
$this->completeSave();
$this->objectStorage->apply(function(TDBMObject $object) {
/* @var $object TDBMObject */
if (!$object->db_onerror && $object->getTDBMObjectState() == "loaded")
{
$object->setTDBMObjectState("not loaded");
}
});
}
/**
* Returns transient objects.
* getTransientObjectsFromSQL executes the SQL request passed, and returns a set of objects matching this request.
* The objects returned will not be saved in database if they are modified.
*
* This method is particularly useful for retrieving aggregated data for instance (requests with GROUP BY).
*
* For instance you can use getTransientObjectsFromSQL to rertrieve the number of users in each country:
*
* $objects = getTransientObjectsFromSQL("SELECT country_code, count(user_id) AS cnt FROM users GROUP BY country_code");
* foreach ($objects as $object) {
* echo "Country $object->country_code has $object->cnt users";
* }
*
* Note that using getObjectsFromSQL for such requests would be a mistake since getObjectsFromSQL is retrieving objects
* that can be saved later.
*
* TODO: make the result a TDBMObjectArray instead of an array.
*
* @param string $sql
* @return array the result of your query
*/
public function getTransientObjectsFromSQL($sql,$classname=null) {
if ($this->dbConnection == null) {
throw new TDBMException("Error while calling TDBMObject::getObject(): No connection has been established on the database!");
}
return $this->dbConnection->getAll($sql, \PDO::FETCH_CLASS,$classname);
}
private function to_explain_string($path) {
$msg = '';
foreach ($path as $constraint) {
if ($constraint['type']=='1*') {
$msg .= 'Table "'.$constraint['table1'].'" points to "'.$constraint['table2'].'" through its foreign key "'.$constraint['col1'].'"\n';
}
elseif ($constraint['type']=='*1') {
$msg .= 'Table "'.$constraint['table1'].'" is pointed by "'.$constraint['table2'].'" through its foreign key "'.$constraint['col2'].'"\n';
}
}
return $msg;
}
/**
* Returns an array of paths going from "$table" to the tables passed in the array "$tables"
*
* @param string $table The base table
* @param array $tables The destination tables
* @return unknown
*/
private function static_find_paths($table, $tables) {
$this->loadCache();
$path = array();
$queue = array(array($table,array()));
$found = false;
$found_depth = 0;
$tables_paths = array();
$cached_tables_paths = array();
// Let's fill the $tables_paths that will contain the name of the tables needed (and the paths soon).
// Also, let's use this moment to check if the tables we are looking for are not in cache.
foreach ($tables as $tablename) {
$cached_path = $this->getPathFromCache($table, $tablename);
if ($cached_path === null) {
$tables_paths[]['name'] = $tablename;
} else {
$cached_path_array = array();
$cached_path_array['name'] = $tablename;
$cached_path_array['founddepth'] = count($cached_path);
$cached_path_array['paths'][] = $cached_path;
$cached_tables_paths[] = $cached_path_array;
}
}
if (count($tables_paths)>0) {
// Let's get the maximum execution time and let's take 90% of it:
$max_execution_time = ini_get("max_execution_time")*0.9;
while (!empty($queue))
{
$ret = $this->find_paths_iter($tables_paths, $path, $queue);
if ($found && $found_depth != count($path))
{
break;
}
if ($ret==true)
{
// Ok, we got one, we will continue a bit more until we reach the next level in the tree,
// just to see if there is no ambiguity
//$found_paths[] = $path;
$found = true;
$found_depth = count($path);
}
// At each iteration, let's check the time.
if ($this->trackExecutionTime && microtime(true)-self::$script_start_up_time > $max_execution_time && $max_execution_time!=0) {
// Call check table names
$this->checkTablesExist($tables);
// If no excecution thrown we still have a risk to run out of time.
throw new TDBMException("Your request is too slow. 90% of the total amount of execution time allocated to this page has passed. Try to allocate more time for the execution of PHP pages by changing the max_execution_time parameter in php.ini");
}
}
}
$ambiguity =false;
$msg = '';
foreach ($tables_paths as $table_path) {
// If any table has not been found, throw an exception
if (!isset($table_path['founddepth']) || $table_path['founddepth']==null) {
// First, check if the tables do exist.
$this->checkTablesExist(array($table, $table_path['name']));
// Else, throw an error.
throw new TDBMException("Unable to find a path between table ".$table." and table ".$table_path['name'].".\nIt is likely that a constraint is missing.");
}
// If any table has more than 1 way to be reached, throw an exception.
if (count($table_path['paths'])>1) {