-
Notifications
You must be signed in to change notification settings - Fork 18
/
db.php
654 lines (579 loc) · 13.1 KB
/
db.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<?php
/**
* Class SQLSRV_DataBase
*
* @version 0.2.0
* @license GPLv2
*/
class SQLSRV_DataBase {
/**
* The last ran query
*
* The last query is retained in case you want to do extended error handling in some way
*
* @since 0.1.0
* @access private
* @var string
*/
private $last_query = '';
/**
* The last Id from an sql->insert call
*
* @since 0.1.0
* @access private
* @var int
*/
private $last_insert_id = null;
/**
* Hold all errors encountered while processing a query/class construct
*
* @since 0.1.0
* @access private
* @var array
*/
private $error = array();
/**
* The database connection is held here
*
* @since 0.1.0
* @access private
* @var false|null|resource
*/
private $db = null;
/**
* The Database Schema is read into memory and kept here
*
* This is done because MSSQL is very picky about data types and containers, so if enabled
* the class will download the schema and keep it on hand to properly handle various data types
*
* @since 0.2.0
* @access private
* @var array|bool|mixed
*/
private $schema = false;
/**
* The storage location for the DB schema
*
* @since 0.2.0
* @access private
* @var null|string
*/
private $schema_location = null;
/**
* The numbrs of rows affected by a query
*
* @since 0.1.0
* @var int
*/
public $num_rows = 0;
/**
* If a query has returned any rows or not
*
* @since 0.1.0
* @var bool
*/
public $has_rows = false;
/**
* If a connection ot the database exists
*
* @since 0.1.0
* @var bool
*/
public $is_connected = false;
/**
* Database Username
*
* @since 0.1.0
* @access protected
* @var string
*/
protected $dbuser;
/**
* Database Password
*
* @since 0.1.0
* @access protected
* @var string
*/
protected $dbpassword;
/**
* Database Host
* @since 0.1.0
* @var string
*/
protected $dbhost;
/**
* Database Name
* @since 0.1.0
* @var string
*/
protected $dbname;
/**
* Database Port
* @since 0.1.0
* @var int
*/
protected $dbport;
/**
* SQLSRV_DataBase constructor.
*
* @since 0.1.0
* @since 0.2.0 Added the optional `$build_schema` parameter
*
* @param string $dbuser MSSQL database user
* @param string $dbpassword MSSQL database password
* @param string $dbname MSSQL database name
* @param string $dbhost MSSQL database host
* @param int $dbport MSSQL database port
* @param mixed $build_schema Where (if at all) to store the DB schema
*/
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost, $dbport = 1433, $build_schema = false ) {
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
$this->dbport = $dbport;
$this->is_connected = $this->db_connect();
// If we've chosen to build a database schema, this is done on construct
if ( $this->is_connected && $build_schema ) {
if ( is_string( $build_schema ) ) {
$this->schema_location = $build_schema;
}
else {
// Set the schema store location to be alongside the DB class
$this->schema_location = dirname( __FILE__ );
}
$this->schema = $this->build_schema();
}
}
/**
* Connect to and select database
*
* @since 0.1.0
* @return bool
*/
public function db_connect() {
$serverName = "tcp:" . $this->dbhost . ", " . $this->dbport;
$connectionOptions = array(
"Database" => $this->dbname,
"UID" => $this->dbuser,
"PWD" => $this->dbpassword
);
// Create the connection resource
$this->db = sqlsrv_connect( $serverName, $connectionOptions );
// If the connection fails we get a false value and build our error log
if ( false === $this->db )
{
/*
* We don't use log_error() here as the values passed from a failed connection
* are not compatible with the errors passed from a failed query
*/
$error = sqlsrv_errors();
$this->error[] = $error;
error_log( 'Database failure: ' . print_r($error, true) );
return false;
}
sqlsrv_configure( 'WarningsReturnAsErrors', true );
return true;
}
/**
* Build the database schema based on table structures
*
* @param bool $force Force rewrite the schemas file
*
* @since 0.2.0
*
* @return array|bool|mixed
*/
private function build_schema( $force = false ) {
$schema_file = $this->schema_location . '/db-schema.php';
/*
* We return the data of the existing schema file if it exists and we aren't force re-writing it
*/
if ( file_exists( $schema_file ) && ! $force ) {
return json_decode( file_get_contents( $schema_file ) );
}
// Check if we can open the file location for writing
if ( ! $file = fopen( $schema_file, "w+" ) ) {
return false;
}
$schema = array();
$tables = $this->get_results( "
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE = 'BASE TABLE'
AND
TABLE_CATALOG = '" . addslashes( DB_NAME ) . "'
" );
foreach( $tables AS $table ) {
$schema[ $table->TABLE_NAME ] = array();
$columns = $this->get_results( "
EXEC
sp_columns
" . $table->TABLE_NAME . "
" );
foreach( $columns AS $column ) {
$schema[ $table->TABLE_NAME ][ $column->COLUMN_NAME ] = $column;
}
}
fwrite( $file, json_encode( $schema ) );
fclose( $file );
return $schema;
}
/**
* Prepare values based on either the expected schema data (if it exists) or by what type of data it is
*
* @param string $table
* @param string $column
* @param mixed $value
*
* @since 0.2.0
*
* @return string
*/
private function schema_prepare_value( $table, $column, $value ) {
if ( false === $this->schema || ! isset( $this->schema->$table ) || ! isset( $this->schema->$table->$column ) ) {
if ( null === $value ) {
return 'NULL';
}
elseif ( ctype_digit( str_replace( array( '.', '-' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
return $value;
}
else {
return "'" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$schema = $this->schema->$table->$column;
$numerics = array(
'int',
'decimal',
'money'
);
if ( in_array( $schema->TYPE_NAME, $numerics ) ) {
if ( null === $value || '' === $value ) {
if ( 1 == $schema->NULLABLE ) {
return 'NULL';
}
else {
return 0;
}
}
else {
return $value;
}
}
else {
if ( null === $value || empty( $value ) ) {
if ( 1 == $schema->NULLABLE ) {
return 'NULL';
}
else {
return "''";
}
}
}
return "'" . addslashes( utf8_decode( $value ) ) . "'";
}
/**
* Prepare the DB class for a new query
*
* @since 0.1.0
*
* @return void
*/
private function prepare() {
$this->error = array();
$this->last_insert_id = null;
$this->last_query = '';
$this->num_rows = 0;
$this->has_rows = false;
}
/**
* Log errors to the error container of the class and to the systems error log
*
* @param array $errors
*
* @since 0.1.0
*
* @return void
*/
private function log_error( $errors ) {
foreach( $errors AS $error ) {
$new_error = array(
'SQLSTATE' => $error['SQLSTATE'],
'code' => $error['code'],
'message' => $error['message'],
'query' => $this->last_query
);
error_log( var_export( $new_error, true ) );
$this->error[] = $new_error;
}
}
/**
* Update values in a table that matches the give ncriterias
*
* @param string $table
* @param array $what
* @param array $where
*
* @since 0.1.0
*
* @return void
*/
public function update( $table, $what, $where = array() ) {
$set = '';
$check = '';
foreach( $what AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
if ( ! empty( $set ) ) {
$set .= ', ';
}
$set .= $table . '.' . $field . ' = ';
$set .= $this->schema_prepare_value( $table, $field, $value );
}
foreach( $where AS $field => $value ) {
$check .= ' AND ' . $table . '.' . $field;
if ( null === $value ) {
$check .= ' IS NULL';
}
elseif ( ctype_digit( str_replace( array( '.', '-' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
$check .= ' = ' . $value;
}
else {
$check .= " = '" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$result = $this->query( "
UPDATE
" . $table . "
SET
" . $set . "
WHERE
1 = 1
" . $check . "
", false );
}
/**
* Delete rows in a table based on the given criterias
*
* @param string $table
* @param array $where
*
* @since 0.1.0
*
* @return void
*/
public function delete( $table, $where = array() ) {
$check = '';
foreach( $where AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
$check .= ' AND ' . $table . '.' . $field;
if ( null === $value ) {
$check .= ' IS NULL';
}
if ( ctype_digit( str_replace( array( '.', '-' ), '', $value ) ) && substr_count( $value, '.' ) < 2 ) {
$check .= ' = ' . $value;
}
else {
$check .= " = '" . addslashes( utf8_decode( $value ) ) . "'";
}
}
$result = $this->query( "
DELETE FROM
" . $table . "
WHERE
1 = 1
" . $check . "
", false );
}
/**
* Insert a new row and populate it with the given values
*
* @param string $table
* @param array $data
*
* @since 0.1.0
*
* @return void
*/
public function insert( $table, $data ) {
$fields = '';
$values = '';
foreach( $data AS $field => $value ) {
$field = trim( $field );
$value = trim( $value );
if ( ! empty( $fields ) ) {
$fields .= ', ';
}
if ( ! empty( $values ) ) {
$values .= ', ';
}
$fields .= $table . '.' . $field;
$values .= $this->schema_prepare_value( $table, $field, $value );
}
$result = $this->query( "
INSERT INTO
" . $table . " ( " . $fields . " )
VALUES ( " . $values . " )
", false );
}
/**
* Get a single row from the database and return it in the given format
*
* @param string $query
* @param string $format
*
* @since 0.1.0
*
* @return array|bool|null|object
*/
public function get_row( $query, $format = 'object' ) {
$request = $this->query( $query );
if ( ! $this->has_error() ) {
if ( 'array' == $format ) {
$response = sqlsrv_fetch_array( $request, SQLSRV_FETCH_ASSOC );
}
else {
$response = sqlsrv_fetch_object( $request );
}
}
else {
$response = false;
}
return $response;
}
/**
* Get all the rows returned by a query to the database
*
* @param string $query
* @param string $format
*
* @since 0.1.0
*
* @return array|bool
*/
public function get_results( $query, $format = 'object' ) {
$response = array();
$request = $this->query( $query );
if ( $this->has_error() ) {
$response = false;
}
else {
if ( 'array' == $format ) {
while ( $answer = sqlsrv_fetch_array( $request, SQLSRV_FETCH_ASSOC ) ) {
$response[] = $answer;
}
}
else {
while ( $answer = sqlsrv_fetch_object( $request ) ) {
$response[] = $answer;
}
}
}
return $response;
}
/**
* Return the primary index value from a table
*
* @since 0.2.0
*
* @return bool|int
*/
public function last_insert_id() {
if ( $this->has_error() || empty( $this->last_query ) ) {
return false;
}
if ( empty( $this->last_insert_id ) ) {
$this->last_insert_id = $this->get_row( "SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]" );
}
return $this->last_insert_id->SCOPE_IDENTITY;
}
/**
* @since 0.1.0
* @deprecated 0.2.0 Use last_insert_id()
* @see last_insert_id()
*
* @return bool|int
*/
public function get_last_id() {
return $this->last_insert_id();
}
/**
* Runs the actual query against the database
*
* @param string $query
* @param bool $can_get_rows
*
* @since 0.1.0
*
* @return bool|resource
*/
public function query( $query, $can_get_rows = true ) {
// If no connection is found we try to restore it
if ( ! $this->is_connected ) {
$this->is_connected = $this->db_connect();
// If we couldn't reconnect we break out early
if ( ! $this->is_connected ) {
return false;
}
}
$this->prepare();
$this->last_query = $query;
$doing_query = sqlsrv_query( $this->db, $query );
if ( false === $doing_query ) {
if ( null != ( $errors = sqlsrv_errors() ) ) {
$this->log_error( $errors );
}
}
else {
$this->has_rows = true;
$this->num_rows = sqlsrv_num_rows( $doing_query );
}
if ( $can_get_rows ) {
if ( sqlsrv_has_rows( $doing_query ) ) {
$this->has_rows = true;
} else {
$this->has_rows = false;
}
}
return $doing_query;
}
/**
* Return a list of errors encountered on the last query, or false
*
* @since 0.2.0
*
* @return array|bool
*/
public function has_error() {
if ( ! empty( $this->error ) ) {
return $this->error;
}
return false;
}
/**
* @since 0.1.0
* @deprecated 0.2.0 Use has_error() instead
* @see has_error()
*
* @return array|bool
*/
public function hasError() {
return $this->has_error();
}
/**
* Return the last ran query in its entirety
*
* @since 0.1.0
*
* @return string
*/
public function get_last_query() {
return $this->last_query;
}
}