class PostgreSQLDatabase extends Database (View source)

PostgreSQL connector class.

Traits

Provides extensions to this object to integrate it with standard config API methods.

Constants

PARTIAL_QUERY

FULL_QUERY

MASTER_DATABASE

MASTER_SCHEMA

Config options

optimistic_connect bool

In cases where your environment does not have 'SHOW DATABASES' permission, you can set this to true. Then selectDatabase() will always connect without doing databaseExists() check.

from  Database
allow_query_master_postgres bool

Determines whether to check a database exists on the host by querying the 'postgres' database and running createDatabase.

model_schema_as_database

For instances where multiple databases are used beyond the initial connection you may set this option to true to force database switches to switch schemas instead of using databases. This may be useful if the database user does not have cross-database permissions, and in cases where multiple databases are used (such as in running test cases).

search_language

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.

default_fts_cluster_method
default_fts_search_method

Properties

protected static array $whitelist_array

To use, call from _config.php Example:

Database::setWhitelistQueryArray([
     'Qualmark' => 'partial_query',
     'SELECT "Version" FROM "SiteTree_Live" WHERE "ID" = ?' => 'full_query',
])
from  Database
protected DBConnector $connector

Database connector object

from  Database
protected int $queryCount

Amount of queries executed, for debugging purposes.

from  Database
protected PostgreSQLSchemaManager $schemaManager

Database schema manager object

protected DBQueryBuilder $queryBuilder

Query builder object

from  Database
protected string $schema

The currently selected database schema name.

protected bool $transactionNesting
protected bool $supportsTransactions

Toggle if transactions are supported. Defaults to true.

protected string $databaseOriginal

The database name specified at initial connection

protected string $schemaOriginal

The schema name specified at initial construction. When model_schema_as_database is set to true selecting the $databaseOriginal database will instead reset the schema to this

protected array $parameters

Connection parameters specified at inital connection

Methods

public
getConnector()

Get the current connector

from  Database
public
setConnector(DBConnector $connector)

Injector injection point for connector dependency

from  Database
public
getSchemaManager()

Returns the current schema manager

from  Database
public
setSchemaManager(DBSchemaManager $schemaManager)

Injector injection point for schema manager

from  Database
public
getQueryBuilder()

Returns the current query builder

from  Database
public
setQueryBuilder(DBQueryBuilder $queryBuilder)

Injector injection point for schema manager

from  Database
public
query(string $sql, int $errorLevel = E_USER_ERROR)

Execute the given SQL query.

from  Database
public
preparedQuery(string $sql, array $parameters, int $errorLevel = E_USER_ERROR)

Execute the given SQL parameterised query with the specified arguments

from  Database
protected
bool
previewWrite(string $sql)

Determines if the query should be previewed, and thus interrupted silently.

from  Database
protected
mixed
benchmarkQuery(string $sql, callable $callback, array $parameters = [])

Allows the display and benchmarking of queries as they are being run

from  Database
protected
displayQuery(mixed $query, float $endtime)

Display query message

from  Database
public static 
setWhitelistQueryArray(array $whitelistArray)

Add the sql queries that need to be partially or fully matched

from  Database
public static 
array
getWhitelistQueryArray()

Get the sql queries that need to be partially or fully matched

from  Database
public
int
getGeneratedID(string $table)

Get the autogenerated ID from the previous INSERT query.

from  Database
public
bool
isActive()

Determines if we are connected to a server AND have a valid database selected.

from  Database
public
string
escapeString(mixed $value)

Returns an escaped string. This string won't be quoted, so would be suitable for appending to other quoted strings.

from  Database
public
string
quoteString(mixed $value)

Wrap a string into DB-specific quotes.

from  Database
public
string
escapeIdentifier(string|array $value, string $separator = '.')

Escapes an identifier (table / database name). Typically the value is simply double quoted. Don't pass in already escaped identifiers in, as this will double escape the value!

from  Database
protected
array
escapeColumnKeys(array $fieldValues)

Escapes unquoted columns keys in an associative array

from  Database
public
manipulate(array $manipulation)

Execute a complex manipulation on the database.

from  Database
public
quiet()

Enable suppression of database messages.

