Completed
Push — master ( 4f05e7...d82db7 )
by Ivan
02:15
created

DB::rollback()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2.0625
1
<?php
2
3
namespace vakata\database;
4
5
use \vakata\collection\Collection;
6
use \vakata\database\schema\Table;
7
use \vakata\database\schema\TableQuery;
8
use \vakata\database\schema\TableRelation;
9
10
/**
11
 * A database abstraction with support for various drivers (mySQL, postgre, oracle, msSQL, sphinx, and even PDO).
12
 */
13
class DB implements DBInterface
14
{
15
    /**
16
     * @var DriverInterface
17
     */
18
    protected $driver;
19
    /**
20
     * @var Table[]
21
     */
22
    protected $tables = [];
23
24
    /**
25
     * Create an instance.
26
     *
27
     * @param DriverInterface|string $driver a driver instance or a connection string
28
     */
29 3
    public function __construct($driver) {
30 3
        $this->driver = $driver instanceof DriverInterface ? $driver : static::getDriver($driver);
31 3
    }
32
    /**
33
     * Create a driver instance from a connection string
34
     * @param string $connectionString the connection string
35
     * @return DriverInterface
36
     */
37 3
    public static function getDriver(string $connectionString)
38
    {
39
        $connection = [
40 3
            'orig' => $connectionString,
41
            'type' => null,
42
            'user' => null,
43
            'pass' => null,
44
            'host' => null,
45
            'port' => null,
46
            'name' => null,
47
            'opts' => []
48
        ];
49
        $aliases = [
50 3
            'mysqli' => 'mysql',
51
            'pg' => 'postgre',
52
            'oci' => 'oracle',
53
            'firebird' => 'ibase'
54
        ];
55 3
        $connectionString = array_pad(explode('://', $connectionString, 2), 2, '');
56 3
        $connection['type'] = $connectionString[0];
57 3
        $connectionString = $connectionString[1];
58 3
        if (strpos($connectionString, '@') !== false) {
59 3
            $connectionString = array_pad(explode('@', $connectionString, 2), 2, '');
60 3
            list($connection['user'], $connection['pass']) = array_pad(explode(':', $connectionString[0], 2), 2, '');
61 3
            $connectionString = $connectionString[1];
62
        }
63 3
        $connectionString = array_pad(explode('/', $connectionString, 2), 2, '');
64 3
        list($connection['host'], $connection['port']) = array_pad(explode(':', $connectionString[0], 2), 2, null);
65 3
        $connectionString = $connectionString[1];
66 3
        if ($pos = strrpos($connectionString, '?')) {
67 3
            $opt = substr($connectionString, $pos + 1);
68 3
            parse_str($opt, $connection['opts']);
69 3
            if ($connection['opts'] && count($connection['opts'])) {
70 3
                $connectionString = substr($connectionString, 0, $pos);
71
            } else {
72
                $connection['opts'] = [];
73
            }
74
        }
75 3
        $connection['name'] = $connectionString;
76 3
        $connection['type'] = isset($aliases[$connection['type']]) ?
77
            $aliases[$connection['type']] :
78 3
            $connection['type'];
79 3
        $tmp = '\\vakata\\database\\driver\\'.strtolower($connection['type']).'\\Driver';
80 3
        return new $tmp($connection);
81
    }
82
    /**
83
     * Prepare a statement.
84
     * Use only if you need a single query to be performed multiple times with different parameters.
85
     *
86
     * @param string $sql the query to prepare - use `?` for arguments
87
     * @return StatementInterface the prepared statement
88
     */
89 1
    public function prepare(string $sql) : StatementInterface
90
    {
91 1
        return $this->driver->prepare($sql);
92
    }
93 8
    protected function expand(string $sql, $par = null) : array
94
    {
95 8
        $new = '';
96 8
        $par = array_values($par);
97 8
        if (substr_count($sql, '?') === 2 && !is_array($par[0])) {
98 3
            $par = [ $par ];
99
        }
100 8
        $parts = explode('??', $sql);
101 8
        $index = 0;
102 8
        foreach ($parts as $part) {
103 8
            $tmp = explode('?', $part);
104 8
            $new .= $part;
105 8
            $index += count($tmp) - 1;
106 8
            if (isset($par[$index])) {
107 8
                if (!is_array($par[$index])) {
108
                    $par[$index] = [ $par[$index] ];
109
                }
110 8
                $params = $par[$index];
111 8
                array_splice($par, $index, 1, $params);
112 8
                $index += count($params);
113 8
                $new .= implode(',', array_fill(0, count($params), '?'));
114
            }
115
        }
116 8
        return [ $new, $par ];
117
    }
118
    /**
119
     * Run a query (prepare & execute).
120
     * @param string      $sql  SQL query
121
     * @param array|null  $par parameters (optional)
122
     * @return ResultInterface the result of the execution
123
     */
124 27
    public function query(string $sql, $par = null) : ResultInterface
125
    {
126 27
        $par = isset($par) ? (is_array($par) ? $par : [$par]) : [];
127 27
        if (strpos($sql, '??') && count($par)) {
128 8
            list($sql, $par) = $this->expand($sql, $par);
129
        }
130 27
        return $this->driver->prepare($sql)->execute($par);
131
    }
132
    /**
133
     * Run a SELECT query and get an array-like result.
134
     * When using `get` the data is kept in the database client and fetched as needed (not in PHP memory as with `all`)
135
     *
136
     * @param string   $sql      SQL query
137
     * @param array    $par      parameters
138
     * @param string   $key      column name to use as the array index
139
     * @param bool     $skip     do not include the column used as index in the value (defaults to `false`)
140
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
141
     *
142
     * @return Collection the result of the execution
143
     */
144 21
    public function get(string $sql, $par = null, string $key = null, bool $skip = false, bool $opti = true): Collection
145
    {
146 21
        $coll = Collection::from($this->query($sql, $par));
147 21
        if (($keys = $this->driver->option('mode')) && in_array($keys, ['strtoupper', 'strtolower'])) {
148
            $coll->map(function ($v) use ($keys) {
149 1
                $new = [];
150 1
                foreach ($v as $k => $vv) {
151 1
                    $new[call_user_func($keys, $k)] = $vv;
152
                }
153 1
                return $new;
154 1
            });
155
        }
156 21
        if ($key !== null) {
157
            $coll->mapKey(function ($v) use ($key) { return $v[$key]; });
158
        }
159 21
        if ($skip) {
160
            $coll->map(function ($v) use ($key) { unset($v[$key]); return $v; });
161
        }
162 21
        if ($opti) {
163
            $coll->map(function ($v) { return count($v) === 1 ? current($v) : $v; });
164
        }
165 21
        return $coll;
166
    }
167
    /**
168
     * Run a SELECT query and get a single row
169
     * @param string   $sql      SQL query
170
     * @param array    $par      parameters
171
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
172
     * @return Collection the result of the execution
173
     */
174 7
    public function one(string $sql, $par = null, bool $opti = true)
175
    {
176 7
        return $this->get($sql, $par, null, false, $opti)->value();
177
    }
178
    /**
179
     * Run a SELECT query and get an array
180
     * @param string   $sql      SQL query
181
     * @param array    $par      parameters
182
     * @param string   $key      column name to use as the array index
183
     * @param bool     $skip     do not include the column used as index in the value (defaults to `false`)
184
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
185
     * @return Collection the result of the execution
186
     */
187 2
    public function all(string $sql, $par = null, string $key = null, bool $skip = false, bool $opti = true) : array
188
    {
189 2
        return $this->get($sql, $par, $key, $skip, $opti)->toArray();
190
    }
191
    /**
192
     * Begin a transaction.
193
     * @return $this
194
     */
195 1
    public function begin() : DBInterface
196
    {
197 1
        if (!$this->driver->begin()) {
198
            throw new DBException('Could not begin');
199
        }
200 1
        return $this;
201
    }
202
    /**
203
     * Commit a transaction.
204
     * @return $this
205
     */
206 1
    public function commit() : DBInterface
207
    {
208 1
        if (!$this->driver->commit()) {
209
            throw new DBException('Could not commit');
210
        }
211 1
        return $this;
212
    }
213
    /**
214
     * Rollback a transaction.
215
     * @return $this
216
     */
217 1
    public function rollback() : DBInterface
218
    {
219 1
        if (!$this->driver->rollback()) {
220
            throw new DBException('Could not rollback');
221
        }
222 1
        return $this;
223
    }
224
    /**
225
     * Get the current driver name (`"mysql"`, `"postgre"`, etc).
226
     * @return string the current driver name
227
     */
228 2
    public function driver() : string
229
    {
230 2
        return array_reverse(explode('\\', get_class($this->driver)))[1];
231
    }
232
233 13
    public function definition(string $table, bool $detectRelations = true) : Table
234
    {
235 13
        return isset($this->tables[$table]) ?
236
            $this->tables[$table] :
237 13
            $this->driver->table($table, $detectRelations);
238
    }
239
    /**
240
     * Parse all tables from the database.
241
     * @return $this
242
     */
243
    public function parseSchema()
244
    {
245
        $this->tables = $this->driver->tables();
246
        return $this;
247
    }
248
    /**
249
     * Get the full schema as an array that you can serialize and store
250
     * @return array
251
     */
252 1
    public function getSchema($asPlainArray = true)
253
    {
254
        return !$asPlainArray ? $this->tables : array_map(function ($table) {
255
            return [
256
                'name' => $table->getName(),
257
                'pkey' => $table->getPrimaryKey(),
258
                'comment' => $table->getComment(),
259
                'columns' => array_map(function ($column) {
260
                    return [
261
                        'name' => $column->getName(),
262
                        'type' => $column->getType(),
263
                        'comment' => $column->getComment(),
264
                        'values' => $column->getValues(),
265
                        'default' => $column->getDefault(),
266
                        'nullable' => $column->isNullable()
267
                    ];
268
                }, $table->getFullColumns()),
269
                'relations' => array_map(function ($rel) {
270
                    $relation = clone $rel;
271
                    $relation->table = $relation->table->getName();
272
                    if ($relation->pivot) {
273
                        $relation->pivot = $relation->pivot->getName();
274
                    }
275
                    return (array)$relation;
276
                }, $table->getRelations())
277
            ];
278 1
        }, $this->tables);
279
    }
280
    /**
281
     * Load the schema data from a schema definition array (obtained from getSchema)
282
     * @param  array        $data the schema definition
283
     * @return $this
284
     */
285
    public function setSchema(array $data)
286
    {
287
        foreach ($data as $tableData) {
288
            $this->tables[$tableData['name']] = (new Table($tableData['name']))
289
                        ->setPrimaryKey($tableData['pkey'])
290
                        ->setComment($tableData['comment'])
291
                        ->addColumns($tableData['columns']);
292
        }
293
        foreach ($data as $tableData) {
294
            $table = $this->definition($tableData['name']);
295
            foreach ($tableData['relations'] as $relationName => $relationData) {
296
                $relationData['table'] = $this->definition($relationData['table']);
297
                if ($relationData['pivot']) {
298
                    $relationData['pivot'] = $this->definition($relationData['pivot']);
299
                }
300
                $table->addRelation(new TableRelation(
301
                    $relationData['name'],
302
                    $relationData['table'],
303
                    $relationData['keymap'],
304
                    $relationData['many'],
305
                    $relationData['pivot'] ?? null,
306
                    $relationData['pivot_keymap'],
307
                    $relationData['sql'],
308
                    $relationData['par']
309
                ));
310
            }
311
        }
312
        return $this;
313
    }
314
315
    /**
316
     * Initialize a table query
317
     * @param string $table the table to query
318
     * @return TableQuery
319
     */
320 13
    public function table($table)
321
    {
322 13
        return new TableQuery($this, $this->definition($table));
323
    }
324 13
    public function __call($method, $args)
325
    {
326 13
        return $this->table($method);
327
    }
328
}