Skip to content

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:

  1. Finding incompatible SQL: Raw SQL queries hidden inside string literals.
  2. 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)).
  3. 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 ​

mermaid
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:

bash
# 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 --fail

Detected Constructs ​

RuleDetected SyntaxSuggested Replacement
pg-json-operatorcol->>'key'where('col->key', ...), whereJsonNumber()
pg-cast::bigint, ::text, ::jsonbEloquent casts, Portable::castText()
nulls-first-lastNULLS LAST, NULLS FIRSTorderByNullsLast()
pg-jsonb-functionjsonb_set, jsonb_array_lengthincrementJson(), whereJsonLength()
mysql-backtick\id`` in raw SQLwrap() or standard Eloquent
ifnullIFNULL(a, b)COALESCE(a, b)
mysql-ifIF(expr, a, b)CASE WHEN ... THEN ... ELSE ... END
mysql-limit-offsetLIMIT 10, 20LIMIT 20 OFFSET 10
on-duplicate-keyON DUPLICATE KEY UPDATEupsert() or updateOrInsert()
group-concatGROUP_CONCAT(...)Portable expression or application logic
having-without-group-by->having() without ->groupBy(), select ... having without group bywhereHas('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:

  • HAVING without GROUP BY: withCount('tags')->having('tags_count', '>=', 2) runs on MySQL; MatrixOne and PostgreSQL want the selected columns grouped, SQLite refuses a non-aggregate query. The having-without-group-by rule flags a builder statement that calls having*() without groupBy(), and a raw select ... having literal without group 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 a belongsToMany relation add table.* to the select even after select() (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) with 705%25... from a bot): MySQL casts the string and finds nothing, MatrixOne fails with invalid argument cast to uint64 (a 500 error). Validate the input (->whereNumber('id') on routes). The values come from requests.
  • Case-sensitive comparisons: MatrixOne compares varchar case-sensitively, unlike MySQL's utf8mb4_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:

bash
php artisan db:create matrixone
php artisan migrate --database=matrixone

Step 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:

bash
# 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=1000

Without --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 ​

text
+----------------------+------------+----------------------+---------------------------------------------------+
| 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:

bash
# 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=2000

Key Copy Features ​

  1. 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), and db:create grants it to the roles it creates. laravel-matrixone 1.3 reads them from SHOW CREATE TABLE and needs no grant.
  2. Value Conversion via ValueMapper:
    • Timestamps with timezone offsets are converted to UTC for MySQL datetime columns.
    • Booleans convert to true/false for PostgreSQL and 1/0 for 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.
  3. Sequence & Identity Reset: After copying into PostgreSQL or CockroachDB, sequence counters (GENERATED BY DEFAULT AS IDENTITY or SERIAL) are updated to exceed the highest copied primary key, preventing duplicate key collisions on subsequent inserts.
  4. Throttling: --max-rows-per-second and --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.
  5. 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).
  6. 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. --resume is refused the same way for such a table. Empty the table, or copy with --truncate.
    • --truncate empties the target tables before copying (one truncate statement for every table on the PostgreSQL family, which refuses to truncate a table referenced by a foreign key otherwise; delete on SQLite). It cannot be combined with --resume.
    • Paginates using keyset ordering (--chunk=500), avoiding heavy OFFSET queries.
    • Batches hold --chunk rows and --chunk-bytes of values at most (16MiB by default, e.g. --chunk-bytes=4MiB): a quarter of MatrixOne's and MySQL 8's 64 MB max_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 rowid key, read from the source and left out of the target rows.
    • Detects rows ignored by the target and flags tables as incomplete if rows were skipped.

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:

bash
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(*) only
  • count(*) of every table of the source (not information_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 --chunk rows and --chunk-bytes of values at most, as for copy) 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 as 1/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.

Released under the MIT License.