-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.php
executable file
·439 lines (329 loc) · 8.39 KB
/
Connection.php
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php
namespace Nether\Database;
use Nether\Common;
use PDO;
use Stringable;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class Connection
extends Common\Prototype
implements Common\Interfaces\ToArray {
#[Common\Meta\PropertyListable]
public ?string
$Name;
#[Common\Meta\PropertyListable]
public string
$Type;
#[Common\Meta\PropertyListable]
public string
$Hostname;
#[Common\Meta\PropertyListable]
public string
$Database;
#[Common\Meta\PropertyListable]
public string
$Username;
#[Common\Meta\PropertyListable]
public string
$Password;
#[Common\Meta\PropertyListable]
public string
$Charset;
#[Common\Meta\PropertyListable]
public bool
$Auto;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
protected PDO
$Driver;
protected ?Verse
$Verse;
protected int
$QueryCount = 0;
protected float
$QueryTime = 0;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
public function
__Construct(
string $Type,
string $Hostname,
string $Database,
string $Username,
string $Password,
string $Charset='utf8mb4',
?string $Name=NULL,
bool $Auto=FALSE
) {
$this->Type = $Type;
$this->Hostname = $Hostname;
$this->Database = $Database;
$this->Username = $Username;
$this->Password = $Password;
$this->Charset = $Charset;
$this->Name = $Name;
$this->Auto = $Auto;
return;
}
public function
__ToString():
string {
return $this->GetDSN();
}
public function
__DebugInfo():
array {
return [
'Type' => $this->Type,
'Hostname' => $this->Hostname,
'Database' => $this->Database,
'Username' => Common\Values::DebugProtectValue($this->Username),
'Password' => Common\Values::DebugProtectValue($this->Password),
'Charset' => $this->Charset,
'IsConnected' => $this->IsConnected()
];
}
public function
ToArray():
array {
$Props = array_map(
(fn(Common\Prototype\PropertyInfo $P)=> $this->{$P->Name}),
static::FetchPropertiesWithAttribute(Common\Meta\PropertyListable::class)
);
return $Props;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
public function
IsConnected():
bool {
return isset($this->Driver);
}
public function
Connect():
static {
if(isset($this->Driver))
return $this;
$this->Driver = new PDO(
$this->GetDSN(),
$this->Username,
$this->Password
);
$this->Driver->SetAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_SILENT
);
return $this;
}
public function
GetDSN():
string {
if($this->Type === 'mysql')
return sprintf(
'%s:host=%s;dbname=%s;charset=%s',
$this->Type,
$this->Hostname,
$this->Database,
$this->Charset
);
if($this->Type === 'sqlite')
return sprintf(
'%s:%s',
$this->Type,
$this->Database
);
////////
return sprintf(
'%s:host=%s;dbname=%s, %s, %s;charset=%s',
$this->Type,
$this->Hostname,
$this->Database,
$this->Username,
$this->Password,
$this->Charset
);
}
public function
GetDriver():
PDO {
return $this->Driver;
}
public function
GetQueryCount():
int {
return $this->QueryCount;
}
public function
GetQueryTime():
float {
return $this->QueryTime;
}
public function
GetInsertID():
mixed {
return $this->Driver->LastInsertID();
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
public function
NewVerse():
Verse {
/*//
@date 2022-02-18
begin a new verse.
//*/
$this->Verse = new Verse($this);
return $this->Verse;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
public function
Query(string $Format, array|object $Argv=[]):
Result {
/*//
@date 2022-02-18
execute a query and return a result.
//*/
$Statement = NULL;
$SQL = NULL;
$Dataset = [];
$QueryTime = 0;
$this->Connect();
//ob_start();
//var_dump($this->Driver);
//error_log(ob_get_clean());
// convert to an object if not an object.
if($Argv instanceof Common\Datastore)
$Argv = $Argv->GetData();
if(!is_array($Argv))
$Argv = (array)$Argv;
// handle if we gave it an object that implements stringable.
// mostly for use with Verse but you could send your own object
// in here as well.
if($Format instanceof Stringable)
$SQL = (string)$Format;
else
$SQL = $Format;
// build a dataset that directly maps to the bound parameters in
// the query with no unused values.
$this->Query_BuildDataset($SQL, $Argv, $Dataset);
$this->Query_ExpandDataset($SQL, $Argv, $Dataset);
// prepare the query statement.
$QueryTime = microtime(TRUE);
$Statement = $this->Driver->Prepare($SQL);
if(!$Statement)
throw new Error\QueryPrepareFailure;
// execute the query statement.
$Result = new Result($this, $Statement, $Dataset);
$this->QueryCount += 1;
$this->QueryTime += microtime(TRUE) - $QueryTime;
return $Result;
}
public function
Query_BuildDataset(string $SQL, array $Argv, array &$Dataset):
void {
/*//
@modifies $Dataset
@date 2022-02-18
fetch an array which describes all the bound data in this query and
relate it to the arguments which were passed to query. expands arrays
that are bound to a single param into multiple params, and detects
pre-expanded arguments and binds them to their argument.
//*/
$Binding = NULL;
$Param = NULL;
$Arg = NULL;
$Key = NULL;
$Bound = NULL;
$Dataset = [];
preg_match_all('/:([a-z0-9_]+)/i', $SQL, $Bound);
$Bound = $Bound[1];
foreach($Bound as $Binding) {
$Param = ":{$Binding}";
// make sure all the bindings were prefixed with the colon
// if not already.
if(array_key_exists($Binding, $Argv))
$Dataset[$Param] = $Argv[$Binding];
elseif(array_key_exists($Param, $Argv))
$Dataset[$Param] = $Argv[$Param];
// if an expanded binding was found, find the common argument
// that it should match with for data expansion later.
elseif(substr($Binding, 0, 2) === '__') {
$Key = preg_replace('/__(.+?)__\d+/', '\\1', $Binding);
$Param = ":{$Key}";
if(!array_key_exists($Param, $Dataset) && array_key_exists($Key, $Argv))
$Dataset[$Param] = $Argv[$Key];
elseif(!array_key_exists($Param, $Dataset) && array_key_exists($Param, $Argv))
$Dataset[$Param] = $Argv[$Param];
}
}
// arguments which were not bound to a named argument just get
// added on to the dataset letting the keys inc as they may. this
// is to support the older ? style of binding token.
foreach($Argv as $Key => $Arg)
if(is_int($Key))
$Dataset[] = $Arg;
return;
}
public function
Query_ExpandDataset(string &$SQL, array $Argv, array &$Dataset):
void {
/*//
@modifies $SQL
@modifies $Dataset
@date 2022-02-18
iterate over a dataset to find any arrays that need to be expanded into
flat values to match up with any expanded bindings. so if there is a
parameter named :ObjectID and it is an array in the dataset, it will be
expanded into :__ObjectID__0, :__ObjectID__1, etc.
//*/
$Key = NULL;
$Value = NULL;
$NewKey = NULL;
$K = NULL;
$V = NULL;
foreach($Dataset as $Key => $Value) {
if(!is_array($Value))
continue;
// explode an array into multiple tokens.
$NewKey = str_replace(':', ':__', $Key);
$NewBindings = [];
foreach($Value as $K => $V) {
$NewBindings[] = $Binding = "{$NewKey}__{$K}";
$Dataset[$Binding] = $V;
}
// update the query string and dataset array for the updated
// exploded bindings.
$SQL = str_replace(
$Key,
implode(',', $NewBindings),
$SQL
);
unset($Dataset[$Key]);
}
return;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
static public function
LoadFromJSON(string $Filename):
void {
/*//
@date 2022-02-19
populate the configuration from a json file.
//*/
if(!file_exists($Filename))
throw new Error\ConfigFileNotFound($Filename);
////////
$Data = json_decode(
file_get_contents($Filename),
TRUE
);
// @todo 2022-02-19 schema check
//Option::Set(
// Database::OptDatabaseConnections,
// $Data
//);
return;
}
}