forked from UnionOfRAD/lithium
/
Database.php
1790 lines (1619 loc) · 54.4 KB
/
Database.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
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace lithium\data\source;
use PDO;
use PDOException;
use lithium\util\Set;
use lithium\util\String;
use lithium\util\Inflector;
use lithium\core\ConfigException;
use lithium\core\NetworkException;
use lithium\data\model\QueryException;
use lithium\data\model\Query;
use InvalidArgumentException;
use UnexpectedValueException;
/**
* The `Database` class provides the base-level abstraction for SQL-oriented relational databases.
* It handles all aspects of abstraction, including formatting for basic query types and SQL
* fragments (i.e. for joins), converting `Query` objects to SQL, and various other functionality
* which is shared across multiple relational databases.
*
* @see lithium\data\model\Query
*/
abstract class Database extends \lithium\data\Source {
/**
* @var PDO
*/
public $connection;
/**
* The supported column types and their default values
*
* @var array
*/
protected $_columns = array(
'string' => array('length' => 255)
);
/**
* Strings used to render the given statement
*
* @see lithium\data\source\Database::renderCommand()
* @var array
*/
protected $_strings = array(
'create' => "INSERT INTO {:source} ({:fields}) VALUES ({:values});{:comment}",
'update' => "UPDATE {:source} SET {:fields} {:conditions};{:comment}",
'delete' => "DELETE {:flags} FROM {:source} {:conditions};{:comment}",
'join' => "{:mode} JOIN {:source} {:alias} {:constraints}",
'schema' => "CREATE TABLE {:source} (\n{:columns}{:constraints}){:table};{:comment}",
'drop' => "DROP TABLE {:exists}{:source};"
);
/**
* Classes used by `Database`.
*
* @var array
*/
protected $_classes = array(
'entity' => 'lithium\data\entity\Record',
'set' => 'lithium\data\collection\RecordSet',
'relationship' => 'lithium\data\model\Relationship',
'result' => 'lithium\data\source\database\adapter\pdo\Result',
'schema' => 'lithium\data\Schema',
'query' => 'lithium\data\model\Query'
);
/**
* List of SQL operators, paired with handling options.
*
* @var array
*/
protected $_operators = array(
'=' => array('multiple' => 'IN'),
'<' => array(),
'>' => array(),
'<=' => array(),
'>=' => array(),
'!=' => array('multiple' => 'NOT IN'),
'<>' => array('multiple' => 'NOT IN'),
'BETWEEN' => array('format' => 'BETWEEN ? AND ?'),
'LIKE' => array(),
'NOT LIKE' => array(),
'IS' => array(),
'IS NOT' => array()
);
protected $_constraintTypes = array(
'AND' => true,
'and' => true,
'OR' => true,
'or' => true
);
/**
* A pair of opening/closing quote characters used for quoting identifiers in SQL queries.
*
* @var array
*/
protected $_quotes = array();
/**
* Array of named callable objects representing different strategies for performing specific
* types of queries.
*
* @var array
*/
protected $_strategies = array();
/**
* Getter/Setter for the connection's encoding
* Abstract. Must be defined by child class.
*
* @param mixed $encoding
* @return mixed.
*/
abstract public function encoding($encoding = null);
/**
* Return the last errors produced by a the execution of a query.
* Abstract. Must be defined by child class.
*
*/
abstract public function error();
/**
* Execute a given query
* Abstract. Must be defined by child class.
*
* @see lithium\data\source\Database::renderCommand()
* @param string $sql The sql string to execute
* @return resource
*/
abstract protected function _execute($sql);
/**
* Get the last insert id from the database.
* Abstract. Must be defined by child class.
*
* @param $query lithium\data\model\Query $context The given query.
* @return void
*/
abstract protected function _insertId($query);
/**
* Creates the database object and set default values for it.
*
* Options defined:
* - 'database' _string_ Name of the database to use. Defaults to `null`.
* - 'host' _string_ Name/address of server to connect to. Defaults to 'localhost'.
* - 'login' _string_ Username to use when connecting to server. Defaults to 'root'.
* - 'password' _string_ Password to use when connecting to server. Defaults to `''`.
* - 'persistent' _boolean_ If true a persistent connection will be attempted, provided the
* adapter supports it. Defaults to `true`.
*
* @param $config array Array of configuration options.
* @return Database object.
*/
public function __construct(array $config = array()) {
$defaults = array(
'persistent' => true,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => null,
'encoding' => null,
'dsn' => null,
'options' => array()
);
parent::__construct($config + $defaults);
}
/**
* Initialize `Database::$_strategies` because Closures cannot be created within the class
* definition.
*
* @see lithium\data\source\Database::$_strategies
*/
protected function _init() {
parent::_init();
$formatters = $this->_formatters();
foreach ($this->_columns as $type => $column) {
if (isset($formatters[$type])) {
$this->_columns[$type]['formatter'] = $formatters[$type];
}
}
$this->_strings += array(
'read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' .
'{:having} {:order} {:limit};{:comment}'
);
$this->_strategies += array(
'joined' => function($self, $model, $context) {
$with = $context->with();
$strategy = function($me, $model, $tree, $path, $from, &$deps) use ($self, $context, $with) {
foreach ($tree as $name => $childs) {
if (!$rel = $model::relations($name)) {
throw new QueryException("Model relationship `{$name}` not found.");
}
$constraints = array();
$alias = $name;
$relPath = $path ? $path . '.' . $name : $name;
if (isset($with[$relPath])) {
list($unallowed, $allowed) = Set::slice($with[$relPath], array(
'alias',
'constraints'
));
if ($unallowed) {
$message = "Only `'alias'` and `'constraints'` are allowed in ";
$message .= "`'with'` using the `'joined'` strategy.";
throw new QueryException($message);
}
extract($with[$relPath]);
}
$to = $context->alias($alias, $relPath);
$deps[$to] = $deps[$from];
$deps[$to][] = $from;
if ($context->relationships($relPath) === null) {
$context->relationships($relPath, array(
'type' => $rel->type(),
'model' => $rel->to(),
'fieldName' => $rel->fieldName(),
'alias' => $to
));
$self->join($context, $rel, $from, $to, $constraints);
}
if (!empty($childs)) {
$me($me, $rel->to(), $childs, $relPath, $to, $deps);
}
}
};
$tree = Set::expand(array_fill_keys(array_keys($with), false));
$alias = $context->alias();
$deps = array($alias => array());
$strategy($strategy, $model, $tree, '', $alias, $deps);
$models = $context->models();
foreach ($context->fields() as $field) {
if (!is_string($field)) {
continue;
}
list($alias, $field) = $self->invokeMethod('_splitFieldname', array($field));
$alias = $alias ?: $field;
if ($alias && isset($models[$alias])) {
foreach ($deps[$alias] as $depAlias) {
$depModel = $models[$depAlias];
$context->fields(array($depAlias => (array) $depModel::meta('key')));
}
}
}
},
'nested' => function($self, $model, $context) {
throw new QueryException("This strategy is not yet implemented.");
}
);
}
public function connect() {
$this->_isConnected = false;
$config = $this->_config;
if (!$config['database']) {
throw new ConfigException('No Database configured');
}
if (!$config['dsn']) {
throw new ConfigException('No DSN setup for DB Connection');
}
$dsn = $config['dsn'];
$options = $config['options'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->connection = new PDO($dsn, $config['login'], $config['password'], $options);
} catch (PDOException $e) {
preg_match('/SQLSTATE\[(.+?)\]/', $e->getMessage(), $code);
$code = $code[1] ?: 0;
switch (true) {
case $code === 'HY000' || substr($code, 0, 2) === '08':
$msg = "Unable to connect to host `{$config['host']}`.";
throw new NetworkException($msg, null, $e);
break;
case in_array($code, array('28000', '42000')):
$msg = "Host connected, but could not access database `{$config['database']}`.";
throw new ConfigException($msg, null, $e);
break;
}
throw new ConfigException("An unknown configuration error has occured.", null, $e);
}
$this->_isConnected = true;
if ($this->_config['encoding']) {
$this->encoding($this->_config['encoding']);
}
return $this->_isConnected;
}
/**
* Disconnects the adapter from the database.
*
* @return boolean Returns `true` on success, else `false`.
*/
public function disconnect() {
if ($this->_isConnected) {
unset($this->connection);
$this->_isConnected = false;
}
return true;
}
/**
* Field name handler to ensure proper escaping.
*
* @param string $name Field or identifier name.
* @return string Returns `$name` quoted according to the rules and quote characters of the
* database adapter subclass.
*/
public function name($name) {
$open = reset($this->_quotes);
$close = next($this->_quotes);
list($first, $second) = $this->_splitFieldname($name);
if ($first) {
return "{$open}{$first}{$close}.{$open}{$second}{$close}";
}
return preg_match('/^[a-z0-9_-]+$/i', $name) ? "{$open}{$name}{$close}" : $name;
}
/**
* Return the alias and the field name from an identifier name.
*
* @param string $field Field name or identifier name.
* @return array Returns an array with the alias (or `null` if not applicable) as first value
* and the field name as second value.
*/
protected function _splitFieldname($field) {
if (is_string($field)) {
if (preg_match('/^[a-z0-9_-]+\.([a-z0-9_-]+|\*)$/i', $field)) {
return explode('.', $field, 2);
}
}
return array(null, $field);
}
/**
* Return the field name from a conditions key.
*
* @param string $field Field or identifier name.
* @return string Returns the field name without the table alias, if applicable.
* @todo Eventually, this should be refactored and moved to the Query or Schema
* class. Also, by handling field resolution in this way we are not handling
* cases where query conditions use the same field name in multiple tables.
* e.g. Foos.bar and Bars.bar will both return bar.
*/
protected function _fieldName($field) {
if (is_string($field)) {
if (preg_match('/^[a-z0-9_-]+\.[a-z0-9_-]+$/i', $field)) {
list($first, $second) = explode('.', $field, 2);
return $second;
}
}
return $field;
}
/**
* Converts a given value into the proper type based on a given schema definition.
*
* @see lithium\data\source\Database::schema()
* @param mixed $value The value to be converted. Arrays will be recursively converted.
* @param array $schema Formatted array from `lithium\data\source\Database::schema()`
* @return mixed value with converted type
*/
public function value($value, array $schema = array()) {
if (is_array($value)) {
foreach ($value as $key => $val) {
$value[$key] = $this->value($val, isset($schema[$key]) ? $schema[$key] : $schema);
}
return $value;
}
if (is_object($value) && isset($value->scalar)) {
return $value->scalar;
}
if ($value === null) {
return 'NULL';
}
$type = isset($schema['type']) ? $schema['type'] : $this->_introspectType($value);
$column = isset($this->_columns[$type]) ? $this->_columns[$type] : null;
return $this->_cast($type, $value, $column, $schema);
}
/**
* Cast a value according to a column type, used by `Database::value()`
*
* @see lithium\data\source\Database::value()
* @param string $type Name of the column type
* @param string $value Value to cast
* @param array $column The column definition
* @return mixed Casted value
*/
protected function _cast($type, $value, $column, $schema = array()) {
$column += array('formatter' => null, 'format' => null);
$schema += array('default' => null, 'null' => false);
if (is_object($value)) {
return $value;
}
if ($formatter = $column['formatter']) {
$format = $column['format'];
return $format ? $formatter($format, $value) : $formatter($value);
}
return $this->connection->quote($value);
}
/**
* Provide an associative array of Closures to be used as the "formatter" key inside of the
* `Database::$_columns` specification. Each Closure should return the appropriately quoted
* or unquoted value and accept one or two parameters:
* - @param mixed $value to be formatted
* - @param mixed $format to apply to $value
*
* @see lithium\data\source\Database::$_columns
* @see lithium\data\source\Database::_init()
* @return array of column types to Closure formatter
*/
protected function _formatters() {
$self = $this;
$datetime = $timestamp = $date = $time = function($format, $value) use ($self) {
if ($format && (($time = strtotime($value)) !== false)) {
$value = date($format, $time);
}
return $self->connection->quote($value);
};
return compact('datetime', 'timestamp', 'date', 'time') + array(
'boolean' => function($value) {
return $value ? 1 : 0;
}
);
}
/**
* Inserts a new record into the database based on a the `Query`. The record is updated
* with the id of the insert.
*
* @see lithium\util\String::insert()
* @param object $query An SQL query string, or `lithium\data\model\Query` object instance.
* @param array $options If $query is a string, $options contains an array of bind values to be
* escaped, quoted, and inserted into `$query` using `String::insert()`.
* @return boolean Returns `true` if the query succeeded, otherwise `false`.
* @filter
*/
public function create($query, array $options = array()) {
return $this->_filter(__METHOD__, compact('query', 'options'), function($self, $params) {
$query = $params['query'];
$model = $entity = $object = $id = null;
if (is_object($query)) {
$object = $query;
$model = $query->model();
$params = $query->export($self);
$entity =& $query->entity();
$query = $self->renderCommand('create', $params, $query);
} else {
$query = String::insert($query, $self->value($params['options']));
}
if (!$self->invokeMethod('_execute', array($query))) {
return false;
}
if ($entity) {
if (($model) && !$model::key($entity)) {
$id = $self->invokeMethod('_insertId', array($object));
}
$entity->sync($id);
}
return true;
});
}
/**
* Reads records from a database using a `lithium\data\model\Query` object or raw SQL string.
*
* @param string|object $query `lithium\data\model\Query` object or SQL string.
* @param array $options If `$query` is a raw string, contains the values that will be escaped
* and quoted. Other options:
* - `'return'` _string_: switch return between `'array'`, `'item'`, or
* `'resource'` _string_: Defaults to `'item'`.
* @return mixed Determined by `$options['return']`.
* @filter
*/
public function read($query, array $options = array()) {
$defaults = array(
'return' => is_string($query) ? 'array' : 'item',
'schema' => null,
'quotes' => $this->_quotes
);
$options += $defaults;
return $this->_filter(__METHOD__, compact('query', 'options'), function($self, $params) {
$query = $params['query'];
$args = $params['options'];
$return = $args['return'];
unset($args['return']);
$model = is_object($query) ? $query->model() : null;
if (is_string($query)) {
$sql = String::insert($query, $self->value($args));
} else {
if (!$data = $self->invokeMethod('_queryExport', array($query))) {
return false;
}
$sql = $self->renderCommand($data['type'], $data);
}
$result = $self->invokeMethod('_execute', array($sql));
switch ($return) {
case 'resource':
return $result;
case 'array':
$columns = $args['schema'] ?: $self->schema($query, $result);
if (!is_array(reset($columns))) {
$columns = array('' => $columns);
}
$i = 0;
$records = array();
foreach ($result as $data) {
$offset = 0;
$records[$i] = array();
foreach ($columns as $path => $cols) {
$len = count($cols);
$values = array_combine($cols, array_slice($data, $offset, $len));
if ($path) {
$records[$i][$path] = $values;
} else {
$records[$i] += $values;
}
$offset += $len;
}
$i++;
}
return Set::expand($records);
case 'item':
return $model::create(array(), compact('query', 'result') + array(
'class' => 'set', 'defaults' => false
));
}
});
}
/**
* Helper which export the query export
*
* @param object $query The query object
* @return array The export array
*/
protected function &_queryExport($query) {
$data = $query->export($this);
if ($query->limit() && ($model = $query->model())) {
foreach ($query->relationships() as $relation) {
if ($relation['type'] === 'hasMany') {
$name = $model::meta('name');
$key = $model::key();
$fields = $data['fields'];
$fieldname = $this->name("{$name}.{$key}");
$data['fields'] = "DISTINCT({$fieldname}) AS _ID_";
$sql = $this->renderCommand('read', $data);
$result = $this->_execute($sql);
$ids = array();
while ($row = $result->next()) {
$ids[] = $row[0];
}
if (!$ids) {
$return = null;
return $return;
}
$data['fields'] = $fields;
$data['limit'] = '';
$data['conditions'] = $this->conditions(array(
"{$name}.{$key}" => $ids
), $query);
return $data;
}
}
}
return $data;
}
/**
* Updates a record in the database based on the given `Query`.
*
* @param object $query A `lithium\data\model\Query` object
* @param array $options none
* @return boolean
* @filter
*/
public function update($query, array $options = array()) {
return $this->_filter(__METHOD__, compact('query', 'options'), function($self, $params) {
$query = $params['query'];
$params = $query->export($self);
$sql = $self->renderCommand('update', $params, $query);
$result = (boolean) $self->invokeMethod('_execute', array($sql));
if ($result && is_object($query) && $query->entity()) {
$query->entity()->sync();
}
return $result;
});
}
/**
* Deletes a record in the database based on the given `Query`.
*
* @param object $query An SQL string, or `lithium\data\model\Query` object instance.
* @param array $options If `$query` is a string, `$options` is the array of quoted/escaped
* parameter values to be inserted into the query.
* @return boolean Returns `true` on successful query execution (not necessarily if records are
* deleted), otherwise `false`.
* @filter
*/
public function delete($query, array $options = array()) {
return $this->_filter(__METHOD__, compact('query', 'options'), function($self, $params) {
$query = $params['query'];
$isObject = is_object($query);
if ($isObject) {
$sql = $self->renderCommand('delete', $query->export($self), $query);
} else {
$sql = String::insert($query, $self->value($params['options']));
}
$result = (boolean) $self->invokeMethod('_execute', array($sql));
if ($result && $isObject && $query->entity()) {
$query->entity()->sync(null, array(), array('dematerialize' => true));
}
return $result;
});
}
/**
* Executes calculation-related queries, such as those required for `count` and other
* aggregates.
*
* @param string $type Only accepts `count`.
* @param mixed $query The query to be executed.
* @param array $options Optional arguments for the `read()` query that will be executed
* to obtain the calculation result.
* @return integer Result of the calculation.
*/
public function calculation($type, $query, array $options = array()) {
$query->calculate($type);
switch ($type) {
case 'count':
if (strpos($fields = $this->fields($query->fields(), $query), ',') !== false) {
$fields = "*";
}
$query->fields("COUNT({$fields}) as count", true);
$query->map(array($query->alias() => array('count')));
list($record) = $this->read($query, $options)->data();
return isset($record['count']) ? intval($record['count']) : null;
}
}
/**
* Defines or modifies the default settings of a relationship between two models.
*
* @param string $class the primary model of the relationship
* @param string $type the type of the relationship (hasMany, hasOne, belongsTo)
* @param string $name the name of the relationship
* @param array $config relationship options
* @return array Returns an array containing the configuration for a model relationship.
*/
public function relationship($class, $type, $name, array $config = array()) {
$primary = $class::meta('key');
if (is_array($primary)) {
$key = array_combine($primary, $primary);
} elseif ($type === 'hasMany' || $type === 'hasOne') {
$secondary = Inflector::underscore(Inflector::singularize($class::meta('name')));
$key = array($primary => "{$secondary}_id");
} else {
$key = Inflector::underscore(Inflector::singularize($name)) . '_id';
}
$from = $class;
$fieldName = $this->relationFieldName($type, $name);
$config += compact('type', 'name', 'key', 'from', 'fieldName');
return $this->_instance('relationship', $config);
}
/**
* Determines the set of methods to be used when exporting query values.
*
* @return array
*/
public function methods() {
$result = parent::methods();
$key = array_search('schema', $result);
unset($result[$key]);
return $result;
}
/**
* Returns a given `type` statement for the given data, rendered from `Database::$_strings`.
*
* @param string $type One of `'create'`, `'read'`, `'update'`, `'delete'` or `'join'`.
* @param string $data The data to replace in the string.
* @param string $context
* @return string
*/
public function renderCommand($type, $data = null, $context = null) {
if (is_object($type)) {
$context = $type;
$data = $context->export($this);
$type = $context->type();
}
if (!isset($this->_strings[$type])) {
throw new InvalidArgumentException("Invalid query type `{$type}`.");
}
$template = $this->_strings[$type];
$data = array_filter($data);
$placeholders = array();
foreach ($data as $key => $value) {
$placeholders[$key] = "{{$key}}";
}
$template = String::insert($template, $placeholders, array('clean' => true));
return trim(String::insert($template, $data, array('before' => '{')));
}
/**
* Builds an array of keyed on the fully-namespaced `Model` with array of fields as values
* for the given `Query`
*
* @param data\model\Query $query A Query instance.
* @param object $resource
* @param object $context
*/
public function schema($query, $resource = null, $context = null) {
if (is_object($query)) {
$query->applyStrategy($this);
return $this->_schema($query, $this->_fields($query->fields(), $query));
}
$result = array();
$count = $resource->resource()->columnCount();
for ($i = 0; $i < $count; $i++) {
$meta = $resource->resource()->getColumnMeta($i);
$result[] = $meta['name'];
}
return $result;
}
/**
* Helper method for `data\model\Database::shema()`
*
* @param data\model\Query $query A Query instance.
* @param array $fields Array of formatted fields.
*/
protected function _schema($query, $fields = null) {
$model = $query->model();
$paths = $query->paths($this);
$models = $query->models($this);
$alias = $query->alias();
$result = array();
if (!$model) {
foreach ($fields as $field => $value) {
if (is_array($value)) {
$result[$field] = array_keys($value);
} else {
$result[''][] = $field;
}
}
return $result;
}
if (!$fields) {
foreach ($paths as $alias => $relation) {
$model = $models[$alias];
$result[$relation] = $model::schema()->names();
}
return $result;
}
$unalias = function ($value) {
if (is_object($value) && isset($value->scalar)) {
$value = $value->scalar;
}
$aliasing = preg_split("/\s+as\s+/i", $value);
return isset($aliasing[1]) ? $aliasing[1] : $value;
};
if (isset($fields[0])) {
$raw = array_map($unalias, $fields[0]);
unset($fields[0]);
}
$fields = isset($fields[$alias]) ? array($alias => $fields[$alias]) + $fields : $fields;
foreach ($fields as $field => $value) {
if (is_array($value)) {
if (isset($value['*'])) {
$relModel = $models[$field];
$result[$paths[$field]] = $relModel::schema()->names();
} else {
$result[$paths[$field]] = array_map($unalias, array_keys($value));
}
}
}
if (isset($raw)) {
$result[''] = isset($result['']) ? array_merge($raw, $result['']) : $raw;
}
return $result;
}
/**
* Returns a string of formatted conditions to be inserted into the query statement. If the
* query conditions are defined as an array, key pairs are converted to SQL strings.
*
* Conversion rules are as follows:
*
* - If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL
* fragment and returned.
*
* @param string|array $conditions The conditions for this query.
* @param object $context The current `lithium\data\model\Query` instance.
* @param array $options
* - `prepend` _boolean_: Whether the return string should be prepended with the
* `WHERE` keyword.
* @return string Returns the `WHERE` clause of an SQL query.
*/
public function conditions($conditions, $context, array $options = array()) {
$defaults = array('prepend' => 'WHERE');
$options += $defaults;
return $this->_conditions($conditions, $context, $options);
}
/**
* Returns a string of formatted havings to be inserted into the query statement. If the
* query havings are defined as an array, key pairs are converted to SQL strings.
*
* Conversion rules are as follows:
*
* - If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL
* fragment and returned.
*
* @param string|array $conditions The havings for this query.
* @param object $context The current `lithium\data\model\Query` instance.
* @param array $options
* - `prepend` _boolean_: Whether the return string should be prepended with the
* `HAVING` keyword.
* @return string Returns the `HAVING` clause of an SQL query.
*/
public function having($conditions, $context, array $options = array()) {
$defaults = array('prepend' => 'HAVING');
$options += $defaults;
return $this->_conditions($conditions, $context, $options);
}
/**
* Returns a string of formatted conditions to be inserted into the query statement. If the
* query conditions are defined as an array, key pairs are converted to SQL strings.
*
* Conversion rules are as follows:
*
* - If `$key` is numeric and `$value` is a string, `$value` is treated as a literal SQL
* fragment and returned.
*
* @param string|array $conditions The conditions for this query.
* @param object $context The current `lithium\data\model\Query` instance.
* @param array $options
* - `prepend` mixed: The string to prepend or false for no prepending
* @return string Returns an SQL conditions clause.
*/
protected function _conditions($conditions, $context, array $options = array()) {
$defaults = array('prepend' => false);
$ops = $this->_operators;
$options += $defaults;
switch (true) {
case empty($conditions):
return '';
case is_string($conditions):
return $options['prepend'] ? $options['prepend'] . " {$conditions}" : $conditions;
case !is_array($conditions):
return '';
}
$result = array();
foreach ($conditions as $key => $value) {
$return = $this->_processConditions($key, $value, $context);
if ($return) {
$result[] = $return;
}
}
$result = join(" AND ", $result);
return ($options['prepend'] && $result) ? $options['prepend'] . " {$result}" : $result;
}
protected function _processConditions($key, $value, $context, $schema = null, $glue = 'AND') {
$constraintTypes =& $this->_constraintTypes;
$model = $context->model();
$models = $context->models();
list($first, $second) = $this->_splitFieldname($key);
if ($first && isset($models[$first]) && $class = $models[$first]) {
$schema = $class::schema();
} elseif ($model) {
$schema = $model::schema();
}
$fieldMeta = $schema ? (array) $schema->fields($second) : array();
switch (true) {
case (is_numeric($key) && is_string($value)):
return $value;
case is_object($value) && isset($value->scalar):
if (is_numeric($key)) {
return $this->value($value);
}
case is_scalar($value) || is_null($value):
if ($context && ($context->type() === 'read') && ($alias = $context->alias())) {
$key = $this->_aliasing($key, $alias);
}
if (isset($value)) {
return $this->name($key) . ' = ' . $this->value($value, $fieldMeta);
}
return $this->name($key) . ' IS NULL';
case is_numeric($key) && is_array($value):
$result = array();
foreach ($value as $cKey => $cValue) {
$result[] = $this->_processConditions($cKey, $cValue, $context, $schema, $glue);
}
return '(' . implode(' ' . $glue . ' ', $result) . ')';
case (is_string($key) && is_object($value)):
$value = trim(rtrim($this->renderCommand($value), ';'));
return "{$this->name($key)} IN ({$value})";
case is_array($value) && isset($constraintTypes[strtoupper($key)]):
$result = array();
$glue = strtoupper($key);
foreach ($value as $cKey => $cValue) {
$result[] = $this->_processConditions($cKey, $cValue, $context, $schema, $glue);
}
return '(' . implode(' ' . $glue . ' ', $result) . ')';
case $result = $this->_processOperator($key, $value, $fieldMeta, $glue):
return $result;
case is_array($value):
$value = join(', ', $this->value($value, $fieldMeta));
return "{$this->name($key)} IN ({$value})";
}
}
/**
* Helper method used by `_processConditions`.
*
* @param string The field name string.
* @param array The operator to parse.
* @param array The schema of the field.
* @param string The glue operator (e.g `'AND'` or '`OR`'.
* @return mixed Returns the operator expression string or `false` if no operator
* is applicable.
* @throws A `QueryException` if the operator is not supported.
*/
protected function _processOperator($key, $value, $fieldMeta, $glue) {
if (!is_string($key) || !is_array($value)) {
return false;
}