Completed
Push — master ( f88857...648d22 )
by Oleg
04:16
created

MysqlDriver::rawQuery()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.4285
cc 3
eloc 10
nc 4
nop 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A MysqlDriver::getDriverType() 0 4 1
A MysqlDriver::listTables() 0 4 1
1
<?php /** MysqlDriverMicro */
2
3
namespace Micro\Db\Drivers;
4
5
/**
6
 * MySQL Driver class file.
7
 *
8
 * @author Oleg Lunegov <[email protected]>
9
 * @link https://github.com/linpax/microphp-framework
10
 * @copyright Copyright (c) 2013 Oleg Lunegov
11
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
12
 * @package Micro
13
 * @subpackage Db\Drivers
14
 * @version 1.0
15
 * @since 1.0
16
 */
17
class MysqlDriver extends Driver
18
{
19
    /**
20
     * Set current database
21
     *
22
     * @access public
23
     *
24
     * @param string $dbName Database name
25
     *
26
     * @return boolean
27
     */
28
    public function switchDatabase($dbName)
29
    {
30
        return $this->conn->exec("USE {$dbName};") !== false;
31
    }
32
33
    /**
34
     * Info of database
35
     *
36
     * @access public
37
     * @param string $dbName Database name
38
     * @return array
39
     */
40
    public function infoDatabase($dbName)
41
    {
42
        $sth = $this->conn->query("SHOW TABLE STATUS FROM {$dbName};");
43
44
        $result = [];
45
        foreach ($sth->fetchAll() AS $row) {
46
            $result[] = [
47
                'name' => $row['Name'],
48
                'engine' => $row['Engine'],
49
                'rows' => $row['Rows'],
50
                'length' => $row['Avg_row_length'],
51
                'increment' => $row['Auto_increment'],
52
                'collation' => $row['Collation']
53
            ];
54
        }
55
56
        return $result;
57
    }
58
59
    /**
60
     * List database names on this connection
61
     *
62
     * @access public
63
     * @return array
64
     */
65
    public function listDatabases()
66
    {
67
        $sql = 'SHOW DATABASES;';
68
69
        if ($this->getDriverType() === 'pgsql') {
70
            $sql = 'SELECT datname FROM pg_database;';
71
        }
72
73
        $sth = $this->conn->query($sql);
74
        $result = [];
75
76
        foreach ($sth->fetchAll() AS $row) {
77
            $result[] = $row[0];
78
        }
79
80
        return $result;
81
    }
82
83
    public function getDriverType()
84
    {
85
        return $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
86
    }
87
88
    /**
89
     * List tables in db
90
     *
91
     * @access public
92
     * @return array
93
     */
94
    public function listTables()
95
    {
96
        return $this->conn->query('SHOW TABLES;')->fetchAll(\PDO::FETCH_COLUMN, 0);
97
    }
98
99
    /**
100
     * Create a new table
101
     *
102
     * @param string $name Table name
103
     * @param array $elements Table elements
104
     * @param string $params Table params
105
     *
106
     * @return int
107
     */
108
    public function createTable($name, array $elements = [], $params = '')
109
    {
110
        return $this->conn->exec(
111
            sprintf('SELECT TABLE IF NOT EXISTS `%s` (%s) %s;', $name, implode(', ', $elements), $params)
112
        );
113
    }
114
115
    /**
116
     * Remove table from database
117
     *
118
     * @access public
119
     *
120
     * @param string $name Table name
121
     *
122
     * @return mixed
123
     */
124
    public function removeTable($name)
125
    {
126
        return $this->conn->exec("DROP TABLE {$name};");
127
    }
128
129
    /**
130
     * Clear all data from table
131
     *
132
     * @access public
133
     *
134
     * @param string $name Table name
135
     *
136
     * @return int
137
     */
138
    public function clearTable($name)
139
    {
140
        return $this->conn->exec("TRUNCATE {$name};");
141
    }
142
143
    /**
144
     * Get array fields into table
145
     *
146
     * @access public
147
     *
148
     * @param string $table Table name
149
     *
150
     * @return array
151
     */
152
    public function listFields($table)
153
    {
154
        $sth = $this->conn->query("SHOW COLUMNS FROM {$table};");
155
156
        $result = [];
157
        foreach ($sth->fetchAll(\PDO::FETCH_ASSOC) as $row) {
158
            $result[] = [
159
                'field' => $row['Field'],
160
                'type' => $row['Type'],
161
                'null' => $row['Null'],
162
                'key' => $row['Key'],
163
                'default' => $row['Default'],
164
                'extra' => $row['Extra']
165
            ];
166
        }
167
168
        return $result;
169
    }
170
171
    /**
172
     * Get info of a field
173
     *
174
     * @access public
175
     *
176
     * @param string $field Field name
177
     * @param string $table Table name
178
     *
179
     * @return array|boolean
180
     */
181
    public function fieldInfo($field, $table)
182
    {
183
        if ($this->fieldExists($field, $table)) {
184
            return $this->conn->query("SELECT {$field} FROM {$table} LIMIT 1;")->getColumnMeta(0);
185
        }
186
187
        return false;
188
    }
189
190
    /**
191
     * Insert row into table
192
     *
193
     * @access public
194
     *
195
     * @param string $table Table name
196
     * @param array $line Line or lines to added
197
     * @param bool $multi Is multi rows
198
     *
199
     * @return bool
200
     */
201
    public function insert($table, array $line = [], $multi = false)
202
    {
203
        $fields = '`' . implode('`, `', array_keys($multi ? $line[0] : $line)) . '`';
204
205
        $values = ':'.implode(', :', array_keys($multi ? $line[0] : $line));
206
        $rows = $multi ? $line : [$line];
207
        $id = null;
208
209
        if ($rows) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rows of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
210
            $this->conn->beginTransaction();
211
212
            $dbh = null;
213
            foreach ($rows AS $row) {
214
                $dbh = $this->conn->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$values});")->execute($row);
215
            }
