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 driverName() : string |
229
|
|
|
{ |
230
|
2 |
|
return array_reverse(explode('\\', get_class($this->driver)))[1]; |
231
|
|
|
} |
232
|
|
|
/** |
233
|
|
|
* Get an option from the driver |
234
|
|
|
* |
235
|
|
|
* @param string $key the option name |
236
|
|
|
* @param mixed $default the default value to return if the option key is not defined |
237
|
|
|
* @return mixed the option value |
238
|
|
|
*/ |
239
|
|
|
public function driverOption(string $key, $default = null) |
240
|
|
|
{ |
241
|
|
|
return $this->driver->option($key, $default); |
242
|
|
|
} |
243
|
|
|
|
244
|
13 |
|
public function definition(string $table, bool $detectRelations = true) : Table |
245
|
|
|
{ |
246
|
13 |
|
return isset($this->tables[$table]) ? |
247
|
|
|
$this->tables[$table] : |
248
|
13 |
|
$this->driver->table($table, $detectRelations); |
249
|
|
|
} |
250
|
|
|
/** |
251
|
|
|
* Parse all tables from the database. |
252
|
|
|
* @return $this |
253
|
|
|
*/ |
254
|
|
|
public function parseSchema() |
255
|
|
|
{ |
256
|
|
|
$this->tables = $this->driver->tables(); |
257
|
|
|
return $this; |
258
|
|
|
} |
259
|
|
|
/** |
260
|
|
|
* Get the full schema as an array that you can serialize and store |
261
|
|
|
* @return array |
262
|
|
|
*/ |
263
|
1 |
|
public function getSchema($asPlainArray = true) |
264
|
|
|
{ |
265
|
|
|
return !$asPlainArray ? $this->tables : array_map(function ($table) { |
266
|
|
|
return [ |
267
|
|
|
'name' => $table->getName(), |
268
|
|
|
'pkey' => $table->getPrimaryKey(), |
269
|
|
|
'comment' => $table->getComment(), |
270
|
|
|
'columns' => array_map(function ($column) { |
271
|
|
|
return [ |
272
|
|
|
'name' => $column->getName(), |
273
|
|
|
'type' => $column->getType(), |
274
|
|
|
'comment' => $column->getComment(), |
275
|
|
|
'values' => $column->getValues(), |
276
|
|
|
'default' => $column->getDefault(), |
277
|
|
|
'nullable' => $column->isNullable() |
278
|
|
|
]; |
279
|
|
|
}, $table->getFullColumns()), |
280
|
|
|
'relations' => array_map(function ($rel) { |
281
|
|
|
$relation = clone $rel; |
282
|
|
|
$relation->table = $relation->table->getName(); |
283
|
|
|
if ($relation->pivot) { |
284
|
|
|
$relation->pivot = $relation->pivot->getName(); |
285
|
|
|
} |
286
|
|
|
return (array)$relation; |
287
|
|
|
}, $table->getRelations()) |
288
|
|
|
]; |
289
|
1 |
|
}, $this->tables); |
290
|
|
|
} |
291
|
|
|
/** |
292
|
|
|
* Load the schema data from a schema definition array (obtained from getSchema) |
293
|
|
|
* @param array $data the schema definition |
294
|
|
|
* @return $this |
295
|
|
|
*/ |
296
|
|
|
public function setSchema(array $data) |
297
|
|
|
{ |
298
|
|
|
foreach ($data as $tableData) { |
299
|
|
|
$this->tables[$tableData['name']] = (new Table($tableData['name'])) |
300
|
|
|
->setPrimaryKey($tableData['pkey']) |
301
|
|
|
->setComment($tableData['comment']) |
302
|
|
|
->addColumns($tableData['columns']); |
303
|
|
|
} |
304
|
|
|
foreach ($data as $tableData) { |
305
|
|
|
$table = $this->definition($tableData['name']); |
306
|
|
|
foreach ($tableData['relations'] as $relationName => $relationData) { |
307
|
|
|
$relationData['table'] = $this->definition($relationData['table']); |
308
|
|
|
if ($relationData['pivot']) { |
309
|
|
|
$relationData['pivot'] = $this->definition($relationData['pivot']); |
310
|
|
|
} |
311
|
|
|
$table->addRelation(new TableRelation( |
312
|
|
|
$relationData['name'], |
313
|
|
|
$relationData['table'], |
314
|
|
|
$relationData['keymap'], |
315
|
|
|
$relationData['many'], |
316
|
|
|
$relationData['pivot'] ?? null, |
317
|
|
|
$relationData['pivot_keymap'], |
318
|
|
|
$relationData['sql'], |
319
|
|
|
$relationData['par'] |
320
|
|
|
)); |
321
|
|
|
} |
322
|
|
|
} |
323
|
|
|
return $this; |
324
|
|
|
} |
325
|
|
|
|
326
|
|
|
/** |
327
|
|
|
* Initialize a table query |
328
|
|
|
* @param string $table the table to query |
329
|
|
|
* @return TableQuery |
330
|
|
|
*/ |
331
|
13 |
|
public function table($table) |
332
|
|
|
{ |
333
|
13 |
|
return new TableQuery($this, $this->definition($table)); |
334
|
|
|
} |
335
|
13 |
|
public function __call($method, $args) |
336
|
|
|
{ |
337
|
13 |
|
return $this->table($method); |
338
|
|
|
} |
339
|
|
|
} |