-
Notifications
You must be signed in to change notification settings - Fork 383
/
Postgres.php
executable file
·7445 lines (6510 loc) · 222 KB
/
Postgres.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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* A Class that implements the DB Interface for Postgres
* Note: This Class uses ADODB and returns RecordSets.
*
* $Id: Postgres.php,v 1.320 2008/02/20 20:43:09 ioguix Exp $
*/
include_once('./classes/database/ADODB_base.php');
class Postgres extends ADODB_base {
var $major_version = 8.3;
// Max object name length
var $_maxNameLen = 63;
// Store the current schema
var $_schema;
// Map of database encoding names to HTTP encoding names. If a
// database encoding does not appear in this list, then its HTTP
// encoding name is the same as its database encoding name.
var $codemap = array(
'BIG5' => 'BIG5',
'EUC_CN' => 'GB2312',
'EUC_JP' => 'EUC-JP',
'EUC_KR' => 'EUC-KR',
'EUC_TW' => 'EUC-TW',
'GB18030' => 'GB18030',
'GBK' => 'GB2312',
'ISO_8859_5' => 'ISO-8859-5',
'ISO_8859_6' => 'ISO-8859-6',
'ISO_8859_7' => 'ISO-8859-7',
'ISO_8859_8' => 'ISO-8859-8',
'JOHAB' => 'CP1361',
'KOI8' => 'KOI8-R',
'LATIN1' => 'ISO-8859-1',
'LATIN2' => 'ISO-8859-2',
'LATIN3' => 'ISO-8859-3',
'LATIN4' => 'ISO-8859-4',
'LATIN5' => 'ISO-8859-9',
'LATIN6' => 'ISO-8859-10',
'LATIN7' => 'ISO-8859-13',
'LATIN8' => 'ISO-8859-14',
'LATIN9' => 'ISO-8859-15',
'LATIN10' => 'ISO-8859-16',
'SJIS' => 'SHIFT_JIS',
'SQL_ASCII' => 'US-ASCII',
'UHC' => 'WIN949',
'UTF8' => 'UTF-8',
'WIN866' => 'CP866',
'WIN874' => 'CP874',
'WIN1250' => 'CP1250',
'WIN1251' => 'CP1251',
'WIN1252' => 'CP1252',
'WIN1256' => 'CP1256',
'WIN1258' => 'CP1258'
);
var $defaultprops = array('', '', '');
// Extra "magic" types. BIGSERIAL was added in PostgreSQL 7.2.
var $extraTypes = array('SERIAL', 'BIGSERIAL');
// Foreign key stuff. First element MUST be the default.
var $fkactions = array('NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT');
var $fkdeferrable = array('NOT DEFERRABLE', 'DEFERRABLE');
var $fkinitial = array('INITIALLY IMMEDIATE', 'INITIALLY DEFERRED');
var $fkmatches = array('MATCH SIMPLE', 'MATCH FULL');
// Function properties
var $funcprops = array( array('', 'VOLATILE', 'IMMUTABLE', 'STABLE'),
array('', 'CALLED ON NULL INPUT', 'RETURNS NULL ON NULL INPUT'),
array('', 'SECURITY INVOKER', 'SECURITY DEFINER'));
// Default help URL
var $help_base;
// Help sub pages
var $help_page;
// Name of id column
var $id = 'oid';
// Supported join operations for use with view wizard
var $joinOps = array('INNER JOIN' => 'INNER JOIN', 'LEFT JOIN' => 'LEFT JOIN', 'RIGHT JOIN' => 'RIGHT JOIN', 'FULL JOIN' => 'FULL JOIN');
// Map of internal language name to syntax highlighting name
var $langmap = array(
'sql' => 'SQL',
'plpgsql' => 'SQL',
'php' => 'PHP',
'phpu' => 'PHP',
'plphp' => 'PHP',
'plphpu' => 'PHP',
'perl' => 'Perl',
'perlu' => 'Perl',
'plperl' => 'Perl',
'plperlu' => 'Perl',
'java' => 'Java',
'javau' => 'Java',
'pljava' => 'Java',
'pljavau' => 'Java',
'plj' => 'Java',
'plju' => 'Java',
'python' => 'Python',
'pythonu' => 'Python',
'plpython' => 'Python',
'plpythonu' => 'Python',
'ruby' => 'Ruby',
'rubyu' => 'Ruby',
'plruby' => 'Ruby',
'plrubyu' => 'Ruby'
);
// Predefined size types
var $predefined_size_types = array('abstime','aclitem','bigserial','boolean','bytea','cid','cidr','circle','date','float4','float8','gtsvector','inet','int2','int4','int8','macaddr','money','oid','path','polygon','refcursor','regclass','regoper','regoperator','regproc','regprocedure','regtype','reltime','serial','smgr','text','tid','tinterval','tsquery','tsvector','varbit','void','xid');
// List of all legal privileges that can be applied to different types
// of objects.
var $privlist = array(
'table' => array('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'RULE', 'REFERENCES', 'TRIGGER', 'ALL PRIVILEGES'),
'view' => array('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'RULE', 'REFERENCES', 'TRIGGER', 'ALL PRIVILEGES'),
'sequence' => array('SELECT', 'UPDATE', 'ALL PRIVILEGES'),
'database' => array('CREATE', 'TEMPORARY', 'CONNECT', 'ALL PRIVILEGES'),
'function' => array('EXECUTE', 'ALL PRIVILEGES'),
'language' => array('USAGE', 'ALL PRIVILEGES'),
'schema' => array('CREATE', 'USAGE', 'ALL PRIVILEGES'),
'tablespace' => array('CREATE', 'ALL PRIVILEGES')
);
// List of characters in acl lists and the privileges they
// refer to.
var $privmap = array(
'r' => 'SELECT',
'w' => 'UPDATE',
'a' => 'INSERT',
'd' => 'DELETE',
'R' => 'RULE',
'x' => 'REFERENCES',
't' => 'TRIGGER',
'X' => 'EXECUTE',
'U' => 'USAGE',
'C' => 'CREATE',
'T' => 'TEMPORARY',
'c' => 'CONNECT'
);
// Rule action types
var $rule_events = array('SELECT', 'INSERT', 'UPDATE', 'DELETE');
// Select operators
var $selectOps = array('=' => 'i', '!=' => 'i', '<' => 'i', '>' => 'i', '<=' => 'i', '>=' => 'i',
'<<' => 'i', '>>' => 'i', '<<=' => 'i', '>>=' => 'i',
'LIKE' => 'i', 'NOT LIKE' => 'i', 'ILIKE' => 'i', 'NOT ILIKE' => 'i', 'SIMILAR TO' => 'i',
'NOT SIMILAR TO' => 'i', '~' => 'i', '!~' => 'i', '~*' => 'i', '!~*' => 'i',
'IS NULL' => 'p', 'IS NOT NULL' => 'p', 'IN' => 'x', 'NOT IN' => 'x',
'@@' => 'i', '@@@' => 'i', '@>' => 'i', '<@' => 'i',
'@@ to_tsquery' => 't', '@@@ to_tsquery' => 't', '@> to_tsquery' => 't', '<@ to_tsquery' => 't',
'@@ plainto_tsquery' => 't', '@@@ plainto_tsquery' => 't', '@> plainto_tsquery' => 't', '<@ plainto_tsquery' => 't');
// Array of allowed trigger events
var $triggerEvents= array('INSERT', 'UPDATE', 'DELETE', 'INSERT OR UPDATE', 'INSERT OR DELETE',
'DELETE OR UPDATE', 'INSERT OR DELETE OR UPDATE');
// When to execute the trigger
var $triggerExecTimes = array('BEFORE', 'AFTER');
// How often to execute the trigger
var $triggerFrequency = array('ROW','STATEMENT');
// Array of allowed type alignments
var $typAligns = array('char', 'int2', 'int4', 'double');
// The default type alignment
var $typAlignDef = 'int4';
// Default index type
var $typIndexDef = 'BTREE';
// Array of allowed index types
var $typIndexes = array('BTREE', 'RTREE', 'GIST', 'GIN', 'HASH');
// Array of allowed type storage attributes
var $typStorages = array('plain', 'external', 'extended', 'main');
// The default type storage
var $typStorageDef = 'plain';
/**
* Constructor
* @param $conn The database connection
*/
function Postgres($conn) {
$this->ADODB_base($conn);
}
// Formatting functions
/**
* Cleans (escapes) a string
* @param $str The string to clean, by reference
* @return The cleaned string
*/
function clean(&$str) {
if ($str === null) return null;
$str = str_replace("\r\n","\n",$str);
if (function_exists('pg_escape_string'))
$str = pg_escape_string($str);
else
$str = addslashes($str);
return $str;
}
/**
* Cleans (escapes) an object name (eg. table, field)
* @param $str The string to clean, by reference
* @return The cleaned string
*/
function fieldClean(&$str) {
if ($str === null) return null;
$str = str_replace('"', '""', $str);
return $str;
}
/**
* Cleans (escapes) an array of field names
* @param $arr The array to clean, by reference
* @return The cleaned array
*/
function fieldArrayClean(&$arr) {
foreach ($arr as $k => $v) {
if ($v === null) continue;
$arr[$k] = str_replace('"', '""', $v);
}
return $arr;
}
/**
* Cleans (escapes) an array
* @param $arr The array to clean, by reference
* @return The cleaned array
*/
function arrayClean(&$arr) {
foreach ($arr as $k => $v) {
if ($v === null) continue;
if (function_exists('pg_escape_string'))
$arr[$k] = pg_escape_string($v);
else
$arr[$k] = addslashes($v);
}
return $arr;
}
/**
* Escapes bytea data for display on the screen
* @param $data The bytea data
* @return Data formatted for on-screen display
*/
function escapeBytea($data) {
if (function_exists('pg_escape_bytea'))
return stripslashes(pg_escape_bytea($data));
else {
$translations = array('\\a' => '\\007', '\\b' => '\\010', '\\t' => '\\011', '\\n' => '\\012', '\\v' => '\\013', '\\f' => '\\014', '\\r' => '\\015');
return strtr(addCSlashes($data, "\0..\37\177..\377"), $translations);
}
}
/**
* Outputs the HTML code for a particular field
* @param $name The name to give the field
* @param $value The value of the field. Note this could be 'numeric(7,2)' sort of thing...
* @param $type The database type of the field
* @param $actions An array of javascript action name to the code to execute on that action
*/
function printField($name, $value, $type, $actions = array(),$szExtra="") {
global $lang;
// Determine actions string
$action_str = '';
foreach ($actions as $k => $v) {
$action_str .= " {$k}=\"" . htmlspecialchars($v) . "\"";
}
switch (substr($type,0,9)) {
case 'bool':
case 'boolean':
if ($value !== null && $value == '') $value = null;
elseif ($value == 'true') $value = 't';
elseif ($value == 'false') $value = 'f';
// If value is null, 't' or 'f'...
if ($value === null || $value == 't' || $value == 'f') {
echo "<select name=\"", htmlspecialchars($name), "\"{$action_str}>\n";
echo "<option value=\"\"", ($value === null) ? ' selected="selected"' : '', "></option>\n";
echo "<option value=\"t\"", ($value == 't') ? ' selected="selected"' : '', ">{$lang['strtrue']}</option>\n";
echo "<option value=\"f\"", ($value == 'f') ? ' selected="selected"' : '', ">{$lang['strfalse']}</option>\n";
echo "</select>\n";
}
else {
echo "<input name=\"", htmlspecialchars($name), "\" value=\"", htmlspecialchars($value), "\" size=\"35\"{$action_str} {$szExtra} />\n";
}
break;
case 'bytea':
case 'bytea[]':
$value = $this->escapeBytea($value);
case 'text':
case 'text[]':
case 'xml':
case 'xml[]':
$n = substr_count($value, "\n");
$n = $n < 5 ? 5 : $n;
$n = $n > 20 ? 20 : $n;
echo "<textarea name=\"", htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"75\"{$action_str}>\n";
echo htmlspecialchars($value);
echo "</textarea>\n";
break;
case 'character':
case 'character[]':
$n = substr_count($value, "\n");
$n = $n < 5 ? 5 : $n;
$n = $n > 20 ? 20 : $n;
echo "<textarea name=\"", htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"35\"{$action_str}>\n";
echo htmlspecialchars($value);
echo "</textarea>\n";
break;
default:
echo "<input name=\"", htmlspecialchars($name), "\" value=\"", htmlspecialchars($value), "\" size=\"35\"{$action_str} {$szExtra} />\n";
break;
}
}
/**
* Formats a value or expression for sql purposes
* @param $type The type of the field
* @param $format VALUE or EXPRESSION
* @param $value The actual value entered in the field. Can be NULL
* @return The suitably quoted and escaped value.
*/
function formatValue($type, $format, $value) {
switch ($type) {
case 'bool':
case 'boolean':
if ($value == 't')
return 'TRUE';
elseif ($value == 'f')
return 'FALSE';
elseif ($value == '')
return 'NULL';
else
return $value;
break;
default:
// Checking variable fields is difficult as there might be a size
// attribute...
if (strpos($type, 'time') === 0) {
// Assume it's one of the time types...
if ($value == '') return "''";
elseif (strcasecmp($value, 'CURRENT_TIMESTAMP') == 0
|| strcasecmp($value, 'CURRENT_TIME') == 0
|| strcasecmp($value, 'CURRENT_DATE') == 0
|| strcasecmp($value, 'LOCALTIME') == 0
|| strcasecmp($value, 'LOCALTIMESTAMP') == 0) {
return $value;
}
elseif ($format == 'EXPRESSION')
return $value;
else {
$this->clean($value);
return "'{$value}'";
}
}
else {
if ($format == 'VALUE') {
$this->clean($value);
return "'{$value}'";
}
return $value;
}
}
}
/**
* Formats a type correctly for display. Postgres 7.0 had no 'format_type'
* built-in function, and hence we need to do it manually.
* @param $typname The name of the type
* @param $typmod The contents of the typmod field
*/
function formatType($typname, $typmod) {
// This is a specific constant in the 7.0 source
$varhdrsz = 4;
// If the first character is an underscore, it's an array type
$is_array = false;
if (substr($typname, 0, 1) == '_') {
$is_array = true;
$typname = substr($typname, 1);
}
// Show lengths on bpchar and varchar
if ($typname == 'bpchar') {
$len = $typmod - $varhdrsz;
$temp = 'character';
if ($len > 1)
$temp .= "({$len})";
}
elseif ($typname == 'varchar') {
$temp = 'character varying';
if ($typmod != -1)
$temp .= "(" . ($typmod - $varhdrsz) . ")";
}
elseif ($typname == 'numeric') {
$temp = 'numeric';
if ($typmod != -1) {
$tmp_typmod = $typmod - $varhdrsz;
$precision = ($tmp_typmod >> 16) & 0xffff;
$scale = $tmp_typmod & 0xffff;
$temp .= "({$precision}, {$scale})";
}
}
else $temp = $typname;
// Add array qualifier if it's an array
if ($is_array) $temp .= '[]';
return $temp;
}
// Help functions
/**
* Fetch a URL (or array of URLs) for a given help page.
*/
function getHelp($help) {
$this->getHelpPages();
if (isset($this->help_page[$help])) {
if (is_array($this->help_page[$help])) {
$urls = array();
foreach ($this->help_page[$help] as $link) {
$urls[] = $this->help_base . $link;
}
return $urls;
} else
return $this->help_base . $this->help_page[$help];
} else
return null;
}
function getHelpPages() {
include_once('./help/PostgresDoc83.php');
return $this->help_page;
}
// Database functions
/**
* Return all information about a particular database
* @param $database The name of the database to retrieve
* @return The database info
*/
function getDatabase($database) {
$this->clean($database);
$sql = "SELECT * FROM pg_database WHERE datname='{$database}'";
return $this->selectSet($sql);
}
/**
* Return all database available on the server
* @return A list of databases, sorted alphabetically
*/
function getDatabases($currentdatabase = NULL) {
global $conf, $misc;
$server_info = $misc->getServerInfo();
if (isset($conf['owned_only']) && $conf['owned_only'] && !$this->isSuperUser($server_info['username'])) {
$username = $server_info['username'];
$this->clean($username);
$clause = " AND pr.rolname='{$username}'";
}
else $clause = '';
if ($currentdatabase != NULL)
$orderby = "ORDER BY pdb.datname = '{$currentdatabase}' DESC, pdb.datname";
else
$orderby = "ORDER BY pdb.datname";
if (!$conf['show_system'])
$where = ' AND NOT pdb.datistemplate';
else
$where = ' AND pdb.datallowconn';
$sql = "SELECT pdb.datname AS datname, pr.rolname AS datowner, pg_encoding_to_char(encoding) AS datencoding,
(SELECT description FROM pg_catalog.pg_shdescription pd WHERE pdb.oid=pd.objoid) AS datcomment,
(SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=pdb.dattablespace) AS tablespace,
pg_catalog.pg_database_size(pdb.oid) as dbsize
FROM pg_catalog.pg_database pdb LEFT JOIN pg_catalog.pg_roles pr ON (pdb.datdba = pr.oid)
WHERE true
{$where}
{$clause}
{$orderby}";
return $this->selectSet($sql);
}
/**
* Return the database comment of a db from the shared description table
* @param string $database the name of the database to get the comment for
* @return recordset of the db comment info
*/
function getDatabaseComment($database) {
$this->clean($database);
$sql = "SELECT description FROM pg_catalog.pg_database JOIN pg_catalog.pg_shdescription ON (oid=objoid) WHERE pg_database.datname = '{$database}' ";
return $this->selectSet($sql);
}
/**
* Return the database owner of a db
* @param string $database the name of the database to get the owner for
* @return recordset of the db owner info
*/
function getDatabaseOwner($database) {
$this->clean($database);
$sql = "SELECT usename FROM pg_user, pg_database WHERE pg_user.usesysid = pg_database.datdba AND pg_database.datname = '{$database}' ";
return $this->selectSet($sql);
}
/**
* Returns the current database encoding
* @return The encoding. eg. SQL_ASCII, UTF-8, etc.
*/
function getDatabaseEncoding() {
// Try to avoid a query if at all possible (5)
if (function_exists('pg_parameter_status')) {
$encoding = pg_parameter_status($this->conn->_connectionID, 'server_encoding');
if ($encoding !== false) return $encoding;
}
$sql = "SELECT getdatabaseencoding() AS encoding";
return $this->selectField($sql, 'encoding');
}
/**
* Returns the current default_with_oids setting
* @return default_with_oids setting
*/
function getDefaultWithOid() {
// Try to avoid a query if at all possible (5)
if (function_exists('pg_parameter_status')) {
$default = pg_parameter_status($this->conn->_connectionID, 'default_with_oids');
if ($default !== false) return $default;
}
$sql = "SHOW default_with_oids";
return $this->selectField($sql, 'default_with_oids');
}
/**
* Creates a database
* @param $database The name of the database to create
* @param $encoding Encoding of the database
* @param $tablespace (optional) The tablespace name
* @return 0 success
* @return -1 tablespace error
* @return -2 comment error
*/
function createDatabase($database, $encoding, $tablespace = '', $comment = '') {
$this->fieldClean($database);
$this->clean($encoding);
$this->fieldClean($tablespace);
$this->fieldClean($comment);
if ($encoding == '') {
$sql = "CREATE DATABASE \"{$database}\"";
} else {
$sql = "CREATE DATABASE \"{$database}\" WITH ENCODING='{$encoding}'";
}
if ($tablespace != '' && $this->hasTablespaces()) $sql .= " TABLESPACE \"{$tablespace}\"";
$status = $this->execute($sql);
if ($status != 0) return -1;
if ($comment != '' && $this->hasSharedComments()) {
$status = $this->setComment('DATABASE',$database,'',$comment);
if ($status != 0) return -2;
}
return 0;
}
/**
* Renames a database, note that this operation cannot be
* performed on a database that is currently being connected to
* @param string $oldName name of database to rename
* @param string $newName new name of database
* @return int 0 on success
*/
function alterDatabaseRename($oldName, $newName) {
$this->clean($oldName);
$this->clean($newName);
if ($oldName != $newName) {
$sql = "ALTER DATABASE \"{$oldName}\" RENAME TO \"{$newName}\"";
return $this->execute($sql);
}
else //just return success, we're not going to do anything
return 0;
}
/**
* Drops a database
* @param $database The name of the database to drop
* @return 0 success
*/
function dropDatabase($database) {
$this->fieldClean($database);
$sql = "DROP DATABASE \"{$database}\"";
return $this->execute($sql);
}
/**
* Changes ownership of a database
* This can only be done by a superuser or the owner of the database
* @param string $dbName database to change ownership of
* @param string $newOwner user that will own the database
* @return int 0 on success
*/
function alterDatabaseOwner($dbName, $newOwner) {
$this->clean($dbName);
$this->clean($newOwner);
$sql = "ALTER DATABASE \"{$dbName}\" OWNER TO \"{$newOwner}\"";
return $this->execute($sql);
}
/**
* Alters a database
* the multiple return vals are for postgres 8+ which support more functionality in alter database
* @param $dbName The name of the database
* @param $newName new name for the database
* @param $newOwner The new owner for the database
* @return 0 success
* @return -1 transaction error
* @return -2 owner error
* @return -3 rename error
* @return -4 comment error
*/
function alterDatabase($dbName, $newName, $newOwner = '', $comment = '') {
$this->clean($dbName);
$this->clean($newName);
$this->clean($newOwner);
$this->clean($comment);
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
if ($dbName != $newName) {
$status = $this->alterDatabaseRename($dbName, $newName);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
}
$status = $this->alterDatabaseOwner($newName, $newOwner);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
if (trim($comment) != '' ) {
$status = $this->setComment('DATABASE', $dbName, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
}
return $this->endTransaction();
}
/**
* Returns prepared transactions information
* @param $database (optional) Find only prepared transactions executed in a specific database
* @return A recordset
*/
function getPreparedXacts($database = null) {
if ($database === null)
$sql = "SELECT * FROM pg_prepared_xacts";
else {
$this->clean($database);
$sql = "SELECT transaction, gid, prepared, owner FROM pg_prepared_xacts
WHERE database='{$database}' ORDER BY owner";
}
return $this->selectSet($sql);
}
/**
* Searches all system catalogs to find objects that match a certain name.
* @param $term The search term
* @param $filter The object type to restrict to ('' means no restriction)
* @return A recordset
*/
function findObject($term, $filter) {
global $conf;
// Escape search term for ILIKE match
$term = str_replace('_', '\\_', $term);
$term = str_replace('%', '\\%', $term);
$this->clean($term);
$this->clean($filter);
// Exclude system relations if necessary
if (!$conf['show_system']) {
// XXX: The mention of information_schema here is in the wrong place, but
// it's the quickest fix to exclude the info schema from 7.4
$where = " AND pn.nspname NOT LIKE 'pg\\\\_%' AND pn.nspname != 'information_schema'";
$lan_where = "AND pl.lanispl";
}
else {
$where = '';
$lan_where = '';
}
// Apply outer filter
$sql = '';
if ($filter != '') {
$sql = "SELECT * FROM (";
}
$sql .= "
SELECT 'SCHEMA' AS type, oid, NULL AS schemaname, NULL AS relname, nspname AS name
FROM pg_catalog.pg_namespace pn WHERE nspname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT CASE WHEN relkind='r' THEN 'TABLE' WHEN relkind='v' THEN 'VIEW' WHEN relkind='S' THEN 'SEQUENCE' END, pc.oid,
pn.nspname, NULL, pc.relname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn
WHERE pc.relnamespace=pn.oid AND relkind IN ('r', 'v', 'S') AND relname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT CASE WHEN pc.relkind='r' THEN 'COLUMNTABLE' ELSE 'COLUMNVIEW' END, NULL, pn.nspname, pc.relname, pa.attname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_attribute pa WHERE pc.relnamespace=pn.oid AND pc.oid=pa.attrelid
AND pa.attname ILIKE '%{$term}%' AND pa.attnum > 0 AND NOT pa.attisdropped AND pc.relkind IN ('r', 'v') {$where}
UNION ALL
SELECT 'FUNCTION', pp.oid, pn.nspname, NULL, pp.proname || '(' || pg_catalog.oidvectortypes(pp.proargtypes) || ')' FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pn
WHERE pp.pronamespace=pn.oid AND NOT pp.proisagg AND pp.proname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'INDEX', NULL, pn.nspname, pc.relname, pc2.relname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_index pi, pg_catalog.pg_class pc2 WHERE pc.relnamespace=pn.oid AND pc.oid=pi.indrelid
AND pi.indexrelid=pc2.oid
AND NOT EXISTS (
SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pc2.tableoid AND d.objid = pc2.oid AND d.deptype = 'i' AND c.contype IN ('u', 'p')
)
AND pc2.relname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'CONSTRAINTTABLE', NULL, pn.nspname, pc.relname, pc2.conname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_constraint pc2 WHERE pc.relnamespace=pn.oid AND pc.oid=pc2.conrelid AND pc2.conrelid != 0
AND CASE WHEN pc2.contype IN ('f', 'c') THEN TRUE ELSE NOT EXISTS (
SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pc2.tableoid AND d.objid = pc2.oid AND d.deptype = 'i' AND c.contype IN ('u', 'p')
) END
AND pc2.conname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'CONSTRAINTDOMAIN', pt.oid, pn.nspname, pt.typname, pc.conname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn,
pg_catalog.pg_constraint pc WHERE pt.typnamespace=pn.oid AND pt.oid=pc.contypid AND pc.contypid != 0
AND pc.conname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'TRIGGER', NULL, pn.nspname, pc.relname, pt.tgname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_trigger pt WHERE pc.relnamespace=pn.oid AND pc.oid=pt.tgrelid
AND (NOT pt.tgisconstraint OR NOT EXISTS
(SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pt.tableoid AND d.objid = pt.oid AND d.deptype = 'i' AND c.contype = 'f'))
AND pt.tgname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'RULETABLE', NULL, pn.nspname AS schemaname, c.relname AS tablename, r.rulename FROM pg_catalog.pg_rewrite r
JOIN pg_catalog.pg_class c ON c.oid = r.ev_class
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = c.relnamespace
WHERE c.relkind='r' AND r.rulename != '_RETURN' AND r.rulename ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'RULEVIEW', NULL, pn.nspname AS schemaname, c.relname AS tablename, r.rulename FROM pg_catalog.pg_rewrite r
JOIN pg_catalog.pg_class c ON c.oid = r.ev_class
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = c.relnamespace
WHERE c.relkind='v' AND r.rulename != '_RETURN' AND r.rulename ILIKE '%{$term}%' {$where}
";
// Add advanced objects if show_advanced is set
if ($conf['show_advanced']) {
$sql .= "
UNION ALL
SELECT CASE WHEN pt.typtype='d' THEN 'DOMAIN' ELSE 'TYPE' END, pt.oid, pn.nspname, NULL,
pt.typname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn
WHERE pt.typnamespace=pn.oid AND typname ILIKE '%{$term}%'
AND (pt.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = pt.typrelid))
{$where}
UNION ALL
SELECT 'OPERATOR', po.oid, pn.nspname, NULL, po.oprname FROM pg_catalog.pg_operator po, pg_catalog.pg_namespace pn
WHERE po.oprnamespace=pn.oid AND oprname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'CONVERSION', pc.oid, pn.nspname, NULL, pc.conname FROM pg_catalog.pg_conversion pc,
pg_catalog.pg_namespace pn WHERE pc.connamespace=pn.oid AND conname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT 'LANGUAGE', pl.oid, NULL, NULL, pl.lanname FROM pg_catalog.pg_language pl
WHERE lanname ILIKE '%{$term}%' {$lan_where}
UNION ALL
SELECT DISTINCT ON (p.proname) 'AGGREGATE', p.oid, pn.nspname, NULL, p.proname FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace pn ON p.pronamespace=pn.oid
WHERE p.proisagg AND p.proname ILIKE '%{$term}%' {$where}
UNION ALL
SELECT DISTINCT ON (po.opcname) 'OPCLASS', po.oid, pn.nspname, NULL, po.opcname FROM pg_catalog.pg_opclass po,
pg_catalog.pg_namespace pn WHERE po.opcnamespace=pn.oid
AND po.opcname ILIKE '%{$term}%' {$where}
";
}
// Otherwise just add domains
else {
$sql .= "
UNION ALL
SELECT 'DOMAIN', pt.oid, pn.nspname, NULL,
pt.typname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn
WHERE pt.typnamespace=pn.oid AND pt.typtype='d' AND typname ILIKE '%{$term}%'
AND (pt.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = pt.typrelid))
{$where}
";
}
if ($filter != '') {
// We use like to make RULE, CONSTRAINT and COLUMN searches work
$sql .= ") AS sub WHERE type LIKE '{$filter}%' ";
}
$sql .= "ORDER BY type, schemaname, relname, name";
return $this->selectSet($sql);
}
/**
* Returns the specified variable information.
* @return the field
*/
function getVariable($setting) {
$sql = "SHOW $setting";
return $this->selectSet($sql);
}
/**
* Returns all available variable information.
* @return A recordset
*/
function getVariables() {
$sql = "SHOW ALL";
return $this->selectSet($sql);
}
// Schema functons
/**
* Return all schemas in the current database. This differs from the version
* in 7.3 only in that it considers the information_schema to be a system schema.
* @return All schemas, sorted alphabetically
*/
function getSchemas() {
global $conf, $slony;
if (!$conf['show_system']) {
$where = "WHERE nspname NOT LIKE 'pg@_%' ESCAPE '@' AND nspname != 'information_schema'";
if (isset($slony) && $slony->isEnabled()) {
$temp = $slony->slony_schema;
$this->clean($temp);
$where .= " AND nspname != '{$temp}'";
}
}
else $where = "WHERE nspname !~ '^pg_t(emp_[0-9]+|oast)$'";
$sql = "
SELECT pn.nspname, pu.usename AS nspowner,
pg_catalog.obj_description(pn.oid, 'pg_namespace') AS nspcomment
FROM pg_catalog.pg_namespace pn
LEFT JOIN pg_catalog.pg_user pu ON (pn.nspowner = pu.usesysid)
{$where}
ORDER BY nspname";
return $this->selectSet($sql);
}
/**
* Return all information relating to a schema
* @param $schema The name of the schema
* @return Schema information
*/
function getSchemaByName($schema) {
$this->clean($schema);
$sql = "
SELECT nspname, nspowner, r.rolname AS ownername, nspacl,
pg_catalog.obj_description(pn.oid, 'pg_namespace') as nspcomment
FROM pg_catalog.pg_namespace pn
LEFT JOIN pg_authid as r ON pn.nspowner = r.oid
WHERE nspname='{$schema}'";
return $this->selectSet($sql);
}
/**
* Sets the current working schema. Will also set Class variable.
* @param $schema The the name of the schema to work in
* @return 0 success
*/
function setSchema($schema) {
// Get the current schema search path, including 'pg_catalog'.
$search_path = $this->getSearchPath();
// Prepend $schema to search path
array_unshift($search_path, $schema);
$status = $this->setSearchPath($search_path);
if ($status == 0) {
$this->clean($schema);
$this->_schema = $schema;
return 0;
}
else return $status;
}
/**
* Sets the current schema search path
* @param $paths An array of schemas in required search order
* @return 0 success
* @return -1 Array not passed
* @return -2 Array must contain at least one item
*/
function setSearchPath($paths) {
if (!is_array($paths)) return -1;
elseif (sizeof($paths) == 0) return -2;
elseif (sizeof($paths) == 1 && $paths[0] == '') {
// Need to handle empty paths in some cases
$paths[0] = 'pg_catalog';
}
// Loop over all the paths to check that none are empty
$temp = array();
foreach ($paths as $schema) {
if ($schema != '') $temp[] = $schema;
}
$this->fieldArrayClean($temp);
$sql = 'SET SEARCH_PATH TO "' . implode('","', $temp) . '"';
return $this->execute($sql);
}
/**
* Creates a new schema.
* @param $schemaname The name of the schema to create
* @param $authorization (optional) The username to create the schema for.
* @param $comment (optional) If omitted, defaults to nothing
* @return 0 success
*/
function createSchema($schemaname, $authorization = '', $comment = '') {
$this->fieldClean($schemaname);
$this->fieldClean($authorization);
$this->clean($comment);
$sql = "CREATE SCHEMA \"{$schemaname}\"";
if ($authorization != '') $sql .= " AUTHORIZATION \"{$authorization}\"";
if ($comment != '') {
$status = $this->beginTransaction();
if ($status != 0) return -1;
}
// Create the new schema
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set the comment
if ($comment != '') {
$status = $this->setComment('SCHEMA', $schemaname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return $this->endTransaction();
}
return 0;
}
/**
* Updates a schema.
* @param $schemaname The name of the schema to drop
* @param $comment The new comment for this schema
* @param $owner The new owner for this schema
* @return 0 success
*/
function updateSchema($schemaname, $comment, $name, $owner) {
$this->fieldClean($schemaname);
$this->fieldClean($name);
$this->fieldClean($owner);
$this->clean($comment);
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->setComment('SCHEMA', $schemaname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$schema_rs = $this->getSchemaByName($schemaname);