ResultCacheStatement.php 4.94 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Cache;

5
use ArrayIterator;
6
use Doctrine\Common\Cache\Cache;
7 8
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\Driver\Statement;
9
use Doctrine\DBAL\FetchMode;
10 11 12
use InvalidArgumentException;
use IteratorAggregate;
use PDO;
13 14 15
use function array_merge;
use function array_values;
use function reset;
16 17 18 19 20 21 22 23 24 25 26 27 28 29

/**
 * Cache statement for SQL results.
 *
 * A result is saved in multiple cache keys, there is the originally specified
 * cache key which is just pointing to result rows by key. The following things
 * have to be ensured:
 *
 * 1. lifetime of the original key has to be longer than that of all the individual rows keys
 * 2. if any one row key is missing the query has to be re-executed.
 *
 * Also you have to realize that the cache will load the whole result into memory at once to ensure 2.
 * This means that the memory usage for cached results might increase by using this feature.
 */
30
class ResultCacheStatement implements IteratorAggregate, ResultStatement
31
{
32
    /** @var Cache */
33
    private $resultCache;
34

35
    /** @var string */
36 37
    private $cacheKey;

38
    /** @var string */
39 40
    private $realKey;

41
    /** @var int */
42 43
    private $lifetime;

44
    /** @var Statement */
45 46 47 48
    private $statement;

    /**
     * Did we reach the end of the statement?
49
     *
50
     * @var bool
51 52 53
     */
    private $emptied = false;

54
    /** @var mixed[] */
55 56
    private $data;

57
    /** @var int */
58
    private $defaultFetchMode = FetchMode::MIXED;
59

60
    /**
61 62 63
     * @param string $cacheKey
     * @param string $realKey
     * @param int    $lifetime
64
     */
65
    public function __construct(Statement $stmt, Cache $resultCache, $cacheKey, $realKey, $lifetime)
66
    {
67
        $this->statement   = $stmt;
68
        $this->resultCache = $resultCache;
69 70 71
        $this->cacheKey    = $cacheKey;
        $this->realKey     = $realKey;
        $this->lifetime    = $lifetime;
72 73 74
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
75
     * {@inheritdoc}
76 77 78
     */
    public function closeCursor()
    {
79
        $this->statement->closeCursor();
80
        if (! $this->emptied || $this->data === null) {
81
            return true;
82
        }
83

84 85 86
        $data = $this->resultCache->fetch($this->cacheKey);
        if (! $data) {
            $data = [];
87
        }
88 89 90 91
        $data[$this->realKey] = $this->data;

        $this->resultCache->save($this->cacheKey, $data, $this->lifetime);
        unset($this->data);
92 93

        return true;
94 95 96
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
97
     * {@inheritdoc}
98 99 100 101 102 103
     */
    public function columnCount()
    {
        return $this->statement->columnCount();
    }

Benjamin Morel's avatar
Benjamin Morel committed
104 105 106
    /**
     * {@inheritdoc}
     */
107
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
108
    {
109
        $this->defaultFetchMode = $fetchMode;
Benjamin Morel's avatar
Benjamin Morel committed
110 111

        return true;
112 113
    }

Benjamin Morel's avatar
Benjamin Morel committed
114 115 116
    /**
     * {@inheritdoc}
     */
117 118
    public function getIterator()
    {
119
        $data = $this->fetchAll();
Benjamin Morel's avatar
Benjamin Morel committed
120

121
        return new ArrayIterator($data);
122 123
    }

124
    /**
Benjamin Morel's avatar
Benjamin Morel committed
125
     * {@inheritdoc}
126
     */
127
    public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
128
    {
129
        if ($this->data === null) {
130
            $this->data = [];
131 132
        }

133 134
        $row = $this->statement->fetch(FetchMode::ASSOCIATIVE);

135
        if ($row) {
136
            $this->data[] = $row;
137

138
            $fetchMode = $fetchMode ?: $this->defaultFetchMode;
139

Sergei Morozov's avatar
Sergei Morozov committed
140
            if ($fetchMode === FetchMode::ASSOCIATIVE) {
141
                return $row;
142 143
            }

Sergei Morozov's avatar
Sergei Morozov committed
144
            if ($fetchMode === FetchMode::NUMERIC) {
145
                return array_values($row);
146 147
            }

Sergei Morozov's avatar
Sergei Morozov committed
148
            if ($fetchMode === FetchMode::MIXED) {
149
                return array_merge($row, array_values($row));
150 151
            }

Sergei Morozov's avatar
Sergei Morozov committed
152
            if ($fetchMode === FetchMode::COLUMN) {
153
                return reset($row);
154
            }
155

156
            throw new InvalidArgumentException('Invalid fetch-style given for caching result.');
157
        }
158

159
        $this->emptied = true;
Benjamin Morel's avatar
Benjamin Morel committed
160

161 162 163 164
        return false;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
165
     * {@inheritdoc}
166
     */
167
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
168
    {
169 170 171 172
        $this->data    = $this->statement->fetchAll($fetchMode, $fetchArgument, $ctorArgs);
        $this->emptied = true;

        return $this->data;
173 174 175
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
176
     * {@inheritdoc}
177 178 179
     */
    public function fetchColumn($columnIndex = 0)
    {
180
        $row = $this->fetch(FetchMode::NUMERIC);
Benjamin Morel's avatar
Benjamin Morel committed
181

182
        // TODO: verify that return false is the correct behavior
183
        return $row[$columnIndex] ?? false;
184 185 186
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
187
     * Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement
188 189 190 191 192 193 194
     * executed by the corresponding object.
     *
     * If the last SQL statement executed by the associated Statement object was a SELECT statement,
     * some databases may return the number of rows returned by that statement. However,
     * this behaviour is not guaranteed for all databases and should not be
     * relied on for portable applications.
     *
195
     * @return int The number of rows.
196 197 198 199 200
     */
    public function rowCount()
    {
        return $this->statement->rowCount();
    }
201
}