first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-08-17 17:19:25 -04:00
commit 27aeffcfa3
904 changed files with 239087 additions and 0 deletions
+526
View File
@@ -0,0 +1,526 @@
<?php
declare(strict_types=1);
/**
* 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;
use CodeIgniter\Database\RawSql;
/**
* 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
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$insertKeys = implode(', ', $keys);
$hasPrimaryKey = in_array('PRIMARY', array_column($this->db->getIndexData($table), 'type'), true);
// ORA-00001 measures
$sql = 'INSERT' . ($hasPrimaryKey ? '' : ' ALL') . ' INTO ' . $table . ' (' . $insertKeys . ")\n{:_table_:}";
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value) => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index) => $index . ' ' . $key,
$keys,
$value
)),
$values
)
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* 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 ($limit !== null && $limit !== 0) {
$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 !== 0 ? ' 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();
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.');
}
return ''; // @codeCoverageIgnore
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$alias = $this->QBOptions['alias'] ?? '"_u"';
// Oracle doesn't support ignore on updates so we will use MERGE
$sql = 'MERGE INTO ' . $table . "\n";
$sql .= "USING (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'ON (' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints
)
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE\n";
$sql .= "SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value) => $table . '.' . $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $alias . '.' . $value),
array_keys($updateFields),
$updateFields
)
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value) => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index) => $index . ' ' . $key,
$keys,
$value
)) . ' FROM DUAL',
$values
)
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if (empty($constraints)) {
$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' || $index->type === 'UNIQUE') && $hasAllFields;
});
// only take first index
foreach ($uniqueIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '"_upsert"';
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
$sql = 'MERGE INTO ' . $table . "\nUSING (\n{:_table_:}";
$sql .= ") {$alias}\nON (";
$sql .= implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints
)
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value) => $key . ($value instanceof RawSql ?
" = {$value}" :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields
)
);
$sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES ";
$sql .= (' ('
. implode(', ', array_map(static fn ($columnName) => "{$alias}.{$columnName}", $keys))
. ')');
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value) => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index) => $index . ' ' . $key,
$keys,
$value
)),
$values
)
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _deleteBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '_u';
$sql = 'DELETE ' . $table . "\n";
$sql .= "WHERE EXISTS (SELECT * FROM (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'WHERE ' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
$value instanceof RawSql ?
$value :
(
is_string($key) ?
$table . '.' . $key . ' = ' . $alias . '.' . $value :
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints
)
);
// convert binds in where
foreach ($this->QBWhere as $key => $where) {
foreach ($this->binds as $field => $bind) {
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
}
}
$sql .= ' ' . str_replace(
'WHERE ',
'AND ',
$this->compileWhereHaving('QBWhere')
) . ')';
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value) => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index) => $index . ' ' . $key,
$keys,
$value
)),
$values
)
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Gets column names from a select query
*/
protected function fieldsFromQuery(string $sql): array
{
return $this->db->query('SELECT * FROM (' . $sql . ') "_u_" WHERE ROWNUM = 1')->getFieldNames();
}
}
+744
View File
@@ -0,0 +1,744 @@
<?php
declare(strict_types=1);
/**
* 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
*
* @extends BaseConnection<resource, resource>
*/
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
'tns' => '/^\(DESCRIPTION=(\(.+\)){2,}\)$/',
// Easy Connect string (Oracle 10g+).
// https://docs.oracle.com/en/database/oracle/oracle-database/23/netag/configuring-naming-methods.html#GUID-36F3A17D-843C-490A-8A23-FB0FE005F8E8
// [//]host[:port][/[service_name][:server_type][/instance_name]]
'ec' => '/^
(\/\/)?
(\[)?[a-z0-9.:_-]+(\])? # Host or IP address
(:[1-9][0-9]{0,4})? # Port
(
(\/)
([a-z0-9.$_]+)? # Service name
(:[a-z]+)? # Server type
(\/[a-z0-9$_]+)? # Instance name
)?
$/ix',
// Instance name (defined in tnsnames.ora)
'in' => '/^[a-z0-9$_]+$/i',
];
/**
* 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 DSN format.
*/
private function isValidDSN(): bool
{
if ($this->DSN === null || $this->DSN === '') {
return false;
}
foreach ($this->validDSNs as $regexp) {
if (preg_match($regexp, $this->DSN)) {
return true;
}
}
return false;
}
/**
* Connect to the database.
*
* @return false|resource
*/
public function connect(bool $persistent = false)
{
if (! $this->isValidDSN()) {
$this->buildDSN();
}
$func = $persistent ? 'oci_pconnect' : 'oci_connect';
return ($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 false|resource
*/
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 new DatabaseException($e->getMessage(), $e->getCode(), $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 = str_starts_with(strtoupper(ltrim($commentStrippedSql)), 'INSERT');
if (! $isInsertQuery) {
return '';
}
preg_match('/(?is)\b(?:into)\s+("?\w+"?)/', $commentStrippedSql, $match);
$tableName = $match[1] ?? '';
return str_starts_with($tableName, '"') ? 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 (str_contains($table, '.')) {
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 list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
if (str_contains($table, '.')) {
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;
$retval[$i]->nullable = $query[$i]->NULLABLE === 'Y';
$retval[$i]->default = $query[$i]->DATA_DEFAULT;
}
return $retval;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
if (str_contains($table, '.')) {
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 array<string, 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,
ac.delete_rule
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.position = acc.position
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();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->CONSTRAINT_NAME]['constraint_name'] = $row->CONSTRAINT_NAME;
$indexes[$row->CONSTRAINT_NAME]['table_name'] = $row->TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['column_name'][] = $row->COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_table_name'] = $row->FOREIGN_TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_column_name'][] = $row->FOREIGN_COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['on_delete'] = $row->DELETE_RULE;
$indexes[$row->CONSTRAINT_NAME]['on_update'] = null;
$indexes[$row->CONSTRAINT_NAME]['match'] = null;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* 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 !== '' && ! str_contains($this->hostname, '/') && ! str_contains($this->hostname, ':');
$easyConnectablePort = ($this->port !== '') && ctype_digit((string) $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_';
}
}
+314
View File
@@ -0,0 +1,314 @@
<?php
declare(strict_types=1);
/**
* 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';
/**
* Foreign Key Allowed Actions
*
* @var array
*/
protected $fkAllowActions = ['CASCADE', 'SET NULL', 'NO ACTION'];
/**
* ALTER TABLE
*
* @param string $alterType ALTER type
* @param string $table Table name
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return list<string>|string SQL string
* @phpstan-return ($alterType is 'DROP' ? string : list<string>)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
if ($alterType === 'DROP') {
$columnNamesToDrop = $processedFields;
$fields = array_map(
fn ($field) => $this->db->escapeIdentifiers(trim($field)),
is_string($columnNamesToDrop) ? explode(',', $columnNamesToDrop) : $columnNamesToDrop
);
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($processedFields); $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.
// If a not null constraint is added to a column with a not null constraint,
// ORA-01442 will occur.
$wantToAddNull = ! str_contains($processedFields[$i]['null'], ' NOT');
$currentNullable = $nullableMap[$processedFields[$i]['name']];
if ($wantToAddNull === true && $currentNullable === true) {
$processedFields[$i]['null'] = '';
} elseif ($processedFields[$i]['null'] === '' && $currentNullable === false) {
// Nullable by default
$processedFields[$i]['null'] = ' NULL';
} elseif ($wantToAddNull === false && $currentNullable === false) {
$processedFields[$i]['null'] = '';
}
}
if ($processedFields[$i]['_literal'] !== false) {
$processedFields[$i] = "\n\t" . $processedFields[$i]['_literal'];
} else {
$processedFields[$i]['_literal'] = "\n\t" . $this->_processColumn($processedFields[$i]);
if (! empty($processedFields[$i]['comment'])) {
$sqls[] = 'COMMENT ON COLUMN '
. $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($processedFields[$i]['name'])
. ' IS ' . $processedFields[$i]['comment'];
}
if ($alterType === 'MODIFY' && ! empty($processedFields[$i]['new_name'])) {
$sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($processedFields[$i]['name'])
. ' TO ' . $this->db->escapeIdentifiers($processedFields[$i]['new_name']);
}
$processedFields[$i] = "\n\t" . $processedFields[$i]['_literal'];
}
}
$sql .= ' ' . $alterType . ' ';
$sql .= count($processedFields) === 1
? $processedFields[0]
: '(' . implode(',', $processedFields) . ')';
// 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 ON NULL AS IDENTITY';
}
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
$constraint = '';
// @todo: can't cover multi pattern when set type.
if ($processedField['type'] === 'VARCHAR2' && str_starts_with($processedField['length'], "('")) {
$constraint = ' CHECK(' . $this->db->escapeIdentifiers($processedField['name'])
. ' IN ' . $processedField['length'] . ')';
$processedField['length'] = '(' . max(array_map(mb_strlen(...), explode("','", mb_substr($processedField['length'], 2, -2)))) . ')' . $constraint;
} elseif (isset($this->primaryKeys['fields']) && count($this->primaryKeys['fields']) === 1 && $processedField['name'] === $this->primaryKeys['fields'][0]) {
$processedField['unique'] = '';
}
return $this->db->escapeIdentifiers($processedField['name'])
. ' ' . $processedField['type'] . $processedField['length']
. $processedField['unsigned']
. $processedField['default']
. $processedField['auto_increment']
. $processedField['null']
. $processedField['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;
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;
}
/**
* Constructs sql to check if key is a constraint.
*/
protected function _dropKeyAsConstraint(string $table, string $constraintName): string
{
return "SELECT constraint_name FROM all_constraints WHERE table_name = '"
. trim($table, '"') . "' AND index_name = '"
. trim($constraintName, '"') . "'";
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
/**
* 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;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Prepared query for OCI8
*
* @extends BasePreparedQuery<resource, resource, resource>
*/
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.
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
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'] ?? '';
if ($this->db->DBDebug) {
throw new DatabaseException($this->errorString . ' code: ' . $this->errorCode);
}
}
$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 (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
foreach (array_keys($data) as $key) {
oci_bind_by_name($this->statement, ':' . $key, $data[$key]);
}
$result = oci_execute($this->statement, $this->db->commitMode);
if ($result && $this->lastInsertTableName !== '') {
$this->db->lastInsertedTableName = $this->lastInsertTableName;
}
return $result;
}
/**
* Returns the statement resource for the prepared query or false when preparing failed.
*
* @return resource|null
*/
public function _getResult()
{
return $this->statement;
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return oci_free_statement($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);
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
/**
* 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;
use stdClass;
/**
* Result for OCI8
*
* @extends BaseResult<resource, resource>
*/
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 array|false
*/
protected function fetchAssoc()
{
return oci_fetch_assoc($this->resultID);
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return Entity|false|object|stdClass
*/
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())->injectRawData((array) $row);
}
$instance = new $className();
foreach (get_object_vars($row) as $key => $value) {
$instance->{$key} = $value;
}
return $instance;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* 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 never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}