Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DataQuery.php « Query « lib - github.com/nextcloud/user_sql.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8f7f99063940f149d55d290e79b3b61015c1e1fc (plain)
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
<?php
/**
 * Nextcloud - user_sql
 *
 * @copyright 2018 Marcin Łojewski <dev@mlojewski.me>
 * @author    Marcin Łojewski <dev@mlojewski.me>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace OCA\UserSQL\Query;

use Doctrine\DBAL\Driver\Statement;
use OC\DB\Connection;
use OC\DB\ConnectionFactory;
use OCA\UserSQL\Constant\DB;
use OCA\UserSQL\Constant\Query;
use OCA\UserSQL\Properties;
use OCP\ILogger;

/**
 * Used to query a database.
 *
 * @author Marcin Łojewski <dev@mlojewski.me>
 */
class DataQuery
{
    /**
     * @var string The application name.
     */
    private $appName;
    /**
     * @var ILogger The logger instance.
     */
    private $logger;
    /**
     * @var Properties The properties array.
     */
    private $properties;
    /**
     * @var QueryProvider The query provider.
     */
    private $queryProvider;
    /**
     * @var Connection The database connection.
     */
    private $connection;

    /**
     * The class constructor.
     *
     * @param string        $AppName       The application name.
     * @param ILogger       $logger        The logger instance.
     * @param Properties    $properties    The properties array.
     * @param QueryProvider $queryProvider The query provider.
     */
    public function __construct(
        $AppName, ILogger $logger, Properties $properties,
        QueryProvider $queryProvider
    ) {
        $this->appName = $AppName;
        $this->logger = $logger;
        $this->properties = $properties;
        $this->queryProvider = $queryProvider;
        $this->connection = false;
    }

    /**
     * Execute an update query.
     *
     * @param string $queryName The query name.
     * @param array  $params    The query parameters.
     *
     * @see Query
     * @return bool TRUE on success, FALSE otherwise.
     */
    public function update($queryName, $params = [])
    {
        return $this->execQuery($queryName, $params) !== false;
    }

    /**
     * Run a given query and return the result.
     *
     * @param string $queryName The query to execute.
     * @param array  $params    The query parameters to bind.
     * @param int    $limit     Results limit. Defaults to -1 (no limit).
     * @param int    $offset    Results offset. Defaults to 0.
     *
     * @return Statement|bool Result of query or FALSE on failure.
     */
    private function execQuery(
        $queryName, $params = [], $limit = -1, $offset = 0
    ) {
        if ($this->connection === false) {
            $this->connectToDatabase();
        }

        $query = $this->queryProvider[$queryName];
        $result = $this->connection->prepare($query, $limit, $offset);

        foreach ($params as $param => $value) {
            $result->bindValue(":" . $param, $value);
        }

        $this->logger->debug(
            "Executing query:" . $query . ", " . implode(",", $params),
            ["app" => $this->appName]
        );

        if ($result->execute() !== true) {
            $error = $result->errorInfo();
            $this->logger->error(
                "Could not execute the query: " . implode(", ", $error),
                ["app" => $this->appName]
            );
            return false;
        }

        return $result;
    }

    /**
     * Connect to the database using Nextcloud's DBAL.
     */
    private function connectToDatabase()
    {
        $connectionFactory = new ConnectionFactory(
            \OC::$server->getSystemConfig()
        );

        $parameters = array(
            "host" => $this->properties[DB::HOSTNAME],
            "password" => $this->properties[DB::PASSWORD],
            "user" => $this->properties[DB::USERNAME],
            "dbname" => $this->properties[DB::DATABASE],
            "tablePrefix" => ""
        );

        $this->connection = $connectionFactory->getConnection(
            $this->properties[DB::DRIVER], $parameters
        );

        $this->logger->debug(
            "Database connection established.", ["app" => $this->appName]
        );
    }

    /**
     * Fetch a value from the first row and the first column which
     * the given query returns. Empty result set is consider to be a failure.
     *
     * @param string $queryName The query to execute.
     * @param array  $params    The query parameters to bind.
     * @param bool   $failure   Value returned on database query failure.
     *                          Defaults to FALSE.
     *
     * @return array|bool Queried value or $failure value on failure.
     */
    public function queryValue($queryName, $params = [], $failure = false)
    {
        $result = $this->execQuery($queryName, $params);
        if ($result === false) {
            return false;
        }

        $row = $result->fetch(\PDO::FETCH_COLUMN);
        if ($row === false) {
            return $failure;
        }

        return $row;
    }

    /**
     * Fetch values from the first column which the given query returns.
     *
     * @param string $queryName The query to execute.
     * @param array  $params    The query parameters to bind.
     * @param int    $limit     Results limit. Defaults to -1 (no limit).
     * @param int    $offset    Results offset. Defaults to 0.
     *
     * @return array|bool Queried column or FALSE on failure.
     */
    public function queryColumn(
        $queryName, $params = [], $limit = -1, $offset = 0
    ) {
        $result = $this->execQuery($queryName, $params, $limit, $offset);
        if ($result === false) {
            return false;
        }

        $column = $result->fetchAll(\PDO::FETCH_COLUMN);
        return $column;
    }

    /**
     * Fetch entity returned by the given query.
     *
     * @param string $queryName   The query to execute.
     * @param string $entityClass The entity class name.
     * @param array  $params      The query parameters to bind.
     *
     * @return mixed|null The queried entity, NULL if it does not exists or
     *                    FALSE on failure.
     */
    public function queryEntity($queryName, $entityClass, $params = [])
    {
        $result = $this->execQuery($queryName, $params);
        if ($result === false) {
            return false;
        }

        $result->setFetchMode(\PDO::FETCH_CLASS, $entityClass);
        $entity = $result->fetch();

        if ($entity === false) {
            return null;
        }

        if (empty($entity) === true) {
            $this->logger->debug(
                "Empty result for query: " . $queryName,
                ["app" => $this->appName]
            );
            return null;
        }

        return $entity;
    }

    /**
     * Fetch entities returned by the given query.
     *
     * @param string $queryName   The query to execute.
     * @param string $entityClass The entity class name.
     * @param array  $params      The query parameters to bind.
     * @param int    $limit       Results limit. Defaults to -1 (no limit).
     * @param int    $offset      Results offset. Defaults to 0.
     *
     * @return mixed|null The queried entities or FALSE on failure.
     */
    public function queryEntities(
        $queryName, $entityClass, $params = [], $limit = -1, $offset = 0
    ) {
        $result = $this->execQuery($queryName, $params, $limit, $offset);
        if ($result === false) {
            return false;
        }

        $result->setFetchMode(\PDO::FETCH_CLASS, $entityClass);
        $entities = $result->fetchAll();

        return $entities;
    }
}