1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Database\Table;
9:
10: use Nette;
11: use Nette\Database\Context;
12: use Nette\Database\IConventions;
13:
14:
15: 16: 17: 18:
19: class Selection implements \Iterator, IRowContainer, \ArrayAccess, \Countable
20: {
21: use Nette\SmartObject;
22:
23:
24: protected $context;
25:
26:
27: protected $conventions;
28:
29:
30: protected $cache;
31:
32:
33: protected $sqlBuilder;
34:
35:
36: protected $name;
37:
38:
39: protected $primary;
40:
41:
42: protected $primarySequence = false;
43:
44:
45: protected $rows;
46:
47:
48: protected $data;
49:
50:
51: protected $dataRefreshed = false;
52:
53:
54: protected $globalRefCache;
55:
56:
57: protected $refCache;
58:
59:
60: protected $generalCacheKey;
61:
62:
63: protected $specificCacheKey;
64:
65:
66: protected $aggregation = [];
67:
68:
69: protected $accessedColumns;
70:
71:
72: protected $previousAccessedColumns;
73:
74:
75: protected $observeCache = false;
76:
77:
78: protected $keys = [];
79:
80:
81: 82: 83: 84: 85: 86: 87:
88: public function __construct(Context $context, IConventions $conventions, $tableName, Nette\Caching\IStorage $cacheStorage = null)
89: {
90: $this->context = $context;
91: $this->conventions = $conventions;
92: $this->name = $tableName;
93:
94: $this->cache = $cacheStorage ? new Nette\Caching\Cache($cacheStorage, 'Nette.Database.' . md5($context->getConnection()->getDsn())) : null;
95: $this->primary = $conventions->getPrimary($tableName);
96: $this->sqlBuilder = new SqlBuilder($tableName, $context);
97: $this->refCache = &$this->getRefTable($refPath)->globalRefCache[$refPath];
98: }
99:
100:
101: public function __destruct()
102: {
103: $this->saveCacheState();
104: }
105:
106:
107: public function __clone()
108: {
109: $this->sqlBuilder = clone $this->sqlBuilder;
110: }
111:
112:
113: 114: 115:
116: public function getName()
117: {
118: return $this->name;
119: }
120:
121:
122: 123: 124: 125:
126: public function getPrimary($throw = true)
127: {
128: if ($this->primary === null && $throw) {
129: throw new \LogicException("Table '{$this->name}' does not have a primary key.");
130: }
131: return $this->primary;
132: }
133:
134:
135: 136: 137:
138: public function getPrimarySequence()
139: {
140: if ($this->primarySequence === false) {
141: $this->primarySequence = $this->context->getStructure()->getPrimaryKeySequence($this->name);
142: }
143:
144: return $this->primarySequence;
145: }
146:
147:
148: 149: 150: 151:
152: public function setPrimarySequence($sequence)
153: {
154: $this->primarySequence = $sequence;
155: return $this;
156: }
157:
158:
159: 160: 161:
162: public function getSql()
163: {
164: return $this->sqlBuilder->buildSelectQuery($this->getPreviousAccessedColumns());
165: }
166:
167:
168: 169: 170: 171: 172:
173: public function getPreviousAccessedColumns()
174: {
175: if ($this->cache && $this->previousAccessedColumns === null) {
176: $this->accessedColumns = $this->previousAccessedColumns = $this->cache->load($this->getGeneralCacheKey());
177: if ($this->previousAccessedColumns === null) {
178: $this->previousAccessedColumns = [];
179: }
180: }
181:
182: return array_keys(array_filter((array) $this->previousAccessedColumns));
183: }
184:
185:
186: 187: 188: 189:
190: public function getSqlBuilder()
191: {
192: return $this->sqlBuilder;
193: }
194:
195:
196:
197:
198:
199: 200: 201: 202: 203:
204: public function get($key)
205: {
206: $clone = clone $this;
207: return $clone->wherePrimary($key)->fetch();
208: }
209:
210:
211: 212: 213: 214:
215: public function fetch()
216: {
217: $this->execute();
218: $return = current($this->data);
219: next($this->data);
220: return $return;
221: }
222:
223:
224: 225: 226: 227: 228:
229: public function fetchField($column = null)
230: {
231: if ($column) {
232: $this->select($column);
233: }
234:
235: $row = $this->fetch();
236: if ($row) {
237: return $column ? $row[$column] : array_values($row->toArray())[0];
238: }
239:
240: return false;
241: }
242:
243:
244: 245: 246:
247: public function fetchPairs($key = null, $value = null)
248: {
249: return Nette\Database\Helpers::toPairs($this->fetchAll(), $key, $value);
250: }
251:
252:
253: 254: 255:
256: public function fetchAll()
257: {
258: return iterator_to_array($this);
259: }
260:
261:
262: 263: 264:
265: public function fetchAssoc($path)
266: {
267: $rows = array_map('iterator_to_array', $this->fetchAll());
268: return Nette\Utils\Arrays::associate($rows, $path);
269: }
270:
271:
272:
273:
274:
275: 276: 277: 278: 279:
280: public function select($columns, ...$params)
281: {
282: $this->emptyResultSet();
283: $this->sqlBuilder->addSelect($columns, ...$params);
284: return $this;
285: }
286:
287:
288: 289: 290: 291: 292:
293: public function wherePrimary($key)
294: {
295: if (is_array($this->primary) && Nette\Utils\Arrays::isList($key)) {
296: if (isset($key[0]) && is_array($key[0])) {
297: $this->where($this->primary, $key);
298: } else {
299: foreach ($this->primary as $i => $primary) {
300: $this->where($this->name . '.' . $primary, $key[$i]);
301: }
302: }
303: } elseif (is_array($key) && !Nette\Utils\Arrays::isList($key)) {
304: $this->where($key);
305: } else {
306: $this->where($this->name . '.' . $this->getPrimary(), $key);
307: }
308:
309: return $this;
310: }
311:
312:
313: 314: 315: 316: 317: 318:
319: public function where($condition, ...$params)
320: {
321: $this->condition($condition, $params);
322: return $this;
323: }
324:
325:
326: 327: 328: 329: 330: 331: 332:
333: public function joinWhere($tableChain, $condition, ...$params)
334: {
335: $this->condition($condition, $params, $tableChain);
336: return $this;
337: }
338:
339:
340: 341: 342: 343: 344:
345: protected function condition($condition, array $params, $tableChain = null)
346: {
347: $this->emptyResultSet();
348: if (is_array($condition) && $params === []) {
349: foreach ($condition as $key => $val) {
350: if (is_int($key)) {
351: $this->condition($val, [], $tableChain);
352: } else {
353: $this->condition($key, [$val], $tableChain);
354: }
355: }
356: } elseif ($tableChain) {
357: $this->sqlBuilder->addJoinCondition($tableChain, $condition, ...$params);
358: } else {
359: $this->sqlBuilder->addWhere($condition, ...$params);
360: }
361: }
362:
363:
364: 365: 366: 367: 368: 369: 370:
371: public function whereOr(array $parameters)
372: {
373: if (count($parameters) < 2) {
374: return $this->where($parameters);
375: }
376: $columns = [];
377: $values = [];
378: foreach ($parameters as $key => $val) {
379: if (is_int($key)) {
380: $columns[] = $val;
381: } elseif (strpos($key, '?') === false) {
382: $columns[] = $key . ' ?';
383: $values[] = $val;
384: } else {
385: $qNumber = substr_count($key, '?');
386: if ($qNumber > 1 && (!is_array($val) || $qNumber !== count($val))) {
387: throw new Nette\InvalidArgumentException('Argument count does not match placeholder count.');
388: }
389: $columns[] = $key;
390: $values = array_merge($values, $qNumber > 1 ? $val : [$val]);
391: }
392: }
393: $columnsString = '(' . implode(') OR (', $columns) . ')';
394: return $this->where($columnsString, $values);
395: }
396:
397:
398: 399: 400: 401: 402:
403: public function order($columns, ...$params)
404: {
405: $this->emptyResultSet();
406: $this->sqlBuilder->addOrder($columns, ...$params);
407: return $this;
408: }
409:
410:
411: 412: 413: 414: 415: 416:
417: public function limit($limit, $offset = null)
418: {
419: $this->emptyResultSet();
420: $this->sqlBuilder->setLimit($limit, $offset);
421: return $this;
422: }
423:
424:
425: 426: 427: 428: 429: 430:
431: public function page($page, $itemsPerPage, &$numOfPages = null)
432: {
433: if (func_num_args() > 2) {
434: $numOfPages = (int) ceil($this->count('*') / $itemsPerPage);
435: }
436: if ($page < 1) {
437: $itemsPerPage = 0;
438: }
439: return $this->limit($itemsPerPage, ($page - 1) * $itemsPerPage);
440: }
441:
442:
443: 444: 445: 446: 447:
448: public function group($columns, ...$params)
449: {
450: $this->emptyResultSet();
451: $this->sqlBuilder->setGroup($columns, ...$params);
452: return $this;
453: }
454:
455:
456: 457: 458: 459: 460:
461: public function having($having, ...$params)
462: {
463: $this->emptyResultSet();
464: $this->sqlBuilder->setHaving($having, ...$params);
465: return $this;
466: }
467:
468:
469: 470: 471: 472: 473: 474:
475: public function alias($tableChain, $alias)
476: {
477: $this->sqlBuilder->addAlias($tableChain, $alias);
478: return $this;
479: }
480:
481:
482:
483:
484:
485: 486: 487: 488: 489:
490: public function aggregation($function)
491: {
492: $selection = $this->createSelectionInstance();
493: $selection->getSqlBuilder()->importConditions($this->getSqlBuilder());
494: $selection->select($function);
495: foreach ($selection->fetch() as $val) {
496: return $val;
497: }
498: }
499:
500:
501: 502: 503: 504: 505:
506: public function count($column = null)
507: {
508: if (!$column) {
509: $this->execute();
510: return count($this->data);
511: }
512: return $this->aggregation("COUNT($column)");
513: }
514:
515:
516: 517: 518: 519: 520:
521: public function min($column)
522: {
523: return $this->aggregation("MIN($column)");
524: }
525:
526:
527: 528: 529: 530: 531:
532: public function max($column)
533: {
534: return $this->aggregation("MAX($column)");
535: }
536:
537:
538: 539: 540: 541: 542:
543: public function sum($column)
544: {
545: return $this->aggregation("SUM($column)");
546: }
547:
548:
549:
550:
551:
552: protected function execute()
553: {
554: if ($this->rows !== null) {
555: return;
556: }
557:
558: $this->observeCache = $this;
559:
560: if ($this->primary === null && $this->sqlBuilder->getSelect() === null) {
561: throw new Nette\InvalidStateException('Table with no primary key requires an explicit select clause.');
562: }
563:
564: try {
565: $result = $this->query($this->getSql());
566:
567: } catch (Nette\Database\DriverException $exception) {
568: if (!$this->sqlBuilder->getSelect() && $this->previousAccessedColumns) {
569: $this->previousAccessedColumns = false;
570: $this->accessedColumns = [];
571: $result = $this->query($this->getSql());
572: } else {
573: throw $exception;
574: }
575: }
576:
577: $this->rows = [];
578: $usedPrimary = true;
579: foreach ($result->getPdoStatement() as $key => $row) {
580: $row = $this->createRow($result->normalizeRow($row));
581: $primary = $row->getSignature(false);
582: $usedPrimary = $usedPrimary && (string) $primary !== '';
583: $this->rows[$usedPrimary ? $primary : $key] = $row;
584: }
585: $this->data = $this->rows;
586:
587: if ($usedPrimary && $this->accessedColumns !== false) {
588: foreach ((array) $this->primary as $primary) {
589: $this->accessedColumns[$primary] = true;
590: }
591: }
592: }
593:
594:
595: 596: 597:
598: protected function createRow(array $row)
599: {
600: return new ActiveRow($row, $this);
601: }
602:
603:
604: 605: 606:
607: public function createSelectionInstance($table = null)
608: {
609: return new self($this->context, $this->conventions, $table ?: $this->name, $this->cache ? $this->cache->getStorage() : null);
610: }
611:
612:
613: 614: 615:
616: protected function createGroupedSelectionInstance($table, $column)
617: {
618: return new GroupedSelection($this->context, $this->conventions, $table, $column, $this, $this->cache ? $this->cache->getStorage() : null);
619: }
620:
621:
622: 623: 624:
625: protected function query($query)
626: {
627: return $this->context->queryArgs($query, $this->sqlBuilder->getParameters());
628: }
629:
630:
631: protected function emptyResultSet($clearCache = true, $deleteRererencedCache = true)
632: {
633: if ($this->rows !== null && $clearCache) {
634: $this->saveCacheState();
635: }
636:
637: if ($clearCache) {
638:
639: $this->previousAccessedColumns = null;
640: $this->generalCacheKey = null;
641: }
642:
643: $this->rows = null;
644: $this->specificCacheKey = null;
645: $this->refCache['referencingPrototype'] = [];
646: if ($deleteRererencedCache) {
647: $this->refCache['referenced'] = [];
648: }
649: }
650:
651:
652: protected function saveCacheState()
653: {
654: if ($this->observeCache === $this && $this->cache && !$this->sqlBuilder->getSelect() && $this->accessedColumns !== $this->previousAccessedColumns) {
655: $previousAccessed = $this->cache->load($this->getGeneralCacheKey());
656: $accessed = $this->accessedColumns;
657: $needSave = is_array($accessed) && is_array($previousAccessed)
658: ? array_intersect_key($accessed, $previousAccessed) !== $accessed
659: : $accessed !== $previousAccessed;
660:
661: if ($needSave) {
662: $save = is_array($accessed) && is_array($previousAccessed) ? $previousAccessed + $accessed : $accessed;
663: $this->cache->save($this->getGeneralCacheKey(), $save);
664: $this->previousAccessedColumns = null;
665: }
666: }
667: }
668:
669:
670: 671: 672: 673:
674: protected function getRefTable(&$refPath)
675: {
676: return $this;
677: }
678:
679:
680: 681: 682:
683: protected function loadRefCache()
684: {
685: }
686:
687:
688: 689: 690: 691: 692:
693: protected function getGeneralCacheKey()
694: {
695: if ($this->generalCacheKey) {
696: return $this->generalCacheKey;
697: }
698:
699: $key = [__CLASS__, $this->name, $this->sqlBuilder->getConditions()];
700: $trace = [];
701: foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $item) {
702: $trace[] = isset($item['file'], $item['line']) ? $item['file'] . $item['line'] : null;
703: }
704:
705: $key[] = $trace;
706: return $this->generalCacheKey = md5(serialize($key));
707: }
708:
709:
710: 711: 712: 713: 714:
715: protected function getSpecificCacheKey()
716: {
717: if ($this->specificCacheKey) {
718: return $this->specificCacheKey;
719: }
720:
721: return $this->specificCacheKey = $this->sqlBuilder->getSelectQueryHash($this->getPreviousAccessedColumns());
722: }
723:
724:
725: 726: 727: 728: 729: 730:
731: public function accessColumn($key, $selectColumn = true)
732: {
733: if (!$this->cache) {
734: return false;
735: }
736:
737: if ($key === null) {
738: $this->accessedColumns = false;
739: $currentKey = key((array) $this->data);
740: } elseif ($this->accessedColumns !== false) {
741: $this->accessedColumns[$key] = $selectColumn;
742: }
743:
744: if ($selectColumn && $this->previousAccessedColumns && ($key === null || !isset($this->previousAccessedColumns[$key])) && !$this->sqlBuilder->getSelect()) {
745: if ($this->sqlBuilder->getLimit()) {
746: $generalCacheKey = $this->generalCacheKey;
747: $sqlBuilder = $this->sqlBuilder;
748:
749: $primaryValues = [];
750: foreach ((array) $this->rows as $row) {
751: $primary = $row->getPrimary();
752: $primaryValues[] = is_array($primary) ? array_values($primary) : $primary;
753: }
754:
755: $this->emptyResultSet(false);
756: $this->sqlBuilder = clone $this->sqlBuilder;
757: $this->sqlBuilder->setLimit(null, null);
758: $this->wherePrimary($primaryValues);
759:
760: $this->generalCacheKey = $generalCacheKey;
761: $this->previousAccessedColumns = [];
762: $this->execute();
763: $this->sqlBuilder = $sqlBuilder;
764: } else {
765: $this->emptyResultSet(false);
766: $this->previousAccessedColumns = [];
767: $this->execute();
768: }
769:
770: $this->dataRefreshed = true;
771:
772:
773: if (isset($currentKey)) {
774: while (key($this->data) !== null && key($this->data) !== $currentKey) {
775: next($this->data);
776: }
777: }
778: }
779: return $this->dataRefreshed;
780: }
781:
782:
783: 784: 785: 786:
787: public function removeAccessColumn($key)
788: {
789: if ($this->cache && is_array($this->accessedColumns)) {
790: $this->accessedColumns[$key] = false;
791: }
792: }
793:
794:
795: 796: 797: 798:
799: public function getDataRefreshed()
800: {
801: return $this->dataRefreshed;
802: }
803:
804:
805:
806:
807:
808: 809: 810: 811: 812:
813: public function insert($data)
814: {
815: if ($data instanceof self) {
816: $return = $this->context->queryArgs($this->sqlBuilder->buildInsertQuery() . ' ' . $data->getSql(), $data->getSqlBuilder()->getParameters());
817:
818: } else {
819: if ($data instanceof \Traversable) {
820: $data = iterator_to_array($data);
821: }
822: $return = $this->context->query($this->sqlBuilder->buildInsertQuery() . ' ?values', $data);
823: }
824:
825: $this->loadRefCache();
826:
827: if ($data instanceof self || $this->primary === null) {
828: unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
829: return $return->getRowCount();
830: }
831:
832: $primarySequenceName = $this->getPrimarySequence();
833: $primaryAutoincrementKey = $this->context->getStructure()->getPrimaryAutoincrementKey($this->name);
834:
835: $primaryKey = [];
836: foreach ((array) $this->primary as $key) {
837: if (isset($data[$key])) {
838: $primaryKey[$key] = $data[$key];
839: }
840: }
841:
842:
843: if (!empty($primarySequenceName) && $primaryAutoincrementKey) {
844: $primaryKey[$primaryAutoincrementKey] = $this->context->getInsertId($this->context->getConnection()->getSupplementalDriver()->delimite($primarySequenceName));
845:
846:
847: } elseif ($primaryAutoincrementKey) {
848: $primaryKey[$primaryAutoincrementKey] = $this->context->getInsertId($primarySequenceName);
849:
850:
851: } elseif (is_array($this->primary)) {
852: foreach ($this->primary as $key) {
853: if (!isset($data[$key])) {
854: return $data;
855: }
856: }
857:
858:
859: } elseif ($this->primary && isset($data[$this->primary])) {
860: $primaryKey = $data[$this->primary];
861:
862:
863: } else {
864: unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
865: return $return->getRowCount();
866: }
867:
868: $row = $this->createSelectionInstance()
869: ->select('*')
870: ->wherePrimary($primaryKey)
871: ->fetch();
872:
873: if ($this->rows !== null) {
874: if ($signature = $row->getSignature(false)) {
875: $this->rows[$signature] = $row;
876: $this->data[$signature] = $row;
877: } else {
878: $this->rows[] = $row;
879: $this->data[] = $row;
880: }
881: }
882:
883: return $row;
884: }
885:
886:
887: 888: 889: 890: 891: 892:
893: public function update($data)
894: {
895: if ($data instanceof \Traversable) {
896: $data = iterator_to_array($data);
897:
898: } elseif (!is_array($data)) {
899: throw new Nette\InvalidArgumentException;
900: }
901:
902: if (!$data) {
903: return 0;
904: }
905:
906: return $this->context->queryArgs(
907: $this->sqlBuilder->buildUpdateQuery(),
908: array_merge([$data], $this->sqlBuilder->getParameters())
909: )->getRowCount();
910: }
911:
912:
913: 914: 915: 916:
917: public function delete()
918: {
919: return $this->query($this->sqlBuilder->buildDeleteQuery())->getRowCount();
920: }
921:
922:
923:
924:
925:
926: 927: 928: 929: 930: 931: 932:
933: public function getReferencedTable(ActiveRow $row, $table, $column = null)
934: {
935: if (!$column) {
936: $belongsTo = $this->conventions->getBelongsToReference($this->name, $table);
937: if (!$belongsTo) {
938: return false;
939: }
940: list($table, $column) = $belongsTo;
941: }
942: if (!$row->accessColumn($column)) {
943: return false;
944: }
945:
946: $checkPrimaryKey = $row[$column];
947:
948: $referenced = &$this->refCache['referenced'][$this->getSpecificCacheKey()]["$table.$column"];
949: $selection = &$referenced['selection'];
950: $cacheKeys = &$referenced['cacheKeys'];
951: if ($selection === null || ($checkPrimaryKey !== null && !isset($cacheKeys[$checkPrimaryKey]))) {
952: $this->execute();
953: $cacheKeys = [];
954: foreach ($this->rows as $row) {
955: if ($row[$column] === null) {
956: continue;
957: }
958:
959: $key = $row[$column];
960: $cacheKeys[$key] = true;
961: }
962:
963: if ($cacheKeys) {
964: $selection = $this->createSelectionInstance($table);
965: $selection->where($selection->getPrimary(), array_keys($cacheKeys));
966: } else {
967: $selection = [];
968: }
969: }
970:
971: return isset($selection[$checkPrimaryKey]) ? $selection[$checkPrimaryKey] : null;
972: }
973:
974:
975: 976: 977: 978: 979: 980: 981:
982: public function getReferencingTable($table, $column, $active = null)
983: {
984: if (strpos($table, '.') !== false) {
985: list($table, $column) = explode('.', $table);
986: } elseif (!$column) {
987: $hasMany = $this->conventions->getHasManyReference($this->name, $table);
988: if (!$hasMany) {
989: return null;
990: }
991: list($table, $column) = $hasMany;
992: }
993:
994: $prototype = &$this->refCache['referencingPrototype'][$this->getSpecificCacheKey()]["$table.$column"];
995: if (!$prototype) {
996: $prototype = $this->createGroupedSelectionInstance($table, $column);
997: $prototype->where("$table.$column", array_keys((array) $this->rows));
998: }
999:
1000: $clone = clone $prototype;
1001: $clone->setActive($active);
1002: return $clone;
1003: }
1004:
1005:
1006:
1007:
1008:
1009: public function rewind()
1010: {
1011: $this->execute();
1012: $this->keys = array_keys($this->data);
1013: reset($this->keys);
1014: }
1015:
1016:
1017:
1018: public function current()
1019: {
1020: if (($key = current($this->keys)) !== false) {
1021: return $this->data[$key];
1022: } else {
1023: return false;
1024: }
1025: }
1026:
1027:
1028: 1029: 1030:
1031: public function key()
1032: {
1033: return current($this->keys);
1034: }
1035:
1036:
1037: public function next()
1038: {
1039: do {
1040: next($this->keys);
1041: } while (($key = current($this->keys)) !== false && !isset($this->data[$key]));
1042: }
1043:
1044:
1045: public function valid()
1046: {
1047: return current($this->keys) !== false;
1048: }
1049:
1050:
1051:
1052:
1053:
1054: 1055: 1056: 1057: 1058: 1059:
1060: public function offsetSet($key, $value)
1061: {
1062: $this->execute();
1063: $this->rows[$key] = $value;
1064: }
1065:
1066:
1067: 1068: 1069: 1070: 1071:
1072: public function offsetGet($key)
1073: {
1074: $this->execute();
1075: return $this->rows[$key];
1076: }
1077:
1078:
1079: 1080: 1081: 1082: 1083:
1084: public function offsetExists($key)
1085: {
1086: $this->execute();
1087: return isset($this->rows[$key]);
1088: }
1089:
1090:
1091: 1092: 1093: 1094: 1095:
1096: public function offsetUnset($key)
1097: {
1098: $this->execute();
1099: unset($this->rows[$key], $this->data[$key]);
1100: }
1101: }
1102: