-
Notifications
You must be signed in to change notification settings - Fork 8
/
driver_pgsql.php
579 lines (493 loc) · 19.2 KB
/
driver_pgsql.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
<?php
/**
* @package PostgreSQL_For_Wordpress
* @version $Id$
* @author Hawk__, www.hawkix.net
*/
/**
* Provides a driver for PostgreSQL
*
* This file maps original mysql_* functions with PostgreSQL equivalents
*
* This was originally based on usleepless's original 'mysql2pgsql.php' file, many thanks to him
*/
// Check pgsql extension is loaded
if ( !extension_loaded('pgsql') )
wp_die( 'Your PHP installation appears to be missing the PostgreSQL extension which is required by WordPress with PG4WP.' );
// Initializing some variables
$GLOBALS['pg4wp_version'] = '7.0';
$GLOBALS['pg4wp_result'] = 0;
$GLOBALS['pg4wp_numrows_query'] = '';
$GLOBALS['pg4wp_ins_table'] = '';
$GLOBALS['pg4wp_ins_field'] = '';
$GLOBALS['pg4wp_last_insert'] = '';
$GLOBALS['pg4wp_connstr'] = '';
$GLOBALS['pg4wp_conn'] = false;
function wpsql_num_rows($result)
{ return pg_num_rows($result); }
function wpsql_numrows($result)
{ return pg_num_rows($result); }
function wpsql_num_fields($result)
{ return pg_num_fields($result); }
function wpsql_fetch_field($result)
{ return 'tablename'; }
function wpsql_fetch_object($result)
{ return pg_fetch_object($result); }
function wpsql_free_result($result)
{ return pg_free_result($result); }
function wpsql_affected_rows()
{
if( $GLOBALS['pg4wp_result'] === false)
return 0;
else
return pg_affected_rows($GLOBALS['pg4wp_result']);
}
function wpsql_fetch_row($result)
{ return pg_fetch_row($result); }
function wpsql_data_seek($result, $offset)
{ return pg_result_seek ( $result, $offset ); }
function wpsql_error()
{ if( $GLOBALS['pg4wp_conn']) return pg_last_error(); else return ''; }
function wpsql_fetch_assoc($result) { return pg_fetch_assoc($result); }
function wpsql_escape_string($s) { return pg_escape_string($s); }
function wpsql_real_escape_string($s,$c=NULL) { return pg_escape_string($s); }
function wpsql_get_server_info() { return '5.0.30'; } // Just want to fool wordpress ...
function wpsql_result($result, $i, $fieldname)
{ return pg_fetch_result($result, $i, $fieldname); }
// This is a fake connection except during installation
function wpsql_connect($dbserver, $dbuser, $dbpass)
{
$GLOBALS['pg4wp_connstr'] = '';
$hostport = explode(':', $dbserver);
if( !empty( $hostport[0]))
$GLOBALS['pg4wp_connstr'] .= ' host='.$hostport[0];
if( !empty( $hostport[1]))
$GLOBALS['pg4wp_connstr'] .= ' port='.$hostport[1];
if( !empty( $dbuser))
$GLOBALS['pg4wp_connstr'] .= ' user='.$dbuser;
if( !empty( $dbpass))
$GLOBALS['pg4wp_connstr'] .= ' password='.$dbpass;
elseif( !PG4WP_INSECURE)
wp_die( 'Connecting to your PostgreSQL database without a password is considered insecure.
<br />If you want to do it anyway, please set "PG4WP_INSECURE" to true in your "db.php" file.' );
// While installing, we test the connection to 'template1' (as we don't know the effective dbname yet)
if( defined('WP_INSTALLING') && WP_INSTALLING)
return wpsql_select_db( 'template1');
return 1;
}
// The effective connection happens here
function wpsql_select_db($dbname, $connection_id = 0)
{
$pg_connstr = $GLOBALS['pg4wp_connstr'].' dbname='.$dbname;
$GLOBALS['pg4wp_conn'] = pg_connect($pg_connstr);
if( $GLOBALS['pg4wp_conn'])
{
$ver = pg_version($GLOBALS['pg4wp_conn']);
if( isset($ver['server']))
$GLOBALS['pg4wp_version'] = $ver['server'];
}
// Now we should be connected, we "forget" about the connection parameters (if this is not a "test" connection)
if( !defined('WP_INSTALLING') || !WP_INSTALLING)
$GLOBALS['pg4wp_connstr'] = '';
// Execute early transmitted commands if needed
if( isset($GLOBALS['pg4wp_pre_sql']) && !empty($GLOBALS['pg4wp_pre_sql']))
foreach( $GLOBALS['pg4wp_pre_sql'] as $sql2run)
wpsql_query( $sql2run);
return $GLOBALS['pg4wp_conn'];
}
function wpsql_fetch_array($result)
{
$res = pg_fetch_array($result);
if( is_array($res) )
foreach($res as $v => $k )
$res[$v] = trim($k);
return $res;
}
function wpsql_query($sql)
{
if( !$GLOBALS['pg4wp_conn'])
{
// Catch SQL to be executed as soon as connected
$GLOBALS['pg4wp_pre_sql'][] = $sql;
return true;
}
$initial = $sql;
$sql = pg4wp_rewrite( $sql );
/**
* Run query
*/
$GLOBALS['pg4wp_result'] = pg_query( $sql );
// debug
if( (PG4WP_DEBUG || PG4WP_LOG_ERRORS) && $GLOBALS['pg4wp_result'] === false && $err = pg_last_error())
{
$ignore = false;
if( defined('WP_INSTALLING') && WP_INSTALLING) {
global $table_prefix;
$ignore = strpos($err, 'relation "'.$table_prefix);
}
if( ! $ignore ) {
error_log('['.microtime(true)."] Error running :\n$initial\n---- converted to ----\n$sql\n----> $err\n---------------------\n", 3, PG4WP_LOG.'pg4wp_errors.log');
}
}
return $GLOBALS['pg4wp_result'];
}
function wpsql_insert_id($lnk = NULL)
{
global $wpdb;
$ins_field = $GLOBALS['pg4wp_ins_field'];
$table = PG4WP_SCHEMA.'.'.$GLOBALS['pg4wp_ins_table'];
$lastq = $GLOBALS['pg4wp_last_insert'];
$seq = $table . '_seq';
$data = null;
// Table 'term_relationships' doesn't have a sequence
if( $table == PG4WP_SCHEMA.'.'.$wpdb->term_relationships)
{
$sql = 'NO QUERY';
$data = 0;
}
// When using WP_Import plugin, ID is defined in the query
elseif('post_author' == $ins_field && false !== strpos($lastq,'ID'))
{
$sql = 'ID was in query ';
$pattern = '/.+\'(\d+).+$/';
preg_match($pattern, $lastq, $matches);
$data = $matches[1];
// We should update the sequence on the next non-INSERT query
$GLOBALS['pg4wp_queued_query'] = "SELECT SETVAL('$seq',(SELECT MAX(\"ID\") FROM $table)+1);";
}
else
{
$sql = "SELECT last_value FROM $seq";
$res = pg_query($sql);
if( false !== $res) {
$data = pg_fetch_result($res, 0, 0);
} elseif( PG4WP_DEBUG || PG4WP_ERROR_LOG)
{
$log = '['.microtime(true)."] wpsql_insert_id() was called with '$table' and '$ins_field'".
" and generated an error. The latest INSERT query was :\n'$lastq'\n";
error_log( $log, 3, PG4WP_LOG.'pg4wp_errors.log');
}
}
if( PG4WP_DEBUG && $sql)
error_log( '['.microtime(true)."] Getting inserted ID for '$table' ('$ins_field') : $sql => $data\n", 3, PG4WP_LOG.'pg4wp_insertid.log');
return $data;
}
/**
* Rewrite the query
* @return string
*/
function pg4wp_rewrite( $sql)
{
global $wpdb;
$logto = 'queries';
// The end of the query may be protected against changes
$end = '';
// Remove unusefull spaces
$initial = $sql = trim($sql);
// SELECT
if( 0 === strpos($sql, 'SELECT'))
{
$logto = 'SELECT';
preg_match('/FROM\s+([^ ,]+)(?:\s*,\s*([^ ,]+))*\s+/', $sql, $matches);
unset($matches[0]);
foreach ($matches as $table) {
if (FALSE === strstr('.', $table)){
$sql = str_replace($table, PG4WP_SCHEMA.'.'.$table, $sql);
$table = PG4WP_SCHEMA.'.'.$table;
}
}
// SQL_CALC_FOUND_ROWS doesn't exist in PostgreSQL but it's needed for correct paging
if( false !== strpos($sql, 'SQL_CALC_FOUND_ROWS'))
{
$sql = str_replace('SQL_CALC_FOUND_ROWS', '', $sql);
$GLOBALS['pg4wp_numrows_query'] = $sql;
if( PG4WP_DEBUG)
error_log( '['.microtime(true)."] Number of rows required for :\n$sql\n---------------------\n", 3, PG4WP_LOG.'pg4wp_NUMROWS.log');
}
elseif( false !== strpos($sql, 'FOUND_ROWS()'))
{
// Here we convert the latest query into a COUNT query
$sql = $GLOBALS['pg4wp_numrows_query'];
// Remove any LIMIT ... clause (this is the blocking part)
$pattern = '/\s+LIMIT.+/';
$sql = preg_replace( $pattern, '', $sql);
// Now add the COUNT() statement
$pattern = '/SELECT\s+([^\s]+)\s+(FROM.+)/';
$sql = preg_replace( $pattern, 'SELECT COUNT($1) $2', $sql);
}
// Handle CAST( ... AS CHAR)
$sql = preg_replace( '/CAST\((.+) AS CHAR\)/', 'CAST($1 AS TEXT)', $sql);
// Handle COUNT(*)...ORDER BY...
$sql = preg_replace( '/COUNT(.+)ORDER BY.+/s', 'COUNT$1', $sql);
// In order for users counting to work...
$matches = array();
if( preg_match_all( '/COUNT[^C]+\),/',$sql, $matches))
{
foreach( $matches[0] as $num => $one)
{
$sub = substr( $one, 0, -1);
$sql = str_replace( $sub, $sub.' AS count'.$num, $sql);
}
}
$pattern = '/LIMIT[ ]+(\d+),[ ]*(\d+)/';
$sql = preg_replace($pattern, 'LIMIT $2 OFFSET $1', $sql);
$pattern = '/DATE_ADD[ ]*\(([^,]+),([^\)]+)\)/';
$sql = preg_replace( $pattern, '($1 + $2)', $sql);
// UNIX_TIMESTAMP in MYSQL returns an integer
$pattern = '/UNIX_TIMESTAMP\(([^\)]+)\)/';
$sql = preg_replace( $pattern, 'ROUND(DATE_PART(\'epoch\',$1))', $sql);
$date_funcs = array(
'DAYOFMONTH(' => 'EXTRACT(DAY FROM ',
'YEAR(' => 'EXTRACT(YEAR FROM ',
'MONTH(' => 'EXTRACT(MONTH FROM ',
'DAY(' => 'EXTRACT(DAY FROM ',
);
// MySQL ORDER BY FIELD conversion
if (strstr($sql, 'ORDER BY FIELD') !== FALSE)
{
preg_match_all('/ORDER BY FIELD\(\s([a-zA-Z\.\_]+[^,\s]),\s([0-9,]+)\s\)/', $sql, $params);
$values = preg_split('/\,/', $params[2][0]);
$order = 'ORDER BY CASE ';
foreach ($values as $i => $value)
{
$order .= ' WHEN ' . $params[1][0] . '=' . $value . ' THEN ' . ($i + 1);
}
$order .= ' END';
$sql = str_replace($params[0][0], $order, $sql);
}
$sql = str_replace( 'ORDER BY post_date DESC', 'ORDER BY YEAR(post_date) DESC, MONTH(post_date) DESC', $sql);
$sql = str_replace( 'ORDER BY post_date ASC', 'ORDER BY YEAR(post_date) ASC, MONTH(post_date) ASC', $sql);
$sql = str_replace( array_keys($date_funcs), array_values($date_funcs), $sql);
$curryear = date( 'Y');
$sql = str_replace( 'FROM \''.$curryear, 'FROM TIMESTAMP \''.$curryear, $sql);
// MySQL 'IF' conversion - Note : NULLIF doesn't need to be corrected
$pattern = '/ (?<!NULL)IF[ ]*\(([^,]+),([^,]+),([^\)]+)\)/';
$sql = preg_replace( $pattern, ' CASE WHEN $1 THEN $2 ELSE $3 END', $sql);
$sql = str_replace('GROUP BY '.$wpdb->prefix.'posts.ID', '' , $sql);
$sql = str_replace("!= ''", '<> 0', $sql);
// MySQL 'LIKE' is case insensitive by default, whereas PostgreSQL 'LIKE' is
$sql = str_replace( ' LIKE ', ' ILIKE ', $sql);
// INDEXES are not yet supported
if( false !== strpos( $sql, 'USE INDEX (comment_date_gmt)'))
$sql = str_replace( 'USE INDEX (comment_date_gmt)', '', $sql);
// HB : timestamp fix for permalinks
$sql = str_replace( 'post_date_gmt > 1970', 'post_date_gmt > to_timestamp (\'1970\')', $sql);
// Akismet sometimes doesn't write 'comment_ID' with 'ID' in capitals where needed ...
if( false !== strpos( $sql, $wpdb->comments)) {
$sql = str_replace(' comment_id ', ' comment_ID ', $sql);
}
} // UPDATE
elseif( 0 === strpos($sql, 'UPDATE'))
{
$logto = 'UPDATE';
preg_match('/UPDATE [`]?(\w+){1}[`]?/', $sql, $matches);
$table = $matches[1];
if (strstr('.', $table) === FALSE){
$sql = str_replace($table, PG4WP_SCHEMA.'.'.$table, $sql);
}
$pattern = '/LIMIT[ ]+\d+/';
$sql = preg_replace($pattern, '', $sql);
// For correct bactick removal
$pattern = '/[ ]*`([^` ]+)`[ ]*=/';
$sql = preg_replace( $pattern, ' $1 =', $sql);
// For correct ID quoting
$pattern = '/[ ]*([^ ]*ID[^ ]*)[ ]*=/';
$sql = preg_replace( $pattern, ' "$1" =', $sql);
// This will avoid modifications to anything following ' SET '
list($sql,$end) = explode( ' SET ', $sql, 2);
$end = ' SET '.$end;
} // UPDATE
elseif( 0 === strpos($sql, 'INSERT'))
{
$logto = 'INSERT';
preg_match('/INSERT INTO [`]?(\w+){1}[`]?/', $sql, $matches);
$table = $matches[1];
if (strstr('.', $table) === FALSE){
$sql = str_replace($table, PG4WP_SCHEMA.'.'.$table, $sql);
}
$GLOBALS['pg4wp_ins_table'] = $table;
$sql = str_replace('(0,',"('0',", $sql);
$sql = str_replace('(1,',"('1',", $sql);
// Fix inserts into wp_categories
if( false !== strpos($sql, 'INSERT INTO '.$wpdb->categories))
{
$sql = str_replace('"cat_ID",', '', $sql);
$sql = str_replace("VALUES ('0',", "VALUES(", $sql);
}
// Those are used when we need to set the date to now() in gmt time
$sql = str_replace( "'0000-00-00 00:00:00'", 'now() AT TIME ZONE \'gmt\'', $sql);
// Multiple values group when calling INSERT INTO don't always work
if( false !== strpos( $sql, $wpdb->options) && false !== strpos( $sql, '), ('))
{
$pattern = '/INSERT INTO.+VALUES/';
preg_match($pattern, $sql, $matches);
$insert = $matches[0];
$sql = str_replace( '), (', ');'.$insert.'(', $sql);
}
// Support for "INSERT ... ON DUPLICATE KEY UPDATE ..." is a dirty hack
// consisting in deleting the row before inserting it
if( false !== $pos = strpos( $sql, 'ON DUPLICATE KEY'))
{
// Get the elements we need (table name, first field, corresponding value)
$pattern = '/INSERT INTO\s+([^\(]+)\(([^,]+)[^\(]+VALUES\s*\(([^,]+)/';
preg_match($pattern, $sql, $matches);
$table = trim( $matches[1], ' `');
if( !in_array(trim($matches[1],'` '), array($wpdb->posts,$wpdb->comments)))
{
// Remove 'ON DUPLICATE KEY UPDATE...' and following
$sql = substr( $sql, 0, $pos);
// Add a delete query to handle the maybe existing data
$sql = 'DELETE FROM '.$table.' WHERE '.$matches[2].' = '.$matches[3].';'.$sql;
}
}
// To avoid Encoding errors when inserting data coming from outside
if( preg_match('/^.{1}/us',$sql,$ar) != 1)
$sql = utf8_encode($sql);
// This will avoid modifications to anything following ' VALUES'
list($sql,$end) = explode( ' VALUES', $sql, 2);
$end = ' VALUES'.$end;
// When installing, the sequence for table terms has to be updated
if( defined('WP_INSTALLING') && WP_INSTALLING && false !== strpos($sql, 'INSERT INTO `'.PG4WP_SCHEMA.'.'.$wpdb->terms.'`')) {
$end .= ';SELECT setval(\''.PG4WP_SCHEMA.'.'.$wpdb->terms.'_seq\', (SELECT MAX(term_id) FROM '.PG4WP_SCHEMA.'.'.$wpdb->terms.')+1);';
}
} // DELETE
elseif( 0 === strpos( $sql, 'DELETE' ))
{
$logto = 'DELETE';
preg_match('/FROM [`]?(\w+){1}[`]?/', $sql, $matches);
$table = $matches[1];
if (FALSE === strstr('.', $table)){
$sql = str_replace($table, PG4WP_SCHEMA.'.'.$table, $sql);
$table = PG4WP_SCHEMA.'.'.$table;
}
// LIMIT is not allowed in DELETE queries
$sql = str_replace( 'LIMIT 1', '', $sql);
$sql = str_replace( ' REGEXP ', ' ~ ', $sql);
// This handles removal of duplicate entries in table options
if( false !== strpos( $sql, 'DELETE o1 FROM ')) {
$sql = "DELETE FROM $table WHERE option_id IN " .
"(SELECT o1.option_id FROM $wpdb->options AS o1, $wpdb->options AS o2 " .
"WHERE o1.option_name = o2.option_name " .
"AND o1.option_id < o2.option_id)";
}
if ( false !== strrpos( $sql, 'DELETE a, b')) {
preg_match_all('/WHERE(.*[\n]?)*/m', $sql, $matches);
$conditions = $matches[0][0];
$sql = "DELETE FROM $table WHERE option_id = ANY" .
"(SELECT unnest(ARRAY[a.option_id, b.option_id]) FROM $table a, $table b " . $conditions . ')';
$sql = preg_replace('/(option_value)(\s<\s[0-9]*)/', 'option_value::bigint$2', $sql);
}
// Akismet sometimes doesn't write 'comment_ID' with 'ID' in capitals where needed ...
if( false !== strpos( $sql, $wpdb->comments)) {
$sql = str_replace(' comment_id ', ' comment_ID ', $sql);
}
}
// Fix tables listing
elseif( 0 === strpos($sql, 'SHOW TABLES'))
{
$logto = 'SHOWTABLES';
$sql = 'SELECT tablename FROM pg_tables WHERE schemaname = \''.PG4WP_SCHEMA.'\';';
}
// Rewriting optimize table
elseif( 0 === strpos($sql, 'OPTIMIZE TABLE'))
{
$logto = 'OPTIMIZE';
preg_match('/OPTIMIZE TABLE (\w+){1}/', $sql, $matches);
$table = $matches[1];
if (strstr('.', $table) === FALSE){
$sql = str_replace($table, PG4WP_SCHEMA.'.'.$table, $sql);
}
$sql = str_replace( 'OPTIMIZE TABLE', 'VACUUM', $sql);
}
// Handle 'SET NAMES ... COLLATE ...'
elseif( 0 === strpos($sql, 'SET NAMES') && false !== strpos($sql, 'COLLATE'))
{
$logto = 'SETNAMES';
$sql = "SET NAMES 'utf8'";
}
// Load up upgrade and install functions as required
$begin = substr( $sql, 0, 3);
$search = array( 'SHO', 'ALT', 'DES', 'CRE', 'DRO');
if( in_array($begin, $search))
{
require_once( PG4WP_ROOT.'/driver_pgsql_install.php');
$sql = pg4wp_installing( $sql, $logto);
}
// WP 2.9.1 uses a comparison where text data is not quoted
$pattern = '/AND meta_value = (-?\d+)/';
$sql = preg_replace( $pattern, 'AND meta_value = \'$1\'', $sql);
// Generic "INTERVAL xx YEAR|MONTH|DAY|HOUR|MINUTE|SECOND" handler
$pattern = '/INTERVAL[ ]+(\d+)[ ]+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)/';
$sql = preg_replace( $pattern, "'\$1 \$2'::interval", $sql);
$pattern = '/DATE_SUB[ ]*\(([^,]+),([^\)]+)\)/';
$sql = preg_replace( $pattern, '($1::timestamp - $2)', $sql);
// Remove illegal characters
$sql = str_replace('`', '', $sql);
// Field names with CAPITALS need special handling
if( false !== strpos($sql, 'ID'))
{
$pattern = '/ID([^ ])/';
$sql = preg_replace($pattern, 'ID $1', $sql);
$pattern = '/ID$/';
$sql = preg_replace($pattern, 'ID ', $sql);
$pattern = '/\(ID/';
$sql = preg_replace($pattern, '( ID', $sql);
$pattern = '/,ID/';
$sql = preg_replace($pattern, ', ID', $sql);
$pattern = '/[0-9a-zA-Z_]+ID/';
$sql = preg_replace($pattern, '"$0"', $sql);
$pattern = '/\.ID/';
$sql = preg_replace($pattern, '."ID"', $sql);
$pattern = '/[\s]ID /';
$sql = preg_replace($pattern, ' "ID" ', $sql);
$pattern = '/"ID "/';
$sql = preg_replace($pattern, ' "ID" ', $sql);
} // CAPITALS
// Empty "IN" statements are erroneous
$sql = str_replace( 'IN (\'\')', 'IN (NULL)', $sql);
$sql = str_replace( 'IN ( \'\' )', 'IN (NULL)', $sql);
$sql = str_replace( 'IN ()', 'IN (NULL)', $sql);
if( in_array($logto, array('SELECT', 'UPDATE')) )
{
// Add schema to JOIN query
if (false !== strstr($sql, 'JOIN')){
preg_match_all('/JOIN\s(\w+){1}/', $sql, $matches);
foreach ($matches[1] as $join_table) {
$sql = str_replace($join_table, PG4WP_SCHEMA.'.'.$join_table, $sql);
}
}
}
// Put back the end of the query if it was separated
$sql .= $end;
// For insert ID catching
if( $logto == 'INSERT')
{
$pattern = '/INSERT INTO ([\w\.]+)\s+\([ a-zA-Z_"]+/';
//$GLOBALS['pg4wp_ins_table'] = $matches[1];
$match_list = split(' ', $matches[0]);
if( $GLOBALS['pg4wp_ins_table'])
{
$GLOBALS['pg4wp_ins_field'] = trim($match_list[3],' () ');
if(! $GLOBALS['pg4wp_ins_field']) {
$GLOBALS['pg4wp_ins_field'] = trim($match_list[4],' () ');
}
}
$GLOBALS['pg4wp_last_insert'] = $sql;
}
elseif( isset($GLOBALS['pg4wp_queued_query']))
{
pg_query($GLOBALS['pg4wp_queued_query']);
unset($GLOBALS['pg4wp_queued_query']);
}
// Correct quoting for PostgreSQL 9.1+ compatibility
$sql = str_replace( "\\'", "''", $sql);
$sql = str_replace( '\"', '"', $sql);
if( PG4WP_DEBUG)
{
if( $initial != $sql)
error_log( '['.microtime(true)."] Converting :\n$initial\n---- to ----\n$sql\n---------------------\n", 3, PG4WP_LOG.'pg4wp_'.$logto.'.log');
else
error_log( '['.microtime(true)."] $sql\n---------------------\n", 3, PG4WP_LOG.'pg4wp_unmodified.log');
}
return $sql;
}