/
PostgreSQLDatabase.php
2210 lines (1844 loc) · 70.5 KB
/
PostgreSQLDatabase.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
/**
* @package sapphire
* @subpackage model
*/
/**
* PostgreSQL connector class.
* @package sapphire
* @subpackage model
*/
class PostgreSQLDatabase extends SS_Database {
/**
* Connection to the DBMS.
* @var resource
*/
private $dbConn;
/**
* True if we are connected to a database.
* @var boolean
*/
private $active;
/**
* The name of the database.
* @var string
*/
private $database;
/*
* This holds the name of the original database
* So if you switch to another for unit tests, you
* can then switch back in order to drop the temp database
*/
private $database_original;
/**
* The database schema name.
* @var string
*/
private $schema;
/*
* This holds the parameters that the original connection was created with,
* so we can switch back to it if necessary (used for unit tests)
*/
private $parameters;
/*
* These two values describe how T-search will work.
* You can use either GiST or GIN, and '@@' (gist) or '@@@' (gin)
* Combinations of these two will also work, so you'll need to pick
* one which works best for you
*/
public $default_fts_cluster_method='GIN';
public $default_fts_search_method='@@@';
private $supportsTransactions=true;
/**
* Determines whether to check a database exists on the host by
* querying the 'postgres' database and running createDatabase.
*
* Some locked down systems prevent access to the 'postgres' table in
* which case you need to set this to false.
*/
public static $check_database_exists = true;
/**
* This holds a copy of all the constraint results that are returned
* via the function constraintExists(). This is a bit faster than
* repeatedly querying this column, and should allow the database
* to use it's built-in caching features for better queries.
*
* @var array
*/
private static $cached_constraints=array();
/**
*
* This holds a copy of all the queries that run through the function orderMoreSpecifically()
* It appears to be a performance bottleneck at times.
*
* @var array
*/
private static $cached_ordered_specifically=array();
/**
*
* This holds a copy of all the queries that run through the function fieldList()
* This is one of the most-often called functions, and repeats itself a great deal in the unit tests.
*
* @var array
*/
private static $cached_fieldlists=array();
/**
* Override the language that tsearch uses. By default it is 'english, but
* could be any of the supported languages that can be found in the
* pg_catalog.pg_ts_config table.
*
* @var string
*/
private $search_language='english';
/**
* Connect to a PostgreSQL database.
* @param array $parameters An map of parameters, which should include:
* - server: The server, eg, localhost
* - username: The username to log on with
* - password: The password to log on with
* - database: The database to connect to
*/
public function __construct($parameters) {
//We will store these connection parameters for use elsewhere (ie, unit tests)
$this->parameters=$parameters;
$this->connectDatabase();
$this->database_original=$this->database;
}
/*
* Uses whatever connection details are in the $parameters array to connect to a database of a given name
*/
function connectDatabase(){
$parameters=$this->parameters;
if(!$parameters)
return false;
($parameters['username']!='') ? $username=' user=' . $parameters['username'] : $username='';
($parameters['password']!='') ? $password=' password=' . $parameters['password'] : $password='';
if(!isset($this->database))
$dbName=$parameters['database'];
else $dbName=$this->database;
$port = empty($parameters['port']) ? 5432 : $parameters['port'];
// First, we need to check that this database exists. To do this, we will connect to the 'postgres' database first
// some setups prevent access to this database so set PostgreSQLDatabase::$check_database_exists = false
if(self::$check_database_exists) {
$this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=postgres' . $username . $password);
if(!$this->databaseExists($dbName))
$this->createDatabase($dbName);
}
//Now we can be sure that this database exists, so we can connect to it
$this->dbConn = pg_connect('host=' . $parameters['server'] . ' port=' . $port . ' dbname=' . $dbName . $username . $password);
//By virtue of getting here, the connection is active:
$this->active=true;
$this->database = $dbName;
if(!$this->dbConn) {
$this->databaseError("Couldn't connect to PostgreSQL database");
return false;
}
// Set up the schema if required
$schema = isset($parameters['schema']) ? $parameters['schema'] : $this->currentSchema();
// Edge-case - database with no schemas:
if(!$schema) $schema = "public";
if(!$this->schemaExists($schema))
$this->createSchema($schema);
$this->setSchema($schema);
// Set the timezone if required.
if(isset($parameters['timezone'])) $this->query(sprintf("SET SESSION TIME ZONE '%s'", $parameters['timezone']));
return true;
}
/**
* Not implemented, needed for PDO
*/
public function getConnect($parameters) {
return null;
}
/**
* Return the parameters used to construct this database connection
*/
public function getParameters() {
return $this->parameters;
}
/**
* Returns true if this database supports collations
* TODO: get rid of this?
* @return boolean
*/
public function supportsCollations() {
return true;
}
public function supportsTimezoneOverride() {
return true;
}
/**
* Get the version of PostgreSQL.
* @return string
*/
public function getVersion() {
$version = pg_version($this->dbConn);
if(isset($version['server'])) return $version['server'];
else return false;
}
/**
* Get the database server, namely PostgreSQL.
* @return string
*/
public function getDatabaseServer() {
return "postgresql";
}
public function query($sql, $errorLevel = E_USER_ERROR) {
if(isset($_REQUEST['previewwrite']) && in_array(strtolower(substr($sql,0,strpos($sql,' '))), array('insert','update','delete','replace'))) {
Debug::message("Will execute: $sql");
return;
}
if(isset($_REQUEST['showqueries'])) {
$starttime = microtime(true);
}
$handle = pg_query($this->dbConn, $sql);
if(isset($_REQUEST['showqueries'])) {
$endtime = round((microtime(true) - $starttime) * 1000, 1);
Debug::message("\n$sql\n{$endtime}ms\n", false);
}
DB::$lastQuery=$handle;
if(!$handle && $errorLevel) $this->databaseError("Couldn't run query: $sql | " . pg_last_error($this->dbConn), $errorLevel);
return new PostgreSQLQuery($this, $handle);
}
public function getGeneratedID($table) {
$result=DB::query("SELECT last_value FROM \"{$table}_ID_seq\";");
$row=$result->first();
return $row['last_value'];
}
/**
* OBSOLETE: Get the ID for the next new record for the table.
*
* @var string $table The name od the table.
* @return int
*/
public function getNextID($table) {
user_error('getNextID is OBSOLETE (and will no longer work properly)', E_USER_WARNING);
$result = $this->query("SELECT MAX(ID)+1 FROM \"$table\"")->value();
return $result ? $result : 1;
}
public function isActive() {
return $this->active ? true : false;
}
/*
* You can create a database based either on a supplied name, or from whatever is in the $this->database value
*/
public function createDatabase($name=false) {
if(!$name)
$name=$this->database;
$this->query("CREATE DATABASE \"$name\";");
$this->connectDatabase();
}
/**
* Drop the database that this object is currently connected to.
* Use with caution.
*/
public function dropDatabase() {
//First, we need to switch back to the original database so we can drop the current one
$db_to_drop=$this->database;
$this->selectDatabase($this->database_original);
$this->connectDatabase();
$this->query("DROP DATABASE \"$db_to_drop\"");
}
/**
* Drop the database that this object is currently connected to.
* Use with caution.
*/
public function dropDatabaseByName($dbName) {
if($dbName!=$this->database)
$this->query("DROP DATABASE \"$dbName\";");
}
/**
* Returns the name of the currently selected database
*/
public function currentDatabase() {
return $this->database;
}
/**
* Switches to the given database.
* If the database doesn't exist, you should call createDatabase() after calling selectDatabase()
*/
public function selectDatabase($dbname) {
$this->database=$dbname;
$this->tableList = $this->fieldList = $this->indexList = null;
return true;
}
/**
* Returns true if the named database exists.
*/
public function databaseExists($name) {
// We have to use addslashes here, since there may not be a database connection to base the Convert::raw2sql
// function off.
$SQL_name=addslashes($name);
return $this->query("SELECT datname FROM pg_database WHERE datname='$SQL_name';")->first() ? true : false;
}
/**
* Returns a column
*/
public function allDatabaseNames() {
return $this->query("SELECT datname FROM pg_database WHERE datistemplate=false;")->column();
}
/**
* Returns true if the schema exists in the current database
* @param string $name
* @return boolean
*/
public function schemaExists($name) {
$SQL_name = pg_escape_string($this->dbConn, $name);
return $this->query("SELECT nspname FROM pg_catalog.pg_namespace WHERE nspname = '{$SQL_name}';")->first() ? true : false;
}
/**
* Creates a schema in the current database
* @param string $name
*/
public function createSchema($name) {
$SQL_name = pg_escape_string($this->dbConn, $name);
$this->query("CREATE SCHEMA \"{$SQL_name}\";");
}
/**
* Drops a schema from the database. Use carefully!
* @param string $name
*/
public function dropSchema($name) {
$SQL_name = pg_escape_string($this->dbConn, $name);
$this->query("DROP SCHEMA \"{$SQL_name}\" CASCADE;");
}
/**
* Returns the name of the current schema in use
*/
public function currentSchema() {
return $this->query('SELECT current_schema()')->value();
}
/**
* Utility method to manually set the schema to an alternative
* Check existance & sets search path to the supplied schema name
* @param string $schema
*/
public function setSchema($schema) {
if(!$this->schemaExists($schema))
$this->databaseError("Schema $schema does not exist");
$this->setSchemaSearchPath($schema);
$this->schema = $schema;
}
/**
* Override the schema search path. Search using the arguments supplied.
* NOTE: The search path is normally set through setSchema() and only
* one schema is selected. The facility to add more than one schema to
* the search path is provided as an advanced PostgreSQL feature for raw
* SQL queries. Sapphire cannot search for datamodel tables in alternate
* schemas, so be wary of using alternate schemas within the ORM environment.
* @param string $arg1 First schema to use
* @param string $arg2 Second schema to use
* @param string $argN Nth schema to use
*/
public function setSchemaSearchPath() {
if(func_num_args() == 0)
$this->databaseError('At least one Schema must be supplied to set a search path.');
$args = array_values(func_get_args());
foreach($args as $key => $schema)
$args[$key] = '"' . pg_escape_string($this->dbConn, $schema) . '"';
$args_SQL =implode(",", $args);
$this->query("SET search_path TO {$args_SQL}");
}
public function createTable($tableName, $fields = null, $indexes = null, $options = null, $extensions = null) {
$fieldSchemas = $indexSchemas = "";
if($fields) foreach($fields as $k => $v) $fieldSchemas .= "\"$k\" $v,\n";
if(isset($this->class)){
$addOptions = (isset($options[$this->class])) ? $options[$this->class] : null;
} else $addOptions=null;
//First of all, does this table already exist
$doesExist=$this->TableExists($tableName);
if($doesExist) {
// Table already exists, just return the name, in line with baseclass documentation.
return $tableName;
}
//If we have a fulltext search request, then we need to create a special column
//for GiST searches
$fulltexts='';
$triggers='';
if($indexes){
foreach($indexes as $name=>$this_index){
if(is_array($this_index) && $this_index['type']=='fulltext'){
$ts_details=$this->fulltext($this_index, $tableName, $name);
$fulltexts.=$ts_details['fulltexts'] . ', ';
$triggers.=$ts_details['triggers'];
}
}
}
if($indexes) foreach($indexes as $k => $v) $indexSchemas .= $this->getIndexSqlDefinition($tableName, $k, $v) . "\n";
//Do we need to create a tablespace for this item?
if($extensions && isset($extensions['tablespace'])){
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
$tableSpace=' TABLESPACE ' . $extensions['tablespace']['name'];
} else
$tableSpace='';
$this->query("CREATE TABLE \"$tableName\" (
$fieldSchemas
$fulltexts
primary key (\"ID\")
)$tableSpace; $indexSchemas $addOptions");
if($triggers!=''){
$this->query($triggers);
}
//If we have a partitioning requirement, we do that here:
if($extensions && isset($extensions['partitions'])){
$this->createOrReplacePartition($tableName, $extensions['partitions'], $indexes, $extensions);
}
//Lastly, clustering goes here:
if($extensions && isset($extensions['cluster'])){
DB::query("CLUSTER \"$tableName\" USING \"{$extensions['cluster']}\";");
}
return $tableName;
}
/**
* Builds the internal Postgres index name given the silverstripe table and index name
* @param string $tableName
* @param string $indexName
* @param string $prefix The optional prefix for the index. Defaults to "ix" for indexes.
* @return string The postgres name of the index
*/
function buildPostgresIndexName($tableName, $indexName, $prefix = 'ix') {
// Assume all indexes also contain the table name
// MD5 the table/index name combo to keep it to a fixed length.
// Exclude the prefix so that the trigger name can be easily generated from the index name
$indexNamePG = "{$prefix}_" . md5("{$tableName}_{$indexName}");
// Limit to 63 characters
if (strlen($indexNamePG) > 63)
return substr($indexNamePG, 0, 63);
return $indexNamePG;
}
/**
* Builds the internal Postgres trigger name given the silverstripe table and trigger name
* @param string $tableName
* @param string $triggerName
* @return string The postgres name of the trigger
*/
function buildPostgresTriggerName($tableName, $triggerName) {
// Kind of cheating, but behaves the same way as indexes
return $this->buildPostgresIndexName($tableName, $triggerName, 'ts');
}
/**
* Alter a table's schema.
* @param $table The name of the table to alter
* @param $newFields New fields, a map of field name => field schema
* @param $newIndexes New indexes, a map of index name => index type
* @param $alteredFields Updated fields, a map of field name => field schema
* @param $alteredIndexes Updated indexes, a map of index name => index type
*/
public function alterTable($tableName, $newFields = null, $newIndexes = null, $alteredFields = null, $alteredIndexes = null, $alteredOptions = null, $advancedOptions = null) {
$alterList = array();
if($newFields) foreach($newFields as $fieldName => $fieldSpec) {
$alterList[] = "ADD \"$fieldName\" $fieldSpec";
}
if ($alteredFields) foreach ($alteredFields as $indexName => $indexSpec) {
$val = $this->alterTableAlterColumn($tableName, $indexName, $indexSpec);
if (!empty($val)) $alterList[] = $val;
}
//Do we need to do anything with the tablespaces?
if($alteredOptions && isset($advancedOptions['tablespace'])){
$this->createOrReplaceTablespace($advancedOptions['tablespace']['name'], $advancedOptions['tablespace']['location']);
$this->query("ALTER TABLE \"$tableName\" SET TABLESPACE {$advancedOptions['tablespace']['name']};");
}
//DB ABSTRACTION: we need to change the constraints to be a separate 'add' command,
//see http://www.postgresql.org/docs/8.1/static/sql-altertable.html
$alterIndexList=Array();
//Pick up the altered indexes here:
$fieldList = $this->fieldList($tableName);
$fulltexts=false;
$drop_triggers=false;
$triggers=false;
if($alteredIndexes) foreach($alteredIndexes as $indexName=>$indexSpec) {
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$indexNamePG = $this->buildPostgresIndexName($tableName, $indexName);
if($indexSpec['type']=='fulltext') {
//For full text indexes, we need to drop the trigger, drop the index, AND drop the column
//Go and get the tsearch details:
$ts_details = $this->fulltext($indexSpec, $tableName, $indexName);
//Drop this column if it already exists:
//No IF EXISTS option is available for Postgres <9.0
if(array_key_exists($ts_details['ts_name'], $fieldList)){
$fulltexts.="ALTER TABLE \"{$tableName}\" DROP COLUMN \"{$ts_details['ts_name']}\";";
}
// We'll execute these later:
$triggerNamePG = $this->buildPostgresTriggerName($tableName, $indexName);
$drop_triggers.= "DROP TRIGGER IF EXISTS \"$triggerNamePG\" ON \"$tableName\";";
$fulltexts .= "ALTER TABLE \"{$tableName}\" ADD COLUMN {$ts_details['fulltexts']};";
$triggers .= $ts_details['triggers'];
}
// Create index action (including fulltext)
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
$createIndex = $this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
if($createIndex!==false) $alterIndexList[] = $createIndex;
}
//Add the new indexes:
if($newIndexes) foreach($newIndexes as $indexName => $indexSpec){
$indexSpec = $this->parseIndexSpec($indexName, $indexSpec);
$indexNamePG = $this->buildPostgresIndexName($tableName, $indexName);
//If we have a fulltext search request, then we need to create a special column
//for GiST searches
//Pick up the new indexes here:
if($indexSpec['type']=='fulltext') {
$ts_details=$this->fulltext($indexSpec, $tableName, $indexName);
if(!isset($fieldList[$ts_details['ts_name']])){
$fulltexts.="ALTER TABLE \"{$tableName}\" ADD COLUMN {$ts_details['fulltexts']};";
$triggers.=$ts_details['triggers'];
}
}
//Check that this index doesn't already exist:
$indexes=$this->indexList($tableName);
if(isset($indexes[$indexName])){
$alterIndexList[] = "DROP INDEX IF EXISTS \"$indexNamePG\";";
}
$createIndex=$this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
if($createIndex!==false)
$alterIndexList[] = $createIndex;
}
if($alterList) {
$alterations = implode(",\n", $alterList);
$this->query("ALTER TABLE \"$tableName\" " . $alterations);
}
//Do we need to create a tablespace for this item?
if($advancedOptions && isset($advancedOptions['extensions']['tablespace'])){
$extensions=$advancedOptions['extensions'];
$this->createOrReplaceTablespace($extensions['tablespace']['name'], $extensions['tablespace']['location']);
}
if($alteredOptions && isset($this->class) && isset($alteredOptions[$this->class])) {
$this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[$this->class]));
Database::alteration_message(
sprintf("Table %s options changed: %s", $tableName, $alteredOptions[$this->class]),
"changed"
);
}
//Create any fulltext columns and triggers here:
if($fulltexts) $this->query($fulltexts);
if($drop_triggers) $this->query($drop_triggers);
if($triggers) {
$this->query($triggers);
$triggerbits=explode(';', $triggers);
foreach($triggerbits as $trigger){
$trigger_fields=$this->triggerFieldsFromTrigger($trigger);
if($trigger_fields){
//We need to run a simple query to force the database to update the triggered columns
$this->query("UPDATE \"{$tableName}\" SET \"{$trigger_fields[0]}\"=\"$trigger_fields[0]\";");
}
}
}
foreach($alterIndexList as $alteration) $this->query($alteration);
//If we have a partitioning requirement, we do that here:
if($advancedOptions && isset($advancedOptions['partitions'])){
$this->createOrReplacePartition($tableName, $advancedOptions['partitions']);
}
//Lastly, clustering goes here:
if ($advancedOptions && isset($advancedOptions['cluster'])) {
$clusterIndex = $this->buildPostgresIndexName($tableName, $advancedOptions['cluster']);
DB::query("CLUSTER \"$tableName\" USING \"$clusterIndex\";");
} else {
//Check that clustering is not on this table, and if it is, remove it:
//This is really annoying. We need the oid of this table:
$stats=DB::query("SELECT relid FROM pg_stat_user_tables WHERE relname='" . $this->addslashes($tableName) . "';")->first();
$oid=$stats['relid'];
//Now we can run a long query to get the clustered status:
//If anyone knows a better way to get the clustered status, then feel free to replace this!
$clustered=DB::query("SELECT c2.relname, i.indisclustered FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i WHERE c.oid = '$oid' AND c.oid = i.indrelid AND i.indexrelid = c2.oid AND indisclustered='t';")->first();
if($clustered)
DB::query("ALTER TABLE \"$tableName\" SET WITHOUT CLUSTER;");
}
}
/*
* Creates an ALTER expression for a column in PostgreSQL
*
* @param $tableName Name of the table to be altered
* @param $colName Name of the column to be altered
* @param $colSpec String which contains conditions for a column
* @return string
*/
private function alterTableAlterColumn($tableName, $colName, $colSpec){
// First, we split the column specifications into parts
// TODO: this returns an empty array for the following string: int(11) not null auto_increment
// on second thoughts, why is an auto_increment field being passed through?
$pattern = '/^([\w()]+)\s?((?:not\s)?null)?\s?(default\s[\w\']+)?\s?(check\s[\w()\'",\s]+)?$/i';
preg_match($pattern, $colSpec, $matches);
if(sizeof($matches)==0) return '';
if($matches[1]=='serial8') return '';
if(isset($matches[1])) {
$alterCol = "ALTER COLUMN \"$colName\" TYPE $matches[1]\n";
// SET null / not null
if(!empty($matches[2])) {
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[2]";
}
// SET default (we drop it first, for reasons of precaution)
if(!empty($matches[3])) {
$alterCol .= ",\nALTER COLUMN \"$colName\" DROP DEFAULT";
$alterCol .= ",\nALTER COLUMN \"$colName\" SET $matches[3]";
}
// SET check constraint (The constraint HAS to be dropped)
$existing_constraint=$this->query("SELECT conname FROM pg_constraint WHERE conname='{$tableName}_{$colName}_check';")->value();
if(isset($matches[4])) {
//Take this new constraint and see what's outstanding from the target table:
$constraint_bits=explode('(', $matches[4]);
$constraint_values=trim($constraint_bits[2], ')');
$constraint_values_bits=explode(',', $constraint_values);
$default=trim($constraint_values_bits[0], " '");
//Now go and convert anything that's not in this list to 'Page'
//We have to run this as a query, not as part of the alteration queries due to the way they are constructed.
$updateConstraint='';
$updateConstraint.="UPDATE \"{$tableName}\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
if($this->hasTable("{$tableName}_Live")) {
$updateConstraint.="UPDATE \"{$tableName}_Live\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
}
if($this->hasTable("{$tableName}_versions")) {
$updateConstraint.="UPDATE \"{$tableName}_versions\" SET \"$colName\"='$default' WHERE \"$colName\" NOT IN ($constraint_values);";
}
DB::query($updateConstraint);
}
//First, delete any existing constraint on this column, even if it's no longer an enum
if($existing_constraint)
$alterCol .= ",\nDROP CONSTRAINT \"{$tableName}_{$colName}_check\"";
//Now create the constraint (if we've asked for one)
if(!empty($matches[4]))
$alterCol .= ",\nADD CONSTRAINT \"{$tableName}_{$colName}_check\" $matches[4]";
}
return isset($alterCol) ? $alterCol : '';
}
public function renameTable($oldTableName, $newTableName) {
$this->query("ALTER TABLE \"$oldTableName\" RENAME TO \"$newTableName\"");
unset(self::$cached_fieldlists[$oldTableName]);
}
/**
* Repairs and reindexes the table. This might take a long time on a very large table.
* @var string $tableName The name of the table.
* @return boolean Return true if the table has integrity after the method is complete.
*/
public function checkAndRepairTable($tableName) {
$this->runTableCheckCommand("VACUUM FULL ANALYZE \"$tableName\"");
$this->runTableCheckCommand("REINDEX TABLE \"$tableName\"");
return true;
}
/**
* Helper function used by checkAndRepairTable.
* @param string $sql Query to run.
* @return boolean Returns true no matter what; we're not currently checking the status of the command
*/
protected function runTableCheckCommand($sql) {
$testResults = $this->query($sql);
return true;
}
public function createField($tableName, $fieldName, $fieldSpec) {
$this->query("ALTER TABLE \"$tableName\" ADD \"$fieldName\" $fieldSpec");
}
/**
* Change the database type of the given field.
* @param string $tableName The name of the tbale the field is in.
* @param string $fieldName The name of the field to change.
* @param string $fieldSpec The new field specification
*/
public function alterField($tableName, $fieldName, $fieldSpec) {
$this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec");
}
/**
* Change the database column name of the given field.
*
* @param string $tableName The name of the table the field is in.
* @param string $oldName The name of the field to change.
* @param string $newName The new name of the field
*/
public function renameField($tableName, $oldName, $newName) {
$fieldList = $this->fieldList($tableName);
if(array_key_exists($oldName, $fieldList)) {
$this->query("ALTER TABLE \"$tableName\" RENAME COLUMN \"$oldName\" TO \"$newName\"");
//Remove this from the cached list:
unset(self::$cached_fieldlists[$tableName]);
}
}
public function fieldList($table) {
//Query from http://www.alberton.info/postgresql_meta_info.html
//This gets us more information than we need, but I've included it all for the moment....
//if(!isset(self::$cached_fieldlists[$table])){
$fields = $this->query("SELECT ordinal_position, column_name, data_type, column_default, is_nullable, character_maximum_length, numeric_precision, numeric_scale FROM information_schema.columns WHERE table_name = '" . $this->addslashes($table) . "' ORDER BY ordinal_position;");
$output = array();
if($fields) foreach($fields as $field) {
switch($field['data_type']){
case 'character varying':
//Check to see if there's a constraint attached to this column:
//$constraint=$this->query("SELECT conname,pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE r.contype = 'c' AND conname='" . $table . '_' . $field['column_name'] . "_check' ORDER BY 1;")->first();
$constraint=$this->constraintExists($table . '_' . $field['column_name'] . '_check');
if($constraint){
//Now we need to break this constraint text into bits so we can see what we have:
//Examples:
//CHECK ("CanEditType"::text = ANY (ARRAY['LoggedInUsers'::character varying, 'OnlyTheseUsers'::character varying, 'Inherit'::character varying]::text[]))
//CHECK ("ClassName"::text = 'PageComment'::text)
//TODO: replace all this with a regular expression!
$value=$constraint['pg_get_constraintdef'];
$value=substr($value, strpos($value,'='));
$value=str_replace("''", "'", $value);
$in_value=false;
$constraints=Array();
$current_value='';
for($i=0; $i<strlen($value); $i++){
$char=substr($value, $i, 1);
if($in_value)
$current_value.=$char;
if($char=="'"){
if(!$in_value)
$in_value=true;
else {
$in_value=false;
$constraints[]=substr($current_value, 0, -1);
$current_value='';
}
}
}
if(sizeof($constraints)>0){
//Get the default:
$default=trim(substr($field['column_default'], 0, strpos($field['column_default'], '::')), "'");
$output[$field['column_name']]=$this->enum(Array('default'=>$default, 'name'=>$field['column_name'], 'enums'=>$constraints));
}
} else{
$output[$field['column_name']]='varchar(' . $field['character_maximum_length'] . ')';
}
break;
case 'numeric':
$output[$field['column_name']]='decimal(' . $field['numeric_precision'] . ',' . $field['numeric_scale'] . ') default ' . (int)$field['column_default'];
break;
case 'integer':
$output[$field['column_name']]='integer default ' . (int)$field['column_default'];
break;
case 'timestamp without time zone':
$output[$field['column_name']]='timestamp';
break;
case 'smallint':
$output[$field['column_name']]='smallint default ' . (int)$field['column_default'];
break;
case 'time without time zone':
$output[$field['column_name']]='time';
break;
case 'double precision':
$output[$field['column_name']]='float';
break;
default:
$output[$field['column_name']] = $field;
}
}
// self::$cached_fieldlists[$table]=$output;
//}
//return self::$cached_fieldlists[$table];
return $output;
}
/**
*
* This allows the cached values for a table's field list to be erased.
* If $tablename is empty, then the whole cache is erased.
*
* @param string $tableName
*
* @return boolean
*/
function clearCachedFieldlist($tableName=false){
if($tableName) unset(self::$cached_fieldlists[$tableName]);
else self::$cached_fieldlists=array();
return true;
}
/**
* Create an index on a table.
* @param string $tableName The name of the table.
* @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see Database::requireIndex() for more details.
*/
public function createIndex($tableName, $indexName, $indexSpec) {
$createIndex=$this->getIndexSqlDefinition($tableName, $indexName, $indexSpec);
if($createIndex!==false) $this->query();
}
/*
* This takes the index spec which has been provided by a class (ie static $indexes = blah blah)
* and turns it into a proper string.
* Some indexes may be arrays, such as fulltext and unique indexes, and this allows database-specific
* arrays to be created.
* @see parseIndexSpec() for approximate inverse
*/
public function convertIndexSpec($indexSpec, $asDbValue=false, $table=''){
if(!$asDbValue){
if(is_array($indexSpec)){
//Here we create a db-specific version of whatever index we need to create.
switch($indexSpec['type']){
case 'fulltext':
$indexSpec='fulltext (' . $indexSpec['value'] . ')';
break;
case 'unique':
$indexSpec='unique (' . $indexSpec['value'] . ')';
break;
case 'hash':
$indexSpec='using hash (' . $indexSpec['value'] . ')';
break;
case 'index':
//The default index is 'btree', which we'll use by default (below):
default:
$indexSpec='using btree (' . $indexSpec['value'] . ')';
break;
}
}
} else {
$indexSpec = $this->buildPostgresIndexName($table, $indexSpec);
}
return $indexSpec;
}
/**
* Splits a spec string safely, considering quoted columns, whitespace,
* and cleaning brackets
* @param string $spec The input index specification
* @return array List of columns in the spec
*/
function explodeColumnString($spec) {
// Remove any leading/trailing brackets and outlying modifiers
// E.g. 'unique (Title, "QuotedColumn");' => 'Title, "QuotedColumn"'
$containedSpec = preg_replace('/(.*\(\s*)|(\s*\).*)/', '', $spec);
// Split potentially quoted modifiers
// E.g. 'Title, "QuotedColumn"' => array('Title', 'QuotedColumn')
return preg_split('/"?\s*,\s*"?/', trim($containedSpec, '(") '));
}
/**
* Builds a properly quoted column list from an array
* @param array $columns List of columns to implode
* @return string A properly quoted list of column names
*/
function implodeColumnList($columns) {
if(empty($columns)) return '';
return '"' . implode('","', $columns) . '"';
}
/**
* Given an index specification in the form of a string ensure that each
* column name is property quoted, stripping brackets and modifiers.
* This index may also be in the form of a "CREATE INDEX..." sql fragment
* @param string $spec The input specification or query. E.g. 'unique (Column1, Column2)'
* @return string The properly quoted column list. E.g. '"Column1", "Column2"'
*/
function quoteColumnSpecString($spec) {
$bits = $this->explodeColumnString($spec);
return $this->implodeColumnList($bits);
}
/**
* Given an index spec determines the index type
* @param type $spec
* @return string
*/
function determineIndexType($spec) {
// check array spec
if(is_array($spec) && isset($spec['type'])) {
return $spec['type'];
} elseif (!is_array($spec) && preg_match('/(?<type>\w+)\s*\(/', $spec, $matchType)) {
return strtolower($matchType['type']);
} else {
return 'index';
}
}