from  Database
public
clearAllData()

Clear all data out of the database

from  Database
public
clearTable(string $table)

Delete all entries from the table instead of truncating it.

public
string
nullCheckClause(string $field, bool $isNull)

Generates a WHERE clause for null comparison check

from  Database
public
string
comparisonClause(string $field, string $value, bool $exact = false, bool $negate = false, bool $caseSensitive = null, bool $parameterised = false)

Generate a WHERE clause for text matching.

public
string
formattedDatetimeClause(string $date, string $format)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime in a certain format

public
string
datetimeIntervalClause(string $date, string $interval)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime addition

public
string
datetimeDifferenceClause(string $date1, string $date2)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime substraction

public
string
concatOperator()

String operator for concatenation of strings

from  Database
public
bool
supportsCollations()

Returns true if this database supports collations

public
bool
supportsTimezoneOverride()

Can the database override timezone as a connection setting, or does it use the system timezone exclusively?

public
string
getVersion()

Query for the version of the currently connected database

from  Database
public
string
getDatabaseServer()

Get the database server type (e.g. mysql, postgresql).

public
int
affectedRows()

Return the number of rows affected by the previous operation.

from  Database
public
searchEngine(array $classesToSearch, string $keywords, int $start, int $pageLength, string $sortBy = "ts_rank DESC", string $extraFilter = "", bool $booleanSearch = false, string $alternativeFileFilter = "", bool $invertedMatch = false)

The core search engine configuration.

public
bool
supportsTransactions()

Determines if this database supports transactions

public
bool
supportsSavepoints()

Does this database support savepoints in transactions By default it is assumed that they don't unless they are explicitly enabled.

from  Database
public
bool
supportsTransactionMode(string $mode)

Determines if the used database supports given transactionMode as an argument to startTransaction() If transactions are completely unsupported, returns false.

from  Database
public
withTransaction(callable $callback, callable $errorCallback = null, bool|string $transactionMode = false, bool $errorIfTransactionsUnsupported = false)

Invoke $callback within a transaction

from  Database
public
supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering'))

No description

public
transactionStart($transaction_mode = false, $session_characteristics = false)

Start a prepared transaction See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options

public
transactionSavepoint(string $savepoint)

Create a savepoint that you can jump back to if you encounter problems

public
bool|null
transactionRollback(string|bool $savepoint = false)

Rollback or revert to a savepoint if your queries encounter problems If you encounter a problem at any point during a transaction, you may need to rollback that particular query, or return to a savepoint

public
bool|null
transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

public
int
transactionDepth()

Return depth of current transaction

public
bool
supportsLocks()

Determines if the used database supports application-level locks, which is different from table- or row-level locking.

from  Database
public
bool
canLock(string $name)

Returns if the lock is available.

from  Database
public
bool
getLock(string $name, int $timeout = 5)

Sets an application-level lock so that no two processes can run at the same time, also called a "cooperative advisory lock".

from  Database
public
bool
releaseLock(string $name)

Remove an application-level lock file to allow another process to run (if the execution aborts (e.g. due to an error) all locks are automatically released).

from  Database
public
connect(array $parameters)

Instruct the database to generate a live connection

public
bool
databaseExists(string $name)

Determine if the database with the specified name exists

from  Database
public
array
databaseList()

Retrieves the list of all databases the user has access to

