/
OcDb.php
496 lines (432 loc) · 15.4 KB
/
OcDb.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
<?php
namespace Utils\Database;
use PDOException;
use PDOStatement;
use Utils\Debug\Debug;
class OcDb extends OcPdo
{
const BIND_CHAR = ':'; //
/**
* This the ONLY way on which instance of this class
* should be accessed
*
* Returns instance of itself.
*
* @return OcDb object
*/
public static function instance()
{
$instance = parent::instance();
return $instance;
}
/**
* @return one row from result, or FALSE if there are no more rows available
* The data is returned as an array indexed by column name, as returned in your
* SQL SELECT
*/
public function dbResultFetch( PDOStatement $stmt = null, $fetchStyle=null)
{
if(!is_null($stmt)){
if(is_null($fetchStyle)){
return $stmt->fetch();
}else{
return $stmt->fetch($fetchStyle);
}
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* for queries witch LIMIT 1 return only one row
* and reset database class preparing it for next job.
*/
public function dbResultFetchOneRowOnly( PDOStatement $stmt = null )
{
if(!is_null($stmt)){
$result = $stmt->fetch();
$stmt->closeCursor();
return $result;
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* The returned array contains all of the remaining rows
* (if you have previously called dbResultFetch(), or all returned rows if not)
* in the result set. The array represents each row as an array indexed by column name,
* as returned in your SQL SELECT. An empty array is returned
* if there are zero results to fetch, or FALSE on failure.
*
* @return all rows from result as complex array.
*/
public function dbResultFetchAll(
PDOStatement $stmt = null, $fetchStyle = null )
{
if(!is_null($stmt)){
if(is_null($fetchStyle)){
$result = $stmt->fetchAll();
}else{
$result = $stmt->fetchAll($fetchStyle);
}
$stmt->closeCursor();
return $result;
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* This method returns array of objects which are returned by $rowToObjectCallback function.
*
* @param PDOStatement $stmt
* @param callable $rowToObjectCallback
* @return array
*/
public function dbFetchAllAsObjects(PDOStatement $stmt, $rowToObjectCallback)
{
if(is_callable($rowToObjectCallback)){
$result = [];
while($row = $this->dbResultFetch($stmt, OcDb::FETCH_ASSOC)){
$result[] = $rowToObjectCallback($row);
}
return $result;
}
$this->error('', new PDOException(__METHOD__.': rowToObjectCallback param must be callable!'));
}
/**
* Returns assoc. array generated by setting $keyCol value as array key
* and $valCol as its value.
*
* @param PDOStatement $stmt
* @param string $keyCol - column name to use for result key
* @param string $valCol - column name to use for result value
*/
public function dbFetchAsKeyValArray(PDOStatement $stmt, $keyCol, $valCol)
{
$result = [];
if(!is_null($stmt)){
while($row = $this->dbResultFetch($stmt, OcDb::FETCH_ASSOC)){
$result[$row[$keyCol]] = $row[$valCol];
}
return $result;
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* Returns array with values of $keyCol column.
*
* @param PDOStatement $stmt
* @param string $keyCol - column name to use for result key
* @return array
*/
public function dbFetchOneColumnArray(PDOStatement $stmt, $keyCol)
{
$result = [];
if(!is_null($stmt)){
while($row = $this->dbResultFetch($stmt, OcDb::FETCH_ASSOC)){
$result[] = $row[$keyCol];
}
return $result;
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* This method returns the value from first column of first row in statement
*
* @param PDOStatement $stmt -
* @param unknown $default - default value to return if there is no results
*/
protected function dbResultFetchValue( PDOStatement $stmt, $default){
$row = $this->dbResultFetch($stmt);
$stmt->closeCursor();
if ($row) {
$value = reset($row);
if ($value == null){
return $default;
} else {
return $value;
}
} else {
return $default;
}
}
/**
* @return number of row in results (i.e. number of rows returned by SQL SELECT)
* or the number of rows affected by the last DELETE, INSERT, or UPDATE statement
*/
public function rowCount( PDOStatement $stmt = null )
{
if(!is_null($stmt)){
return $stmt->rowCount();
}
$this->error('', new PDOException(__METHOD__.': call PDOstatement issue!'));
}
/**
* simple querry
* Use only with static queries, Queries should contain no variables.
* For queries with variables use paramQery method
*
* @param string $query
* @return PDOStatement obj, if the query succeeded; null otherwise
*/
public function simpleQuery($query)
{
try {
$stmt = $this->prepare($query);
$stmt->setFetchMode(self::FETCH_ASSOC);
$stmt->execute();
} catch (PDOException $e) {
$this->error('Query: '.$query, $e);
return null;
}
if ($this->debug) {
self::debugOut(__METHOD__.":\n\nQuery: ".$query);
}
return $stmt;
}
/**
* Executes given query. If the query return no rows, or null value, default value is returned.
* Otherwise, value of first column in a first row is returned.
*
* @param $query Query to be executed
* @param $default Default value
*
* @return
*/
public function simpleQueryValue($query, $default)
{
$stmt = $this->simpleQuery($query);
return $this->dbResultFetchValue($stmt, $default);
}
/**
* @param $query - string, with params representation instead variables.
* @param $params - array with variables.
*
* [keyname][value]
* [keyname][data_type]
*
* example:
* ----------------------------------------------------------------------------------
* $query: 'SELECT * FROM tabele WHERE field1 = :variable1 AND field2 = :variable2'
* $params['variable1']['value'] = 1;
* $params['variable1']['data_type'] = 'integer';
* $params['variable2']['value'] = 'cat is very lovelly animal';
* $params['variable2']['data_type'] = 'string';
* ----------------------------------------------------------------------------------
* data type can be:
*
* - 'boolean' Represents a boolean data type.
* - 'null' Represents the SQL NULL data type.
* - 'integer' or 'int' or 'i' Represents the SQL INTEGER data type.
* - 'string' or 'str' or 's' Represents the SQL CHAR, VARCHAR, or other string data type.
* - 'large' Represents the SQL large object data type.
* - 'recordset' Represents a recordset type. Not currently supported by any drivers.
*
* @return PDOStatement obj, if the query succeeded; null otherwise
*/
public function paramQuery(/*PHP7: string*/ $query, array $params)
{
try {
$stmt = $this->prepare($query);
foreach ($params as $key => $val) {
switch ($val['data_type']) {
case 'integer':
case 'int':
case 'i':
$stmt->bindParam($key, $val['value'], self::PARAM_INT);
break;
case 'boolean':
$stmt->bindParam($key, $val['value'], self::PARAM_BOOL);
break;
case 'string':
case 'str':
case 's':
$stmt->bindParam($key, $val['value'], self::PARAM_STR);
break;
case 'null':
$stmt->bindParam($key, $val['value'], self::PARAM_NULL);
break;
case 'large':
$stmt->bindParam($key, $val['value'], self::PARAM_LOB);
break;
case 'recordset':
$stmt->bindParam($key, $val['value'], self::PARAM_STMT);
break;
default:
return null;
}
}
$stmt->setFetchMode(self::FETCH_ASSOC);
$stmt->execute();
} catch (PDOException $e) {
$this->error("Query:\n$query\n\nParams:\n".implode(' | ', $params), $e);
return null;
}
if ($this->debug) {
self::debugOut(__METHOD__.":\n\nQuery:\n$query\n\nParams:\n".implode(' | ', $params));
}
return $stmt;
}
/**
* Executes given query, as described in method paramQuery().
* If the query return no rows, or null value, default value is returned.
* Otherwise, value from first column of the first row is returned.
*
* @param $query Query to be executed
* @param $default Default value
* @param $params Query params
*
* @return
*/
public function paramQueryValue($query, $default, array $params)
{
$stmt = $this->paramQuery($query, $params);
return $this->dbResultFetchValue($stmt, $default);
}
/**
* @param $query - string, with params representation instead variables.
* @param $param1, param2 .. paramN - variables.
*
*
* example:
* ----------------------------------------------------------------------------------
* $param1 = 1;
* $param2 = 'cat is very lovelly animal';
* // note that variable in query MUST be in format :1, :2, :3 (and so on).
* $query = 'SELECT something FROM tabele WHERE field1=:1 AND field2=:2';
*
* multiVariableQuery($query, $param1, $param2 )
* ----------------------------------------------------------------------------------
*
* @return PDOStatement obj, if the query succeeded; null otherwise
*/
public function multiVariableQuery($query)
{
$argList = func_get_args(); //get list of params
// check if params are passed as array
if (2 === func_num_args() && is_array($argList[1])) {
$argList = $argList[1];
}else{
unset($argList[0]); //remove query from arg. lists (rest are params)
}
try {
$stmt = $this->prepare($query);
$i = 1;
foreach($argList as $param){
$stmt->bindValue(self::BIND_CHAR . $i++, $param);
}
$stmt->setFetchMode(self::FETCH_ASSOC);
$stmt->execute();
} catch (PDOException $e) {
$message = 'Query|Params: '.$query.' | '.implode(' | ', $argList);
$this->error($message, $e);
return null;
}
if ($this->debug) {
self::debugOut(__METHOD__.":\n\nQuery|Params: $query | ".implode(' | ', $argList));
}
return $stmt;
}
/**
* Executes given query, as described in method multiVariableQuery().
* If the query return no rows, or null value, default value is returned.
* Otherwise, value of first column in a first row is returned.
*
* @param params - Query to be executed, default value, query params
*
* @return
*/
public function multiVariableQueryValue($query, $default)
{
$argList = func_get_args();
$numArgs = func_num_args();
if ( $numArgs <= 2 ) {
//only query + default value=> use simpleQuery
$e = new PDOException('Improper using of '.__METHOD__.' . Too less arguments. Use simpleQueryValue() instead');
$this->error('Improper using of '.__METHOD__, $e, false, false); //skip sending email
return $this->simpleQueryValue($query, $default);
}else {
// check if params are passed as array
if ($numArgs == 3 && is_array($argList[2])) {
$argList = $argList[2];
}else{
$argList = array_slice($argList, 2);
}
}
//more params - remove first two from argList and call...
$stmt = $this->multiVariableQuery($query, $argList);
return $this->dbResultFetchValue($stmt, $default);
}
/**
* This method enables SQL STRICT-MODE (STRICT_ALL_TABLES)
* in current db session (instance)
*/
public function enableStrictMode()
{
$sqlMode = $this->getSqlMode();
$modes = explode(',', $sqlMode);
if(($key = array_search('STRICT_ALL_TABLES', $modes)) !== false) {
$trace = Debug::getTraceStr();
error_log(__METHOD__.": Sql Strict-mode already enabled! ($trace)");
return;
}
$modes[] = 'STRICT_ALL_TABLES';
$sqlMode = implode(',', $modes);
$this->simpleQuery("SET sql_mode = '$sqlMode'");
}
/**
* This method disables SQL STRICT-MODE (STRICT_ALL_TABLES)
* in current db session (instance)
*/
public function disableStrictMode()
{
$sqlMode = $this->getSqlMode();
$modes = explode(',', $sqlMode);
if(($key = array_search('STRICT_ALL_TABLES', $modes)) !== false) {
unset($modes[$key]);
}else{
$trace = Debug::getTraceStr();
error_log(__METHOD__.": Sql Strict-mode already disabled! ($trace)");
return;
}
$sqlMode = implode(',', $modes);
$this->simpleQuery("SET sql_mode = '$sqlMode'");
}
/**
* This method returns sql-mode from current DB session
*/
public function getSqlMode()
{
return $this->dbResultFetchOneRowOnly(
$this->simpleQuery("SELECT @@sql_mode AS sql_mode"))['sql_mode'];
}
/**
* Quote limit and offset values - it can't be bind by pdo->bind :(
* @param int $limit
* @param int $offset
* @return number[$limit, $offset]
*/
public function quoteLimitOffset($limit, $offset=null){
if(is_null($limit) || !is_numeric($limit)){
$limit = 1000000000; //very large row number
}else{
$limit = (int) $limit;
}
if(is_null($offset) || !is_numeric($offset)){
$offset = 0; // no-offset
}else{
$offset = (int) $offset;
}
return array($limit, $offset);
}
/**
* Quote string before use in DB query
* (needs for IN strings etc.)
*
* @param string $str
* @return string
*/
public function quoteString($str)
{
$value = $this->quote($str, self::PARAM_STR);
$value = substr($value, 1, -1); //remove ' char from the begining and end of the string
$value = mb_ereg_replace('&', '\&', $value); //escape '&' char
return $value;
}
}