Files
Testbed/app/Database/Db2/Db2SchemaBuilder.php
T
2026-11-11 13:18:47 +00:00

281 lines
8.8 KiB
PHP

<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (! $schema || ! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"'.str_replace('"', '""', $schema).'"."'.
str_replace('"', '""', trim($name)).'"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (! is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' => '"'.str_replace('"', '""', $schema).
'"."'.str_replace('"', '""', $name).'"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO, CAST(COALESCE(\"DEFAULT\", '') AS VARCHAR(4096)) AS COLDEFAULT,
CASE WHEN \"DEFAULT\" IS NULL THEN 'Y' ELSE 'N' END AS NO_DEFAULT
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$typeName = trim($row->TYPENAME);
$type = $typeName === 'CHARACTER' ? 'CHAR' : $typeName;
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '('.(int) $row->LENGTH.')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '('.(int) $row->LENGTH.','.(int) $row->SCALE.')';
} elseif (strtoupper($type) === 'TIMESTAMP') {
$type .= '('.(int) $row->SCALE.')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => $row->NO_DEFAULT === 'Y' ? null : trim($row->COLDEFAULT),
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
'SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ',
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (! isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
'SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.CONSTNAME = R.REFKEYNAME
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ',
[$schema, $table]
);
$rules = ['A' => 'no action', 'C' => 'cascade', 'N' => 'set null', 'R' => 'restrict'];
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (! isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => $rules[trim($row->UPDATERULE)] ?? trim($row->UPDATERULE),
'on_delete' => $rules[trim($row->DELETERULE)] ?? trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}