/
jDaoGenerator.class.php
1243 lines (1049 loc) · 44.3 KB
/
jDaoGenerator.class.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
/**
* @package jelix
* @subpackage dao
*
* @author Gérald Croes, Laurent Jouanneau
* @contributor Laurent Jouanneau
* @contributor Bastien Jaillot (bug fix)
* @contributor Julien Issler, Guillaume Dugas
* @contributor Philippe Villiers
*
* @copyright 2001-2005 CopixTeam, 2005-2017 Laurent Jouanneau
* @copyright 2007-2008 Julien Issler
* This class was get originally from the Copix project (CopixDAOGeneratorV1, Copix 2.3dev20050901, http://www.copix.org)
* Few lines of code are still copyrighted 2001-2005 CopixTeam (LGPL licence).
* Initial authors of this Copix class are Gerald Croes and Laurent Jouanneau,
* and this class was rewrited for Jelix by Laurent Jouanneau
*
* @see http://www.jelix.org
* @licence http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file
*/
/**
* This is a generator which creates php class from dao xml file.
*
* It is called by jDaoCompiler
*
* @package jelix
* @subpackage dao
*
* @see jDaoCompiler
*/
class jDaoGenerator
{
/**
* the dao definition.
*
* @var jDaoParser
*/
protected $_dataParser;
/**
* The DaoRecord ClassName.
*
* @var string
*/
protected $_DaoRecordClassName;
/**
* the DAO classname.
*
* @var string
*/
protected $_DaoClassName;
protected $propertiesListForInsert = 'PrimaryTable';
protected $aliasWord = ' AS ';
/**
* @var jDbTools
*/
protected $tools;
protected $_daoId;
protected $_daoPath;
protected $_dbType;
/**
* the real name of the main table.
*/
protected $tableRealName = '';
/**
* the real name of the main table, escaped in SQL
* so it is ready to include into a SQL query.
*/
protected $tableRealNameEsc = '';
protected $sqlWhereClause = '';
protected $sqlFromClause = '';
protected $sqlSelectClause = '';
/**
* constructor.
*
* @param jSelectorDao $selector
* @param jDbTools $tools
* @param jDaoParser $daoParser
*/
public function __construct($selector, $tools, $daoParser)
{
$this->_daoId = $selector->toString();
$this->_daoPath = $selector->getPath();
$this->_dbType = $selector->dbType;
$this->_dataParser = $daoParser;
$this->_DaoClassName = $selector->getDaoClass();
$this->_DaoRecordClassName = $selector->getDaoRecordClass();
$this->tools = $tools;
}
/**
* build all classes.
*/
public function buildClasses()
{
$src = array();
$src[] = ' require_once ( JELIX_LIB_PATH .\'dao/jDaoRecordBase.class.php\');';
$src[] = ' require_once ( JELIX_LIB_PATH .\'dao/jDaoFactoryBase.class.php\');';
// prepare some values to generate properties and methods
$this->buildFromWhereClause();
$this->sqlSelectClause = $this->buildSelectClause();
$tables = $this->_dataParser->getTables();
$pkFields = $this->_getPrimaryFieldsList();
$this->tableRealName = $tables[$this->_dataParser->getPrimaryTable()]['realname'];
$this->tableRealNameEsc = $this->_encloseName('\'.$this->_conn->prefixTable(\''.$this->tableRealName.'\').\'');
$sqlPkCondition = $this->buildSimpleConditions($pkFields);
if ($sqlPkCondition != '') {
$sqlPkCondition = ($this->sqlWhereClause != '' ? ' AND ' : ' WHERE ').$sqlPkCondition;
}
//-----------------------
// Build the record class
//-----------------------
$userRecord = $this->_dataParser->getUserRecord();
if ($userRecord) {
$src[] = ' require_once (\''.$userRecord->getPath().'\');';
$extendedObject = $userRecord->resource.'DaoRecord';
} else {
$extendedObject = 'jDaoRecordBase';
}
$src[] = "\nclass ".$this->_DaoRecordClassName.' extends '.$extendedObject.' {';
$properties = array();
foreach ($this->_dataParser->getProperties() as $id => $field) {
$properties[$id] = get_object_vars($field);
if ($field->defaultValue !== null) {
$src[] = ' public $'.$id.'='.var_export($field->defaultValue, true).';';
} else {
$src[] = ' public $'.$id.';';
}
}
$src[] = ' public function getSelector() { return "'.$this->_daoId.'"; }';
$src[] = ' public function getProperties() { return '.$this->_DaoClassName.'::$_properties; }';
$src[] = ' public function getPrimaryKeyNames() { return '.$this->_DaoClassName.'::$_pkFields; }';
$src[] = '}';
//--------------------
// Build the dao class
//--------------------
$src[] = "\nclass ".$this->_DaoClassName.' extends jDaoFactoryBase {';
$src[] = ' protected $_tables = '.var_export($tables, true).';';
$src[] = ' protected $_primaryTable = \''.$this->_dataParser->getPrimaryTable().'\';';
$src[] = ' protected $_selectClause=\''.$this->sqlSelectClause.'\';';
$src[] = ' protected $_fromClause;';
$src[] = ' protected $_whereClause=\''.$this->sqlWhereClause.'\';';
$src[] = ' protected $_DaoRecordClassName=\''.$this->_DaoRecordClassName.'\';';
$src[] = ' protected $_daoSelector = \''.$this->_daoId.'\';';
if ($this->tools->trueValue != '1') {
$src[] = ' protected $trueValue ='.var_export($this->tools->trueValue, true).';';
$src[] = ' protected $falseValue ='.var_export($this->tools->falseValue, true).';';
}
if ($this->_dataParser->hasEvent('deletebefore') || $this->_dataParser->hasEvent('delete')) {
$src[] = ' protected $_deleteBeforeEvent = true;';
}
if ($this->_dataParser->hasEvent('deleteafter') || $this->_dataParser->hasEvent('delete')) {
$src[] = ' protected $_deleteAfterEvent = true;';
}
if ($this->_dataParser->hasEvent('deletebybefore') || $this->_dataParser->hasEvent('deleteby')) {
$src[] = ' protected $_deleteByBeforeEvent = true;';
}
if ($this->_dataParser->hasEvent('deletebyafter') || $this->_dataParser->hasEvent('deleteby')) {
$src[] = ' protected $_deleteByAfterEvent = true;';
}
$src[] = ' public static $_properties = '.var_export($properties, true).';';
$src[] = ' public static $_pkFields = array('.$this->_writeFieldNamesWith($start = '\'', $end = '\'', $beetween = ',', $pkFields).');';
$src[] = ' ';
$src[] = 'public function __construct($conn){';
$src[] = ' parent::__construct($conn);';
$src[] = ' $this->_fromClause = \''.$this->sqlFromClause.'\';';
$src[] = '}';
$src[] = ' ';
$src[] = ' protected function _getPkWhereClauseForSelect($pk){';
$src[] = ' extract($pk);';
$src[] = ' return \''.$sqlPkCondition.'\';';
$src[] = '}';
$src[] = ' ';
$src[] = 'protected function _getPkWhereClauseForNonSelect($pk){';
$src[] = ' extract($pk);';
$src[] = ' return \' where '.$this->buildSimpleConditions($pkFields, '', false).'\';';
$src[] = '}';
//----- Insert method
$src[] = $this->buildInsertMethod($pkFields);
//----- update method
$src[] = $this->buildUpdateMethod($pkFields);
//----- other user methods
$src[] = $this->buildUserMethods();
$src[] = $this->buildEndOfClass();
$src[] = '}'; //end of class
return implode("\n", $src);
}
/**
* build the insert() method in the final class.
*
* @param mixed $pkFields
*
* @return string the source of the method
*/
protected function buildInsertMethod($pkFields)
{
$pkai = $this->getAutoIncrementPKField();
$src = array();
$src[] = 'public function insert ($record){';
if ($pkai !== null) {
// if there is an autoincrement field as primary key
// if a value is given for the autoincrement field, then with do a full insert
$src[] = ' if($record->'.$pkai->name.' > 0 ){';
$src[] = ' $query = \'INSERT INTO '.$this->tableRealNameEsc.' (';
$fields = $this->_getPropertiesBy('PrimaryTable');
list($fields, $values) = $this->_prepareValues($fields, 'insertPattern', 'record->');
$src[] = implode(',', $fields);
$src[] = ') VALUES (';
$src[] = implode(', ', $values);
$src[] = ")';";
$src[] = '}else{';
$fields = $this->_getPropertiesBy($this->propertiesListForInsert);
} else {
$fields = $this->_getPropertiesBy('PrimaryTable');
}
if ($this->_dataParser->hasEvent('insertbefore') || $this->_dataParser->hasEvent('insert')) {
$src[] = ' jEvent::notify("daoInsertBefore", array(\'dao\'=>$this->_daoSelector, \'record\'=>$record));';
}
// if there isn't a autoincrement as primary key, then we do a full insert.
// if there isn't a value for the autoincrement field and if this is a mysql/sqlserver and pgsql,
// we do an insert without given primary key. In other case, we do a full insert.
$src[] = ' $query = \'INSERT INTO '.$this->tableRealNameEsc.' (';
list($fields, $values) = $this->_prepareValues($fields, 'insertPattern', 'record->');
$src[] = implode(',', $fields);
$src[] = ') VALUES (';
$src[] = implode(', ', $values);
$src[] = ")';";
if ($pkai !== null) {
$src[] = '}';
}
$src[] = ' $result = $this->_conn->exec ($query);';
if ($pkai !== null) {
$src[] = ' if(!$result)';
$src[] = ' return false;';
$src[] = ' if($record->'.$pkai->name.' < 1 ) ';
$src[] = $this->buildUpdateAutoIncrementPK($pkai);
}
// we generate a SELECT query to update field on the record object, which are autoincrement or calculated
$fields = $this->_getPropertiesBy('FieldToUpdate');
if (count($fields)) {
$result = array();
foreach ($fields as $id => $prop) {
$result[] = $this->buildSelectPattern($prop->selectPattern, '', $prop->fieldName, $prop->name);
}
$sql = 'SELECT '.(implode(', ', $result)).' FROM '.$this->tableRealNameEsc.' WHERE ';
$sql .= $this->buildSimpleConditions($pkFields, 'record->', false);
$src[] = ' $query =\''.$sql.'\';';
$src[] = ' $rs = $this->_conn->query ($query);';
$src[] = ' $newrecord = $rs->fetch ();';
foreach ($fields as $id => $prop) {
$src[] = ' $record->'.$prop->name.' = $newrecord->'.$prop->name.';';
}
}
if ($this->_dataParser->hasEvent('insertafter') || $this->_dataParser->hasEvent('insert')) {
$src[] = ' jEvent::notify("daoInsertAfter", array(\'dao\'=>$this->_daoSelector, \'record\'=>$record));';
}
$src[] = ' return $result;';
$src[] = '}';
return implode("\n", $src);
}
/**
* build the update() method for the final class.
*
* @param mixed $pkFields
*
* @return string the source of the method
*/
protected function buildUpdateMethod($pkFields)
{
$src = array();
$src[] = 'public function update ($record){';
list($fields, $values) = $this->_prepareValues($this->_getPropertiesBy('PrimaryFieldsExcludePk'), 'updatePattern', 'record->');
if (count($fields)) {
if ($this->_dataParser->hasEvent('updatebefore') || $this->_dataParser->hasEvent('update')) {
$src[] = ' jEvent::notify("daoUpdateBefore", array(\'dao\'=>$this->_daoSelector, \'record\'=>$record));';
}
$src[] = ' $query = \'UPDATE '.$this->tableRealNameEsc.' SET ';
$sqlSet = '';
foreach ($fields as $k => $fname) {
$sqlSet .= ', '.$fname.'= '.$values[$k];
}
$src[] = substr($sqlSet, 1);
$sqlCondition = $this->buildSimpleConditions($pkFields, 'record->', false);
if ($sqlCondition != '') {
$src[] = ' where '.$sqlCondition;
}
$src[] = "';";
$src[] = ' $result = $this->_conn->exec ($query);';
// we generate a SELECT query to update field on the record object, which are autoincrement or calculated
$fields = $this->_getPropertiesBy('FieldToUpdateOnUpdate');
if (count($fields)) {
$result = array();
foreach ($fields as $id => $prop) {
$result[] = $this->buildSelectPattern($prop->selectPattern, '', $prop->fieldName, $prop->name);
}
$sql = 'SELECT '.(implode(', ', $result)).' FROM '.$this->tableRealNameEsc.' WHERE ';
$sql .= $this->buildSimpleConditions($pkFields, 'record->', false);
$src[] = ' $query =\''.$sql.'\';';
$src[] = ' $rs = $this->_conn->query ($query, jDbConnection::FETCH_INTO, $record);';
$src[] = ' $record = $rs->fetch ();';
}
if ($this->_dataParser->hasEvent('updateafter') || $this->_dataParser->hasEvent('update')) {
$src[] = ' jEvent::notify("daoUpdateAfter", array(\'dao\'=>$this->_daoSelector, \'record\'=>$record));';
}
$src[] = ' return $result;';
} else {
//the dao is mapped on a table which contains only primary key : update is impossible
// so we will generate an error on update
$src[] = " throw new jException('jelix~dao.error.update.impossible',array('".$this->_daoId."','".$this->_daoPath."'));";
}
$src[] = ' }'; //ends the update function
return implode("\n", $src);
}
/**
* build all methods defined by the developer in the dao file.
*
* @return string the source of the methods
*/
protected function buildUserMethods()
{
$allField = $this->_getPropertiesBy('All');
$primaryFields = $this->_getPropertiesBy('PrimaryTable');
$src = array();
foreach ($this->_dataParser->getMethods() as $name => $method) {
$defval = $method->getParametersDefaultValues();
if (count($defval)) {
$mparam = '';
foreach ($method->getParameters() as $param) {
$mparam .= ', $'.$param;
if (isset($defval[$param])) {
$mparam .= '=\''.str_replace("'", "\\'", $defval[$param]).'\'';
}
}
$mparam = substr($mparam, 1);
} else {
$mparam = implode(', $', $method->getParameters());
if ($mparam != '') {
$mparam = '$'.$mparam;
}
}
$src[] = ' function '.$method->name.' ('.$mparam.'){';
$limit = '';
switch ($method->type) {
case 'delete':
$this->buildDeleteUserQuery($method, $src, $primaryFields);
break;
case 'update':
$this->buildUpdateUserQuery($method, $src, $primaryFields);
break;
case 'php':
$src[] = $method->getBody();
$src[] = '}';
break;
case 'count':
$this->buildCountUserQuery($method, $src, $allField);
break;
case 'selectfirst':
case 'select':
default:
$limit = $this->buildSelectUserQuery($method, $src, $allField);
}
if ($method->type == 'php') {
continue;
}
switch ($method->type) {
case 'delete':
case 'update':
if ($method->eventBeforeEnabled || $method->eventAfterEnabled) {
$src[] = ' $args = func_get_args();';
$methname = ($method->type == 'update' ? 'Update' : 'Delete');
if ($method->eventBeforeEnabled) {
$src[] = ' jEvent::notify("daoSpecific'.$methname.'Before", array(\'dao\'=>$this->_daoSelector,\'method\'=>\''.
$method->name.'\', \'params\'=>$args));';
}
if ($method->eventAfterEnabled) {
$src[] = ' $result = $this->_conn->exec ($__query);';
$src[] = ' jEvent::notify("daoSpecific'.$methname.'After", array(\'dao\'=>$this->_daoSelector,\'method\'=>\''.
$method->name.'\', \'params\'=>$args));';
$src[] = ' return $result;';
} else {
$src[] = ' return $this->_conn->exec ($__query);';
}
} else {
$src[] = ' return $this->_conn->exec ($__query);';
}
break;
case 'count':
$src[] = ' $__rs = $this->_conn->query($__query);';
$src[] = ' $__res = $__rs->fetch();';
$src[] = ' return intval($__res->c);';
break;
case 'selectfirst':
$src[] = ' $__rs = $this->_conn->limitQuery($__query,0,1);';
$src[] = ' $this->finishInitResultSet($__rs);';
$src[] = ' return $__rs->fetch();';
break;
case 'select':
default:
if ($limit) {
$src[] = ' $__rs = $this->_conn->limitQuery($__query'.$limit.');';
} else {
$src[] = ' $__rs = $this->_conn->query($__query);';
}
$src[] = ' $this->finishInitResultSet($__rs);';
$src[] = ' return $__rs;';
}
$src[] = '}';
}
return implode("\n", $src);
}
/**
* @param mixed $method
* @param mixed $src
* @param mixed $primaryFields
*/
protected function buildDeleteUserQuery($method, &$src, &$primaryFields)
{
$src[] = ' $__query = \'DELETE FROM '.$this->tableRealNameEsc.' \';';
$cond = $method->getConditions();
if ($cond !== null) {
$sqlCond = $this->buildConditions($cond, $primaryFields, $method->getParameters(), false);
if (trim($sqlCond) != '') {
$src[] = '$__query .=\' WHERE '.$sqlCond."';";
}
}
}
/**
* @param mixed $method
* @param mixed $src
* @param mixed $primaryFields
*/
protected function buildUpdateUserQuery($method, &$src, &$primaryFields)
{
$src[] = ' $__query = \'UPDATE '.$this->tableRealNameEsc.' SET ';
$updatefields = $this->_getPropertiesBy('PrimaryFieldsExcludePk');
$sqlSet = '';
foreach ($method->getValues() as $propname => $value) {
if ($value[1]) {
// value is an expression
$expression = $this->parseSQLFunction($value[0]);
// replace all variable name by a php expression
preg_match_all('/\$([a-zA-Z0-9_]+)/', $expression, $varMatches, PREG_OFFSET_CAPTURE);
$parameters = $method->getParameters();
if (count($varMatches[0])) {
$result = '';
$len = 0;
foreach ($varMatches[1] as $k => $var) {
$result .= substr($expression, $len, $len + $varMatches[0][$k][1]);
$len += $varMatches[0][$k][1] + strlen($varMatches[0][$k][0]);
if (in_array($var[0], $parameters)) {
$result .= '\'.'.$this->_preparePHPExpr($varMatches[0][$k][0], $updatefields[$propname], true).'.\'';
} else {
$result .= $varMatches[0][$k][0];
}
}
if ($len < strlen($expression)) {
$result .= substr($expression, $len);
}
$expression = $result;
}
$sqlSet .= ', '.$this->_encloseName($updatefields[$propname]->fieldName).'= '.$expression;
} else {
// value is a simple value
$sqlSet .= ', '.$this->_encloseName($updatefields[$propname]->fieldName).'= '.
$this->tools->escapeValue($updatefields[$propname]->unifiedType, $value[0], false, true);
}
}
$src[] = substr($sqlSet, 1).'\';';
$cond = $method->getConditions();
if ($cond !== null) {
$sqlCond = $this->buildConditions($cond, $primaryFields, $method->getParameters(), false);
if (trim($sqlCond) != '') {
$src[] = '$__query .=\' WHERE '.$sqlCond."';";
}
}
}
/**
* @param mixed $method
* @param mixed $src
* @param mixed $allField
*/
protected function buildCountUserQuery($method, &$src, &$allField)
{
if ($method->distinct != '') {
$properties = $this->_dataParser->getProperties();
$tables = $this->_dataParser->getTables();
$prop = $properties[$method->distinct];
$count = ' DISTINCT '.$this->_encloseName($tables[$prop->table]['name']).'.'.$this->_encloseName($prop->fieldName);
} else {
$count = '*';
}
$src[] = ' $__query = \'SELECT COUNT('.$count.') as c \'.$this->_fromClause.$this->_whereClause;';
$glueCondition = ($this->sqlWhereClause != '' ? ' AND ' : ' WHERE ');
$cond = $method->getConditions();
if ($cond !== null) {
$sqlCond = $this->buildConditions($cond, $allField, $method->getParameters(), true);
if (trim($sqlCond) != '') {
$src[] = '$__query .=\''.$glueCondition.$sqlCond."';";
}
}
}
/**
* @param mixed $method
* @param mixed $src
* @param mixed $allField
*/
protected function buildSelectUserQuery($method, &$src, &$allField)
{
$limit = '';
if ($method->distinct != '') {
$select = '\''.$this->buildSelectClause($method->distinct).'\'';
} else {
$select = ' $this->_selectClause';
}
$src[] = ' $__query = '.$select.'.$this->_fromClause.$this->_whereClause;';
$glueCondition = ($this->sqlWhereClause != '' ? ' AND ' : ' WHERE ');
if ($method->type == 'select' && ($lim = $method->getLimit()) !== null) {
$limit = ', '.$lim['offset'].', '.$lim['count'];
}
$sqlCond = $this->buildConditions($method->getConditions(), $allField, $method->getParameters(), true);
if (trim($sqlCond) != '') {
$src[] = '$__query .=\''.$glueCondition.$sqlCond."';";
}
return $limit;
}
/**
* create FROM clause and WHERE clause for all SELECT query.
*/
protected function buildFromWhereClause()
{
$tables = $this->_dataParser->getTables();
foreach ($tables as $table_name => $table) {
$tables[$table_name]['realname'] = '\'.$this->_conn->prefixTable(\''.$table['realname'].'\').\'';
}
$primarytable = $tables[$this->_dataParser->getPrimaryTable()];
$ptrealname = $this->_encloseName($primarytable['realname']);
$ptname = $this->_encloseName($primarytable['name']);
list($sqlFrom, $sqlWhere) = $this->buildOuterJoins($tables, $ptname);
$sqlFrom = $ptrealname.$this->aliasWord.$ptname.$sqlFrom;
foreach ($this->_dataParser->getInnerJoins() as $tablejoin) {
$table = $tables[$tablejoin];
$tablename = $this->_encloseName($table['name']);
$sqlFrom .= ', '.$this->_encloseName($table['realname']).$this->aliasWord.$tablename;
foreach ($table['fk'] as $k => $fk) {
$sqlWhere .= ' AND '.$ptname.'.'.$this->_encloseName($fk).'='.$tablename.'.'.$this->_encloseName($table['pk'][$k]);
}
}
$this->sqlWhereClause = ($sqlWhere != '' ? ' WHERE '.substr($sqlWhere, 4) : '');
$this->sqlFromClause = ' FROM '.$sqlFrom;
}
/**
* generates the part of the FROM clause for outer joins.
*
* @param mixed $tables
* @param mixed $primaryTableName
*
* @return array [0]=> the part of the FROM clause, [1]=> the part to add to the WHERE clause when needed
*/
protected function buildOuterJoins(&$tables, $primaryTableName)
{
$sqlFrom = '';
foreach ($this->_dataParser->getOuterJoins() as $tablejoin) {
$table = $tables[$tablejoin[0]];
$tablename = $this->_encloseName($table['name']);
$r = $this->_encloseName($table['realname']).$this->aliasWord.$tablename;
$fieldjoin = '';
foreach ($table['fk'] as $k => $fk) {
$fieldjoin .= ' AND '.$primaryTableName.'.'.$this->_encloseName($fk).'='.$tablename.'.'.$this->_encloseName($table['pk'][$k]);
}
$fieldjoin = substr($fieldjoin, 4);
if ($tablejoin[1] == 0) {
$sqlFrom .= ' LEFT JOIN '.$r.' ON ('.$fieldjoin.')';
} elseif ($tablejoin[1] == 1) {
$sqlFrom .= ' RIGHT JOIN '.$r.' ON ('.$fieldjoin.')';
}
}
return array($sqlFrom, '');
}
/**
* build a SELECT clause for all SELECT queries.
*
* @param mixed $distinct
*
* @return string the select clause
*/
protected function buildSelectClause($distinct = false)
{
$result = array();
$tables = $this->_dataParser->getTables();
foreach ($this->_dataParser->getProperties() as $id => $prop) {
$table = $this->_encloseName($tables[$prop->table]['name']).'.';
if ($prop->selectPattern != '') {
$result[] = $this->buildSelectPattern($prop->selectPattern, $table, $prop->fieldName, $prop->name);
}
}
return 'SELECT '.($distinct ? 'DISTINCT ' : '').(implode(', ', $result));
}
/**
* build an item for the select clause.
*
* @param mixed $pattern
* @param mixed $table
* @param mixed $fieldname
* @param mixed $propname
*/
protected function buildSelectPattern($pattern, $table, $fieldname, $propname)
{
if ($pattern == '%s') {
$field = $table.$this->_encloseName($fieldname);
if ($fieldname != $propname) {
$field .= ' as '.$this->_encloseName($propname);
}
} else {
$expression = $this->parseSQLFunction($pattern);
$field = str_replace(
array("'", '%s'),
array("\\'", $table.$this->_encloseName($fieldname)),
$expression
)
.' as '.$this->_encloseName($propname);
}
return $field;
}
protected function buildEndOfClass()
{
return '';
}
/**
* format field names with a start, an end and a between strings.
*
* ex: give 'name' as $info, it will output the result of $field->name
*
* @param string $info property to get from objects in $using
* @param string $start string to add before the info
* @param string $end string to add after the info
* @param string $beetween string to add between each info
* @param jDaoProperty[] $using list of jDaoProperty object. if null, get default fields list
*
* @see jDaoProperty
*
* @return string list of field names separated by the $between character
*/
protected function _writeFieldsInfoWith($info, $start = '', $end = '', $beetween = '', $using = null)
{
$result = array();
if ($using === null) {
//if no fields are provided, using _dataParser's as default.
$using = $this->_dataParser->getProperties();
}
foreach ($using as $id => $field) {
$result[] = $start.$field->{$info}.$end;
}
return implode($beetween, $result);
}
/**
* format field names with start, end and between strings.
*
* @param mixed $start
* @param mixed $end
* @param mixed $beetween
* @param null|mixed $using
*/
protected function _writeFieldNamesWith($start = '', $end = '', $beetween = '', $using = null)
{
return $this->_writeFieldsInfoWith('name', $start, $end, $beetween, $using);
}
protected function _getPrimaryFieldsList()
{
$tables = $this->_dataParser->getTables();
$pkFields = array();
$primTable = $tables[$this->_dataParser->getPrimaryTable()];
$props = $this->_dataParser->getProperties();
// we want to have primary keys as the same order indicated into primarykey attr
foreach ($primTable['pk'] as $pkname) {
foreach ($primTable['fields'] as $f) {
if ($props[$f]->fieldName == $pkname) {
$pkFields[$props[$f]->name] = $props[$f];
break;
}
}
}
return $pkFields;
}
/**
* gets fields that match a condition returned by the $captureMethod.
*
* @internal
*
* @param mixed $captureMethod
*/
protected function _getPropertiesBy($captureMethod)
{
$captureMethod = '_capture'.$captureMethod;
$result = array();
foreach ($this->_dataParser->getProperties() as $field) {
if ($this->{$captureMethod}($field)) {
$result[$field->name] = $field;
}
}
return $result;
}
protected function _capturePrimaryFieldsExcludeAutoIncrement(&$field)
{
return $field->table == $this->_dataParser->getPrimaryTable() && !$field->autoIncrement;
}
protected function _capturePrimaryFieldsExcludePk(&$field)
{
return ($field->table == $this->_dataParser->getPrimaryTable()) && !$field->isPK;
}
protected function _capturePrimaryTable(&$field)
{
return $field->table == $this->_dataParser->getPrimaryTable();
}
protected function _captureAll(&$field)
{
return true;
}
protected function _captureFieldToUpdate(&$field)
{
return $field->table == $this->_dataParser->getPrimaryTable()
&& !$field->isPK
&& !$field->isFK
&& ($field->autoIncrement || ($field->insertPattern != '%s' && $field->selectPattern != ''));
}
protected function _captureFieldToUpdateOnUpdate(&$field)
{
return $field->table == $this->_dataParser->getPrimaryTable()
&& !$field->isPK
&& !$field->isFK
&& ($field->autoIncrement || ($field->updatePattern != '%s' && $field->selectPattern != ''));
}
protected function _captureBinaryField(&$field)
{
return $field->unifiedType == 'binary' || $field->unifiedType == 'varbinary';
}
/**
* get autoincrement PK field.
*
* @param null|mixed $using
*/
protected function getAutoIncrementPKField($using = null)
{
if ($using === null) {
$using = $this->_dataParser->getProperties();
}
foreach ($using as $id => $field) {
if (!$field->isPK) {
continue;
}
if ($field->autoIncrement) {
return $field;
}
}
return null;
}
/**
* build a WHERE clause with conditions on given properties : conditions are
* equality between a variable and the field.
* the variable name is the name of the property, made with an optional prefix
* given in $fieldPrefix parameter.
* This method is called to generate WHERE clause for primary keys.
*
* @param jDaoProperty[] $fields
* @param string $fieldPrefix an optional prefix to prefix variable names
* @param bool $forSelect if true, the table name or table alias will prefix
* the field name in the query
*
* @return string the WHERE clause (without the WHERE keyword)
*
* @internal
*/
protected function buildSimpleConditions(&$fields, $fieldPrefix = '', $forSelect = true)
{
$r = ' ';
$first = true;
foreach ($fields as $field) {
if (!$first) {
$r .= ' AND ';
} else {
$first = false;
}
if ($forSelect) {
$condition = $this->_encloseName($field->table).'.'.$this->_encloseName($field->fieldName);
} else {
$condition = $this->_encloseName($field->fieldName);
}
$var = '$'.$fieldPrefix.$field->name;
$value = $this->_preparePHPExpr($var, $field, !$field->requiredInConditions, '=');
$r .= $condition.'\'.'.$value.'.\'';
}
return $r;
}
protected function _prepareValues($fieldList, $pattern = '', $prefixfield = '')
{
$values = $fields = array();
foreach ((array) $fieldList as $fieldName => $field) {
if ($pattern != '' && $field->{$pattern} == '') {
continue;
}
$value = $this->_preparePHPExpr('$'.$prefixfield.$fieldName, $field, true);
if ($pattern != '') {
$expression = $this->parseSQLFunction($field->{$pattern});
if (strpos($expression, "'") !== false && strpos($expression, "\\'") === false) {
$values[$field->name] = sprintf(str_replace("'", "\\'", $expression), '\'.'.$value.'.\'');
} else {
$values[$field->name] = sprintf($expression, '\'.'.$value.'.\'');
}
} else {
$values[$field->name] = '\'.'.$value.'.\'';
}
$fields[$field->name] = $this->_encloseName($field->fieldName);
}
return array($fields, $values);
}
/**
* build 'where' clause from conditions declared with condition tag in a user method.
*
* @param jDaoConditions $cond the condition object which contains conditions data
* @param jDaoProperty[] $fields
* @param string[] $params list of parameters name of the method
* @param bool $withPrefix true if the field name should be preceded by the table name/table alias
*
* @return string a WHERE clause (without the WHERE keyword) with eventually an ORDER clause
*
* @internal
*/
protected function buildConditions($cond, $fields, $params = array(), $withPrefix = true)
{
if ($cond) {
$sql = $this->buildOneSQLCondition($cond->condition, $fields, $params, $withPrefix, true);
} else {
$sql = '';
}
$order = array();
foreach ($cond->order as $name => $way) {
if (isset($fields[$name])) {
if ($withPrefix) {