Switching Databases: Scan, Audit, Copy & Verify
Switching a production Laravel application from one database engine to another (for example, migrating from CockroachDB to MatrixOne or MySQL to PostgreSQL) involves three major challenges:
- Finding incompatible SQL: Raw SQL queries hidden inside string literals.
- Schema and type mismatches: Columns that are narrower on the target (e.g. 64-bit integer on source fitting into a 32-bit integer column on target, or strings exceeding
varchar(n)). - Data migration safety: Preserving foreign key order, handling time zone offsets, resetting auto-increment sequences, and resuming interrupted transfers.
Laravel DB Portable provides four Artisan commands designed to execute this workflow with confidence.
6-Step Migration Workflow
flowchart LR
A["1. Scan Code"] --> B["2. Migrate Target"]
B --> C["3. Audit Data"]
C --> D["4. Copy Rows"]
D --> E["5. Verify Rows"]
E --> F["6. Switch DB_CONNECTION"]Step 1: Scan for Incompatible SQL (db-portable:scan)
The scanner tokenizes PHP code and inspects string literals. It ignores code comments and non-SQL strings, flagging syntax specific to a database family:
# Scan default paths (app/, database/, routes/) targeting MatrixOne
php artisan db-portable:scan --target=matrixone
# Scan specific directories targeting MySQL and SQLite
php artisan db-portable:scan app/Filament --target=mysql --target=sqlite
# Output JSON and fail CI on findings
php artisan db-portable:scan --json --failDetected Constructs
| Rule | Detected Syntax | Suggested Replacement |
|---|---|---|
pg-json-operator | col->>'key' | where('col->key', ...), whereJsonNumber() |
pg-cast | ::bigint, ::text, ::jsonb | Eloquent casts, Portable::castText() |
nulls-first-last | NULLS LAST, NULLS FIRST | orderByNullsLast() |
pg-jsonb-function | jsonb_set, jsonb_array_length | incrementJson(), whereJsonLength() |
mysql-backtick | \id`` in raw SQL | wrap() or standard Eloquent |
ifnull | IFNULL(a, b) | COALESCE(a, b) |
mysql-if | IF(expr, a, b) | CASE WHEN ... THEN ... ELSE ... END |
mysql-limit-offset | LIMIT 10, 20 | LIMIT 20 OFFSET 10 |
on-duplicate-key | ON DUPLICATE KEY UPDATE | upsert() or updateOrInsert() |
group-concat | GROUP_CONCAT(...) | Portable expression or application logic |
having-without-group-by | ->having() without ->groupBy(), select ... having without group by | whereHas('relation', $callback, '>=', $n), group the selected columns |
What the Scanner Cannot See
Some differences only show with the application's real data and queries. Found while moving Laravel 13 sites from MySQL to MatrixOne:
HAVINGwithoutGROUP BY:withCount('tags')->having('tags_count', '>=', 2)runs on MySQL; MatrixOne and PostgreSQL want the selected columns grouped, SQLite refuses a non-aggregate query. Thehaving-without-group-byrule flags a builder statement that callshaving*()withoutgroupBy(), and a rawselect ... havingliteral withoutgroup by. A query grouped in another statement ($query->groupBy(...)then$query->having(...)) is reported too, and one built through variables across methods is missed.whereHas('tags', $callback, '>=', 2)gives MySQL's result everywhere.paginate()/simplePaginate()of abelongsToManyrelation addtable.*to the select even afterselect()(the columns default to['*']): a join on a table of wide rows. Not an error, but on MatrixOne it reads every column and can exhaust the memory. Pass the columns:$tag->posts()->simplePaginate(10, ['posts.id', 'posts.title']). The scanner cannot tell a relation's type.select *sorted or paginated on a table of wide rows (100 KB of HTML per row): slow or out of memory on MatrixOne. Paginate on the key, then load the page's rows by key. Needs the table sizes, not the code.- A numeric column compared with a non-numeric string (
where('id', $request->id)with705%25...from a bot): MySQL casts the string and finds nothing, MatrixOne fails withinvalid argument cast to uint64(a 500 error). Validate the input (->whereNumber('id')on routes). The values come from requests. - Case-sensitive comparisons: MatrixOne compares
varcharcase-sensitively, unlike MySQL'sutf8mb4_unicode_ci: normalise slugs, emails and names before storing and comparing. - String functions on JSON columns:
length(json_col)fails on MatrixOne; cast to char first or compute in PHP.
Test each application against a copy of its production data (db-portable:copy, then db-portable:verify), not only after migrating and seeding.
Step 2: Migrate Target Database
Create the target database and its user if needed (db:create), then run migrations against the target connection:
php artisan db:create matrixone
php artisan migrate --database=matrixoneStep 3: Audit Data Compatibility (db-portable:audit)
The audit command queries min/max values and string lengths on the source database and verifies that all existing data will fit within the target schema:
# Audit entire schema
php artisan db-portable:audit --from=crdb --to=matrixone
# Audit specific tables
php artisan db-portable:audit --from=crdb --to=matrixone --table=videos --table=orders
# A large or busy source: measure only the 1000 most recent rows of each table (by primary key)
php artisan db-portable:audit --from=crdb --to=matrixone --sample=1000Without --sample the audit reads every row (min, max, longest string per column): a full scan of each table. With it, a value outside the sampled rows goes unseen. Like copy, it skips migrations (--except to change), only looks at the connection's own schema (a MySQL-family server lists every database otherwise), and ignores CockroachDB's hidden rowid.
Sample Audit Output
+----------------------+------------+----------------------+---------------------------------------------------+
| Table | Column | Problem | Details |
+----------------------+------------+----------------------+---------------------------------------------------+
| videos | view_count | integer out of range | int (max 2147483647) but the source has 15950438052|
| toeic_exam_user_logs | exam_score | integer out of range | tinyint unsigned (max 255) but source has 500 |
| videos | title | string too long | varchar(20) but source string is 38 characters |
| tool_only_source | * | missing in target | Table does not exist in target database |
+----------------------+------------+----------------------+---------------------------------------------------+If any columns are reported as out-of-range, widen the column in your target migrations before copying.
Step 4: Copy Data (db-portable:copy)
Copies data from the source database to the target database:
# Dry run to preview row counts
php artisan db-portable:copy --from=crdb --to=matrixone --dry-run
# Copy all tables
php artisan db-portable:copy --from=crdb --to=matrixone
# Copy specific tables
php artisan db-portable:copy --from=crdb --to=matrixone --table=users --table=videos
# Sample latest 500 rows per table
php artisan db-portable:copy --from=crdb --to=matrixone --sample=500
# Resume after an interruption
php artisan db-portable:copy --from=crdb --to=matrixone --resume
# Empty the target tables first (a rerun of a table without a primary key)
php artisan db-portable:copy --from=crdb --to=matrixone --table=taggables --truncate
# Keep a small target alive: at most 256 KiB of values and 2000 rows per second over the whole run
php artisan db-portable:copy --from=crdb --to=matrixone --resume --max-bytes-per-second=256KiB --max-rows-per-second=2000Key Copy Features
- Foreign Key Ordering: Automatically inspects foreign key constraints and copies parent tables before referenced child tables. When the target refuses to list them, the copy goes on in the given order (foreign key checks are off on MySQL-family and SQLite targets) and warns. This happens with laravel-matrixone 1.2, which reads foreign keys from
mo_catalog.mo_foreign_keys, a table a user limited to its database may not read: the warning prints the statement for an admin (grant select on table mo_catalog.mo_foreign_keys to <role>;, the user's current role), anddb:creategrants it to the roles it creates. laravel-matrixone 1.3 reads them fromSHOW CREATE TABLEand needs no grant. - Value Conversion via
ValueMapper:- Timestamps with timezone offsets are converted to UTC for MySQL datetime columns.
- Booleans convert to
true/falsefor PostgreSQL and1/0for MySQL/SQLite. - PHP Arrays, Objects, and Collections are serialized as JSON.
- PHP Enums (UnitEnum and BackedEnum) are mapped to scalar values.
- PostgreSQL / CockroachDB array columns (
text[],STRING[],INT8[]...) become JSON lists on a target without arrays (MySQL family, SQLite); integer, float and boolean elements keep their types.
- Sequence & Identity Reset: After copying into PostgreSQL or CockroachDB, sequence counters (
GENERATED BY DEFAULT AS IDENTITYorSERIAL) are updated to exceed the highest copied primary key, preventing duplicate key collisions on subsequent inserts. - Throttling:
--max-rows-per-secondand--max-bytes-per-second(1MiB,512K,2GiB: binary units for KiB/MiB/GiB, decimal for K/M/G) sleep after each batch until the rows and bytes written since the start fit the rate. Bytes are the length of the written values. A target with little memory (MatrixOne merges and flushes in the background) then keeps up with a long copy; the command prints the rate it kept. - Progress: a table that takes more than 2 seconds shows its rows read so far: a progress bar on a terminal (rows, percent, elapsed and estimated time; cleared before the table's result line), else a line every 30 seconds, so a log stays short (
posts: 5,000 / 16,522 row(s) (30%), 1m 35s). - Idempotence & Keyset Pagination:
- Uses
insertOrIgnore()so interrupted runs can be restarted safely without creating duplicate rows, in tables with a primary or unique key on the target. - A table without one (a pivot table such as
taggables) that already has rows in the target is skipped (skipped: the target already has rows and no primary or unique key..., and the command fails):insertOrIgnore()cannot tell the copied rows from new ones, so a rerun after an interrupted copy would double them.--resumeis refused the same way for such a table. Empty the table, or copy with--truncate. --truncateempties the target tables before copying (onetruncatestatement for every table on the PostgreSQL family, which refuses to truncate a table referenced by a foreign key otherwise;deleteon SQLite). It cannot be combined with--resume.- Paginates using keyset ordering (
--chunk=500), avoiding heavyOFFSETqueries. - Batches hold
--chunkrows and--chunk-bytesof values at most (16MiBby default, e.g.--chunk-bytes=4MiB): a quarter of MatrixOne's and MySQL 8's 64 MBmax_allowed_packet, so a table of 100 KB rows is copied without guessing a smaller--chunk. Pages read from the source shrink the same way. When the target still refuses a batch as too large (Got a packet bigger than 'max_allowed_packet' bytes, too many placeholders), the batch is split in half until it fits and later batches stay under that size; a single row over the limit fails the table, and the failed tables are listed again at the end. - A table without a primary key on CockroachDB is paged on its hidden
rowidkey, read from the source and left out of the target rows. - Detects rows ignored by the target and flags tables as
incompleteif rows were skipped.
- Uses
Step 5: Verify the Copy (db-portable:verify)
Compares the rows of the two connections in PHP, so the result does not depend on how each database computes checksums or formats values:
php artisan db-portable:verify --from=mysql --to=matrixone
php artisan db-portable:verify --from=mysql --to=matrixone --table=posts --show=20
php artisan db-portable:verify --from=mysql --to=matrixone --count # count(*) onlycount(*)of every table of the source (notinformation_schema.tables.table_rows, an estimate on the MySQL family: 11,717 for a table of 16,522 rows on MatrixOne).- Then every row, read from the source in primary-key order (pages of
--chunkrows and--chunk-bytesof values at most, as forcopy) and looked up in the target by key. Each column is compared after normalisation: JSON decoded and encoded again with sorted keys, PostgreSQL arrays against JSON lists, booleans as1/0, decimals without trailing zeros, instants with an offset in UTC,char(n)without the padding, UUIDs in lower case. Text and binary values are compared byte for byte. - A table without a primary key is compared as a set: the count and an order-independent hash of its rows (duplicates included).
- Prints one line per table (
posts ... 16,522 row(s): same rows), then the first differing rows of each table (--show=5):id=2: body differs from byte 70,001 (100,000 bytes on the source, 99,998 on the target),id=3: title 'Third' on the source, 'Third!' on the target,id=4: missing on the target. Exits with a failure when a table differs or is missing on one side.
Checksums computed by the databases are not comparable across families: MatrixOne's md5(cast(col as char)) differs from MySQL's for a text over ~64 KB with the same bytes, and a JSON column is returned formatted differently. Columns of the source missing on the target are listed in the table's line, not compared. Tables only on the target are not checked.