first commit

This commit is contained in:
DESKTOP-DH6BVPV\chiefsoft
2022-11-20 09:46:33 -05:00
commit 6ddfa92eed
618 changed files with 104537 additions and 0 deletions
+230
View File
@@ -0,0 +1,230 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Builder for OCI8
*/
class Builder extends BaseBuilder
{
/**
* Identifier escape character
*
* @var string
*/
protected $escapeChar = '"';
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'"DBMS_RANDOM"."RANDOM"',
];
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by BaseBuilder::count_all_results()
*
* @var string
*/
protected $countString = 'SELECT COUNT(1) ';
/**
* Limit used flag
*
* If we use LIMIT, we'll add a field that will
* throw off num_fields later.
*
* @var bool
*/
protected $limitUsed = false;
/**
* A reference to the database connection.
*
* @var Connection
*/
protected $db;
/**
* Generates a platform-specific insert string from the supplied data.
*/
protected function _insertBatch(string $table, array $keys, array $values): string
{
$insertKeys = implode(', ', $keys);
$hasPrimaryKey = in_array('PRIMARY', array_column($this->db->getIndexData($table), 'type'), true);
// ORA-00001 measures
if ($hasPrimaryKey) {
$sql = 'INSERT INTO ' . $table . ' (' . $insertKeys . ") \n SELECT * FROM (\n";
$selectQueryValues = [];
foreach ($values as $value) {
$selectValues = implode(',', array_map(static fn ($value, $key) => $value . ' as ' . $key, explode(',', substr(substr($value, 1), 0, -1)), $keys));
$selectQueryValues[] = 'SELECT ' . $selectValues . ' FROM DUAL';
}
return $sql . implode("\n UNION ALL \n", $selectQueryValues) . "\n)";
}
$sql = "INSERT ALL\n";
foreach ($values as $value) {
$sql .= ' INTO ' . $table . ' (' . $insertKeys . ') VALUES ' . $value . "\n";
}
return $sql . 'SELECT * FROM DUAL';
}
/**
* Generates a platform-specific replace string from the supplied data
*/
protected function _replace(string $table, array $keys, array $values): string
{
$fieldNames = array_map(static fn ($columnName) => trim($columnName, '"'), $keys);
$uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames) {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY') && $hasAllFields;
});
$replaceableFields = array_filter($keys, static function ($columnName) use ($uniqueIndexes) {
foreach ($uniqueIndexes as $index) {
if (in_array(trim($columnName, '"'), $index->fields, true)) {
return false;
}
}
return true;
});
$sql = 'MERGE INTO ' . $table . "\n USING (SELECT ";
$sql .= implode(', ', array_map(static fn ($columnName, $value) => $value . ' ' . $columnName, $keys, $values));
$sql .= ' FROM DUAL) "_replace" ON ( ';
$onList = [];
$onList[] = '1 != 1';
foreach ($uniqueIndexes as $index) {
$onList[] = '(' . implode(' AND ', array_map(static fn ($columnName) => $table . '."' . $columnName . '" = "_replace"."' . $columnName . '"', $index->fields)) . ')';
}
$sql .= implode(' OR ', $onList) . ') WHEN MATCHED THEN UPDATE SET ';
$sql .= implode(', ', array_map(static fn ($columnName) => $columnName . ' = "_replace".' . $columnName, $replaceableFields));
$sql .= ' WHEN NOT MATCHED THEN INSERT (' . implode(', ', $replaceableFields) . ') VALUES ';
return $sql . (' (' . implode(', ', array_map(static fn ($columnName) => '"_replace".' . $columnName, $replaceableFields)) . ')');
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the truncate() command,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'TRUNCATE TABLE ' . $table;
}
/**
* Compiles a delete string and runs the query
*
* @param mixed $where
*
* @return mixed
*
* @throws DatabaseException
*/
public function delete($where = '', ?int $limit = null, bool $resetData = true)
{
if (! empty($limit)) {
$this->QBLimit = $limit;
}
return parent::delete($where, null, $resetData);
}
/**
* Generates a platform-specific delete string from the supplied data
*/
protected function _delete(string $table): string
{
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
$this->QBLimit = false;
}
return parent::_delete($table);
}
/**
* Generates a platform-specific update string from the supplied data
*/
protected function _update(string $table, array $values): string
{
$valStr = [];
foreach ($values as $key => $val) {
$valStr[] = $key . ' = ' . $val;
}
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
}
return 'UPDATE ' . $this->compileIgnore('update') . $table . ' SET ' . implode(', ', $valStr)
. $this->compileWhereHaving('QBWhere')
. $this->compileOrderBy();
}
/**
* Generates a platform-specific LIMIT clause.
*/
protected function _limit(string $sql, bool $offsetIgnore = false): string
{
$offset = (int) ($offsetIgnore === false ? $this->QBOffset : 0);
if (version_compare($this->db->getVersion(), '12.1', '>=')) {
// OFFSET-FETCH can be used only with the ORDER BY clause
if (empty($this->QBOrderBy)) {
$sql .= ' ORDER BY 1';
}
return $sql . ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $this->QBLimit . ' ROWS ONLY';
}
$this->limitUsed = true;
$limitTemplateQuery = 'SELECT * FROM (SELECT INNER_QUERY.*, ROWNUM RNUM FROM (%s) INNER_QUERY WHERE ROWNUM < %d)' . ($offset ? ' WHERE RNUM >= %d' : '');
return sprintf($limitTemplateQuery, $sql, $offset + $this->QBLimit + 1, $offset);
}
/**
* Resets the query builder values. Called by the get() function
*/
protected function resetSelect()
{
$this->limitUsed = false;
parent::resetSelect();
}
}
+725
View File
@@ -0,0 +1,725 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Query;
use ErrorException;
use stdClass;
/**
* Connection for OCI8
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
protected $DBDriver = 'OCI8';
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '"';
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var array
*/
protected $reservedIdentifiers = [
'*',
'rownum',
];
protected $validDSNs = [
'tns' => '/^\(DESCRIPTION=(\(.+\)){2,}\)$/', // TNS
// Easy Connect string (Oracle 10g+)
'ec' => '/^(\/\/)?[a-z0-9.:_-]+(:[1-9][0-9]{0,4})?(\/[a-z0-9$_]+)?(:[^\/])?(\/[a-z0-9$_]+)?$/i',
'in' => '/^[a-z0-9$_]+$/i', // Instance name (defined in tnsnames.ora)
];
/**
* Reset $stmtId flag
*
* Used by storedProcedure() to prevent execute() from
* re-setting the statement ID.
*/
protected $resetStmtId = true;
/**
* Statement ID
*
* @var resource
*/
protected $stmtId;
/**
* Commit mode flag
*
* @used-by PreparedQuery::_execute()
*
* @var int
*/
public $commitMode = OCI_COMMIT_ON_SUCCESS;
/**
* Cursor ID
*
* @var resource
*/
protected $cursorId;
/**
* Latest inserted table name.
*
* @used-by PreparedQuery::_execute()
*
* @var string|null
*/
public $lastInsertedTableName;
/**
* confirm DNS format.
*/
private function isValidDSN(): bool
{
foreach ($this->validDSNs as $regexp) {
if (preg_match($regexp, $this->DSN)) {
return true;
}
}
return false;
}
/**
* Connect to the database.
*
* @return mixed
*/
public function connect(bool $persistent = false)
{
if (empty($this->DSN) && ! $this->isValidDSN()) {
$this->buildDSN();
}
$func = $persistent ? 'oci_pconnect' : 'oci_connect';
return empty($this->charset)
? $func($this->username, $this->password, $this->DSN)
: $func($this->username, $this->password, $this->DSN, $this->charset);
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
if (is_resource($this->cursorId)) {
oci_free_statement($this->cursorId);
}
if (is_resource($this->stmtId)) {
oci_free_statement($this->stmtId);
}
oci_close($this->connID);
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
if (! $this->connID || ($versionString = oci_server_version($this->connID)) === false) {
return '';
}
if (preg_match('#Release\s(\d+(?:\.\d+)+)#', $versionString, $match)) {
return $this->dataCache['version'] = $match[1];
}
return '';
}
/**
* Executes the query against the database.
*
* @return bool
*/
protected function execute(string $sql)
{
try {
if ($this->resetStmtId === true) {
$this->stmtId = oci_parse($this->connID, $sql);
}
oci_set_prefetch($this->stmtId, 1000);
$result = oci_execute($this->stmtId, $this->commitMode) ? $this->stmtId : false;
$insertTableName = $this->parseInsertTableName($sql);
if ($result && $insertTableName !== '') {
$this->lastInsertedTableName = $insertTableName;
}
return $result;
} catch (ErrorException $e) {
log_message('error', (string) $e);
if ($this->DBDebug) {
throw $e;
}
}
return false;
}
/**
* Get the table name for the insert statement from sql.
*/
public function parseInsertTableName(string $sql): string
{
$commentStrippedSql = preg_replace(['/\/\*(.|\n)*?\*\//m', '/--.+/'], '', $sql);
$isInsertQuery = strpos(strtoupper(ltrim($commentStrippedSql)), 'INSERT') === 0;
if (! $isInsertQuery) {
return '';
}
preg_match('/(?is)\b(?:into)\s+("?\w+"?)/', $commentStrippedSql, $match);
$tableName = $match[1] ?? '';
return strpos($tableName, '"') === 0 ? trim($tableName, '"') : strtoupper($tableName);
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
return oci_num_rows($this->stmtId);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
$sql = 'SELECT "TABLE_NAME" FROM "USER_TABLES"';
if ($tableName !== null) {
return $sql . ' WHERE "TABLE_NAME" LIKE ' . $this->escape($tableName);
}
if ($prefixLimit !== false && $this->DBPrefix !== '') {
return $sql . ' WHERE "TABLE_NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . "%' "
. sprintf($this->likeEscapeStr, $this->likeEscapeChar);
}
return $sql;
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*/
protected function _listColumns(string $table = ''): string
{
if (strpos($table, '.') !== false) {
sscanf($table, '%[^.].%s', $owner, $table);
} else {
$owner = $this->username;
}
return 'SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS
WHERE UPPER(OWNER) = ' . $this->escape(strtoupper($owner)) . '
AND UPPER(TABLE_NAME) = ' . $this->escape(strtoupper($this->DBPrefix . $table));
}
/**
* Returns an array of objects with field data
*
* @return stdClass[]
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
if (strpos($table, '.') !== false) {
sscanf($table, '%[^.].%s', $owner, $table);
} else {
$owner = $this->username;
}
$sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHAR_LENGTH, DATA_PRECISION, DATA_LENGTH, DATA_DEFAULT, NULLABLE
FROM ALL_TAB_COLUMNS
WHERE UPPER(OWNER) = ' . $this->escape(strtoupper($owner)) . '
AND UPPER(TABLE_NAME) = ' . $this->escape(strtoupper($table));
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
$retval = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$length = $query[$i]->CHAR_LENGTH > 0 ? $query[$i]->CHAR_LENGTH : $query[$i]->DATA_PRECISION;
$length ??= $query[$i]->DATA_LENGTH;
$retval[$i]->max_length = $length;
$default = $query[$i]->DATA_DEFAULT;
if ($default === null && $query[$i]->NULLABLE === 'N') {
$default = '';
}
$retval[$i]->default = $default;
$retval[$i]->nullable = $query[$i]->NULLABLE === 'Y';
}
return $retval;
}
/**
* Returns an array of objects with index data
*
* @return stdClass[]
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
if (strpos($table, '.') !== false) {
sscanf($table, '%[^.].%s', $owner, $table);
} else {
$owner = $this->username;
}
$sql = 'SELECT AIC.INDEX_NAME, UC.CONSTRAINT_TYPE, AIC.COLUMN_NAME '
. ' FROM ALL_IND_COLUMNS AIC '
. ' LEFT JOIN USER_CONSTRAINTS UC ON AIC.INDEX_NAME = UC.CONSTRAINT_NAME AND AIC.TABLE_NAME = UC.TABLE_NAME '
. 'WHERE AIC.TABLE_NAME = ' . $this->escape(strtolower($table)) . ' '
. 'AND AIC.TABLE_OWNER = ' . $this->escape(strtoupper($owner)) . ' '
. ' ORDER BY UC.CONSTRAINT_TYPE, AIC.COLUMN_POSITION';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$retVal = [];
$constraintTypes = [
'P' => 'PRIMARY',
'U' => 'UNIQUE',
];
foreach ($query as $row) {
if (isset($retVal[$row->INDEX_NAME])) {
$retVal[$row->INDEX_NAME]->fields[] = $row->COLUMN_NAME;
continue;
}
$retVal[$row->INDEX_NAME] = new stdClass();
$retVal[$row->INDEX_NAME]->name = $row->INDEX_NAME;
$retVal[$row->INDEX_NAME]->fields = [$row->COLUMN_NAME];
$retVal[$row->INDEX_NAME]->type = $constraintTypes[$row->CONSTRAINT_TYPE] ?? 'INDEX';
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
*
* @return stdClass[]
*
* @throws DatabaseException
*/
protected function _foreignKeyData(string $table): array
{
$sql = 'SELECT
acc.constraint_name,
acc.table_name,
acc.column_name,
ccu.table_name foreign_table_name,
accu.column_name foreign_column_name
FROM all_cons_columns acc
JOIN all_constraints ac
ON acc.owner = ac.owner
AND acc.constraint_name = ac.constraint_name
JOIN all_constraints ccu
ON ac.r_owner = ccu.owner
AND ac.r_constraint_name = ccu.constraint_name
JOIN all_cons_columns accu
ON accu.constraint_name = ccu.constraint_name
AND accu.table_name = ccu.table_name
WHERE ac.constraint_type = ' . $this->escape('R') . '
AND acc.table_name = ' . $this->escape($table);
$query = $this->query($sql);
if ($query === false) {
throw new DatabaseException(lang('Database.failGetForeignKeyData'));
}
$query = $query->getResultObject();
$retVal = [];
foreach ($query as $row) {
$obj = new stdClass();
$obj->constraint_name = $row->CONSTRAINT_NAME;
$obj->table_name = $row->TABLE_NAME;
$obj->column_name = $row->COLUMN_NAME;
$obj->foreign_table_name = $row->FOREIGN_TABLE_NAME;
$obj->foreign_column_name = $row->FOREIGN_COLUMN_NAME;
$retVal[] = $obj;
}
return $retVal;
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return <<<'SQL'
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND c.constraint_type = 'R'
AND t.iot_type IS NULL
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint "' || c.constraint_name || '"');
END LOOP;
END;
SQL;
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return <<<'SQL'
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
AND c.constraint_type = 'R'
AND t.iot_type IS NULL
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint "' || c.constraint_name || '"');
END LOOP;
END;
SQL;
}
/**
* Get cursor. Returns a cursor from the database
*
* @return resource
*/
public function getCursor()
{
return $this->cursorId = oci_new_cursor($this->connID);
}
/**
* Executes a stored procedure
*
* @param string $procedureName procedure name to execute
* @param array $params params array keys
* KEY OPTIONAL NOTES
* name no the name of the parameter should be in :<param_name> format
* value no the value of the parameter. If this is an OUT or IN OUT parameter,
* this should be a reference to a variable
* type yes the type of the parameter
* length yes the max size of the parameter
*
* @return bool|Query|Result
*/
public function storedProcedure(string $procedureName, array $params)
{
if ($procedureName === '') {
throw new DatabaseException(lang('Database.invalidArgument', [$procedureName]));
}
// Build the query string
$sql = sprintf(
'BEGIN %s (' . substr(str_repeat(',%s', count($params)), 1) . '); END;',
$procedureName,
...array_map(static fn ($row) => $row['name'], $params)
);
$this->resetStmtId = false;
$this->stmtId = oci_parse($this->connID, $sql);
$this->bindParams($params);
$result = $this->query($sql);
$this->resetStmtId = true;
return $result;
}
/**
* Bind parameters
*
* @param array $params
*
* @return void
*/
protected function bindParams($params)
{
if (! is_array($params) || ! is_resource($this->stmtId)) {
return;
}
foreach ($params as $param) {
oci_bind_by_name(
$this->stmtId,
$param['name'],
$param['value'],
$param['length'] ?? -1,
$param['type'] ?? SQLT_CHR
);
}
}
/**
* Returns the last error code and message.
*
* Must return an array with keys 'code' and 'message':
*
* return ['code' => null, 'message' => null);
*/
public function error(): array
{
// oci_error() returns an array that already contains
// 'code' and 'message' keys, but it can return false
// if there was no error ....
$error = oci_error();
$resources = [$this->cursorId, $this->stmtId, $this->connID];
foreach ($resources as $resource) {
if (is_resource($resource)) {
$error = oci_error($resource);
break;
}
}
return is_array($error)
? $error
: [
'code' => '',
'message' => '',
];
}
public function insertID(): int
{
if (empty($this->lastInsertedTableName)) {
return 0;
}
$indexs = $this->getIndexData($this->lastInsertedTableName);
$fieldDatas = $this->getFieldData($this->lastInsertedTableName);
if (! $indexs || ! $fieldDatas) {
return 0;
}
$columnTypeList = array_column($fieldDatas, 'type', 'name');
$primaryColumnName = '';
foreach ($indexs as $index) {
if ($index->type !== 'PRIMARY' || count($index->fields) !== 1) {
continue;
}
$primaryColumnName = $this->protectIdentifiers($index->fields[0], false, false);
$primaryColumnType = $columnTypeList[$primaryColumnName];
if ($primaryColumnType !== 'NUMBER') {
$primaryColumnName = '';
}
}
if (! $primaryColumnName) {
return 0;
}
$query = $this->query('SELECT DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?', [$this->lastInsertedTableName, $primaryColumnName])->getRow();
$lastInsertValue = str_replace('nextval', 'currval', $query->DATA_DEFAULT ?? '0');
$query = $this->query(sprintf('SELECT %s SEQ FROM DUAL', $lastInsertValue))->getRow();
return (int) ($query->SEQ ?? 0);
}
/**
* Build a DSN from the provided parameters
*
* @return void
*/
protected function buildDSN()
{
if ($this->DSN !== '') {
$this->DSN = '';
}
// Legacy support for TNS in the hostname configuration field
$this->hostname = str_replace(["\n", "\r", "\t", ' '], '', $this->hostname);
if (preg_match($this->validDSNs['tns'], $this->hostname)) {
$this->DSN = $this->hostname;
return;
}
$isEasyConnectableHostName = $this->hostname !== '' && strpos($this->hostname, '/') === false && strpos($this->hostname, ':') === false;
$easyConnectablePort = ! empty($this->port) && ctype_digit($this->port) ? ':' . $this->port : '';
$easyConnectableDatabase = $this->database !== '' ? '/' . ltrim($this->database, '/') : '';
if ($isEasyConnectableHostName && ($easyConnectablePort !== '' || $easyConnectableDatabase !== '')) {
/* If the hostname field isn't empty, doesn't contain
* ':' and/or '/' and if port and/or database aren't
* empty, then the hostname field is most likely indeed
* just a hostname. Therefore we'll try and build an
* Easy Connect string from these 3 settings, assuming
* that the database field is a service name.
*/
$this->DSN = $this->hostname . $easyConnectablePort . $easyConnectableDatabase;
if (preg_match($this->validDSNs['ec'], $this->DSN)) {
return;
}
}
/* At this point, we can only try and validate the hostname and
* database fields separately as DSNs.
*/
if (preg_match($this->validDSNs['ec'], $this->hostname) || preg_match($this->validDSNs['in'], $this->hostname)) {
$this->DSN = $this->hostname;
return;
}
$this->database = str_replace(["\n", "\r", "\t", ' '], '', $this->database);
foreach ($this->validDSNs as $regexp) {
if (preg_match($regexp, $this->database)) {
return;
}
}
/* Well - OK, an empty string should work as well.
* PHP will try to use environment variables to
* determine which Oracle instance to connect to.
*/
$this->DSN = '';
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
$this->commitMode = OCI_NO_AUTO_COMMIT;
return true;
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
$this->commitMode = OCI_COMMIT_ON_SUCCESS;
return oci_commit($this->connID);
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
$this->commitMode = OCI_COMMIT_ON_SUCCESS;
return oci_rollback($this->connID);
}
/**
* Returns the name of the current database being used.
*/
public function getDatabase(): string
{
if (! empty($this->database)) {
return $this->database;
}
return $this->query('SELECT DEFAULT_TABLESPACE FROM USER_USERS')->getRow()->DEFAULT_TABLESPACE ?? '';
}
/**
* Get the prefix of the function to access the DB.
*/
protected function getDriverFunctionPrefix(): string
{
return 'oci_';
}
}
+303
View File
@@ -0,0 +1,303 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for OCI8
*/
class Forge extends BaseForge
{
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr = 'DROP INDEX %s';
/**
* CREATE DATABASE statement
*
* @var false
*/
protected $createDatabaseStr = false;
/**
* CREATE TABLE IF statement
*
* @var false
*
* @deprecated This is no longer used.
*/
protected $createTableIfStr = false;
/**
* DROP TABLE IF EXISTS statement
*
* @var false
*/
protected $dropTableIfStr = false;
/**
* DROP DATABASE statement
*
* @var false
*/
protected $dropDatabaseStr = false;
/**
* UNSIGNED support
*
* @var array|bool
*/
protected $unsigned = false;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $null = 'NULL';
/**
* RENAME TABLE statement
*
* @var string
*/
protected $renameTableStr = 'ALTER TABLE %s RENAME TO %s';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr = 'ALTER TABLE %s DROP CONSTRAINT %s';
/**
* ALTER TABLE
*
* @param string $alterType ALTER type
* @param string $table Table name
* @param array|string $field Column definition
*
* @return string|string[]
*/
protected function _alterTable(string $alterType, string $table, $field)
{
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
if ($alterType === 'DROP') {
$fields = array_map(fn ($field) => $this->db->escapeIdentifiers(trim($field)), is_string($field) ? explode(',', $field) : $field);
return $sql . ' DROP (' . implode(',', $fields) . ') CASCADE CONSTRAINT INVALIDATE';
}
if ($alterType === 'CHANGE') {
$alterType = 'MODIFY';
}
$nullableMap = array_column($this->db->getFieldData($table), 'nullable', 'name');
$sqls = [];
for ($i = 0, $c = count($field); $i < $c; $i++) {
if ($alterType === 'MODIFY') {
// If a null constraint is added to a column with a null constraint,
// ORA-01451 will occur,
// so add null constraint is used only when it is different from the current null constraint.
$isWantToAddNull = strpos($field[$i]['null'], ' NOT') === false;
$currentNullAddable = $nullableMap[$field[$i]['name']];
if ($isWantToAddNull === $currentNullAddable) {
$field[$i]['null'] = '';
}
}
if ($field[$i]['_literal'] !== false) {
$field[$i] = "\n\t" . $field[$i]['_literal'];
} else {
$field[$i]['_literal'] = "\n\t" . $this->_processColumn($field[$i]);
if (! empty($field[$i]['comment'])) {
$sqls[] = 'COMMENT ON COLUMN '
. $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($field[$i]['name'])
. ' IS ' . $field[$i]['comment'];
}
if ($alterType === 'MODIFY' && ! empty($field[$i]['new_name'])) {
$sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($field[$i]['name'])
. ' TO ' . $this->db->escapeIdentifiers($field[$i]['new_name']);
}
$field[$i] = "\n\t" . $field[$i]['_literal'];
}
}
$sql .= ' ' . $alterType . ' ';
$sql .= count($field) === 1
? $field[0]
: '(' . implode(',', $field) . ')';
// RENAME COLUMN must be executed after MODIFY
array_unshift($sqls, $sql);
return $sqls;
}
/**
* Field attribute AUTO_INCREMENT
*
* @return void
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true
&& stripos($field['type'], 'NUMBER') !== false
&& version_compare($this->db->getVersion(), '12.1', '>=')
) {
$field['auto_increment'] = ' GENERATED BY DEFAULT AS IDENTITY';
}
}
/**
* Process column
*/
protected function _processColumn(array $field): string
{
$constraint = '';
// @todo: cant cover multi pattern when set type.
if ($field['type'] === 'VARCHAR2' && strpos($field['length'], "('") === 0) {
$constraint = ' CHECK(' . $this->db->escapeIdentifiers($field['name'])
. ' IN ' . $field['length'] . ')';
$field['length'] = '(' . max(array_map('mb_strlen', explode("','", mb_substr($field['length'], 2, -2)))) . ')' . $constraint;
} elseif (count($this->primaryKeys) === 1 && $field['name'] === $this->primaryKeys[0]) {
$field['unique'] = '';
}
return $this->db->escapeIdentifiers($field['name'])
. ' ' . $field['type'] . $field['length']
. $field['unsigned']
. $field['default']
. $field['auto_increment']
. $field['null']
. $field['unique'];
}
/**
* Performs a data type mapping between different databases.
*
* @return void
*/
protected function _attributeType(array &$attributes)
{
// Reset field lengths for data types that don't support it
// Usually overridden by drivers
switch (strtoupper($attributes['TYPE'])) {
case 'TINYINT':
$attributes['CONSTRAINT'] ??= 3;
// no break
case 'SMALLINT':
$attributes['CONSTRAINT'] ??= 5;
// no break
case 'MEDIUMINT':
$attributes['CONSTRAINT'] ??= 7;
// no break
case 'INT':
case 'INTEGER':
$attributes['CONSTRAINT'] ??= 11;
// no break
case 'BIGINT':
$attributes['CONSTRAINT'] ??= 19;
// no break
case 'NUMERIC':
$attributes['TYPE'] = 'NUMBER';
return;
case 'BOOLEAN':
$attributes['TYPE'] = 'NUMBER';
$attributes['CONSTRAINT'] = 1;
$attributes['UNSIGNED'] = true;
$attributes['NULL'] = false;
return;
case 'DOUBLE':
$attributes['TYPE'] = 'FLOAT';
$attributes['CONSTRAINT'] ??= 126;
return;
case 'DATETIME':
case 'TIME':
$attributes['TYPE'] = 'DATE';
return;
case 'SET':
case 'ENUM':
case 'VARCHAR':
$attributes['CONSTRAINT'] ??= 255;
// no break
case 'TEXT':
case 'MEDIUMTEXT':
$attributes['CONSTRAINT'] ??= 4000;
$attributes['TYPE'] = 'VARCHAR2';
}
}
/**
* Generates a platform-specific DROP TABLE string
*
* @return bool|string
*/
protected function _dropTable(string $table, bool $ifExists, bool $cascade)
{
$sql = parent::_dropTable($table, $ifExists, $cascade);
if ($sql !== true && $cascade === true) {
$sql .= ' CASCADE CONSTRAINTS PURGE';
} elseif ($sql !== true) {
$sql .= ' PURGE';
}
return $sql;
}
protected function _processForeignKeys(string $table): string
{
$sql = '';
$allowActions = [
'CASCADE',
'SET NULL',
'NO ACTION',
];
foreach ($this->foreignKeys as $fkey) {
$nameIndex = $table . '_' . implode('_', $fkey['field']) . '_fk';
$nameIndexFilled = $this->db->escapeIdentifiers($nameIndex);
$foreignKeyFilled = implode(', ', $this->db->escapeIdentifiers($fkey['field']));
$referenceTableFilled = $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['referenceTable']);
$referenceFieldFilled = implode(', ', $this->db->escapeIdentifiers($fkey['referenceField']));
$formatSql = ",\n\tCONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s)";
$sql .= sprintf($formatSql, $nameIndexFilled, $foreignKeyFilled, $referenceTableFilled, $referenceFieldFilled);
if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) {
$sql .= ' ON DELETE ' . $fkey['onDelete'];
}
}
return $sql;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use BadMethodCallException;
use CodeIgniter\Database\BasePreparedQuery;
/**
* Prepared query for OCI8
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* A reference to the db connection to use.
*
* @var Connection
*/
protected $db;
/**
* Latest inserted table name.
*/
private ?string $lastInsertTableName = null;
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Passed to the connection's prepare statement.
* Unused in the OCI8 driver.
*
* @return mixed
*/
public function _prepare(string $sql, array $options = [])
{
if (! $this->statement = oci_parse($this->db->connID, $this->parameterize($sql))) {
$error = oci_error($this->db->connID);
$this->errorCode = $error['code'] ?? 0;
$this->errorString = $error['message'] ?? '';
}
$this->lastInsertTableName = $this->db->parseInsertTableName($sql);
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*/
public function _execute(array $data): bool
{
if (null === $this->statement) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
$lastKey = 0;
foreach (array_keys($data) as $key) {
oci_bind_by_name($this->statement, ':' . $key, $data[$key]);
$lastKey = $key;
}
$result = oci_execute($this->statement, $this->db->commitMode);
if ($result && $this->lastInsertTableName !== '') {
$this->db->lastInsertedTableName = $this->lastInsertTableName;
}
return $result;
}
/**
* Returns the result object for the prepared query.
*
* @return mixed
*/
public function _getResult()
{
return $this->statement;
}
/**
* Replaces the ? placeholders with :0, :1, etc parameters for use
* within the prepared query.
*/
public function parameterize(string $sql): string
{
// Track our current value
$count = 0;
return preg_replace_callback('/\?/', static function ($matches) use (&$count) {
return ':' . ($count++);
}, $sql);
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Entity\Entity;
/**
* Result for OCI8
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return oci_num_fields($this->resultID);
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
return array_map(fn ($fieldIndex) => oci_field_name($this->resultID, $fieldIndex), range(1, $this->getFieldCount()));
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
return array_map(fn ($fieldIndex) => (object) [
'name' => oci_field_name($this->resultID, $fieldIndex),
'type' => oci_field_type($this->resultID, $fieldIndex),
'max_length' => oci_field_size($this->resultID, $fieldIndex),
], range(1, $this->getFieldCount()));
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if (is_resource($this->resultID)) {
oci_free_statement($this->resultID);
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return false
*/
public function dataSeek(int $n = 0)
{
// We can't support data seek by oci
return false;
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return mixed
*/
protected function fetchAssoc()
{
return oci_fetch_assoc($this->resultID);
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return bool|Entity|object
*/
protected function fetchObject(string $className = 'stdClass')
{
$row = oci_fetch_object($this->resultID);
if ($className === 'stdClass' || ! $row) {
return $row;
}
if (is_subclass_of($className, Entity::class)) {
return (new $className())->setAttributes((array) $row);
}
$instance = new $className();
foreach (get_object_vars($row) as $key => $value) {
$instance->{$key} = $value;
}
return $instance;
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Database\OCI8;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for OCI8
*/
class Utils extends BaseUtils
{
/**
* List databases statement
*
* @var string
*/
protected $listDatabases = 'SELECT TABLESPACE_NAME FROM USER_TABLESPACES';
/**
* Platform dependent version of the backup function.
*
* @return mixed
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}