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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
|
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Database\Table;
use Nette;
use Nette\Database\Context;
use Nette\Database\IConventions;
/**
* Filtered table representation.
* Selection is based on the great library NotORM http://www.notorm.com written by Jakub Vrana.
*/
class Selection implements \Iterator, IRowContainer, \ArrayAccess, \Countable
{
use Nette\SmartObject;
/** @var Context */
protected $context;
/** @var IConventions */
protected $conventions;
/** @var Nette\Caching\Cache */
protected $cache;
/** @var SqlBuilder */
protected $sqlBuilder;
/** @var string table name */
protected $name;
/** @var string|array|NULL primary key field name */
protected $primary;
/** @var string|bool primary column sequence name, FALSE for autodetection */
protected $primarySequence = FALSE;
/** @var IRow[] data read from database in [primary key => IRow] format */
protected $rows;
/** @var IRow[] modifiable data in [primary key => IRow] format */
protected $data;
/** @var bool */
protected $dataRefreshed = FALSE;
/** @var mixed cache array of Selection and GroupedSelection prototypes */
protected $globalRefCache;
/** @var mixed */
protected $refCache;
/** @var string */
protected $generalCacheKey;
/** @var string */
protected $specificCacheKey;
/** @var array of [conditions => [key => IRow]]; used by GroupedSelection */
protected $aggregation = [];
/** @var array of touched columns */
protected $accessedColumns;
/** @var array of earlier touched columns */
protected $previousAccessedColumns;
/** @var bool should instance observe accessed columns caching */
protected $observeCache = FALSE;
/** @var array of primary key values */
protected $keys = [];
/**
* Creates filtered table representation.
* @param Context
* @param IConventions
* @param string table name
* @param Nette\Caching\IStorage|NULL
*/
public function __construct(Context $context, IConventions $conventions, $tableName, Nette\Caching\IStorage $cacheStorage = NULL)
{
$this->context = $context;
$this->conventions = $conventions;
$this->name = $tableName;
$this->cache = $cacheStorage ? new Nette\Caching\Cache($cacheStorage, 'Nette.Database.' . md5($context->getConnection()->getDsn())) : NULL;
$this->primary = $conventions->getPrimary($tableName);
$this->sqlBuilder = new SqlBuilder($tableName, $context);
$this->refCache = & $this->getRefTable($refPath)->globalRefCache[$refPath];
}
public function __destruct()
{
$this->saveCacheState();
}
public function __clone()
{
$this->sqlBuilder = clone $this->sqlBuilder;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param bool
* @return string|array|NULL
*/
public function getPrimary($need = TRUE)
{
if ($this->primary === NULL && $need) {
throw new \LogicException("Table '{$this->name}' does not have a primary key.");
}
return $this->primary;
}
/**
* @return string
*/
public function getPrimarySequence()
{
if ($this->primarySequence === FALSE) {
$this->primarySequence = $this->context->getStructure()->getPrimaryKeySequence($this->name);
}
return $this->primarySequence;
}
/**
* @param string
* @return self
*/
public function setPrimarySequence($sequence)
{
$this->primarySequence = $sequence;
return $this;
}
/**
* @return string
*/
public function getSql()
{
return $this->sqlBuilder->buildSelectQuery($this->getPreviousAccessedColumns());
}
/**
* Loads cache of previous accessed columns and returns it.
* @internal
* @return array|false
*/
public function getPreviousAccessedColumns()
{
if ($this->cache && $this->previousAccessedColumns === NULL) {
$this->accessedColumns = $this->previousAccessedColumns = $this->cache->load($this->getGeneralCacheKey());
if ($this->previousAccessedColumns === NULL) {
$this->previousAccessedColumns = [];
}
}
return array_keys(array_filter((array) $this->previousAccessedColumns));
}
/**
* @internal
* @return SqlBuilder
*/
public function getSqlBuilder()
{
return $this->sqlBuilder;
}
/********************* quick access ****************d*g**/
/**
* Returns row specified by primary key.
* @param mixed primary key
* @return IRow or FALSE if there is no such row
*/
public function get($key)
{
$clone = clone $this;
return $clone->wherePrimary($key)->fetch();
}
/**
* @inheritDoc
*/
public function fetch()
{
$this->execute();
$return = current($this->data);
next($this->data);
return $return;
}
/**
* Fetches single field.
* @param string|NULL
* @return mixed|FALSE
*/
public function fetchField($column = NULL)
{
if ($column) {
$this->select($column);
}
$row = $this->fetch();
if ($row) {
return $column ? $row[$column] : array_values($row->toArray())[0];
}
return FALSE;
}
/**
* @inheritDoc
*/
public function fetchPairs($key = NULL, $value = NULL)
{
return Nette\Database\Helpers::toPairs($this->fetchAll(), $key, $value);
}
/**
* @inheritDoc
*/
public function fetchAll()
{
return iterator_to_array($this);
}
/**
* @inheritDoc
*/
public function fetchAssoc($path)
{
$rows = array_map('iterator_to_array', $this->fetchAll());
return Nette\Utils\Arrays::associate($rows, $path);
}
/********************* sql selectors ****************d*g**/
/**
* Adds select clause, more calls appends to the end.
* @param string for example "column, MD5(column) AS column_md5"
* @return self
*/
public function select($columns, ...$params)
{
$this->emptyResultSet();
$this->sqlBuilder->addSelect($columns, ...$params);
return $this;
}
/**
* Adds condition for primary key.
* @param mixed
* @return self
*/
public function wherePrimary($key)
{
if (is_array($this->primary) && Nette\Utils\Arrays::isList($key)) {
if (isset($key[0]) && is_array($key[0])) {
$this->where($this->primary, $key);
} else {
foreach ($this->primary as $i => $primary) {
$this->where($this->name . '.' . $primary, $key[$i]);
}
}
} elseif (is_array($key) && !Nette\Utils\Arrays::isList($key)) { // key contains column names
$this->where($key);
} else {
$this->where($this->name . '.' . $this->getPrimary(), $key);
}
return $this;
}
/**
* Adds where condition, more calls appends with AND.
* @param string condition possibly containing ?
* @param mixed
* @return self
*/
public function where($condition, ...$params)
{
$this->condition($condition, $params);
return $this;
}
/**
* Adds ON condition when joining specified table, more calls appends with AND.
* @param string table chain or table alias for which you need additional left join condition
* @param string condition possibly containing ?
* @param mixed
* @return self
*/
public function joinWhere($tableChain, $condition, ...$params)
{
$this->condition($condition, $params, $tableChain);
return $this;
}
/**
* Adds condition, more calls appends with AND.
* @param string condition possibly containing ?
* @return void
*/
protected function condition($condition, array $params, $tableChain = NULL)
{
$this->emptyResultSet();
if (is_array($condition) && $params === []) { // where(array('column1' => 1, 'column2 > ?' => 2))
foreach ($condition as $key => $val) {
if (is_int($key)) {
$this->condition($val, [], $tableChain); // where('full condition')
} else {
$this->condition($key, [$val], $tableChain); // where('column', 1)
}
}
} elseif ($tableChain) {
$this->sqlBuilder->addJoinCondition($tableChain, $condition, ...$params);
} else {
$this->sqlBuilder->addWhere($condition, ...$params);
}
}
/**
* Adds where condition using the OR operator between parameters.
* More calls appends with AND.
* @param array ['column1' => 1, 'column2 > ?' => 2, 'full condition']
* @return self
* @throws \Nette\InvalidArgumentException
*/
public function whereOr(array $parameters)
{
if (count($parameters) < 2) {
return $this->where($parameters);
}
$columns = [];
$values = [];
foreach ($parameters as $key => $val) {
if (is_int($key)) { // whereOr(['full condition'])
$columns[] = $val;
} elseif (strpos($key, '?') === FALSE) { // whereOr(['column1' => 1])
$columns[] = $key . ' ?';
$values[] = $val;
} else { // whereOr(['column1 > ?' => 1])
$qNumber = substr_count($key, '?');
if ($qNumber > 1 && (!is_array($val) || $qNumber !== count($val))) {
throw new Nette\InvalidArgumentException('Argument count does not match placeholder count.');
}
$columns[] = $key;
$values = array_merge($values, $qNumber > 1 ? $val : [$val]);
}
}
$columnsString = '(' . implode(') OR (', $columns) . ')';
return $this->where($columnsString, $values);
}
/**
* Adds order clause, more calls appends to the end.
* @param string for example 'column1, column2 DESC'
* @return self
*/
public function order($columns, ...$params)
{
$this->emptyResultSet();
$this->sqlBuilder->addOrder($columns, ...$params);
return $this;
}
/**
* Sets limit clause, more calls rewrite old values.
* @param int
* @param int
* @return self
*/
public function limit($limit, $offset = NULL)
{
$this->emptyResultSet();
$this->sqlBuilder->setLimit($limit, $offset);
return $this;
}
/**
* Sets offset using page number, more calls rewrite old values.
* @param int
* @param int
* @return self
*/
public function page($page, $itemsPerPage, & $numOfPages = NULL)
{
if (func_num_args() > 2) {
$numOfPages = (int) ceil($this->count('*') / $itemsPerPage);
}
if ($page < 1) {
$itemsPerPage = 0;
}
return $this->limit($itemsPerPage, ($page - 1) * $itemsPerPage);
}
/**
* Sets group clause, more calls rewrite old value.
* @param string
* @return self
*/
public function group($columns, ...$params)
{
$this->emptyResultSet();
$this->sqlBuilder->setGroup($columns, ...$params);
return $this;
}
/**
* Sets having clause, more calls rewrite old value.
* @param string
* @return self
*/
public function having($having, ...$params)
{
$this->emptyResultSet();
$this->sqlBuilder->setHaving($having, ...$params);
return $this;
}
/**
* Aliases table. Example ':book:book_tag.tag', 'tg'
* @param string
* @param string
* @return self
*/
public function alias($tableChain, $alias)
{
$this->sqlBuilder->addAlias($tableChain, $alias);
return $this;
}
/********************* aggregations ****************d*g**/
/**
* Executes aggregation function.
* @param string select call in "FUNCTION(column)" format
* @return string
*/
public function aggregation($function)
{
$selection = $this->createSelectionInstance();
$selection->getSqlBuilder()->importConditions($this->getSqlBuilder());
$selection->select($function);
foreach ($selection->fetch() as $val) {
return $val;
}
}
/**
* Counts number of rows.
* @param string if it is not provided returns count of result rows, otherwise runs new sql counting query
* @return int
*/
public function count($column = NULL)
{
if (!$column) {
$this->execute();
return count($this->data);
}
return $this->aggregation("COUNT($column)");
}
/**
* Returns minimum value from a column.
* @param string
* @return int
*/
public function min($column)
{
return $this->aggregation("MIN($column)");
}
/**
* Returns maximum value from a column.
* @param string
* @return int
*/
public function max($column)
{
return $this->aggregation("MAX($column)");
}
/**
* Returns sum of values in a column.
* @param string
* @return int
*/
public function sum($column)
{
return $this->aggregation("SUM($column)");
}
/********************* internal ****************d*g**/
protected function execute()
{
if ($this->rows !== NULL) {
return;
}
$this->observeCache = $this;
if ($this->primary === NULL && $this->sqlBuilder->getSelect() === NULL) {
throw new Nette\InvalidStateException('Table with no primary key requires an explicit select clause.');
}
try {
$result = $this->query($this->getSql());
} catch (Nette\Database\DriverException $exception) {
if (!$this->sqlBuilder->getSelect() && $this->previousAccessedColumns) {
$this->previousAccessedColumns = FALSE;
$this->accessedColumns = [];
$result = $this->query($this->getSql());
} else {
throw $exception;
}
}
$this->rows = [];
$usedPrimary = TRUE;
foreach ($result->getPdoStatement() as $key => $row) {
$row = $this->createRow($result->normalizeRow($row));
$primary = $row->getSignature(FALSE);
$usedPrimary = $usedPrimary && (string) $primary !== '';
$this->rows[$usedPrimary ? $primary : $key] = $row;
}
$this->data = $this->rows;
if ($usedPrimary && $this->accessedColumns !== FALSE) {
foreach ((array) $this->primary as $primary) {
$this->accessedColumns[$primary] = TRUE;
}
}
}
protected function createRow(array $row)
{
return new ActiveRow($row, $this);
}
public function createSelectionInstance($table = NULL)
{
return new self($this->context, $this->conventions, $table ?: $this->name, $this->cache ? $this->cache->getStorage() : NULL);
}
protected function createGroupedSelectionInstance($table, $column)
{
return new GroupedSelection($this->context, $this->conventions, $table, $column, $this, $this->cache ? $this->cache->getStorage() : NULL);
}
protected function query($query)
{
return $this->context->queryArgs($query, $this->sqlBuilder->getParameters());
}
protected function emptyResultSet($clearCache = TRUE, $deleteRererencedCache = TRUE)
{
if ($this->rows !== NULL && $clearCache) {
$this->saveCacheState();
}
if ($clearCache) {
// not null in case of missing some column
$this->previousAccessedColumns = NULL;
$this->generalCacheKey = NULL;
}
$this->rows = NULL;
$this->specificCacheKey = NULL;
$this->refCache['referencingPrototype'] = [];
if ($deleteRererencedCache) {
$this->refCache['referenced'] = [];
}
}
protected function saveCacheState()
{
if ($this->observeCache === $this && $this->cache && !$this->sqlBuilder->getSelect() && $this->accessedColumns !== $this->previousAccessedColumns) {
$previousAccessed = $this->cache->load($this->getGeneralCacheKey());
$accessed = $this->accessedColumns;
$needSave = is_array($accessed) && is_array($previousAccessed)
? array_intersect_key($accessed, $previousAccessed) !== $accessed
: $accessed !== $previousAccessed;
if ($needSave) {
$save = is_array($accessed) && is_array($previousAccessed) ? $previousAccessed + $accessed : $accessed;
$this->cache->save($this->getGeneralCacheKey(), $save);
$this->previousAccessedColumns = NULL;
}
}
}
/**
* Returns Selection parent for caching.
* @return self
*/
protected function getRefTable(& $refPath)
{
return $this;
}
/**
* Loads refCache references
*/
protected function loadRefCache()
{
}
/**
* Returns general cache key independent on query parameters or sql limit
* Used e.g. for previously accessed columns caching
* @return string
*/
protected function getGeneralCacheKey()
{
if ($this->generalCacheKey) {
return $this->generalCacheKey;
}
$key = [__CLASS__, $this->name, $this->sqlBuilder->getConditions()];
$trace = [];
foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $item) {
$trace[] = isset($item['file'], $item['line']) ? $item['file'] . $item['line'] : NULL;
};
$key[] = $trace;
return $this->generalCacheKey = md5(serialize($key));
}
/**
* Returns object specific cache key dependent on query parameters
* Used e.g. for reference memory caching
* @return string
*/
protected function getSpecificCacheKey()
{
if ($this->specificCacheKey) {
return $this->specificCacheKey;
}
return $this->specificCacheKey = $this->sqlBuilder->getSelectQueryHash($this->getPreviousAccessedColumns());
}
/**
* @internal
* @param string|NULL column name or NULL to reload all columns
* @param bool
* @return bool if selection requeried for more columns.
*/
public function accessColumn($key, $selectColumn = TRUE)
{
if (!$this->cache) {
return FALSE;
}
if ($key === NULL) {
$this->accessedColumns = FALSE;
$currentKey = key((array) $this->data);
} elseif ($this->accessedColumns !== FALSE) {
$this->accessedColumns[$key] = $selectColumn;
}
if ($selectColumn && $this->previousAccessedColumns && ($key === NULL || !isset($this->previousAccessedColumns[$key])) && !$this->sqlBuilder->getSelect()) {
if ($this->sqlBuilder->getLimit()) {
$generalCacheKey = $this->generalCacheKey;
$sqlBuilder = $this->sqlBuilder;
$primaryValues = [];
foreach ((array) $this->rows as $row) {
$primary = $row->getPrimary();
$primaryValues[] = is_array($primary) ? array_values($primary) : $primary;
}
$this->emptyResultSet(FALSE);
$this->sqlBuilder = clone $this->sqlBuilder;
$this->sqlBuilder->setLimit(NULL, NULL);
$this->wherePrimary($primaryValues);
$this->generalCacheKey = $generalCacheKey;
$this->previousAccessedColumns = [];
$this->execute();
$this->sqlBuilder = $sqlBuilder;
} else {
$this->emptyResultSet(FALSE);
$this->previousAccessedColumns = [];
$this->execute();
}
$this->dataRefreshed = TRUE;
// move iterator to specific key
if (isset($currentKey)) {
while (key($this->data) !== NULL && key($this->data) !== $currentKey) {
next($this->data);
}
}
}
return $this->dataRefreshed;
}
/**
* @internal
* @param string
*/
public function removeAccessColumn($key)
{
if ($this->cache && is_array($this->accessedColumns)) {
$this->accessedColumns[$key] = FALSE;
}
}
/**
* Returns if selection requeried for more columns.
* @return bool
*/
public function getDataRefreshed()
{
return $this->dataRefreshed;
}
/********************* manipulation ****************d*g**/
/**
* Inserts row in a table.
* @param array|\Traversable|Selection array($column => $value)|\Traversable|Selection for INSERT ... SELECT
* @return IRow|int|bool Returns IRow or number of affected rows for Selection or table without primary key
*/
public function insert($data)
{
if ($data instanceof self) {
$return = $this->context->queryArgs($this->sqlBuilder->buildInsertQuery() . ' ' . $data->getSql(), $data->getSqlBuilder()->getParameters());
} else {
if ($data instanceof \Traversable) {
$data = iterator_to_array($data);
}
$return = $this->context->query($this->sqlBuilder->buildInsertQuery() . ' ?values', $data);
}
$this->loadRefCache();
if ($data instanceof self || $this->primary === NULL) {
unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
return $return->getRowCount();
}
$primaryKey = $this->context->getInsertId(
($tmp = $this->getPrimarySequence())
? implode('.', array_map([$this->context->getConnection()->getSupplementalDriver(), 'delimite'], explode('.', $tmp)))
: NULL
);
if ($primaryKey === FALSE) {
unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
return $return->getRowCount();
}
if (is_array($this->getPrimary())) {
$primaryKey = [];
foreach ((array) $this->getPrimary() as $key) {
if (!isset($data[$key])) {
return $data;
}
$primaryKey[$key] = $data[$key];
}
if (count($primaryKey) === 1) {
$primaryKey = reset($primaryKey);
}
}
$row = $this->createSelectionInstance()
->select('*')
->wherePrimary($primaryKey)
->fetch();
if ($this->rows !== NULL) {
if ($signature = $row->getSignature(FALSE)) {
$this->rows[$signature] = $row;
$this->data[$signature] = $row;
} else {
$this->rows[] = $row;
$this->data[] = $row;
}
}
return $row;
}
/**
* Updates all rows in result set.
* Joins in UPDATE are supported only in MySQL
* @param array|\Traversable ($column => $value)
* @return int number of affected rows
*/
public function update($data)
{
if ($data instanceof \Traversable) {
$data = iterator_to_array($data);
} elseif (!is_array($data)) {
throw new Nette\InvalidArgumentException;
}
if (!$data) {
return 0;
}
return $this->context->queryArgs(
$this->sqlBuilder->buildUpdateQuery(),
array_merge([$data], $this->sqlBuilder->getParameters())
)->getRowCount();
}
/**
* Deletes all rows in result set.
* @return int number of affected rows
*/
public function delete()
{
return $this->query($this->sqlBuilder->buildDeleteQuery())->getRowCount();
}
/********************* references ****************d*g**/
/**
* Returns referenced row.
* @param ActiveRow
* @param string
* @param string|NULL
* @return ActiveRow|NULL|FALSE NULL if the row does not exist, FALSE if the relationship does not exist
*/
public function getReferencedTable(ActiveRow $row, $table, $column = NULL)
{
if (!$column) {
$belongsTo = $this->conventions->getBelongsToReference($this->name, $table);
if (!$belongsTo) {
return FALSE;
}
list($table, $column) = $belongsTo;
}
if (!$row->accessColumn($column)) {
return FALSE;
}
$checkPrimaryKey = $row[$column];
$referenced = & $this->refCache['referenced'][$this->getSpecificCacheKey()]["$table.$column"];
$selection = & $referenced['selection'];
$cacheKeys = & $referenced['cacheKeys'];
if ($selection === NULL || ($checkPrimaryKey !== NULL && !isset($cacheKeys[$checkPrimaryKey]))) {
$this->execute();
$cacheKeys = [];
foreach ($this->rows as $row) {
if ($row[$column] === NULL) {
continue;
}
$key = $row[$column];
$cacheKeys[$key] = TRUE;
}
if ($cacheKeys) {
$selection = $this->createSelectionInstance($table);
$selection->where($selection->getPrimary(), array_keys($cacheKeys));
} else {
$selection = [];
}
}
return isset($selection[$checkPrimaryKey]) ? $selection[$checkPrimaryKey] : NULL;
}
/**
* Returns referencing rows.
* @param string
* @param string
* @param int primary key
* @return GroupedSelection
*/
public function getReferencingTable($table, $column, $active = NULL)
{
if (strpos($table, '.') !== FALSE) {
list($table, $column) = explode('.', $table);
} elseif (!$column) {
$hasMany = $this->conventions->getHasManyReference($this->name, $table);
if (!$hasMany) {
return FALSE;
}
list($table, $column) = $hasMany;
}
$prototype = & $this->refCache['referencingPrototype'][$this->getSpecificCacheKey()]["$table.$column"];
if (!$prototype) {
$prototype = $this->createGroupedSelectionInstance($table, $column);
$prototype->where("$table.$column", array_keys((array) $this->rows));
}
$clone = clone $prototype;
$clone->setActive($active);
return $clone;
}
/********************* interface Iterator ****************d*g**/
public function rewind()
{
$this->execute();
$this->keys = array_keys($this->data);
reset($this->keys);
}
/** @return IRow */
public function current()
{
if (($key = current($this->keys)) !== FALSE) {
return $this->data[$key];
} else {
return FALSE;
}
}
/**
* @return string row ID
*/
public function key()
{
return current($this->keys);
}
public function next()
{
do {
next($this->keys);
} while (($key = current($this->keys)) !== FALSE && !isset($this->data[$key]));
}
public function valid()
{
return current($this->keys) !== FALSE;
}
/********************* interface ArrayAccess ****************d*g**/
/**
* Mimic row.
* @param string row ID
* @param IRow
* @return NULL
*/
public function offsetSet($key, $value)
{
$this->execute();
$this->rows[$key] = $value;
}
/**
* Returns specified row.
* @param string row ID
* @return IRow or NULL if there is no such row
*/
public function offsetGet($key)
{
$this->execute();
return $this->rows[$key];
}
/**
* Tests if row exists.
* @param string row ID
* @return bool
*/
public function offsetExists($key)
{
$this->execute();
return isset($this->rows[$key]);
}
/**
* Removes row from result set.
* @param string row ID
* @return NULL
*/
public function offsetUnset($key)
{
$this->execute();
unset($this->rows[$key], $this->data[$key]);
}
}
|