from  Database
public
bool
selectDatabase(string $name, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Change the connection to the specified database, optionally creating the database if it doesn't exist in the current schema.

public
dropSelectedDatabase()

Drop the database that this object is currently connected to.

public
string|null
getSelectedDatabase()

Returns the name of the currently selected database

public
string
now()

Return SQL expression used to represent the current date/time

public
string
random()

Returns the database-specific version of the random() function

public static 
config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

public
mixed
stat(string $name) deprecated

Get inherited config value

public
mixed
uninherited(string $name)

Gets the uninherited value for the given config option

public
$this
set_stat(string $name, mixed $value) deprecated

Update the config value for a given property

public static 
string
default_fts_cluster_method()

Full text cluster method. (e.g. GIN or GiST)

public static 
string
default_fts_search_method()

Full text search method.

public static 
bool
allow_query_master_postgres()

Determines whether to check a database exists on the host by querying the 'postgres' database and running createDatabase.

public static 
bool
model_schema_as_database()

For instances where multiple databases are used beyond the initial connection you may set this option to true to force database switches to switch schemas instead of using databases. This may be useful if the database user does not have cross-database permissions, and in cases where multiple databases are used (such as in running test cases).

public static 
string
search_language()

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.

protected
connectMaster()

No description

protected
connectDefault()

No description

public
selectTimezone(string $timezone)

Sets the system timezone for the database connection

public
string
currentSchema()

Returns the name of the current schema in use

public
bool
setSchema(string $schema, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Utility method to manually set the schema to an alternative Check existance & sets search path to the supplied schema name

public
setSchemaSearchPath(string $arg = null)

Override the schema search path. Search using the arguments supplied.

public
string
schemaToDatabaseName(string $schema)

Determines the name of the current database to be reported externally by substituting the schema name for the database name.

public
string
databaseToSchemaName(string $database)

Translates a requested database name to a schema name to substitute internally.

Details

DBConnector getConnector()

Get the current connector

Return Value

DBConnector

setConnector(DBConnector $connector)

Injector injection point for connector dependency

Parameters

DBConnector $connector

DBSchemaManager getSchemaManager()

Returns the current schema manager

Return Value

DBSchemaManager

setSchemaManager(DBSchemaManager $schemaManager)

Injector injection point for schema manager

Parameters

DBSchemaManager $schemaManager

DBQueryBuilder getQueryBuilder()

Returns the current query builder

Return Value

DBQueryBuilder

setQueryBuilder(DBQueryBuilder $queryBuilder)

Injector injection point for schema manager

Parameters

DBQueryBuilder $queryBuilder

Query query(string $sql, int $errorLevel = E_USER_ERROR)

Execute the given SQL query.

Parameters

string $sql

The SQL query to execute

int $errorLevel

The level of error reporting to enable for the query

Return Value

Query

Query preparedQuery(string $sql, array $parameters, int $errorLevel = E_USER_ERROR)

Execute the given SQL parameterised query with the specified arguments

Parameters

string $sql

The SQL query to execute. The ? character will denote parameters.

array $parameters

An ordered list of arguments.

int $errorLevel

The level of error reporting to enable for the query

Return Value

Query

protected bool previewWrite(string $sql)

Determines if the query should be previewed, and thus interrupted silently.

If so, this function also displays the query via the debugging system. Subclasess should respect the results of this call for each query, and not execute any queries that generate a true response.

Parameters

string $sql

The query to be executed

Return Value

bool

Flag indicating that the query was previewed

protected mixed benchmarkQuery(string $sql, callable $callback, array $parameters = [])

Allows the display and benchmarking of queries as they are being run

Parameters

string $sql

Query to run, and single parameter to callback

callable $callback

Callback to execute code

array $parameters

Parameters for any parameterised query

Return Value

mixed

Result of query

protected displayQuery(mixed $query, float $endtime)

Display query message

Parameters

mixed $query
float $endtime

static setWhitelistQueryArray(array $whitelistArray)

Add the sql queries that need to be partially or fully matched

Parameters

array $whitelistArray

static array getWhitelistQueryArray()

Get the sql queries that need to be partially or fully matched

Return Value

array

int getGeneratedID(string $table)

Get the autogenerated ID from the previous INSERT query.

Parameters

string $table

The name of the table to get the generated ID for

Return Value

int

the most recently generated ID for the specified table

bool isActive()

Determines if we are connected to a server AND have a valid database selected.

Return Value

bool

Flag indicating that a valid database is connected

string escapeString(mixed $value)

Returns an escaped string. This string won't be quoted, so would be suitable for appending to other quoted strings.

Parameters

mixed $value

Value to be prepared for database query

Return Value

string

Prepared string

string quoteString(mixed $value)

Wrap a string into DB-specific quotes.

Parameters

mixed $value

Value to be prepared for database query

Return Value

string

Prepared string

string escapeIdentifier(string|array $value, string $separator = '.')

Escapes an identifier (table / database name). Typically the value is simply double quoted. Don't pass in already escaped identifiers in, as this will double escape the value!

Parameters

string|array $value

The identifier to escape or list of split components

string $separator

Splitter for each component

Return Value

string

protected array escapeColumnKeys(array $fieldValues)

Escapes unquoted columns keys in an associative array

Parameters

array $fieldValues

Return Value

array

List of field values with the keys as escaped column names

manipulate(array $manipulation)

Execute a complex manipulation on the database.

A manipulation is an array of insert / or update sequences. The keys of the array are table names, and the values are map containing 'command' and 'fields'. Command should be 'insert' or 'update', and fields should be a map of field names to field values, NOT including quotes.

The field values could also be in paramaterised format, such as array('MAX(?,?)' => array(42, 69)), allowing the use of raw SQL values such as array('NOW()' => array()).

Parameters

array $manipulation

See also

SQLWriteExpression::addAssignments for syntax examples

quiet()

Enable suppression of database messages.

clearAllData()

Clear all data out of the database

clearTable(string $table)

Delete all entries from the table instead of truncating it.

This gives a massive speed improvement compared to using TRUNCATE, with the caveat that primary keys are not reset etc.

Parameters

string $table

Name of table

See also

\SilverStripe\PostgreSQL\DatabaseAdmin::clearAllData()

string nullCheckClause(string $field, bool $isNull)

Generates a WHERE clause for null comparison check

Parameters

string $field

Quoted field name

bool $isNull

Whether to check for NULL or NOT NULL

Return Value

string

Non-parameterised null comparison clause

string comparisonClause(string $field, string $value, bool $exact = false, bool $negate = false, bool $caseSensitive = null, bool $parameterised = false)

Generate a WHERE clause for text matching.

Parameters

string $field

Quoted field name

string $value

Escaped search. Can include percentage wildcards. Ignored if $parameterised is true.

bool $exact

Exact matches or wildcard support.

bool $negate

Negate the clause.

bool $caseSensitive

Enforce case sensitivity if TRUE or FALSE. Fallback to default collation if set to NULL.

bool $parameterised

Insert the ? placeholder rather than the given value. If this is true then $value is ignored.

Return Value

string SQL

string formattedDatetimeClause(string $date, string $format)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime in a certain format

Parameters

string $date

to be formatted, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'

string $format

to be used, supported specifiers: %Y = Year (four digits) %m = Month (01..12) %d = Day (01..31) %H = Hour (00..23) %i = Minutes (00..59) %s = Seconds (00..59) %U = unix timestamp, can only be used on it's own

Return Value

string

SQL datetime expression to query for a formatted datetime

string datetimeIntervalClause(string $date, string $interval)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime addition

Parameters

string $date

can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'

string $interval

to be added, use the format [sign][integer] [qualifier], e.g. -1 Day, +15 minutes, +1 YEAR supported qualifiers:

  • years
  • months
  • days
  • hours
  • minutes
  • seconds This includes the singular forms as well

Return Value

string

SQL datetime expression to query for a datetime (YYYY-MM-DD hh:mm:ss) which is the result of the addition

string datetimeDifferenceClause(string $date1, string $date2)

Function to return an SQL datetime expression that can be used with Postgres used for querying a datetime substraction

Parameters

string $date1

can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name e.g. '"SiteTree"."Created"'

string $date2

to be subtracted of $date1, can be either 'now', literal datetime like '1973-10-14 10:30:00' or field name, e.g. '"SiteTree"."Created"'

Return Value

string

SQL datetime expression to query for the interval between $date1 and $date2 in seconds which is the result of the subtraction

string concatOperator()

String operator for concatenation of strings

Return Value

string

bool supportsCollations()

Returns true if this database supports collations

Return Value

bool

bool supportsTimezoneOverride()

Can the database override timezone as a connection setting, or does it use the system timezone exclusively?

Return Value

bool

string getVersion()

Query for the version of the currently connected database

Return Value

string

Version of this database

string getDatabaseServer()

Get the database server type (e.g. mysql, postgresql).

This value is passed to the connector as the 'driver' argument when initiating a database connection

Return Value

string

int affectedRows()

Return the number of rows affected by the previous operation.

Return Value

int

PaginatedList searchEngine(array $classesToSearch, string $keywords, int $start, int $pageLength, string $sortBy = "ts_rank DESC", string $extraFilter = "", bool $booleanSearch = false, string $alternativeFileFilter = "", bool $invertedMatch = false)

The core search engine configuration.

Properly extract the search functions out of the core.

Parameters

array $classesToSearch

List of classes to search

string $keywords

Keywords as a string.

int $start

Item to start returning results from

int $pageLength

Number of items per page

string $sortBy

Sort order expression

string $extraFilter

Additional filter

bool $booleanSearch

Flag for boolean search mode

string $alternativeFileFilter
bool $invertedMatch

Return Value

PaginatedList

Search results

Exceptions

Exception

bool supportsTransactions()

Determines if this database supports transactions

Return Value

bool

Flag indicating support for transactions

bool supportsSavepoints()

Does this database support savepoints in transactions By default it is assumed that they don't unless they are explicitly enabled.

Return Value

bool

Flag indicating support for savepoints in transactions

bool supportsTransactionMode(string $mode)

Determines if the used database supports given transactionMode as an argument to startTransaction() If transactions are completely unsupported, returns false.

Parameters

string $mode

Return Value

bool

withTransaction(callable $callback, callable $errorCallback = null, bool|string $transactionMode = false, bool $errorIfTransactionsUnsupported = false)

Invoke $callback within a transaction

Parameters

callable $callback

Callback to run

callable $errorCallback

Optional callback to run after rolling back transaction.

bool|string $transactionMode

Optional transaction mode to use

bool $errorIfTransactionsUnsupported

If true, this method will fail if transactions are unsupported. Otherwise, the $callback will potentially be invoked outside of a transaction.

Exceptions

Exception

supportsExtensions($extensions = array('partitions', 'tablespaces', 'clustering'))

No description

Parameters

$extensions

transactionStart($transaction_mode = false, $session_characteristics = false)

Start a prepared transaction See http://developer.postgresql.org/pgdocs/postgres/sql-set-transaction.html for details on transaction isolation options

Parameters

$transaction_mode
$session_characteristics

transactionSavepoint(string $savepoint)

Create a savepoint that you can jump back to if you encounter problems

Parameters

string $savepoint

Name of savepoint

bool|null transactionRollback(string|bool $savepoint = false)

Rollback or revert to a savepoint if your queries encounter problems If you encounter a problem at any point during a transaction, you may need to rollback that particular query, or return to a savepoint

Parameters

string|bool $savepoint

Name of savepoint, or leave empty to rollback to last savepoint

Return Value

bool|null

Boolean is returned if success state is known, or null if unknown. Note: For error checking purposes null should not be treated as error.

bool|null transactionEnd(bool $chain = false)

Commit everything inside this transaction so far

Parameters

bool $chain

Return Value

bool|null

Boolean is returned if success state is known, or null if unknown. Note: For error checking purposes null should not be treated as error.

int transactionDepth()

Return depth of current transaction

Return Value

int

Nesting level, or 0 if not in a transaction

bool supportsLocks()

Determines if the used database supports application-level locks, which is different from table- or row-level locking.

See getLock() for details.

Return Value

bool

Flag indicating that locking is available

bool canLock(string $name)

Returns if the lock is available.

See supportsLocks() to check if locking is generally supported.

Parameters

string $name

Name of the lock

Return Value

bool

bool getLock(string $name, int $timeout = 5)

Sets an application-level lock so that no two processes can run at the same time, also called a "cooperative advisory lock".

Return FALSE if acquiring the lock fails; otherwise return TRUE, if lock was acquired successfully. Lock is automatically released if connection to the database is broken (either normally or abnormally), making it less prone to deadlocks than session- or file-based locks. Should be accompanied by a releaseLock() call after the logic requiring the lock has completed. Can be called multiple times, in which case locks "stack" (PostgreSQL, SQL Server), or auto-releases the previous lock (MySQL).

Note that this might trigger the database to wait for the lock to be released, delaying further execution.

Parameters

string $name

Name of lock

int $timeout

Timeout in seconds

Return Value

bool

bool releaseLock(string $name)

Remove an application-level lock file to allow another process to run (if the execution aborts (e.g. due to an error) all locks are automatically released).

Parameters

string $name

Name of the lock

Return Value

bool

Flag indicating whether the lock was successfully released

connect(array $parameters)

Instruct the database to generate a live connection

Parameters

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
  • charset: The character set to use. Defaults to utf8
  • timezone: (optional) The timezone offset. For example: +12:00, "Pacific/Auckland", or "SYSTEM"
  • driver: (optional) Driver name

bool databaseExists(string $name)

Determine if the database with the specified name exists

Parameters

string $name

Name of the database to check for

Return Value

bool

Flag indicating whether this database exists

array databaseList()

Retrieves the list of all databases the user has access to

Return Value

array

List of database names

bool selectDatabase(string $name, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Change the connection to the specified database, optionally creating the database if it doesn't exist in the current schema.

Parameters

string $name

Name of the database

bool $create

Flag indicating whether the database should be created if it doesn't exist. If $create is false and the database doesn't exist then an error will be raised

int|bool $errorLevel

The level of error reporting to enable for the query, or false if no error should be raised

Return Value

bool

Flag indicating success

dropSelectedDatabase()

Drop the database that this object is currently connected to.

Use with caution.

string|null getSelectedDatabase()

Returns the name of the currently selected database

Return Value

string|null

Name of the selected database, or null if none selected

string now()

Return SQL expression used to represent the current date/time

Return Value

string

Expression for the current date/time

string random()

Returns the database-specific version of the random() function

Return Value

string

Expression for a random value

static Config_ForClass config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

Return Value

Config_ForClass

mixed stat(string $name) deprecated

deprecated 5.0 Use ->config()->get() instead

Get inherited config value

Parameters

string $name

Return Value

mixed

mixed uninherited(string $name)

Gets the uninherited value for the given config option

Parameters

string $name

Return Value

mixed

$this set_stat(string $name, mixed $value) deprecated

deprecated 5.0 Use ->config()->set() instead

Update the config value for a given property

Parameters

string $name
mixed $value

Return Value

$this

static string default_fts_cluster_method()

Full text cluster method. (e.g. GIN or GiST)

Return Value

string

static string default_fts_search_method()

Full text search method.

Return Value

string

static bool allow_query_master_postgres()

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.

If allow_query_master_postgres is false, and model_schema_as_database is also false, then attempts to create or check databases beyond the initial connection will result in a runtime error.

Return Value

bool

static bool model_schema_as_database()

For instances where multiple databases are used beyond the initial connection you may set this option to true to force database switches to switch schemas instead of using databases. This may be useful if the database user does not have cross-database permissions, and in cases where multiple databases are used (such as in running test cases).

If this is true then the database will only be set during the initial connection, and attempts to change to this database will use the 'public' schema instead

Return Value

bool

static string search_language()

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.

Return Value

string

protected connectMaster()

No description

protected connectDefault()

No description

selectTimezone(string $timezone)

Sets the system timezone for the database connection

Parameters

string $timezone

string currentSchema()

Returns the name of the current schema in use

Return Value

string

Name of current schema

bool setSchema(string $schema, bool $create = false, int|bool $errorLevel = E_USER_ERROR)

Utility method to manually set the schema to an alternative Check existance & sets search path to the supplied schema name

Parameters

string $schema

Name of the schema

bool $create

Flag indicating whether the schema should be created if it doesn't exist. If $create is false and the schema doesn't exist then an error will be raised

int|bool $errorLevel

The level of error reporting to enable for the query, or false if no error should be raised

Return Value

bool

Flag indicating success

setSchemaSearchPath(string $arg = null)

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.

Parameters

string $arg

Schema name to use. Add additional schema names as extra arguments.

string schemaToDatabaseName(string $schema)

Determines the name of the current database to be reported externally by substituting the schema name for the database name.

Should only be used when model_schema_as_database is true

Parameters

string $schema

Name of the schema

Return Value

string

Name of the database to report

string databaseToSchemaName(string $database)

Translates a requested database name to a schema name to substitute internally.

Should only be used when model_schema_as_database is true

Parameters

string $database

Name of the database

Return Value

string

Name of the schema to use for this database internally