-
Notifications
You must be signed in to change notification settings - Fork 66
/
db_mysql.php
476 lines (381 loc) · 12.5 KB
/
db_mysql.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
<?php
/*
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
*/
/**
* Mysql Database class
*
* @copyright AlternC-Team 2000-2017 https://alternc.com/
*
*/
class DB_Sql {
/* public: connection parameters */
private $Host;
private $Database;
private $User;
private $Password;
/* public: configuration parameters */
private $Auto_Free = False; // Set to True for automatic mysql_free_result()
private $Debug = False; // Set to 1 for debugging messages.
private $Halt_On_Error = "no"; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)
private $Seq_Table = "db_sequence";
/* public: result array and current row number */
public /* FIXME */ $Record = array();
private $Row = 0;
private $num_rows;
/* public: current error number and error text */
private $Errno;
private $Error;
/* private: link and query handles */
private $Query_String;
/* PDO related variables */
private $pdo_instance = NULL;
private $pdo_query = NULL;
/**
* Constructor: Connect to the database server
*/
function __construct($db, $host, $user, $passwd) {
$dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);
$options=array(
// \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo_instance = new PDO($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
echo "Mysql", "PDO instance", $e->getMessage();
return FALSE;
}
}
/**
* function for MySQL database connection management
*
* This function manages the connection to the MySQL database.
*
* @param $Database name of the database
* @param $Host DNS of the MySQL hosting server
* @param $User the user's name
* @param $Password the user's password
*
* @return the class variable $Link_ID
*/
function connect($Database = "", $Host = "", $User = "", $Password = "") {
$this->halt('Mysql::connect() : This function should no longer be used');
/* Handle defaults */
if ("" == $Database)
$Database = $this->Database;
if ("" == $Host)
$Host = $this->Host;
if ("" == $User)
$User = $this->User;
if ("" == $Password)
$Password = $this->Password;
if (!$this->pdo_instance) {
$dsn = sprintf('mysql:dbname=%s;host=%s', $Database, $Host);
try {
$this->pdo_instance = new PDO($dsn, $User, $Password);
} catch (PDOException $e) {
$this->halt("Mysql::PDO_instance" . $e->getMessage());
return FALSE;
}
}
return True;
}
/**
* Discard the query result
*
* This function discards the last query result.
*/
function free() {
$this->pdo_query->closeCursor();
}
function is_connected() {
return $this->pdo_instance != FALSE;
}
function last_error() {
return $this->Error;
}
/**
* Perform a query
*
* This function performs the MySQL query described in the string parameter
*
* @param a string describing the MySQL query
* @param arguments is an optionnal array for future use with PDO parametrized requests
* @return the $Query_ID class variable (null if fails)
*/
function query($Query_String, $arguments = false) {
global $debug_alternc;
if (empty($Query_String) || !$this->is_connected())
return FALSE;
$this->Query_String = $Query_String;
if ($this->Debug)
printf("Debug: query = %s<br />\n", $Query_String);
$debug_chrono_start = microtime(true);
if ($arguments===false) {
$this->pdo_query = $this->pdo_instance->query($Query_String);
$exec_state = is_object($this->pdo_query);
} else {
$this->pdo_query = $this->pdo_instance->prepare($this->Query_String);
$exec_state = ($arguments) ? $this->pdo_query->execute($arguments)
: $this->pdo_query->execute();
// WARNING: this ternary is when we pass array() as $arguments
}
$debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000;
$this->Row = 0;
if ($exec_state == FALSE) {
if (is_object($this->pdo_query)) {
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
} else {
$this->Errno = $this->pdo_instance->errorCode();
$this->Error = $this->pdo_instance->errorInfo();
}
if( defined("THROW_EXCEPTIONS") && THROW_EXCEPTIONS ){
$error_msg=$this->Error[2];
throw new \Exception("Mysql query failed : $error_msg");
}
$this->halt("SQL Error: ".$Query_String);
return FALSE;
}
if (isset($debug_alternc)) {
$debug_alternc->add("SQL Query : (".substr($debug_chrono_start,0,5)." ms)\t $Query_String");
$debug_alternc->nb_sql_query++;
$debug_alternc->tps_sql_query += $debug_chrono_start;
}
return TRUE;
}
/**
* walk result set
*
* This function tests if a new record is available in the current
* query result.
*
* @return TRUE if a new record is available
*/
function next_record() {
if (!$this->pdo_query) {
$this->halt("next_record called with no query pending.");
return FALSE;
}
$this->Record = $this->pdo_query->fetch(PDO::FETCH_BOTH);
$this->Row++;
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
if ($this->Record == FALSE) {
if ($this->Auto_Free)
$this->free();
return FALSE;
}
return TRUE;
}
/* pdo equivalent of fetchAll() */
function fetchAll() {
if (!$this->pdo_query) {
$this->halt("next_record called with no query pending.");
return FALSE;
}
$data = $this->pdo_query->fetchAll(PDO::FETCH_BOTH);
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
if ($data == FALSE) {
if ($this->Auto_Free)
$this->free();
return FALSE;
}
return $data;
}
/* pdo equivalent of fetch() */
function fetch($mode=PDO::FETCH_ASSOC) {
if (!$this->pdo_query) {
$this->halt("next_record called with no query pending.");
return FALSE;
}
$data = $this->pdo_query->fetch($mode);
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
if ($data == FALSE) {
if ($this->Auto_Free)
$this->free();
return FALSE;
}
return $data;
}
/**
* table locking
*/
function lock($table, $mode="write") {
if (!$this->is_connected())
return FALSE;
$query="lock tables ";
if (is_array($table)) {
while (list($key,$value)=each($table)) {
if ($key=="read" && $key!=0) {
$query.="$value read, ";
} else {
$query.="$value $mode, ";
}
}
$query=substr($query,0,-2);
} else {
$query.="$table $mode";
}
if (!$this->query($query)) {
$this->halt("lock($table, $mode) failed.");
return FALSE;
}
return TRUE;
}
/**
* table unlocking
*/
function unlock() {
if (!$this->is_connected())
return FALSE;
if (!$this->query('unlock tables')) {
$this->halt("unlock() failed.");
return FALSE;
}
}
/**
* evaluate the result (size, width)
*/
function affected_rows() {
if (!$this->pdo_query) return 0;
return $this->pdo_query->rowCount();
}
function num_rows() {
if (!$this->pdo_query) return 0;
return $this->pdo_query->rowCount();
}
function num_fields() {
if (!$this->pdo_query) return 0;
return $this->pdo_query->columnCount();
}
/**
* shorthand notation
*/
function nf() {
return $this->num_rows();
}
function np() {
print $this->num_rows();
}
/**
* @param string $Name
* @return integer
*/
function f($Name) {
if (isset($this->Record[$Name]))
return $this->Record[$Name];
else
return false;
}
function current_record() {
return $this->Record;
}
function p($Name) {
print $this->Record[$Name];
}
function lastid() {
return $this->pdo_instance->lastInsertId();
}
/**
* Escape a string to use it into a SQL PDO query
* @param string string to escape
* @return string escaped string
*/
function quote($string) {
return $this->pdo_instance->quote($string);
}
/**
* Execute a direct query, not getting any result back
* @param query string query to execute
* @return integer the number of affected rows
*/
function exec($query) {
return $this->pdo_instance->exec($query);
}
/**
* get next sequence numbers
*/
function nextid($seq_name) {
if (!$this->is_connected())
return FALSE;
if ($this->lock($this->Seq_Table)) {
/* get sequence number (locked) and increment */
$q = sprintf("select nextid from %s where seq_name = '%s'",
$this->Seq_Table,
$seq_name);
$this->query($q);
$this->next_record();
$id = $this->f('nextid');
/* No current value, make one */
if (!$id) {
$currentid = 0;
$q = sprintf("insert into %s values('%s', %s)",
$this->Seq_Table,
$seq_name,
$currentid);
$this->query($q);
} else {
$currentid = $id;
}
$nextid = $currentid + 1;
$q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
$this->Seq_Table,
$nextid,
$seq_name);
$this->query($q);
$this->unlock();
} else {
$this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
return FALSE;
}
return $nextid;
}
/**
* DEPRECATED return table metadata
*/
function metadata($table='',$full=false) {
global $msg;
$msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())');
return FALSE;
}
/**
* private: error handling
*/
function halt($msg) {
if ($this->Halt_On_Error == "no")
return;
$this->haltmsg($msg);
if ($this->Halt_On_Error != "report")
die("Session halted.");
}
/**
* private: error handling
*/
function haltmsg($msg) {
printf("</td></tr></table><b>Database error:</b> %s<br />\n", $msg);
printf("<b>MySQL Error</b>: %s (%s)<br />\n",
$this->Errno,
implode("\n", $this->Error));
}
function table_names() {
$this->query("SHOW TABLES");
$return = array();
while ($this->next_record())
$return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database);
return $return;
}
} /* Class DB_Sql */