216
217
            $id = $dbh ? $this->conn->lastInsertId() : false;
218
            $this->conn->commit();
219
        }
220
221
        return $id ?: false;
222
    }
223
224
    /**
225
     * Update row in table
226
     *
227
     * @access public
228
     *
229
     * @param string $table Table name
230
     * @param array $elements Elements to update
231
     * @param string $conditions Conditions for search
232
     *
233
     * @return bool
234
     */
235
    public function update($table, array $elements = [], $conditions = '')
236
    {
237
        $keys = array_keys($elements);
238
        if (0 === count($keys)) {
239
            return false;
240
        }
241
242
        $valStr = [];
243
        foreach ($keys as $key) {
244
            $valStr[] = '`'.$key.'` = :'.$key;
245
        }
246
        $valStr = implode(',', $valStr);
247
248
        if ($conditions) {
249
            $conditions = 'WHERE '.$conditions;
250
        }
251
252
        return $this->conn->prepare("UPDATE {$table} SET {$valStr} {$conditions};")->execute($elements);
253
    }
254
255
    /**
256
     * Delete row from table
257
     *
258
     * @access public
259
     *
260
     * @param string $table Table name
261
     * @param string $conditions Conditions to search
262
     * @param array $params Params array
263
     *
264
     * @return bool
265
     */
266
    public function delete($table, $conditions, array $params = [])
267
    {
268
        return $this->conn->prepare("DELETE FROM {$table} WHERE {$conditions};")->execute($params);
269
    }
270
271
    /**
272
     * Count element in sub-query
273
     *
274
     * @access public
275
     *
276
     * @param string $query Query
277
     * @param string $table Table name
278
     *
279
     * @return integer|boolean
280
     */
281
    public function count($query = '', $table = '')
282
    {
283
        if ($query) {
284
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM ({$query}) AS m;");
285
        } elseif ($table) {
286
            $sth = $this->conn->prepare("SELECT COUNT(*) FROM {$table} AS m;");
287
        } else {
288
            return false;
289
        }
290
        if ($sth->execute()) {
291
            return $sth->fetchColumn();
292
        }
293
294
        return false;
295
    }
296
297
    /**
298
     * Exists element in the table by params
299
     *
300
     * @access public
301
     *
302
     * @param string $table Table name
303
     * @param array $params Params array
304
     *
305
     * @return bool
306
     */
307
    public function exists($table, array $params = [])
308
    {
309
        $keys = [];
310
311
        foreach ($params AS $key => $val) {
312
            $keys[] = $table . '.' . $key . '=\'' . $val . '\'';
313
        }
314
315
        $sth = $this->conn->prepare('SELECT * FROM ' . $table . ' WHERE ' . implode(' AND ', $keys) . ' LIMIT 1;');
316
        /** @noinspection PdoApiUsageInspection */
317
        $sth->execute();
318
319
        return (bool)$sth->rowCount();
320
    }
321
}
322