diff --git a/DB2-SCHEMA-COMPATIBILITY.md b/DB2-SCHEMA-COMPATIBILITY.md index 7740664..2922389 100644 --- a/DB2-SCHEMA-COMPATIBILITY.md +++ b/DB2-SCHEMA-COMPATIBILITY.md @@ -57,3 +57,11 @@ Run the focused live tests with: ```sh APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/SchemaTypesAndIndexesTest.php ``` + + +## Selecting the default schema + +Set `DB2_SCHEMA` to use a specific schema on the database selected by +`DB2_DSN`. If omitted or blank, the connector retains the DSN or server +default and reads `CURRENT SCHEMA` for Laravel catalog lookups. Set +`DB2_SCHEMA=AAMEDIUK` explicitly to retain the former default. diff --git a/DB2-SCHEMA-COMPATIBILITY.md.bak-default-schema-20261111-112222 b/DB2-SCHEMA-COMPATIBILITY.md.bak-default-schema-20261111-112222 new file mode 100644 index 0000000..7740664 --- /dev/null +++ b/DB2-SCHEMA-COMPATIBILITY.md.bak-default-schema-20261111-112222 @@ -0,0 +1,59 @@ +# 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 +``` diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 7ab6985..e55a1a3 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -11,7 +11,7 @@ class AppServiceProvider extends ServiceProvider { public function register(): void { - DB::extend('odbc', function (array $config, string $name) { + DB::extend('odbc', function (array $config, string $name): Db2Connection { $pdo = new PDO( 'odbc:' . ($config['dsn'] ?? 'MEDIUK'), $config['username'] ?? '', @@ -22,16 +22,7 @@ class AppServiceProvider extends ServiceProvider ] ); - $schema = $config['schema'] ?? null; - - if ($schema) { - if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) { - throw new \InvalidArgumentException('Invalid Db2 schema'); - } - - $pdo->exec('SET CURRENT SCHEMA ' . $schema); - } - + $config['schema'] = $this->resolveDb2Schema($pdo, $config['schema'] ?? null); $config['name'] = $name; return new Db2Connection( @@ -43,6 +34,30 @@ class AppServiceProvider extends ServiceProvider }); } + /** + * Apply an explicit schema and read the effective schema for catalog queries. + */ + private function resolveDb2Schema(PDO $pdo, ?string $configuredSchema): string + { + $schema = trim($configuredSchema ?? ''); + + if ($schema !== '') { + if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/D', $schema)) { + throw new \InvalidArgumentException('Invalid Db2 schema'); + } + + $pdo->exec('SET CURRENT SCHEMA '.$schema); + return strtoupper($schema); + } + + $currentSchema = $pdo->query('VALUES CURRENT SCHEMA')->fetchColumn(); + if (! is_string($currentSchema) || trim($currentSchema) === '') { + throw new \RuntimeException('Unable to resolve the current Db2 schema.'); + } + + return rtrim($currentSchema); + } + public function boot(): void { } diff --git a/app/Providers/AppServiceProvider.php.bak-default-schema-20261111-112222 b/app/Providers/AppServiceProvider.php.bak-default-schema-20261111-112222 new file mode 100644 index 0000000..7ab6985 --- /dev/null +++ b/app/Providers/AppServiceProvider.php.bak-default-schema-20261111-112222 @@ -0,0 +1,49 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, + ] + ); + + $schema = $config['schema'] ?? null; + + if ($schema) { + if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) { + throw new \InvalidArgumentException('Invalid Db2 schema'); + } + + $pdo->exec('SET CURRENT SCHEMA ' . $schema); + } + + $config['name'] = $name; + + return new Db2Connection( + $pdo, + $config['database'] ?? '', + $config['prefix'] ?? '', + $config + ); + }); + } + + public function boot(): void + { + } +} diff --git a/config/database.php b/config/database.php index 23b2bce..ff8fc98 100644 --- a/config/database.php +++ b/config/database.php @@ -35,7 +35,7 @@ return [ 'driver' => 'odbc', 'dsn' => env('DB2_DSN', 'MEDIUK'), 'database' => env('DB2_DATABASE', 'MAIN'), - 'schema' => env('DB2_SCHEMA', 'AAMEDIUK'), + 'schema' => env('DB2_SCHEMA'), 'username' => env('DB2_USERNAME', 'db2inst1'), 'password' => env('DB2_PASSWORD', ''), ], diff --git a/config/database.php.bak-default-schema-20261111-112222 b/config/database.php.bak-default-schema-20261111-112222 new file mode 100644 index 0000000..23b2bce --- /dev/null +++ b/config/database.php.bak-default-schema-20261111-112222 @@ -0,0 +1,192 @@ + env('DB_CONNECTION', 'sqlite'), + + /* + |-------------------------------------------------------------------------- + | Database Connections + |-------------------------------------------------------------------------- + | + | Below are all of the database connections defined for your application. + | An example configuration is provided for each database system which + | is supported by Laravel. You're free to add / remove connections. + | + */ + + 'connections' => [ + 'db2_local' => [ + 'driver' => 'odbc', + 'dsn' => env('DB2_DSN', 'MEDIUK'), + 'database' => env('DB2_DATABASE', 'MAIN'), + 'schema' => env('DB2_SCHEMA', 'AAMEDIUK'), + 'username' => env('DB2_USERNAME', 'db2inst1'), + 'password' => env('DB2_PASSWORD', ''), + ], + + 'sqlite' => [ + 'driver' => 'sqlite', + 'url' => env('DB_URL'), + 'database' => env('DB_DATABASE', database_path('database.sqlite')), + 'prefix' => '', + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + 'busy_timeout' => null, + 'journal_mode' => null, + 'synchronous' => null, + 'transaction_mode' => 'DEFERRED', + ], + + 'mysql' => [ + 'driver' => 'mysql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'mariadb' => [ + 'driver' => 'mariadb', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'pgsql' => [ + 'driver' => 'pgsql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '5432'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + 'search_path' => 'public', + 'sslmode' => env('DB_SSLMODE', 'prefer'), + ], + + 'sqlsrv' => [ + 'driver' => 'sqlsrv', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', 'localhost'), + 'port' => env('DB_PORT', '1433'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + // 'encrypt' => env('DB_ENCRYPT', 'yes'), + // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Migration Repository Table + |-------------------------------------------------------------------------- + | + | This table keeps track of all the migrations that have already run for + | your application. Using this information, we can determine which of + | the migrations on disk haven't actually been run on the database. + | + */ + + 'migrations' => [ + 'table' => 'migrations', + 'update_date_on_publish' => true, + ], + + /* + |-------------------------------------------------------------------------- + | Redis Databases + |-------------------------------------------------------------------------- + | + | Redis is an open source, fast, and advanced key-value store that also + | provides a richer body of commands than a typical key-value system + | such as Memcached. You may define your connection settings here. + | + */ + + 'redis' => [ + + 'client' => env('REDIS_CLIENT', 'phpredis'), + + 'options' => [ + 'cluster' => env('REDIS_CLUSTER', 'redis'), + 'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'), + 'persistent' => env('REDIS_PERSISTENT', false), + ], + + 'default' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_DB', '0'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + 'cache' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_CACHE_DB', '1'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + ], + +]; diff --git a/readme.md b/readme.md index f7ef683..bfed376 100755 --- a/readme.md +++ b/readme.md @@ -1,2 +1,165 @@ -### Standard Laravel 13 Install for Developpment +# 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 +``` + +At the container's `root` prompt, switch to the Db2 instance owner. + +```bash +su - db2inst1 +``` + +Wait for the prompt to show `db2inst1`, then load the Db2 environment and list the databases. + +```bash +. ~/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. diff --git a/readme.md.bak-db2-20261111-130747 b/readme.md.bak-db2-20261111-130747 new file mode 100755 index 0000000..f7ef683 --- /dev/null +++ b/readme.md.bak-db2-20261111-130747 @@ -0,0 +1,2 @@ +### Standard Laravel 13 Install for Developpment + diff --git a/readme.md.bak-db2-20261111-131136 b/readme.md.bak-db2-20261111-131136 new file mode 100755 index 0000000..aeaf8bf --- /dev/null +++ b/readme.md.bak-db2-20261111-131136 @@ -0,0 +1,155 @@ +# 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.