db2 driver updates
This commit is contained in:
@@ -1,59 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
|
|
||||||
## 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
|
|
||||||
```
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
# 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
|
|
||||||
vendor/bin/pest --do-not-cache-result tests/Feature/Db2/SchemaTest.php
|
|
||||||
vendor/bin/pest --do-not-cache-result tests/Feature/Db2
|
|
||||||
vendor/bin/pest --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.
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -5,6 +5,7 @@ namespace Modules\Stylist\Providers;
|
|||||||
use Illuminate\Support\Facades\Blade;
|
use Illuminate\Support\Facades\Blade;
|
||||||
use Illuminate\Support\Facades\View;
|
use Illuminate\Support\Facades\View;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Livewire\Livewire;
|
||||||
use Modules\Stylist\Console\CreateThemeCommand;
|
use Modules\Stylist\Console\CreateThemeCommand;
|
||||||
use Modules\Stylist\Console\FindDuplicateViewsCommand;
|
use Modules\Stylist\Console\FindDuplicateViewsCommand;
|
||||||
use Modules\Stylist\Console\InspectThemesCommand;
|
use Modules\Stylist\Console\InspectThemesCommand;
|
||||||
@@ -17,7 +18,6 @@ use Modules\Stylist\Support\ModuleInfo;
|
|||||||
use Modules\Stylist\Theme\Loader;
|
use Modules\Stylist\Theme\Loader;
|
||||||
use Modules\Stylist\Theme\Stylist;
|
use Modules\Stylist\Theme\Stylist;
|
||||||
use Modules\Stylist\Theme\Theme;
|
use Modules\Stylist\Theme\Theme;
|
||||||
use Livewire\Livewire;
|
|
||||||
|
|
||||||
final class StylistServiceProvider extends ServiceProvider
|
final class StylistServiceProvider extends ServiceProvider
|
||||||
{
|
{
|
||||||
@@ -453,7 +453,6 @@ final class StylistServiceProvider extends ServiceProvider
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private function registerLivewireThemeViewPath(): void
|
private function registerLivewireThemeViewPath(): void
|
||||||
{
|
{
|
||||||
$stylist = $this->app->make(Stylist::class);
|
$stylist = $this->app->make(Stylist::class);
|
||||||
|
|||||||
@@ -3,11 +3,9 @@
|
|||||||
namespace App\Database\Db2;
|
namespace App\Database\Db2;
|
||||||
|
|
||||||
use Illuminate\Database\Connection;
|
use Illuminate\Database\Connection;
|
||||||
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
|
|
||||||
use App\Database\Db2\Db2Processor;
|
|
||||||
class Db2Connection extends Connection
|
class Db2Connection extends Connection
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restore SQL NULL values from Db2 workaround expressions
|
* Restore SQL NULL values from Db2 workaround expressions
|
||||||
* before Eloquent processes the results.
|
* before Eloquent processes the results.
|
||||||
@@ -63,6 +61,7 @@ class Db2Connection extends Connection
|
|||||||
}
|
}
|
||||||
|
|
||||||
$previousColumn = null;
|
$previousColumn = null;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,6 +106,4 @@ class Db2Connection extends Connection
|
|||||||
{
|
{
|
||||||
return new Db2Processor;
|
return new Db2Processor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Connection;
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
|
|
||||||
use App\Database\Db2\Db2Processor;
|
|
||||||
class Db2Connection extends Connection
|
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Restore SQL NULL values from Db2 workaround expressions
|
|
||||||
* before Eloquent processes the results.
|
|
||||||
*/
|
|
||||||
public function select(
|
|
||||||
$query,
|
|
||||||
$bindings = [],
|
|
||||||
$useReadPdo = true,
|
|
||||||
array $fetchUsing = []
|
|
||||||
) {
|
|
||||||
$rows = parent::select(
|
|
||||||
$query,
|
|
||||||
$bindings,
|
|
||||||
$useReadPdo,
|
|
||||||
$fetchUsing
|
|
||||||
);
|
|
||||||
|
|
||||||
foreach ($rows as &$row) {
|
|
||||||
if (! is_object($row) && ! is_array($row)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$values = (array) $row;
|
|
||||||
$result = [];
|
|
||||||
$previousColumn = null;
|
|
||||||
|
|
||||||
foreach ($values as $key => $value) {
|
|
||||||
if (
|
|
||||||
is_string($key) &&
|
|
||||||
preg_match('/^__db2_null_flag_[0-9]+$/i', $key)
|
|
||||||
) {
|
|
||||||
if ($previousColumn === null) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 NULL indicator has no preceding column.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((string) $value === '1') {
|
|
||||||
$result[$previousColumn] = null;
|
|
||||||
} elseif ((string) $value !== '0') {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Unexpected Db2 NULL indicator value.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$previousColumn = null;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$result[$key] = $value;
|
|
||||||
$previousColumn = $key;
|
|
||||||
}
|
|
||||||
|
|
||||||
$row = is_object($row)
|
|
||||||
? (object) $result
|
|
||||||
: $result;
|
|
||||||
}
|
|
||||||
unset($row);
|
|
||||||
|
|
||||||
return $rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultQueryGrammar()
|
|
||||||
{
|
|
||||||
return new Db2QueryGrammar($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultSchemaGrammar()
|
|
||||||
{
|
|
||||||
return new Db2SchemaGrammar($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSchemaBuilder()
|
|
||||||
{
|
|
||||||
if (is_null($this->schemaGrammar)) {
|
|
||||||
$this->useDefaultSchemaGrammar();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Db2SchemaBuilder($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultPostProcessor()
|
|
||||||
{
|
|
||||||
return new Db2Processor;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Connection;
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
|
|
||||||
use App\Database\Db2\Db2Processor;
|
|
||||||
class Db2Connection extends Connection
|
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Restore SQL NULL values from Db2 workaround expressions
|
|
||||||
* before Eloquent processes the results.
|
|
||||||
*/
|
|
||||||
public function select(
|
|
||||||
$query,
|
|
||||||
$bindings = [],
|
|
||||||
$useReadPdo = true,
|
|
||||||
array $fetchUsing = []
|
|
||||||
) {
|
|
||||||
$rows = parent::select(
|
|
||||||
$query,
|
|
||||||
$bindings,
|
|
||||||
$useReadPdo,
|
|
||||||
$fetchUsing
|
|
||||||
);
|
|
||||||
|
|
||||||
// Never interpret ordinary raw-query columns as
|
|
||||||
// internal NULL indicators.
|
|
||||||
if (
|
|
||||||
! is_string($query) ||
|
|
||||||
! str_contains($query, '/* DB2_NULL_FLAGS_V1 */')
|
|
||||||
) {
|
|
||||||
return $rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($rows as &$row) {
|
|
||||||
if (! is_object($row) && ! is_array($row)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$values = (array) $row;
|
|
||||||
$result = [];
|
|
||||||
$previousColumn = null;
|
|
||||||
|
|
||||||
foreach ($values as $key => $value) {
|
|
||||||
if (
|
|
||||||
is_string($key) &&
|
|
||||||
preg_match('/^__db2_null_flag_[0-9]+$/i', $key)
|
|
||||||
) {
|
|
||||||
if ($previousColumn === null) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 NULL indicator has no preceding column.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((string) $value === '1') {
|
|
||||||
$result[$previousColumn] = null;
|
|
||||||
} elseif ((string) $value !== '0') {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Unexpected Db2 NULL indicator value.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$previousColumn = null;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$result[$key] = $value;
|
|
||||||
$previousColumn = $key;
|
|
||||||
}
|
|
||||||
|
|
||||||
$row = is_object($row)
|
|
||||||
? (object) $result
|
|
||||||
: $result;
|
|
||||||
}
|
|
||||||
unset($row);
|
|
||||||
|
|
||||||
return $rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultQueryGrammar()
|
|
||||||
{
|
|
||||||
return new Db2QueryGrammar($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultSchemaGrammar()
|
|
||||||
{
|
|
||||||
return new Db2SchemaGrammar($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSchemaBuilder()
|
|
||||||
{
|
|
||||||
if (is_null($this->schemaGrammar)) {
|
|
||||||
$this->useDefaultSchemaGrammar();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Db2SchemaBuilder($this);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDefaultPostProcessor()
|
|
||||||
{
|
|
||||||
return new Db2Processor;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Database\Db2;
|
namespace App\Database\Db2;
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Database\Query\Expression;
|
use Illuminate\Database\Query\Expression;
|
||||||
|
use Illuminate\Database\Query\Grammars\Grammar;
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
class Db2QueryGrammar extends Grammar
|
||||||
{
|
{
|
||||||
@@ -24,7 +24,9 @@ class Db2QueryGrammar extends Grammar
|
|||||||
];
|
];
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
private array $db2ColumnCache = [];
|
||||||
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
* Compile a Db2 MERGE statement for Laravel upserts.
|
||||||
*/
|
*/
|
||||||
@@ -68,32 +70,32 @@ class Db2QueryGrammar extends Grammar
|
|||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
||||||
} else {
|
} else {
|
||||||
$updates[] = "target."
|
$updates[] = 'target.'
|
||||||
. $this->wrap($key)
|
.$this->wrap($key)
|
||||||
. " = "
|
.' = '
|
||||||
. $this->parameter($value);
|
.$this->parameter($value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
$insertColumns = $this->columnize($columns);
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
$insertValues = implode(', ', array_map(
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
fn ($column) => 'source.'.$this->wrap($column),
|
||||||
$columns
|
$columns
|
||||||
));
|
));
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
||||||
. "USING ({$source}) AS source "
|
."USING ({$source}) AS source "
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
.'ON ('.implode(' AND ', $matches).') ';
|
||||||
|
|
||||||
if ($updates !== []) {
|
if ($updates !== []) {
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
$sql .= 'WHEN MATCHED THEN UPDATE SET '
|
||||||
. implode(', ', $updates) . " ";
|
.implode(', ', $updates).' ';
|
||||||
}
|
}
|
||||||
|
|
||||||
return $sql
|
return $sql
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
."WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
||||||
. "VALUES ({$insertValues})";
|
."VALUES ({$insertValues})";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -151,8 +153,8 @@ class Db2QueryGrammar extends Grammar
|
|||||||
|
|
||||||
if ($conditions !== []) {
|
if ($conditions !== []) {
|
||||||
$uniqueConditions[] = '('
|
$uniqueConditions[] = '('
|
||||||
. implode(' AND ', $conditions)
|
.implode(' AND ', $conditions)
|
||||||
. ')';
|
.')';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,15 +167,15 @@ class Db2QueryGrammar extends Grammar
|
|||||||
$insertColumns = $this->columnize($columns);
|
$insertColumns = $this->columnize($columns);
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
$insertValues = implode(', ', array_map(
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
fn ($column) => 'source.'.$this->wrap($column),
|
||||||
$columns
|
$columns
|
||||||
));
|
));
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
||||||
. "USING ({$source}) AS source "
|
."USING ({$source}) AS source "
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
.'ON ('.implode(' OR ', $uniqueConditions).') '
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
."WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
||||||
. "VALUES ({$insertValues})";
|
."VALUES ({$insertValues})";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -214,13 +216,13 @@ class Db2QueryGrammar extends Grammar
|
|||||||
|
|
||||||
foreach ($columns as $column) {
|
foreach ($columns as $column) {
|
||||||
$parts[] = $this->parameter($row[$column])
|
$parts[] = $this->parameter($row[$column])
|
||||||
. ' AS '
|
.' AS '
|
||||||
. $this->wrap($column);
|
.$this->wrap($column);
|
||||||
}
|
}
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
$selects[] = 'SELECT '
|
||||||
. implode(', ', $parts)
|
.implode(', ', $parts)
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
.' FROM SYSIBM.SYSDUMMY1';
|
||||||
}
|
}
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
return implode(' UNION ALL ', $selects);
|
||||||
@@ -231,8 +233,8 @@ class Db2QueryGrammar extends Grammar
|
|||||||
*/
|
*/
|
||||||
public function compileSavepoint($name)
|
public function compileSavepoint($name)
|
||||||
{
|
{
|
||||||
return 'SAVEPOINT ' . $name
|
return 'SAVEPOINT '.$name
|
||||||
. ' ON ROLLBACK RETAIN CURSORS';
|
.' ON ROLLBACK RETAIN CURSORS';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -240,7 +242,7 @@ class Db2QueryGrammar extends Grammar
|
|||||||
*/
|
*/
|
||||||
public function compileSavepointRollBack($name)
|
public function compileSavepointRollBack($name)
|
||||||
{
|
{
|
||||||
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
return 'ROLLBACK TO SAVEPOINT '.$name;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
protected function compileAggregate($query, $aggregate)
|
||||||
@@ -287,7 +289,7 @@ class Db2QueryGrammar extends Grammar
|
|||||||
}
|
}
|
||||||
|
|
||||||
public function compileExists(
|
public function compileExists(
|
||||||
\Illuminate\Database\Query\Builder $query
|
Builder $query
|
||||||
) {
|
) {
|
||||||
$select = $this->compileSelect($query);
|
$select = $this->compileSelect($query);
|
||||||
|
|
||||||
@@ -443,6 +445,7 @@ class Db2QueryGrammar extends Grammar
|
|||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
||||||
$lobs[] = $selected;
|
$lobs[] = $selected;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -466,8 +469,8 @@ class Db2QueryGrammar extends Grammar
|
|||||||
}
|
}
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
$expression = 'COALESCE('
|
||||||
. $wrapped
|
.$wrapped
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
.", CAST('' AS VARCHAR({$length})))";
|
||||||
} else {
|
} else {
|
||||||
$formatted = $type === 'TIMESTAMP'
|
$formatted = $type === 'TIMESTAMP'
|
||||||
? "VARCHAR_FORMAT({$wrapped}, 'YYYY-MM-DD HH24:MI:SS.FF6')"
|
? "VARCHAR_FORMAT({$wrapped}, 'YYYY-MM-DD HH24:MI:SS.FF6')"
|
||||||
@@ -477,24 +480,24 @@ class Db2QueryGrammar extends Grammar
|
|||||||
}
|
}
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
$ordinary[] = new Expression(
|
||||||
$expression . ' AS ' . $alias
|
$expression.' AS '.$alias
|
||||||
);
|
);
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
// Character indicators avoid the PDO_ODBC numeric
|
||||||
// aggregate/binary conversion issue.
|
// aggregate/binary conversion issue.
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
$flagAlias = '__db2_null_flag_'.$indicatorIndex++;
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
// Ensure a generated alias cannot collide with any
|
||||||
// requested output column.
|
// requested output column.
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
while (isset($aliases[strtolower($flagAlias)])) {
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
$flagAlias = '__db2_null_flag_'.$indicatorIndex++;
|
||||||
}
|
}
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
$ordinary[] = new Expression(
|
||||||
'CASE WHEN '
|
'CASE WHEN '
|
||||||
. $wrapped
|
.$wrapped
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
." IS NULL THEN '1' ELSE '0' END AS "
|
||||||
. $this->wrap($flagAlias)
|
.$this->wrap($flagAlias)
|
||||||
);
|
);
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
$hasNullIndicators = true;
|
||||||
|
|||||||
@@ -1,258 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as aggregate';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
return 'fetch first '.(int) $limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$format = match ($type) {
|
|
||||||
'DATE' => 'YYYY-MM-DD',
|
|
||||||
'TIME' => 'HH24:MI:SS',
|
|
||||||
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
|
|
||||||
};
|
|
||||||
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE VARCHAR_FORMAT('
|
|
||||||
. $wrapped
|
|
||||||
. ", '{$format}') END";
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as aggregate';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
return 'fetch first '.(int) $limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,278 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,436 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
// Match all supplied columns. A later stage will add
|
|
||||||
// catalog-aware matching for unique constraints.
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,479 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$indexes = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getIndexes($query->from);
|
|
||||||
|
|
||||||
$uniqueConditions = [];
|
|
||||||
|
|
||||||
foreach ($indexes as $index) {
|
|
||||||
if (! ($index['unique'] ?? false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$indexColumns = $index['columns'] ?? [];
|
|
||||||
|
|
||||||
if ($indexColumns === []) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A unique key can only be compared if every
|
|
||||||
// participating column exists in the source.
|
|
||||||
$conditions = [];
|
|
||||||
|
|
||||||
foreach ($indexColumns as $column) {
|
|
||||||
$matchedColumn = null;
|
|
||||||
|
|
||||||
foreach ($columns as $candidate) {
|
|
||||||
if (strcasecmp($candidate, $column) === 0) {
|
|
||||||
$matchedColumn = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($matchedColumn === null) {
|
|
||||||
$conditions = [];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($matchedColumn);
|
|
||||||
|
|
||||||
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($conditions !== []) {
|
|
||||||
$uniqueConditions[] = '('
|
|
||||||
. implode(' AND ', $conditions)
|
|
||||||
. ')';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($uniqueConditions === []) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,248 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as aggregate';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
return 'fetch first '.(int) $limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$format = match ($type) {
|
|
||||||
'DATE' => 'YYYY-MM-DD',
|
|
||||||
'TIME' => 'HH24:MI:SS',
|
|
||||||
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
|
|
||||||
};
|
|
||||||
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE VARCHAR_FORMAT('
|
|
||||||
. $wrapped
|
|
||||||
. ", '{$format}') END";
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
return parent::compileSelect($modified);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,496 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$indexes = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getIndexes($query->from);
|
|
||||||
|
|
||||||
$uniqueConditions = [];
|
|
||||||
|
|
||||||
foreach ($indexes as $index) {
|
|
||||||
if (! ($index['unique'] ?? false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$indexColumns = $index['columns'] ?? [];
|
|
||||||
|
|
||||||
if ($indexColumns === []) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A unique key can only be compared if every
|
|
||||||
// participating column exists in the source.
|
|
||||||
$conditions = [];
|
|
||||||
|
|
||||||
foreach ($indexColumns as $column) {
|
|
||||||
$matchedColumn = null;
|
|
||||||
|
|
||||||
foreach ($columns as $candidate) {
|
|
||||||
if (strcasecmp($candidate, $column) === 0) {
|
|
||||||
$matchedColumn = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($matchedColumn === null) {
|
|
||||||
$conditions = [];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($matchedColumn);
|
|
||||||
|
|
||||||
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($conditions !== []) {
|
|
||||||
$uniqueConditions[] = '('
|
|
||||||
. implode(' AND ', $conditions)
|
|
||||||
. ')';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($uniqueConditions === []) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepoint($name)
|
|
||||||
{
|
|
||||||
return 'SAVEPOINT ' . $name
|
|
||||||
. ' ON ROLLBACK RETAIN CURSORS';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW rollback-to-savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepointRollBack($name)
|
|
||||||
{
|
|
||||||
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast only the migration batch aggregate to VARCHAR.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,496 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$indexes = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getIndexes($query->from);
|
|
||||||
|
|
||||||
$uniqueConditions = [];
|
|
||||||
|
|
||||||
foreach ($indexes as $index) {
|
|
||||||
if (! ($index['unique'] ?? false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$indexColumns = $index['columns'] ?? [];
|
|
||||||
|
|
||||||
if ($indexColumns === []) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A unique key can only be compared if every
|
|
||||||
// participating column exists in the source.
|
|
||||||
$conditions = [];
|
|
||||||
|
|
||||||
foreach ($indexColumns as $column) {
|
|
||||||
$matchedColumn = null;
|
|
||||||
|
|
||||||
foreach ($columns as $candidate) {
|
|
||||||
if (strcasecmp($candidate, $column) === 0) {
|
|
||||||
$matchedColumn = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($matchedColumn === null) {
|
|
||||||
$conditions = [];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($matchedColumn);
|
|
||||||
|
|
||||||
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($conditions !== []) {
|
|
||||||
$uniqueConditions[] = '('
|
|
||||||
. implode(' AND ', $conditions)
|
|
||||||
. ')';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($uniqueConditions === []) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepoint($name)
|
|
||||||
{
|
|
||||||
return 'SAVEPOINT ' . $name
|
|
||||||
. ' ON ROLLBACK RETAIN CURSORS';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW rollback-to-savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepointRollBack($name)
|
|
||||||
{
|
|
||||||
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast migration batch aggregates, including custom repository tables.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch' &&
|
|
||||||
$query->from === 'migrations'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,495 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$indexes = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getIndexes($query->from);
|
|
||||||
|
|
||||||
$uniqueConditions = [];
|
|
||||||
|
|
||||||
foreach ($indexes as $index) {
|
|
||||||
if (! ($index['unique'] ?? false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$indexColumns = $index['columns'] ?? [];
|
|
||||||
|
|
||||||
if ($indexColumns === []) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A unique key can only be compared if every
|
|
||||||
// participating column exists in the source.
|
|
||||||
$conditions = [];
|
|
||||||
|
|
||||||
foreach ($indexColumns as $column) {
|
|
||||||
$matchedColumn = null;
|
|
||||||
|
|
||||||
foreach ($columns as $candidate) {
|
|
||||||
if (strcasecmp($candidate, $column) === 0) {
|
|
||||||
$matchedColumn = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($matchedColumn === null) {
|
|
||||||
$conditions = [];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($matchedColumn);
|
|
||||||
|
|
||||||
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($conditions !== []) {
|
|
||||||
$uniqueConditions[] = '('
|
|
||||||
. implode(' AND ', $conditions)
|
|
||||||
. ')';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($uniqueConditions === []) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepoint($name)
|
|
||||||
{
|
|
||||||
return 'SAVEPOINT ' . $name
|
|
||||||
. ' ON ROLLBACK RETAIN CURSORS';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW rollback-to-savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepointRollBack($name)
|
|
||||||
{
|
|
||||||
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast migration batch aggregates, including custom repository tables.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
public function compileSelect(\Illuminate\Database\Query\Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,529 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Database\Db2;
|
|
||||||
|
|
||||||
use Illuminate\Database\Query\Grammars\Grammar;
|
|
||||||
use Illuminate\Database\Query\Builder;
|
|
||||||
use Illuminate\Database\Query\Expression;
|
|
||||||
|
|
||||||
class Db2QueryGrammar extends Grammar
|
|
||||||
{
|
|
||||||
protected $selectComponents = [
|
|
||||||
'aggregate',
|
|
||||||
'columns',
|
|
||||||
'from',
|
|
||||||
'indexHint',
|
|
||||||
'joins',
|
|
||||||
'wheres',
|
|
||||||
'groups',
|
|
||||||
'havings',
|
|
||||||
'orders',
|
|
||||||
'offset',
|
|
||||||
'limit',
|
|
||||||
'lock',
|
|
||||||
];
|
|
||||||
|
|
||||||
private array $db2ColumnCache = [];
|
|
||||||
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
|
|
||||||
/**
|
|
||||||
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
||||||
*/
|
|
||||||
public function compileUpsert(
|
|
||||||
Builder $query,
|
|
||||||
array $values,
|
|
||||||
array $uniqueBy,
|
|
||||||
array $update
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
if (! in_array($column, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Upsert key is missing from inserted values: {$column}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$matches = [];
|
|
||||||
|
|
||||||
foreach ($uniqueBy as $column) {
|
|
||||||
$wrapped = $this->wrap($column);
|
|
||||||
|
|
||||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
$updates = [];
|
|
||||||
|
|
||||||
foreach ($update as $key => $value) {
|
|
||||||
if (is_int($key)) {
|
|
||||||
if (! in_array($value, $columns, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
"Unknown upsert update column: {$value}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($value);
|
|
||||||
|
|
||||||
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
} else {
|
|
||||||
$updates[] = "target."
|
|
||||||
. $this->wrap($key)
|
|
||||||
. " = "
|
|
||||||
. $this->parameter($value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
||||||
|
|
||||||
if ($updates !== []) {
|
|
||||||
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
||||||
. implode(', ', $updates) . " ";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Insert rows without replacing existing rows.
|
|
||||||
*
|
|
||||||
* Db2 MERGE ignores rows that match the selected key.
|
|
||||||
*/
|
|
||||||
public function compileInsertOrIgnore(
|
|
||||||
Builder $query,
|
|
||||||
array $values
|
|
||||||
) {
|
|
||||||
$columns = $this->db2MergeColumns($values);
|
|
||||||
$source = $this->db2MergeSource($values, $columns);
|
|
||||||
|
|
||||||
$indexes = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getIndexes($query->from);
|
|
||||||
|
|
||||||
$uniqueConditions = [];
|
|
||||||
|
|
||||||
foreach ($indexes as $index) {
|
|
||||||
if (! ($index['unique'] ?? false)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$indexColumns = $index['columns'] ?? [];
|
|
||||||
|
|
||||||
if ($indexColumns === []) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A unique key can only be compared if every
|
|
||||||
// participating column exists in the source.
|
|
||||||
$conditions = [];
|
|
||||||
|
|
||||||
foreach ($indexColumns as $column) {
|
|
||||||
$matchedColumn = null;
|
|
||||||
|
|
||||||
foreach ($columns as $candidate) {
|
|
||||||
if (strcasecmp($candidate, $column) === 0) {
|
|
||||||
$matchedColumn = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($matchedColumn === null) {
|
|
||||||
$conditions = [];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
$wrapped = $this->wrap($matchedColumn);
|
|
||||||
|
|
||||||
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($conditions !== []) {
|
|
||||||
$uniqueConditions[] = '('
|
|
||||||
. implode(' AND ', $conditions)
|
|
||||||
. ')';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($uniqueConditions === []) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$insertColumns = $this->columnize($columns);
|
|
||||||
|
|
||||||
$insertValues = implode(', ', array_map(
|
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
|
||||||
$columns
|
|
||||||
));
|
|
||||||
|
|
||||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
||||||
. "USING ({$source}) AS source "
|
|
||||||
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
||||||
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
||||||
. "VALUES ({$insertValues})";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate the column layout of a multi-row MERGE.
|
|
||||||
*/
|
|
||||||
private function db2MergeColumns(array $values): array
|
|
||||||
{
|
|
||||||
if ($values === []) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'MERGE requires at least one row.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = array_keys(reset($values));
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
if (array_keys($row) !== $columns) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'All MERGE rows must contain the same columns.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a parameterized Db2 MERGE source.
|
|
||||||
*/
|
|
||||||
private function db2MergeSource(
|
|
||||||
array $values,
|
|
||||||
array $columns
|
|
||||||
): string {
|
|
||||||
$selects = [];
|
|
||||||
|
|
||||||
foreach ($values as $row) {
|
|
||||||
$parts = [];
|
|
||||||
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
$parts[] = $this->parameter($row[$column])
|
|
||||||
. ' AS '
|
|
||||||
. $this->wrap($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
$selects[] = 'SELECT '
|
|
||||||
. implode(', ', $parts)
|
|
||||||
. ' FROM SYSIBM.SYSDUMMY1';
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' UNION ALL ', $selects);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepoint($name)
|
|
||||||
{
|
|
||||||
return 'SAVEPOINT ' . $name
|
|
||||||
. ' ON ROLLBACK RETAIN CURSORS';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compile a Db2 LUW rollback-to-savepoint statement.
|
|
||||||
*/
|
|
||||||
public function compileSavepointRollBack($name)
|
|
||||||
{
|
|
||||||
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileAggregate($query, $aggregate)
|
|
||||||
{
|
|
||||||
$column = $this->columnize($aggregate['columns']);
|
|
||||||
|
|
||||||
if (is_array($query->distinct)) {
|
|
||||||
$column = 'distinct '.$this->columnize($query->distinct);
|
|
||||||
} elseif ($query->distinct && $column !== '*') {
|
|
||||||
$column = 'distinct '.$column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$function = strtolower($aggregate['function']);
|
|
||||||
|
|
||||||
$expression = "{$function}({$column})";
|
|
||||||
|
|
||||||
// PDO_ODBC may return Db2 integer aggregates as binary data.
|
|
||||||
// Cast migration batch aggregates, including custom repository tables.
|
|
||||||
if (
|
|
||||||
$function === 'max' &&
|
|
||||||
count($aggregate['columns']) === 1 &&
|
|
||||||
$aggregate['columns'][0] === 'batch'
|
|
||||||
) {
|
|
||||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'select '.$expression.' as "aggregate"';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileLimit($query, $limit)
|
|
||||||
{
|
|
||||||
$limit = (int) $limit;
|
|
||||||
|
|
||||||
if ((int) ($query->offset ?? 0) > 0) {
|
|
||||||
return 'fetch next '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
return 'fetch first '.$limit.' rows only';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function compileOffset($query, $offset)
|
|
||||||
{
|
|
||||||
return 'offset '.(int) $offset.' rows';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function compileExists(
|
|
||||||
\Illuminate\Database\Query\Builder $query
|
|
||||||
) {
|
|
||||||
$select = $this->compileSelect($query);
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
|
|
||||||
$select
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
|
|
||||||
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
|
|
||||||
|
|
||||||
protected function compileUnions(Builder $query)
|
|
||||||
{
|
|
||||||
$union = clone $query;
|
|
||||||
$union->unionLimit = null;
|
|
||||||
$union->unionOffset = null;
|
|
||||||
$sql = parent::compileUnions($union);
|
|
||||||
|
|
||||||
if ($query->unionOffset !== null) {
|
|
||||||
$sql .= ' '.$this->compileOffset($query, $query->unionOffset);
|
|
||||||
}
|
|
||||||
if ($query->unionLimit !== null) {
|
|
||||||
$sql .= $query->unionOffset > 0
|
|
||||||
? ' fetch next '.(int) $query->unionLimit.' rows only'
|
|
||||||
: ' '.$this->compileLimit($union, $query->unionLimit);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function whereLike(Builder $query, $where)
|
|
||||||
{
|
|
||||||
$column = $this->wrap($where['column']);
|
|
||||||
$pattern = $this->parameter($where['value']);
|
|
||||||
$operator = $where['not'] ? 'not like' : 'like';
|
|
||||||
|
|
||||||
if (! $where['caseSensitive']) {
|
|
||||||
$column = 'UPPER('.$column.')';
|
|
||||||
$pattern = 'UPPER(CAST('.$pattern.' AS VARCHAR(32672 OCTETS)))';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $column.' '.$operator.' '.$pattern;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only result queries can add and then decode the ODBC NULL indicators.
|
|
||||||
public function compileResultSelect(Builder $query)
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! is_string($query->from) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
|
|
||||||
$query->from
|
|
||||||
) ||
|
|
||||||
! empty($query->joins) ||
|
|
||||||
! empty($query->unions) ||
|
|
||||||
! empty($query->groups) ||
|
|
||||||
! empty($query->havings) ||
|
|
||||||
$query->aggregate !== null ||
|
|
||||||
$query->distinct
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = $query->from;
|
|
||||||
|
|
||||||
if (! isset($this->db2ColumnCache[$table])) {
|
|
||||||
$this->db2ColumnCache[$table] = $this->connection
|
|
||||||
->getSchemaBuilder()
|
|
||||||
->getColumns($table);
|
|
||||||
}
|
|
||||||
|
|
||||||
$metadata = [];
|
|
||||||
|
|
||||||
foreach ($this->db2ColumnCache[$table] as $column) {
|
|
||||||
$metadata[strtolower($column['name'])] = $column;
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns = $query->columns ?? ['*'];
|
|
||||||
|
|
||||||
if ($columns === ['*']) {
|
|
||||||
$columns = array_column(
|
|
||||||
$this->db2ColumnCache[$table],
|
|
||||||
'name'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$parsed = [];
|
|
||||||
$aliases = [];
|
|
||||||
|
|
||||||
// Validate the complete selection before modifying any SQL.
|
|
||||||
foreach ($columns as $column) {
|
|
||||||
if (
|
|
||||||
! is_string($column) ||
|
|
||||||
! preg_match(
|
|
||||||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
|
|
||||||
$column,
|
|
||||||
$matches
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$identifier = $matches[1];
|
|
||||||
$parts = explode('.', $identifier);
|
|
||||||
$name = trim(end($parts), '"');
|
|
||||||
$alias = isset($matches[2])
|
|
||||||
? trim($matches[2], '"')
|
|
||||||
: $name;
|
|
||||||
|
|
||||||
$info = $metadata[strtolower($name)] ?? null;
|
|
||||||
|
|
||||||
if ($info === null) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reserved indicator aliases must never be user columns.
|
|
||||||
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Duplicate output names cannot be mapped unambiguously.
|
|
||||||
$aliasKey = strtolower($alias);
|
|
||||||
|
|
||||||
if (isset($aliases[$aliasKey])) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$aliases[$aliasKey] = true;
|
|
||||||
|
|
||||||
$parsed[] = [
|
|
||||||
'original' => $column,
|
|
||||||
'identifier' => $identifier,
|
|
||||||
'alias' => $alias,
|
|
||||||
'info' => $info,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary = [];
|
|
||||||
$lobs = [];
|
|
||||||
$changed = false;
|
|
||||||
$indicatorIndex = 0;
|
|
||||||
$hasNullIndicators = false;
|
|
||||||
|
|
||||||
foreach ($parsed as $entry) {
|
|
||||||
$info = $entry['info'];
|
|
||||||
$type = strtoupper($info['type_name']);
|
|
||||||
$nullable = (bool) ($info['nullable'] ?? false);
|
|
||||||
|
|
||||||
$selected = $entry['original'];
|
|
||||||
$wrapped = $this->wrap($entry['identifier']);
|
|
||||||
$alias = $this->wrap($entry['alias']);
|
|
||||||
|
|
||||||
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
|
|
||||||
$lobs[] = $selected;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
$nullable &&
|
|
||||||
in_array(
|
|
||||||
$type,
|
|
||||||
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
|
|
||||||
true
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
|
|
||||||
$length = 1;
|
|
||||||
|
|
||||||
if (preg_match(
|
|
||||||
'/\((\d+)\)/',
|
|
||||||
$info['type'] ?? '',
|
|
||||||
$lengthMatch
|
|
||||||
)) {
|
|
||||||
$length = max(1, (int) $lengthMatch[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$expression = 'COALESCE('
|
|
||||||
. $wrapped
|
|
||||||
. ", CAST('' AS VARCHAR({$length})))";
|
|
||||||
} else {
|
|
||||||
$expression = 'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN CAST('' AS VARCHAR(32))"
|
|
||||||
. ' ELSE CAST('
|
|
||||||
. $wrapped
|
|
||||||
. ' AS VARCHAR(32)) END';
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
$expression . ' AS ' . $alias
|
|
||||||
);
|
|
||||||
|
|
||||||
// Character indicators avoid the PDO_ODBC numeric
|
|
||||||
// aggregate/binary conversion issue.
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
|
|
||||||
// Ensure a generated alias cannot collide with any
|
|
||||||
// requested output column.
|
|
||||||
while (isset($aliases[strtolower($flagAlias)])) {
|
|
||||||
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$ordinary[] = new Expression(
|
|
||||||
'CASE WHEN '
|
|
||||||
. $wrapped
|
|
||||||
. " IS NULL THEN '1' ELSE '0' END AS "
|
|
||||||
. $this->wrap($flagAlias)
|
|
||||||
);
|
|
||||||
|
|
||||||
$hasNullIndicators = true;
|
|
||||||
$changed = true;
|
|
||||||
} else {
|
|
||||||
$ordinary[] = $selected;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lobs !== [] && $ordinary !== []) {
|
|
||||||
$changed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $changed) {
|
|
||||||
return parent::compileSelect($query);
|
|
||||||
}
|
|
||||||
|
|
||||||
$modified = clone $query;
|
|
||||||
$modified->columns = array_merge($ordinary, $lobs);
|
|
||||||
|
|
||||||
$sql = parent::compileSelect($modified);
|
|
||||||
|
|
||||||
// Only mark SELECT statements that actually contain
|
|
||||||
// generated NULL indicator columns.
|
|
||||||
if ($hasNullIndicators) {
|
|
||||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $sql;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -27,7 +27,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
{
|
{
|
||||||
$schema = $this->connection->getConfig('schema');
|
$schema = $this->connection->getConfig('schema');
|
||||||
|
|
||||||
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $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.');
|
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,8 +49,8 @@ class Db2SchemaBuilder extends Builder
|
|||||||
throw new \RuntimeException('Unable to read Db2 table name.');
|
throw new \RuntimeException('Unable to read Db2 table name.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
|
$qualified = '"'.str_replace('"', '""', $schema).'"."'.
|
||||||
str_replace('"', '""', trim($name)) . '"';
|
str_replace('"', '""', trim($name)).'"';
|
||||||
|
|
||||||
$this->connection->statement(
|
$this->connection->statement(
|
||||||
"DROP TABLE {$qualified}"
|
"DROP TABLE {$qualified}"
|
||||||
@@ -58,14 +58,13 @@ class Db2SchemaBuilder extends Builder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// BEGIN DB2 SCHEMA INSPECTION
|
// BEGIN DB2 SCHEMA INSPECTION
|
||||||
|
|
||||||
private function db2Schema($schema = null)
|
private function db2Schema($schema = null)
|
||||||
{
|
{
|
||||||
$schema = $schema ?? $this->connection->getConfig('schema');
|
$schema = $schema ?? $this->connection->getConfig('schema');
|
||||||
|
|
||||||
if (!is_string($schema) || $schema === '') {
|
if (! is_string($schema) || $schema === '') {
|
||||||
throw new \RuntimeException('Invalid Db2 schema.');
|
throw new \RuntimeException('Invalid Db2 schema.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,12 +75,13 @@ class Db2SchemaBuilder extends Builder
|
|||||||
$schema = str_replace('""', '"', $schema);
|
$schema = str_replace('""', '"', $schema);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
|
if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
|
||||||
throw new \RuntimeException('Invalid Db2 schema.');
|
throw new \RuntimeException('Invalid Db2 schema.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return strtoupper($schema);
|
return strtoupper($schema);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getTables($schema = null)
|
public function getTables($schema = null)
|
||||||
{
|
{
|
||||||
$schema = $this->db2Schema($schema);
|
$schema = $this->db2Schema($schema);
|
||||||
@@ -102,9 +102,8 @@ class Db2SchemaBuilder extends Builder
|
|||||||
return [
|
return [
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'schema' => $schema,
|
'schema' => $schema,
|
||||||
'schema_qualified_name' =>
|
'schema_qualified_name' => '"'.str_replace('"', '""', $schema).
|
||||||
'"' . str_replace('"', '""', $schema) .
|
'"."'.str_replace('"', '""', $name).'"',
|
||||||
'"."' . str_replace('"', '""', $name) . '"',
|
|
||||||
'type' => $row->TYPE === 'V' ? 'view' : 'table',
|
'type' => $row->TYPE === 'V' ? 'view' : 'table',
|
||||||
'size' => null,
|
'size' => null,
|
||||||
'engine' => null,
|
'engine' => null,
|
||||||
@@ -140,11 +139,11 @@ class Db2SchemaBuilder extends Builder
|
|||||||
$type = $typeName === 'CHARACTER' ? 'CHAR' : $typeName;
|
$type = $typeName === 'CHARACTER' ? 'CHAR' : $typeName;
|
||||||
|
|
||||||
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
|
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
|
||||||
$type .= '(' . (int) $row->LENGTH . ')';
|
$type .= '('.(int) $row->LENGTH.')';
|
||||||
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
|
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
|
||||||
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
|
$type .= '('.(int) $row->LENGTH.','.(int) $row->SCALE.')';
|
||||||
} elseif (strtoupper($type) === 'TIMESTAMP') {
|
} elseif (strtoupper($type) === 'TIMESTAMP') {
|
||||||
$type .= '(' . (int) $row->SCALE . ')';
|
$type .= '('.(int) $row->SCALE.')';
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
@@ -167,7 +166,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
$schema = $this->db2Schema($schema);
|
$schema = $this->db2Schema($schema);
|
||||||
|
|
||||||
$rows = $this->connection->select(
|
$rows = $this->connection->select(
|
||||||
"SELECT I.INDNAME, I.UNIQUERULE,
|
'SELECT I.INDNAME, I.UNIQUERULE,
|
||||||
C.COLNAME, C.COLSEQ
|
C.COLNAME, C.COLSEQ
|
||||||
FROM SYSCAT.INDEXES I
|
FROM SYSCAT.INDEXES I
|
||||||
JOIN SYSCAT.INDEXCOLUSE C
|
JOIN SYSCAT.INDEXCOLUSE C
|
||||||
@@ -175,7 +174,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
AND I.INDNAME = C.INDNAME
|
AND I.INDNAME = C.INDNAME
|
||||||
WHERE I.TABSCHEMA = ?
|
WHERE I.TABSCHEMA = ?
|
||||||
AND I.TABNAME = ?
|
AND I.TABNAME = ?
|
||||||
ORDER BY I.INDNAME, C.COLSEQ",
|
ORDER BY I.INDNAME, C.COLSEQ',
|
||||||
[$schema, $table]
|
[$schema, $table]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -184,7 +183,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$name = trim($row->INDNAME);
|
$name = trim($row->INDNAME);
|
||||||
|
|
||||||
if (!isset($indexes[$name])) {
|
if (! isset($indexes[$name])) {
|
||||||
$indexes[$name] = [
|
$indexes[$name] = [
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'columns' => [],
|
'columns' => [],
|
||||||
@@ -208,7 +207,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
$schema = $this->db2Schema($schema);
|
$schema = $this->db2Schema($schema);
|
||||||
|
|
||||||
$rows = $this->connection->select(
|
$rows = $this->connection->select(
|
||||||
"SELECT R.CONSTNAME,
|
'SELECT R.CONSTNAME,
|
||||||
R.REFTABSCHEMA,
|
R.REFTABSCHEMA,
|
||||||
R.REFTABNAME,
|
R.REFTABNAME,
|
||||||
R.DELETERULE,
|
R.DELETERULE,
|
||||||
@@ -232,7 +231,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
AND RK.COLSEQ = K.COLSEQ
|
AND RK.COLSEQ = K.COLSEQ
|
||||||
WHERE R.TABSCHEMA = ?
|
WHERE R.TABSCHEMA = ?
|
||||||
AND R.TABNAME = ?
|
AND R.TABNAME = ?
|
||||||
ORDER BY R.CONSTNAME, K.COLSEQ",
|
ORDER BY R.CONSTNAME, K.COLSEQ',
|
||||||
[$schema, $table]
|
[$schema, $table]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -242,7 +241,7 @@ class Db2SchemaBuilder extends Builder
|
|||||||
foreach ($rows as $row) {
|
foreach ($rows as $row) {
|
||||||
$name = trim($row->CONSTNAME);
|
$name = trim($row->CONSTNAME);
|
||||||
|
|
||||||
if (!isset($foreignKeys[$name])) {
|
if (! isset($foreignKeys[$name])) {
|
||||||
$foreignKeys[$name] = [
|
$foreignKeys[$name] = [
|
||||||
'name' => $name,
|
'name' => $name,
|
||||||
'columns' => [],
|
'columns' => [],
|
||||||
@@ -278,5 +277,4 @@ class Db2SchemaBuilder extends Builder
|
|||||||
trim($name, '"'),
|
trim($name, '"'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,277 +0,0 @@
|
|||||||
<?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
|
|
||||||
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' => null,
|
|
||||||
'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.TYPE = 'P'
|
|
||||||
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]
|
|
||||||
);
|
|
||||||
|
|
||||||
$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' => trim($row->UPDATERULE),
|
|
||||||
'on_delete' => 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, '"'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,279 +0,0 @@
|
|||||||
<?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, \"DEFAULT\" AS COLDEFAULT, REMARKS,
|
|
||||||
CASE WHEN \"DEFAULT\" IS NULL THEN 1 ELSE 0 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' => (int) $row->NO_DEFAULT === 1 ? 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, '"'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,279 +0,0 @@
|
|||||||
<?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, '"'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
<?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, '"'),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Database\Db2;
|
namespace App\Database\Db2;
|
||||||
|
|
||||||
use Illuminate\Database\Schema\Grammars\Grammar;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Database\Schema\ColumnDefinition;
|
||||||
|
use Illuminate\Database\Schema\Grammars\Grammar;
|
||||||
use Illuminate\Support\Fluent;
|
use Illuminate\Support\Fluent;
|
||||||
|
|
||||||
class Db2SchemaGrammar extends Grammar
|
class Db2SchemaGrammar extends Grammar
|
||||||
@@ -180,7 +182,7 @@ class Db2SchemaGrammar extends Grammar
|
|||||||
|
|
||||||
protected function typeString(Fluent $column)
|
protected function typeString(Fluent $column)
|
||||||
{
|
{
|
||||||
return 'VARCHAR(' . ($column->length ?: 255) . ')';
|
return 'VARCHAR('.($column->length ?: 255).')';
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function typeChar(Fluent $column)
|
protected function typeChar(Fluent $column)
|
||||||
@@ -281,30 +283,30 @@ class Db2SchemaGrammar extends Grammar
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
|
protected function typeJson(ColumnDefinition $column)
|
||||||
{
|
{
|
||||||
return 'CLOB(1M)';
|
return 'CLOB(1M)';
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
|
protected function typeJsonb(ColumnDefinition $column)
|
||||||
{
|
{
|
||||||
return 'CLOB(1M)';
|
return 'CLOB(1M)';
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
|
protected function typeTinyText(ColumnDefinition $column)
|
||||||
{
|
{
|
||||||
return 'VARCHAR(255)';
|
return 'VARCHAR(255)';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function compileInsertOrIgnore(
|
public function compileInsertOrIgnore(
|
||||||
\Illuminate\Database\Query\Builder $query,
|
Builder $query,
|
||||||
array $values
|
array $values
|
||||||
) {
|
) {
|
||||||
if (empty($values)) {
|
if (empty($values)) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!is_array(reset($values))) {
|
if (! is_array(reset($values))) {
|
||||||
$values = [$values];
|
$values = [$values];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,10 +322,10 @@ class Db2SchemaGrammar extends Grammar
|
|||||||
$rows = [];
|
$rows = [];
|
||||||
|
|
||||||
foreach ($values as $row) {
|
foreach ($values as $row) {
|
||||||
$rows[] = '(' . implode(
|
$rows[] = '('.implode(
|
||||||
', ',
|
', ',
|
||||||
array_fill(0, count($columns), '?')
|
array_fill(0, count($columns), '?')
|
||||||
) . ')';
|
).')';
|
||||||
}
|
}
|
||||||
|
|
||||||
$source = implode(', ', $rows);
|
$source = implode(', ', $rows);
|
||||||
@@ -351,7 +353,7 @@ class Db2SchemaGrammar extends Grammar
|
|||||||
implode(
|
implode(
|
||||||
', ',
|
', ',
|
||||||
array_map(
|
array_map(
|
||||||
fn ($column) => 'source.' . $this->wrap($column),
|
fn ($column) => 'source.'.$this->wrap($column),
|
||||||
$columns
|
$columns
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,227 +0,0 @@
|
|||||||
<?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) {
|
|
||||||
$sql = $this->wrap($column) . ' ' . $this->getType($column);
|
|
||||||
|
|
||||||
if ($column->autoIncrement) {
|
|
||||||
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
|
|
||||||
|
|
||||||
// Laravel's $table->id() does not explicitly
|
|
||||||
// set the primary attribute.
|
|
||||||
$primaryKeys[] = $column->name;
|
|
||||||
}
|
|
||||||
|
|
||||||
$sql .= $column->nullable ? '' : ' NOT NULL';
|
|
||||||
|
|
||||||
if (!is_null($column->default)) {
|
|
||||||
$sql .= ' DEFAULT ' . $this->getDefaultValue($column->default);
|
|
||||||
}
|
|
||||||
|
|
||||||
$columns[] = $sql;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Db2 identity columns are not automatically primary keys.
|
|
||||||
if (!empty($primaryKeys)) {
|
|
||||||
$columns[] = sprintf(
|
|
||||||
'PRIMARY KEY (%s)',
|
|
||||||
$this->columnize($primaryKeys)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return sprintf(
|
|
||||||
'CREATE TABLE %s (%s)',
|
|
||||||
$this->wrapTable($blueprint),
|
|
||||||
implode(', ', $columns)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 PRIMARY KEY (%s)',
|
|
||||||
$this->wrapTable($blueprint),
|
|
||||||
$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->wrap($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->wrap($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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,330 +0,0 @@
|
|||||||
<?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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,355 +0,0 @@
|
|||||||
<?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 === 'TIMESTAMP' ? 'TIMESTAMP(6)' : $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);
|
|
||||||
}
|
|
||||||
|
|
||||||
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());
|
|
||||||
|
|
||||||
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 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)';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function typeLongText(Fluent $column)
|
|
||||||
{
|
|
||||||
return 'CLOB(2M)';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function typeBoolean(Fluent $column)
|
|
||||||
{
|
|
||||||
return 'SMALLINT';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function typeTimestamp(Fluent $column)
|
|
||||||
{
|
|
||||||
return $column->precision === null ? 'TIMESTAMP' : 'TIMESTAMP('.$column->precision.')';
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function typeDateTime(Fluent $column)
|
|
||||||
{
|
|
||||||
return $this->typeTimestamp($column);
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
use App\Database\Db2\Db2Connection;
|
use App\Database\Db2\Db2Connection;
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
use PDO;
|
use PDO;
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
@@ -13,7 +13,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
{
|
{
|
||||||
DB::extend('odbc', function (array $config, string $name): Db2Connection {
|
DB::extend('odbc', function (array $config, string $name): Db2Connection {
|
||||||
$pdo = new PDO(
|
$pdo = new PDO(
|
||||||
'odbc:' . ($config['dsn'] ?? 'MEDIUK'),
|
'odbc:'.($config['dsn'] ?? 'MEDIUK'),
|
||||||
$config['username'] ?? '',
|
$config['username'] ?? '',
|
||||||
$config['password'] ?? '',
|
$config['password'] ?? '',
|
||||||
[
|
[
|
||||||
@@ -47,6 +47,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
}
|
}
|
||||||
|
|
||||||
$pdo->exec('SET CURRENT SCHEMA '.$schema);
|
$pdo->exec('SET CURRENT SCHEMA '.$schema);
|
||||||
|
|
||||||
return strtoupper($schema);
|
return strtoupper($schema);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +59,5 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
return rtrim($currentSchema);
|
return rtrim($currentSchema);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function boot(): void
|
public function boot(): void {}
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -18,7 +18,8 @@
|
|||||||
"livewire/flux": "^2.13.1",
|
"livewire/flux": "^2.13.1",
|
||||||
"livewire/livewire": "^4.1",
|
"livewire/livewire": "^4.1",
|
||||||
"predis/predis": "^3.5",
|
"predis/predis": "^3.5",
|
||||||
"mpba/laravel-modules": "dev-main"
|
"mpba/laravel-modules": "dev-main",
|
||||||
|
"ext-pdo": "*"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"deployer/deployer": "^8.0",
|
"deployer/deployer": "^8.0",
|
||||||
|
|||||||
@@ -37,10 +37,10 @@ return new class extends Migration
|
|||||||
public function down(): void
|
public function down(): void
|
||||||
{
|
{
|
||||||
foreach ([
|
foreach ([
|
||||||
'two_factor_confirmed_at',
|
'two_factor_confirmed_at',
|
||||||
'two_factor_recovery_codes',
|
'two_factor_recovery_codes',
|
||||||
'two_factor_secret',
|
'two_factor_secret',
|
||||||
] as $column) {
|
] as $column) {
|
||||||
if (Schema::hasColumn('users', $column)) {
|
if (Schema::hasColumn('users', $column)) {
|
||||||
Schema::table('users', function (Blueprint $table) use ($column) {
|
Schema::table('users', function (Blueprint $table) use ($column) {
|
||||||
$table->dropColumn($column);
|
$table->dropColumn($column);
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
|
||||||
bootstrap="vendor/autoload.php"
|
|
||||||
colors="true"
|
|
||||||
>
|
|
||||||
<testsuites>
|
|
||||||
<testsuite name="Unit">
|
|
||||||
<directory>tests/Unit</directory>
|
|
||||||
</testsuite>
|
|
||||||
<testsuite name="Feature">
|
|
||||||
<directory>tests/Feature</directory>
|
|
||||||
</testsuite>
|
|
||||||
</testsuites>
|
|
||||||
<source>
|
|
||||||
<include>
|
|
||||||
<directory>app</directory>
|
|
||||||
</include>
|
|
||||||
</source>
|
|
||||||
<php>
|
|
||||||
<env name="APP_ENV" value="testing"/>
|
|
||||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
|
||||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
|
||||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
|
||||||
<env name="CACHE_STORE" value="array"/>
|
|
||||||
<env name="DB_CONNECTION" value="sqlite"/>
|
|
||||||
<env name="DB_DATABASE" value=":memory:"/>
|
|
||||||
<env name="DB_URL" value=""/>
|
|
||||||
<env name="MAIL_MAILER" value="array"/>
|
|
||||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
|
||||||
<env name="SESSION_DRIVER" value="array"/>
|
|
||||||
<env name="PULSE_ENABLED" value="false"/>
|
|
||||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
|
||||||
<env name="NIGHTWATCH_ENABLED" value="false"/>
|
|
||||||
</php>
|
|
||||||
</phpunit>
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
|
||||||
bootstrap="vendor/autoload.php"
|
|
||||||
colors="true"
|
|
||||||
>
|
|
||||||
<testsuites>
|
|
||||||
<testsuite name="Unit">
|
|
||||||
<directory>tests/Unit</directory>
|
|
||||||
</testsuite>
|
|
||||||
<testsuite name="Feature">
|
|
||||||
<directory>tests/Feature</directory>
|
|
||||||
</testsuite>
|
|
||||||
</testsuites>
|
|
||||||
<source>
|
|
||||||
<include>
|
|
||||||
<directory>app</directory>
|
|
||||||
</include>
|
|
||||||
</source>
|
|
||||||
<php>
|
|
||||||
<env name="APP_ENV" value="testing"/>
|
|
||||||
<env name="APP_URL" value="http://localhost"/>
|
|
||||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
|
||||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
|
||||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
|
||||||
<env name="CACHE_STORE" value="array"/>
|
|
||||||
<env name="DB_CONNECTION" value="sqlite"/>
|
|
||||||
<env name="DB_DATABASE" value=":memory:"/>
|
|
||||||
<env name="DB_URL" value=""/>
|
|
||||||
<env name="MAIL_MAILER" value="array"/>
|
|
||||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
|
||||||
<env name="SESSION_DRIVER" value="array"/>
|
|
||||||
<env name="PULSE_ENABLED" value="false"/>
|
|
||||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
|
||||||
<env name="NIGHTWATCH_ENABLED" value="false"/>
|
|
||||||
</php>
|
|
||||||
</phpunit>
|
|
||||||
@@ -162,4 +162,4 @@ git diff --check
|
|||||||
|
|
||||||
A skipped Db2 test means the connection or extension was unavailable. The general application tests use SQLite and the Db2 integration tests use the configured Db2 connection.
|
A skipped Db2 test means the connection or extension was unavailable. The general application tests use SQLite and the Db2 integration tests use the configured Db2 connection.
|
||||||
|
|
||||||
Review the [schema compatibility notes](DB2-SCHEMA-COMPATIBILITY.md) for type mappings, index limits, and when Db2 may require `REORG`. The [query compatibility notes](DB2-QUERY-COMPATIBILITY.md) describe the scope of NULL handling and query support. The [release verification](DB2-RELEASE-VERIFICATION.md) records the tested version matrix and the migration and authenticated passkey-page checks. Browser WebAuthn enrolment and sign-in were outside that verification.
|
Review the [schema compatibility notes](app/Database/Db2/docs/DB2-SCHEMA-COMPATIBILITY.md) for type mappings, index limits, and when Db2 may require `REORG`. The [query compatibility notes](app/Database/Db2/docs/DB2-QUERY-COMPATIBILITY.md) describe the scope of NULL handling and query support. The [release verification](app/Database/Db2/docs/DB2-RELEASE-VERIFICATION.md) records the tested version matrix and the migration and authenticated passkey-page checks. Browser WebAuthn enrolment and sign-in were outside that verification.
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
### Standard Laravel 13 Install for Developpment
|
|
||||||
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
# Laravel 13 with Db2 LUW
|
|
||||||
|
|
||||||
This Laravel application includes a project-local Db2 driver built on PHP PDO_ODBC, unixODBC, and the IBM Db2 CLI driver. The verified setup uses Laravel 13.25.0, PHP 8.5.11 on macOS, and Db2 LUW 12.1.5.0 in Docker.
|
|
||||||
|
|
||||||
## Create a database in Docker
|
|
||||||
|
|
||||||
Run these commands from your Mac terminal. The first command shows the container name and published ports. This setup uses the `Db2-Server` container with port `50000` published to the Mac.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Ports}}'
|
|
||||||
docker exec -it Db2-Server bash
|
|
||||||
su - db2inst1
|
|
||||||
. ~/sqllib/db2profile
|
|
||||||
db2 list db directory
|
|
||||||
```
|
|
||||||
|
|
||||||
If `LARAVEL` does not already appear in the database directory, create it alongside `MAIN`.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
db2 create database LARAVEL
|
|
||||||
```
|
|
||||||
|
|
||||||
Connect to the new database and confirm the target before creating application objects.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
db2 connect to LARAVEL
|
|
||||||
db2 "VALUES CURRENT SERVER"
|
|
||||||
db2 "CREATE SCHEMA DB2_TEST AUTHORIZATION DB2INST1"
|
|
||||||
db2 connect reset
|
|
||||||
```
|
|
||||||
|
|
||||||
Run `CREATE SCHEMA` once if you want the dedicated `DB2_TEST` schema. To use the connection's default schema, skip that statement and omit `DB2_SCHEMA` from Laravel's environment. With the local `db2inst1` account, the fallback previously resolved to `DB2INST1`. The database account needs privileges to create and manage application objects in the chosen schema.
|
|
||||||
|
|
||||||
## Register the ODBC data source on the Mac
|
|
||||||
|
|
||||||
Use a distinct DSN called `LARAVELDB` so the existing `MEDIUK` entry can still point to `MAIN`. Confirm PHP has the ODBC extension and locate the active unixODBC configuration.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
php -r 'print_r(PDO::getAvailableDrivers());'
|
|
||||||
odbcinst -j
|
|
||||||
odbcinst -q -d
|
|
||||||
```
|
|
||||||
|
|
||||||
The driver list should include `odbc`, and unixODBC should list `IBM DB2 ODBC DRIVER`. Add this section once to the active `odbc.ini`. In the verified Mac setup the system file is `/opt/homebrew/etc/odbc.ini`. Back up the file before editing.
|
|
||||||
|
|
||||||
```ini
|
|
||||||
[LARAVELDB]
|
|
||||||
Driver=IBM DB2 ODBC DRIVER
|
|
||||||
Database=LARAVEL
|
|
||||||
Hostname=127.0.0.1
|
|
||||||
Port=50000
|
|
||||||
Protocol=TCPIP
|
|
||||||
```
|
|
||||||
|
|
||||||
Register the same alias with the IBM client. The commands below use the verified installation paths. If `DB2DSDRIVER_CFG_PATH` selects another file, back up and use that active configuration instead.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp -p "$HOME/IBM/db2/clidriver/cfg/db2dsdriver.cfg" \
|
|
||||||
"$HOME/IBM/db2/clidriver/cfg/db2dsdriver.cfg.bak-$(date +%Y%m%d-%H%M%S)"
|
|
||||||
"$HOME/IBM/db2/clidriver/bin/db2cli" writecfg add \
|
|
||||||
-dsn LARAVELDB -database LARAVEL -host 127.0.0.1 -port 50000
|
|
||||||
odbcinst -q -s
|
|
||||||
"$HOME/IBM/db2/clidriver/bin/db2cli" validate -dsn LARAVELDB
|
|
||||||
```
|
|
||||||
|
|
||||||
`SQL1531N` with `LARAVELDB` already listed by unixODBC usually means the IBM client cannot find the alias in its active configuration. Check that the PHP process and your terminal use the same IBM client configuration.
|
|
||||||
|
|
||||||
## Configure Laravel and run migrations
|
|
||||||
|
|
||||||
In the project's `.env`, set the connection details and use your own credentials.
|
|
||||||
|
|
||||||
```dotenv
|
|
||||||
DB_CONNECTION=db2_local
|
|
||||||
DB2_DSN=LARAVELDB
|
|
||||||
DB2_DATABASE=LARAVEL
|
|
||||||
DB2_SCHEMA=DB2_TEST
|
|
||||||
DB2_USERNAME=db2inst1
|
|
||||||
DB2_PASSWORD=your_password
|
|
||||||
```
|
|
||||||
|
|
||||||
The DSN selects the actual target and supplies the host and port. `DB2_DATABASE` is Laravel's connection metadata. This connector gets its network settings from the DSN.
|
|
||||||
|
|
||||||
From the project directory, clear cached configuration and verify the database and schema through Laravel.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
php artisan config:clear
|
|
||||||
php artisan tinker --execute='dump(DB::selectOne("SELECT CURRENT SERVER AS DB_NAME, CURRENT SCHEMA AS SCHEMA_NAME FROM SYSIBM.SYSDUMMY1"));'
|
|
||||||
```
|
|
||||||
|
|
||||||
When the output shows `LARAVEL` and your intended schema, run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
php artisan migrate
|
|
||||||
php artisan migrate:status
|
|
||||||
```
|
|
||||||
|
|
||||||
Create the database first. Migrations create application tables in that database. Existing data in `MAIN` stays there until you transfer it separately.
|
|
||||||
|
|
||||||
## Browse or remove schemas
|
|
||||||
|
|
||||||
DBeaver Community can connect using its **IBM Db2 LUW** driver. Use host `127.0.0.1`, port `50000`, database `LARAVEL`, and your Db2 credentials. DBeaver connects via JDBC and can have a separate connection for `MAIN`. [DBeaver Community download](https://dbeaver.com/edition/community/)
|
|
||||||
|
|
||||||
To inspect the old `DB2_TEST` schema, run the following in the same `db2inst1` shell inside Docker.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
db2 connect to MAIN
|
|
||||||
db2 "VALUES CURRENT SERVER"
|
|
||||||
db2 "LIST TABLES FOR SCHEMA DB2_TEST"
|
|
||||||
```
|
|
||||||
|
|
||||||
After confirming `MAIN`, use `db2 "DROP SCHEMA DB2_TEST RESTRICT"` to remove an empty schema. `SQL0478N` means dependent objects remain. If you intend to permanently delete those objects and their data from `MAIN`, run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
db2 "CALL SYSPROC.ADMIN_DROP_SCHEMA('DB2_TEST', NULL, 'DB2INST1', 'DROP_DB2_TEST_ERRORS')"
|
|
||||||
db2 "SELECT SCHEMANAME FROM SYSCAT.SCHEMATA WHERE SCHEMANAME = 'DB2_TEST'"
|
|
||||||
db2 connect reset
|
|
||||||
```
|
|
||||||
|
|
||||||
Zero rows confirms removal. If the procedure reports an error table, inspect it for individual failures. `SQL1024N` means you need to connect to the database from the current shell first.
|
|
||||||
|
|
||||||
## How the driver works
|
|
||||||
|
|
||||||
| Component | Responsibility |
|
|
||||||
| --- | --- |
|
|
||||||
| [Database configuration](config/database.php) | Defines the `db2_local` connection with the `odbc` driver. |
|
|
||||||
| [AppServiceProvider](app/Providers/AppServiceProvider.php) | Registers the driver with Laravel, opens PDO using the DSN, and applies the configured schema or reads `CURRENT SCHEMA` for metadata. |
|
|
||||||
| [Db2Connection](app/Database/Db2/Db2Connection.php) | Wires up the Db2 builder, grammars, and processor. Decodes the internal NULL indicators on eligible result reads. |
|
|
||||||
| [Db2QueryBuilder](app/Database/Db2/Db2QueryBuilder.php) and [Db2QueryGrammar](app/Database/Db2/Db2QueryGrammar.php) | Compile Db2 pagination, savepoints, case-aware LIKE, and MERGE-based upserts and insert-or-ignore. Apply PDO_ODBC result handling when fetching eligible rows. |
|
|
||||||
| [Db2Processor](app/Database/Db2/Db2Processor.php) | Retrieves generated identities on the same connection after insertion. |
|
|
||||||
| [Db2SchemaGrammar](app/Database/Db2/Db2SchemaGrammar.php) | Converts Laravel schema blueprints into Db2 DDL for tables, columns, indexes, and constraints. |
|
|
||||||
| [Db2SchemaBuilder](app/Database/Db2/Db2SchemaBuilder.php) | Reads table, column, index, and foreign-key metadata from the Db2 catalog. |
|
|
||||||
|
|
||||||
The result-only SQL path adds NULL indicators where needed and formats nullable timestamps for Eloquent date casting. Embedded queries keep their declared columns, which is required for scalar subqueries, `WHERE IN`, and `UNION`.
|
|
||||||
|
|
||||||
On Db2 LUW, unqualified table names resolve in one current schema. Use a qualified table such as `DB::connection('db2_local')->table('ARCHIVE.CUSTOMERS')` to access another schema in the same database, subject to privileges. The IBM i Access `DBQ` library-list setting does not provide a table search path on Db2 LUW.
|
|
||||||
|
|
||||||
Laravel can also select its standard MySQL driver through `DB_CONNECTION=mysql` and the corresponding `DB_*` settings. Switching the connection leaves existing Db2 data in Db2. The release notes cover the verified Db2 setup.
|
|
||||||
|
|
||||||
## Developer workflow
|
|
||||||
|
|
||||||
1. Check the installed Illuminate APIs and the existing driver classes before editing. Keep changes in application code. Add accurate PHPDoc headers and explicit return types to methods you add or modify, matching inherited signatures.
|
|
||||||
2. Reproduce the problem through the normal Laravel entry point in a focused test under [tests/Feature/Db2](tests/Feature/Db2). Use a disposable database or schema. The Db2 tests explicitly use `db2_local`, and the release test creates and removes its own schema.
|
|
||||||
3. Run the focused test against Db2 before the fix. Check the SQL, catalog state, or PHP values relevant to the failure. Run PHP syntax checks on changed files and then rerun the focused and regression suites.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
composer validate --no-check-publish --no-interaction
|
|
||||||
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/ReleaseCompatibilityTest.php
|
|
||||||
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2
|
|
||||||
APP_ENV=testing php artisan test --do-not-cache-result
|
|
||||||
git diff --check
|
|
||||||
```
|
|
||||||
|
|
||||||
A skipped Db2 test means the connection or extension was unavailable. The general application tests use SQLite and the Db2 integration tests use the configured Db2 connection.
|
|
||||||
|
|
||||||
Review the [schema compatibility notes](DB2-SCHEMA-COMPATIBILITY.md) for type mappings, index limits, and when Db2 may require `REORG`. The [query compatibility notes](DB2-QUERY-COMPATIBILITY.md) describe the scope of NULL handling and query support. The [release verification](DB2-RELEASE-VERIFICATION.md) records the tested version matrix and the migration and authenticated passkey-page checks. Browser WebAuthn enrolment and sign-in were outside that verification.
|
|
||||||
@@ -30,7 +30,7 @@ abstract class Db2TestCase extends TestCase
|
|||||||
);
|
);
|
||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
$this->markTestSkipped(
|
$this->markTestSkipped(
|
||||||
'Db2 connection unavailable: ' . $e->getMessage()
|
'Db2 connection unavailable: '.$e->getMessage()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Db2;
|
namespace Tests\Feature\Db2;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class NullHandlingTest extends Db2TestCase
|
class NullHandlingTest extends Db2TestCase
|
||||||
{
|
{
|
||||||
private string $fixtureTable = '';
|
private string $fixtureTable = '';
|
||||||
@@ -14,7 +12,7 @@ class NullHandlingTest extends Db2TestCase
|
|||||||
|
|
||||||
// Each test owns a unique permanent table.
|
// Each test owns a unique permanent table.
|
||||||
// Db2 catalog metadata can discover its columns.
|
// Db2 catalog metadata can discover its columns.
|
||||||
$this->fixtureTable = 'DB2_TEST.DB2T_' .
|
$this->fixtureTable = 'DB2_TEST.DB2T_'.
|
||||||
strtoupper(bin2hex(random_bytes(6)));
|
strtoupper(bin2hex(random_bytes(6)));
|
||||||
|
|
||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ class PaginationIdentityTest extends Db2TestCase
|
|||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
$this->tableName = 'DB2_TEST.DB2T_'.
|
||||||
strtoupper(bin2hex(random_bytes(6)));
|
strtoupper(bin2hex(random_bytes(6)));
|
||||||
|
|
||||||
$this->db()->statement("
|
$this->db()->statement("
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Db2;
|
namespace Tests\Feature\Db2;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
class QueryCompatibilityTest extends Db2TestCase
|
class QueryCompatibilityTest extends Db2TestCase
|
||||||
{
|
{
|
||||||
private ?string $table = null;
|
private ?string $table = null;
|
||||||
@@ -77,7 +79,8 @@ class QueryCompatibilityTest extends Db2TestCase
|
|||||||
|
|
||||||
public function test_eloquent_casts_db2_timestamps_for_security_settings(): void
|
public function test_eloquent_casts_db2_timestamps_for_security_settings(): void
|
||||||
{
|
{
|
||||||
$model = new class extends \Illuminate\Database\Eloquent\Model {
|
$model = new class extends Model
|
||||||
|
{
|
||||||
protected $casts = ['CREATED_AT' => 'datetime', 'LAST_USED_AT' => 'datetime'];
|
protected $casts = ['CREATED_AT' => 'datetime', 'LAST_USED_AT' => 'datetime'];
|
||||||
};
|
};
|
||||||
$model->setConnection('db2_local')->setTable($this->table);
|
$model->setConnection('db2_local')->setTable($this->table);
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Db2;
|
namespace Tests\Feature\Db2;
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\DatabaseMigrationRepository;
|
||||||
|
use Illuminate\Database\Migrations\Migrator;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
|
||||||
class SchemaTest extends Db2TestCase
|
class SchemaTest extends Db2TestCase
|
||||||
@@ -104,8 +106,8 @@ class SchemaTest extends Db2TestCase
|
|||||||
$db = $this->db();
|
$db = $this->db();
|
||||||
$schema = $db->getSchemaBuilder();
|
$schema = $db->getSchemaBuilder();
|
||||||
$table = 'stage5_'.bin2hex(random_bytes(6));
|
$table = 'stage5_'.bin2hex(random_bytes(6));
|
||||||
$repository = new \Illuminate\Database\Migrations\DatabaseMigrationRepository(app('db'), $table.'_history');
|
$repository = new DatabaseMigrationRepository(app('db'), $table.'_history');
|
||||||
$migrator = new \Illuminate\Database\Migrations\Migrator($repository, app('db'), app('files'), app('events'));
|
$migrator = new Migrator($repository, app('db'), app('files'), app('events'));
|
||||||
config(['stage5.table' => $table]);
|
config(['stage5.table' => $table]);
|
||||||
$file = base_path('tests/Fixtures/Db2/2026_01_01_000000_stage5_schema.php');
|
$file = base_path('tests/Fixtures/Db2/2026_01_01_000000_stage5_schema.php');
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ class TransactionTest extends Db2TestCase
|
|||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
$this->tableName = 'DB2_TEST.DB2T_'.
|
||||||
strtoupper(bin2hex(random_bytes(6)));
|
strtoupper(bin2hex(random_bytes(6)));
|
||||||
|
|
||||||
$this->db()->statement("
|
$this->db()->statement("
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Db2;
|
namespace Tests\Feature\Db2;
|
||||||
|
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
|
||||||
class UpsertTest extends Db2TestCase
|
class UpsertTest extends Db2TestCase
|
||||||
{
|
{
|
||||||
private string $tableName = '';
|
private string $tableName = '';
|
||||||
@@ -10,7 +12,7 @@ class UpsertTest extends Db2TestCase
|
|||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
$this->tableName = 'DB2_TEST.DB2T_'.
|
||||||
strtoupper(bin2hex(random_bytes(6)));
|
strtoupper(bin2hex(random_bytes(6)));
|
||||||
|
|
||||||
$this->db()->statement("
|
$this->db()->statement("
|
||||||
@@ -216,7 +218,7 @@ class UpsertTest extends Db2TestCase
|
|||||||
public function test_insert_or_ignore_does_not_hide_check_violations(): void
|
public function test_insert_or_ignore_does_not_hide_check_violations(): void
|
||||||
{
|
{
|
||||||
$this->expectException(
|
$this->expectException(
|
||||||
\Illuminate\Database\QueryException::class
|
QueryException::class
|
||||||
);
|
);
|
||||||
|
|
||||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||||
|
|||||||
Reference in New Issue
Block a user