db2 driver updates
This commit is contained in:
@@ -37,3 +37,23 @@ and Laravel migration registration and rollback.
|
||||
- Migration batch lookup casts query-builder `max('batch')` results to text so
|
||||
Laravel can perform numeric arithmetic through PDO_ODBC. This applies to custom
|
||||
migration history table names as well.
|
||||
|
||||
|
||||
## Phase 7 data types and indexes
|
||||
|
||||
- `char(length)` creates a fixed-width Db2 character column. `uuid()` uses
|
||||
`CHAR(36)` and leaves UUID validation and generation to the application.
|
||||
- `time()` uses Db2 TIME at whole-second precision. Fractional TIME precision
|
||||
raises an exception. Timestamp and datetime definitions accept Db2
|
||||
fractional-second precision, and the catalog reports it for TIMESTAMP.
|
||||
- `renameIndex()` uses Db2's same-schema rename for an application-created
|
||||
index. It preserves key order and uniqueness. Db2 requires the target name
|
||||
to be available in that schema.
|
||||
- Time-zone-aware column types, binary UUID storage, expression indexes,
|
||||
and automatic REORG remain outside the verified scope.
|
||||
|
||||
Run the focused live tests with:
|
||||
|
||||
```sh
|
||||
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/SchemaTypesAndIndexesTest.php
|
||||
```
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Db2 LUW schema and migrations
|
||||
|
||||
The Stage 5 tests use the configured `db2_local` connection. They create randomly named
|
||||
tables and a separate migration history table, then remove them. A skipped test means
|
||||
the connection was unavailable and provides no Db2 verification.
|
||||
|
||||
```sh
|
||||
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/SchemaTest.php
|
||||
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2
|
||||
APP_ENV=testing php artisan test --do-not-cache-result
|
||||
```
|
||||
|
||||
The tests cover table creation, same-schema rename, conditional drop, adding and
|
||||
dropping columns, widening VARCHAR, catalog defaults and identity metadata, composite
|
||||
ordinary and unique index metadata and removal, foreign-key metadata and removal,
|
||||
and Laravel migration registration and rollback.
|
||||
|
||||
## Limits
|
||||
|
||||
- Db2 applies its own rules to type conversions and dependent objects. Table
|
||||
renames require the source and target to be in the same schema. Tables with
|
||||
certain dependencies, including referential constraints, cannot be renamed.
|
||||
- Dropping columns and some type or nullability changes can leave a table in
|
||||
REORG-pending state. The driver does not run administrative utilities. Arrange
|
||||
for a Db2 administrator to run REORG before subsequent operations that require it.
|
||||
- Changing an identity column through Laravel's `change()` is unsupported.
|
||||
Unsigned types, column positioning, expression indexes, full-text indexes
|
||||
and spatial indexes are outside this implementation.
|
||||
- Laravel `unique()` creates a Db2 unique index. Db2 foreign keys require a
|
||||
referenced primary key or unique constraint. A standalone unique index does
|
||||
not establish that constraint. Foreign-key actions must be supported by Db2
|
||||
for the chosen operation.
|
||||
- Column defaults are returned as SQL expressions from the catalog. Catalog
|
||||
output does not reconstruct generated expressions or every Db2 type attribute.
|
||||
- Laravel migration rollback runs `down()` and removes its history entry.
|
||||
The driver does not advertise transactional schema migrations.
|
||||
- Migration batch lookup casts query-builder `max('batch')` results to text so
|
||||
Laravel can perform numeric arithmetic through PDO_ODBC. This applies to custom
|
||||
migration history table names as well.
|
||||
@@ -136,12 +136,15 @@ class Db2SchemaBuilder extends Builder
|
||||
);
|
||||
|
||||
return array_map(static function ($row) {
|
||||
$type = trim($row->TYPENAME);
|
||||
$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 [
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
<?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) {
|
||||
$type = trim($row->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 . ')';
|
||||
}
|
||||
|
||||
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, '"'),
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
<?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) {
|
||||
$type = trim($row->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, '"'),
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -59,7 +59,7 @@ class Db2SchemaGrammar extends Grammar
|
||||
$type = $this->getType($column);
|
||||
$statements = [];
|
||||
|
||||
if (strcasecmp($current['type'], $type) !== 0) {
|
||||
if (strcasecmp($current['type'], $type === 'TIMESTAMP' ? 'TIMESTAMP(6)' : $type) !== 0) {
|
||||
$statements[] = $prefix.' SET DATA TYPE '.$type;
|
||||
}
|
||||
if ($current['nullable'] !== (bool) $column->nullable) {
|
||||
@@ -128,6 +128,12 @@ class Db2SchemaGrammar extends Grammar
|
||||
return 'DROP INDEX '.$this->wrapIndex($blueprint, $command->index);
|
||||
}
|
||||
|
||||
public function compileRenameIndex(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'RENAME INDEX '.$this->wrapIndex($blueprint, $command->from)
|
||||
.' TO '.$this->wrapValue($command->to);
|
||||
}
|
||||
|
||||
private function wrapIndex(Blueprint $blueprint, string $name): string
|
||||
{
|
||||
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
|
||||
@@ -172,6 +178,25 @@ class Db2SchemaGrammar extends Grammar
|
||||
return 'VARCHAR(' . ($column->length ?: 255) . ')';
|
||||
}
|
||||
|
||||
protected function typeChar(Fluent $column)
|
||||
{
|
||||
return 'CHAR('.$column->length.')';
|
||||
}
|
||||
|
||||
protected function typeUuid(Fluent $column)
|
||||
{
|
||||
return 'CHAR(36)';
|
||||
}
|
||||
|
||||
protected function typeTime(Fluent $column)
|
||||
{
|
||||
if ($column->precision !== null && $column->precision !== 0) {
|
||||
throw new \InvalidArgumentException('Db2 TIME does not support fractional-second precision.');
|
||||
}
|
||||
|
||||
return 'TIME';
|
||||
}
|
||||
|
||||
protected function typeText(Fluent $column)
|
||||
{
|
||||
return 'CLOB(1M)';
|
||||
@@ -189,12 +214,12 @@ class Db2SchemaGrammar extends Grammar
|
||||
|
||||
protected function typeTimestamp(Fluent $column)
|
||||
{
|
||||
return 'TIMESTAMP';
|
||||
return $column->precision === null ? 'TIMESTAMP' : 'TIMESTAMP('.$column->precision.')';
|
||||
}
|
||||
|
||||
protected function typeDateTime(Fluent $column)
|
||||
{
|
||||
return 'TIMESTAMP';
|
||||
return $this->typeTimestamp($column);
|
||||
}
|
||||
|
||||
protected function typeDate(Fluent $column)
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Db2;
|
||||
|
||||
use Illuminate\Database\Schema\Grammars\Grammar;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Fluent;
|
||||
|
||||
class Db2SchemaGrammar extends Grammar
|
||||
{
|
||||
protected $modifiers = ['Nullable', 'Default'];
|
||||
|
||||
public function compileCreate(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
$columns = [];
|
||||
$primaryKeys = [];
|
||||
|
||||
foreach ($blueprint->getAddedColumns() as $column) {
|
||||
$columns[] = $this->columnDefinition($column);
|
||||
if ($column->autoIncrement) {
|
||||
$primaryKeys[] = $column->name;
|
||||
}
|
||||
}
|
||||
|
||||
$explicitPrimary = collect($blueprint->getCommands())->contains('name', 'primary');
|
||||
if ($primaryKeys !== [] && ! $explicitPrimary) {
|
||||
$columns[] = sprintf(
|
||||
'PRIMARY KEY (%s)',
|
||||
$this->columnize($primaryKeys)
|
||||
);
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'CREATE TABLE %s (%s)',
|
||||
$this->wrapTable($blueprint),
|
||||
implode(', ', $columns)
|
||||
);
|
||||
}
|
||||
|
||||
public function compileAdd(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'ALTER TABLE '.$this->wrapTable($blueprint).' ADD COLUMN '.$this->columnDefinition($command->column);
|
||||
}
|
||||
|
||||
public function compileChange(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
$column = $command->column;
|
||||
if ($column->autoIncrement) {
|
||||
throw new \RuntimeException('Changing a Db2 identity column is unsupported.');
|
||||
}
|
||||
|
||||
$columns = array_column($this->connection->getSchemaBuilder()->getColumns($blueprint->getTable()), null, 'name');
|
||||
$current = $columns[$column->name] ?? null;
|
||||
if ($current === null || $current['auto_increment']) {
|
||||
throw new \RuntimeException('Db2 change requires an existing non-identity column.');
|
||||
}
|
||||
|
||||
$prefix = 'ALTER TABLE '.$this->wrapTable($blueprint).' ALTER COLUMN '.$this->wrap($column);
|
||||
$type = $this->getType($column);
|
||||
$statements = [];
|
||||
|
||||
if (strcasecmp($current['type'], $type) !== 0) {
|
||||
$statements[] = $prefix.' SET DATA TYPE '.$type;
|
||||
}
|
||||
if ($current['nullable'] !== (bool) $column->nullable) {
|
||||
$statements[] = $prefix.($column->nullable ? ' DROP NOT NULL' : ' SET NOT NULL');
|
||||
}
|
||||
if ($column->default !== null) {
|
||||
$statements[] = $prefix.' SET DEFAULT '.$this->getDefaultValue($column->default);
|
||||
} elseif ($current['default'] !== null) {
|
||||
$statements[] = $prefix.' DROP DEFAULT';
|
||||
}
|
||||
|
||||
return $statements;
|
||||
}
|
||||
|
||||
public function compileDropColumn(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
$columns = array_map(fn ($column) => 'DROP COLUMN '.$this->wrap($column), $command->columns);
|
||||
|
||||
return 'ALTER TABLE '.$this->wrapTable($blueprint).' '.implode(' ', $columns);
|
||||
}
|
||||
|
||||
public function compileDrop(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'DROP TABLE '.$this->wrapTable($blueprint);
|
||||
}
|
||||
|
||||
public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'DROP TABLE IF EXISTS '.$this->wrapTable($blueprint);
|
||||
}
|
||||
|
||||
public function compileRename(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
|
||||
[$targetSchema, $target] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($command->to);
|
||||
if ($targetSchema !== null && $targetSchema !== ($schema ?? $this->connection->getConfig('schema'))) {
|
||||
throw new \RuntimeException('Db2 cannot rename a table across schemas.');
|
||||
}
|
||||
|
||||
return 'RENAME TABLE '.$this->wrapTable($blueprint).' TO '.$this->wrapTable($target);
|
||||
}
|
||||
|
||||
public function compileRenameColumn(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'ALTER TABLE '.$this->wrapTable($blueprint)
|
||||
.' RENAME COLUMN '.$this->wrap($command->from).' TO '.$this->wrap($command->to);
|
||||
}
|
||||
|
||||
public function compileDropForeign(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP FOREIGN KEY '.$this->wrap($command->index);
|
||||
}
|
||||
|
||||
public function compileDropPrimary(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP PRIMARY KEY';
|
||||
}
|
||||
|
||||
public function compileDropUnique(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return $this->compileDropIndex($blueprint, $command);
|
||||
}
|
||||
|
||||
public function compileDropIndex(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return 'DROP INDEX '.$this->wrapIndex($blueprint, $command->index);
|
||||
}
|
||||
|
||||
private function wrapIndex(Blueprint $blueprint, string $name): string
|
||||
{
|
||||
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
|
||||
|
||||
return $schema === null ? $this->wrapValue($name) : $this->wrapValue($schema).'.'.$this->wrapValue($name);
|
||||
}
|
||||
|
||||
private function columnDefinition(Fluent $column): string
|
||||
{
|
||||
$sql = $this->wrap($column).' '.$this->getType($column);
|
||||
|
||||
if ($column->autoIncrement) {
|
||||
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
|
||||
}
|
||||
if (! $column->nullable) {
|
||||
$sql .= ' NOT NULL';
|
||||
}
|
||||
if ($column->default !== null) {
|
||||
$sql .= ' DEFAULT '.$this->getDefaultValue($column->default);
|
||||
}
|
||||
|
||||
return $sql;
|
||||
}
|
||||
|
||||
protected function typeBigInteger(Fluent $column)
|
||||
{
|
||||
return 'BIGINT';
|
||||
}
|
||||
|
||||
protected function typeInteger(Fluent $column)
|
||||
{
|
||||
return 'INTEGER';
|
||||
}
|
||||
|
||||
protected function typeSmallInteger(Fluent $column)
|
||||
{
|
||||
return 'SMALLINT';
|
||||
}
|
||||
|
||||
protected function typeString(Fluent $column)
|
||||
{
|
||||
return 'VARCHAR(' . ($column->length ?: 255) . ')';
|
||||
}
|
||||
|
||||
protected function typeText(Fluent $column)
|
||||
{
|
||||
return 'CLOB(1M)';
|
||||
}
|
||||
|
||||
protected function typeLongText(Fluent $column)
|
||||
{
|
||||
return 'CLOB(2M)';
|
||||
}
|
||||
|
||||
protected function typeBoolean(Fluent $column)
|
||||
{
|
||||
return 'SMALLINT';
|
||||
}
|
||||
|
||||
protected function typeTimestamp(Fluent $column)
|
||||
{
|
||||
return 'TIMESTAMP';
|
||||
}
|
||||
|
||||
protected function typeDateTime(Fluent $column)
|
||||
{
|
||||
return 'TIMESTAMP';
|
||||
}
|
||||
|
||||
protected function typeDate(Fluent $column)
|
||||
{
|
||||
return 'DATE';
|
||||
}
|
||||
|
||||
protected function typeBinary(Fluent $column)
|
||||
{
|
||||
return 'BLOB(1M)';
|
||||
}
|
||||
|
||||
protected function typeDecimal(Fluent $column)
|
||||
{
|
||||
return sprintf(
|
||||
'DECIMAL(%d,%d)',
|
||||
$column->total ?? 8,
|
||||
$column->places ?? 2
|
||||
);
|
||||
}
|
||||
|
||||
public function compilePrimary(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return sprintf(
|
||||
'ALTER TABLE %s ADD CONSTRAINT %s PRIMARY KEY (%s)',
|
||||
$this->wrapTable($blueprint),
|
||||
$this->wrapValue($command->index),
|
||||
$this->columnize($command->columns)
|
||||
);
|
||||
}
|
||||
|
||||
protected function typeMediumText(Fluent $column)
|
||||
{
|
||||
return 'CLOB(16M)';
|
||||
}
|
||||
|
||||
public function compileUnique(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return sprintf(
|
||||
'CREATE UNIQUE INDEX %s ON %s (%s)',
|
||||
$this->wrapIndex($blueprint, $command->index),
|
||||
$this->wrapTable($blueprint),
|
||||
$this->columnize($command->columns)
|
||||
);
|
||||
}
|
||||
|
||||
public function compileIndex(Blueprint $blueprint, Fluent $command)
|
||||
{
|
||||
return sprintf(
|
||||
'CREATE INDEX %s ON %s (%s)',
|
||||
$this->wrapIndex($blueprint, $command->index),
|
||||
$this->wrapTable($blueprint),
|
||||
$this->columnize($command->columns)
|
||||
);
|
||||
}
|
||||
|
||||
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
|
||||
{
|
||||
return 'CLOB(1M)';
|
||||
}
|
||||
|
||||
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
|
||||
{
|
||||
return 'CLOB(1M)';
|
||||
}
|
||||
|
||||
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
|
||||
{
|
||||
return 'VARCHAR(255)';
|
||||
}
|
||||
|
||||
public function compileInsertOrIgnore(
|
||||
\Illuminate\Database\Query\Builder $query,
|
||||
array $values
|
||||
) {
|
||||
if (empty($values)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!is_array(reset($values))) {
|
||||
$values = [$values];
|
||||
}
|
||||
|
||||
$columns = array_keys(reset($values));
|
||||
|
||||
$table = $this->wrapTable($query->from);
|
||||
|
||||
$sourceColumns = implode(
|
||||
', ',
|
||||
array_map(fn ($column) => $this->wrap($column), $columns)
|
||||
);
|
||||
|
||||
$rows = [];
|
||||
|
||||
foreach ($values as $row) {
|
||||
$rows[] = '(' . implode(
|
||||
', ',
|
||||
array_fill(0, count($columns), '?')
|
||||
) . ')';
|
||||
}
|
||||
|
||||
$source = implode(', ', $rows);
|
||||
|
||||
$conditions = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$wrapped = $this->wrap($column);
|
||||
|
||||
$conditions[] = "target.$wrapped = source.$wrapped";
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
'MERGE INTO %s AS target
|
||||
USING (VALUES %s) AS source (%s)
|
||||
ON %s
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (%s)
|
||||
VALUES (%s)',
|
||||
$table,
|
||||
$source,
|
||||
$sourceColumns,
|
||||
implode(' AND ', $conditions),
|
||||
$sourceColumns,
|
||||
implode(
|
||||
', ',
|
||||
array_map(
|
||||
fn ($column) => 'source.' . $this->wrap($column),
|
||||
$columns
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
class SchemaTypesAndIndexesTest extends Db2TestCase
|
||||
{
|
||||
public function test_extended_column_types_round_trip(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$table = 'stage7_'.bin2hex(random_bytes(6));
|
||||
|
||||
try {
|
||||
$schema->create($table, function (Blueprint $table) {
|
||||
$table->char('code', 4);
|
||||
$table->uuid('reference');
|
||||
$table->time('opens_at');
|
||||
$table->timestamp('recorded_at', 3);
|
||||
$table->decimal('amount', 10, 2);
|
||||
});
|
||||
$uuid = '42dcb8f9-073a-4359-983f-ab0491c01dc7';
|
||||
$db->table($table)->insert([
|
||||
'code' => 'ABCD',
|
||||
'reference' => $uuid,
|
||||
'opens_at' => '08:12:30',
|
||||
'recorded_at' => '2026-11-11 08:12:30.123',
|
||||
'amount' => '12345678.90',
|
||||
]);
|
||||
|
||||
$columns = array_column($schema->getColumns($table), null, 'name');
|
||||
$this->assertSame('CHAR(4)', $columns['code']['type']);
|
||||
$this->assertSame('CHAR(36)', $columns['reference']['type']);
|
||||
$this->assertSame('TIME', $columns['opens_at']['type_name']);
|
||||
$this->assertSame('TIMESTAMP(3)', $columns['recorded_at']['type']);
|
||||
$this->assertSame('DECIMAL(10,2)', $columns['amount']['type']);
|
||||
$this->assertSame($uuid, $db->table($table)->value('reference'));
|
||||
$this->assertSame('12345678.90', (string) $db->table($table)->value('amount'));
|
||||
} finally {
|
||||
$schema->dropIfExists($table);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_rename_preserves_a_composite_unique_index(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$name = 'stage7_'.bin2hex(random_bytes(6));
|
||||
$table = $db->getConfig('schema').'.'.$name;
|
||||
|
||||
try {
|
||||
$schema->create($table, function (Blueprint $table) use ($name) {
|
||||
$table->integer('region');
|
||||
$table->integer('code');
|
||||
$table->unique(['region', 'code'], $name.'_old');
|
||||
});
|
||||
$schema->table($table, fn (Blueprint $table) => $table->renameIndex($name.'_old', $name.'_new'));
|
||||
|
||||
$indexes = array_column($schema->getIndexes($table), null, 'name');
|
||||
$this->assertArrayNotHasKey($name.'_old', $indexes);
|
||||
$this->assertTrue($indexes[$name.'_new']['unique']);
|
||||
$this->assertSame(['region', 'code'], $indexes[$name.'_new']['columns']);
|
||||
$schema->table($table, fn (Blueprint $table) => $table->dropUnique($name.'_new'));
|
||||
$this->assertFalse($schema->hasIndex($table, $name.'_new'));
|
||||
} finally {
|
||||
$schema->dropIfExists($table);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user