Integration tests passed on SQLite and the same code failed on MySQL in production
Our test suite used in-memory SQLite for speed. Production ran MySQL 8. A new feature passed every test and then failed in three different ways after deploy: a strict mode error, a case-insensitive unique collision and a different sort order. Why SQLite hides MySQL behaviour and how we test on real MySQL fast.
Our Laravel application's test suite ran against an in-memory SQLite database. The whole suite, about 1,900 tests, took 70 seconds, and developers ran it constantly. Production used MySQL 8.0.
We released a feature that lets businesses import their product catalogue from a CSV file. It had 46 tests, all green. Within an hour of the release, three different errors appeared in production for imports that had worked in every test.
Error 1: strict mode.
SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'sku' at row 1
(SQL: insert into `products` (`sku`, `name`, ...) values (ACME-WIDGET-BLUE-LARGE-2026-EDITION, ...))
sku was VARCHAR(32). Some customer SKUs were longer. In SQLite, the test inserted them without complaint.
Error 2: unique constraint on case.
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'acme-w100' for key 'products.products_tenant_sku_unique'
The CSV contained ACME-W100 and acme-w100 as two different products. Our code treated them as different, and the
test with mixed-case SKUs passed. In MySQL, they collided.
Error 3: ordering. The import preview showed products in a different order than in tests, and a test-only assumption ("the first row is the one with the lowest ID") made the preview mark the wrong row as a duplicate.
SQLite is an excellent database. It is a different database from MySQL, with different rules. Using it as a stand-in means tests verify behaviour that production does not have.
1. Type enforcement and lengths
SQLite uses dynamic typing with "type affinity". A column declared VARCHAR(32) accepts strings of any length; the
length is not enforced. MySQL in its default strict mode (STRICT_TRANS_TABLES is in the default sql_mode since
5.7) rejects a value that is too long with error 1406. In non-strict mode it would silently truncate, which is worse.
Our migrations declared the right lengths. SQLite simply ignored them, so no test ever hit the limit.
2. Collation and case sensitivity
MySQL's default collation for utf8mb4 in 8.0 is utf8mb4_0900_ai_ci: accent-insensitive and case-insensitive. Under
it, 'ACME-W100' = 'acme-w100' is true, and a unique index treats them as the same value. SQLite's default BINARY
collation compares bytes, so they are different.
This difference runs in both directions. Code that relies on case-insensitive lookups (WHERE email = ?) works in
MySQL and fails in SQLite tests, and code that relies on case-sensitive uniqueness passes in SQLite and fails in MySQL,
as here.
3. Ordering without ORDER BY
Neither database guarantees row order without ORDER BY. In practice, SQLite usually returns rows in rowid order for
simple queries, and InnoDB returns them in the order of whichever index it used. Our preview query used a secondary
index on (tenant_id, sku), so MySQL returned rows ordered by SKU, not by insertion. The tests had quietly depended
on SQLite's typical behaviour.
Other differences we found while auditing
| Behaviour | SQLite | MySQL 8 |
|---|---|---|
VARCHAR(n) length |
not enforced | enforced (strict mode) |
| Default text comparison | case-sensitive | case- and accent-insensitive |
| Foreign keys | off unless PRAGMA foreign_keys = ON |
enforced (InnoDB) |
JSON column functions |
JSON1 functions, different syntax for some | ->, ->>, JSON_TABLE |
Row locking (FOR UPDATE) |
not supported; whole-database write lock | row-level locks |
ON DUPLICATE KEY UPDATE |
not supported (uses ON CONFLICT) |
supported |
| Date functions | strftime, datetime |
DATE_FORMAT, TIMESTAMPDIFF |
Laravel's query builder hides some of these behind a common API, which makes it even easier to forget they exist.
Environment
| Item | Value |
|---|---|
| Framework | Laravel 11, PHP 8.3 |
| Tests | PHPUnit, RefreshDatabase, SQLite :memory: |
| Production | MySQL 8.0, utf8mb4_0900_ai_ci, strict mode |
| Impact | catalogue import failed for about 30% of customer files on release day |
1. Fix the code
- Validation now rejects SKUs longer than 32 characters with a clear message per row, before any insert.
- SKUs are normalised to upper case on import, and the import reports duplicates that differ only by case. The behaviour is now explicit, not an accident of the database.
- The preview query has an explicit
ORDER BY row_number, using the CSV's row number stored during parsing.
2. Run tests against MySQL
We moved the test suite to the same database engine and version as production. In CI, a MySQL service container:
services:
mysql:
image: mysql:8.0.39
env:
MYSQL_DATABASE: app_testing
MYSQL_ROOT_PASSWORD: root
ports: ["3306:3306"]
options: >-
--health-cmd="mysqladmin ping -proot" --health-interval=5s --health-retries=10
The image tag matches production's minor version, and the test database uses the same character set, collation and
sql_mode as production, set explicitly in the connection config rather than relying on defaults:
'mysql_testing' => [
'driver' => 'mysql',
'database' => env('DB_DATABASE', 'app_testing'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_0900_ai_ci',
'strict' => true,
'modes' => ['ONLY_FULL_GROUP_BY', 'STRICT_TRANS_TABLES', 'NO_ZERO_IN_DATE',
'NO_ZERO_DATE', 'ERROR_FOR_DIVISION_BY_ZERO', 'NO_ENGINE_SUBSTITUTION'],
],
Locally, developers use the same container through Docker Compose, or Testcontainers for projects that prefer starting the database from the test run itself.
3. Keep it fast
The worry was speed. Our first run against MySQL took 6 minutes instead of 70 seconds. What brought it back down:
- Transactions instead of re-migrating. Laravel's
RefreshDatabasemigrates once per run and wraps each test in a transaction that is rolled back, which is fast on MySQL too. A few tests had usedDatabaseMigrations, which re-runs migrations for every test; we switched them. - Parallel testing.
php artisan test --parallelruns several processes, each with its own database (app_testing_test_1,_2, ...). With 8 processes, the suite takes about 95 seconds. - A tmpfs data directory for the CI container. MySQL's data on a RAM disk avoids disk sync costs; durability does
not matter for test data. Combined with
innodb_flush_log_at_trx_commit=2in the test container. - A schema dump.
php artisan schema:dumpreplaces running hundreds of migrations with loading one SQL file.
Final time: 95 seconds in CI, about two minutes on a laptop. Slightly slower than SQLite, and every test now runs against the database production uses.
4. Keep SQLite where it is right
A few pure unit tests that never touch the database do not need any database. For code that is genuinely database-agnostic (a library meant to support several engines), testing on every supported engine is the answer, not picking the most convenient one.
1. The new suite catches all three original bugs. We reverted the code fixes on a branch and ran the import tests against MySQL:
FAILED Tests\Feature\CatalogImportTest > long sku is rejected
SQLSTATE[22001]: ... Data too long for column 'sku'
FAILED Tests\Feature\CatalogImportTest > case variants are reported as duplicates
SQLSTATE[23000]: ... Duplicate entry 'acme-w100'
FAILED Tests\Feature\CatalogImportTest > preview preserves file order
On SQLite, the same three tests passed.
2. The rest of the suite. Switching engines exposed 14 more failing tests that had been passing on SQLite: three
case-sensitivity assumptions, four missing ORDER BYs, two foreign key violations that SQLite had never enforced, and
five raw queries using SQLite-only date functions. Each was a latent production bug or a test that was asserting
something untrue.
3. A guard against drift. A test asserts that the testing connection's server version, collation and sql_mode
match the values production reports, read from a small JSON file our deploy updates.
4. Security implications. The case-insensitive collation also affects authentication lookups. We confirmed login
matches emails case-insensitively by design, and that password reset tokens, which must be compared exactly, are
stored in a VARBINARY column and compared with hash_equals, so the collation cannot make two different tokens match.
Takeaways
- SQLite and MySQL differ in type enforcement, collation, foreign keys, locking and SQL dialect.
- Tests on a different engine verify behaviour production does not have, in both directions.
- Run integration tests on the same engine, version, collation and
sql_modeas production. - Transactions per test, parallel runs, tmpfs and a schema dump keep a real-database suite fast.
References: SQLite datatypes and type affinity, MySQL server SQL modes, MySQL character sets and collations, Laravel testing, running tests in parallel.
Add a label
Embed this post
<iframe src="https://hibug.me/integration-tests-sqlite-pass-mysql-fails" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I lead a small team responsible for observability and quality tooling, and I spend a fair share of my time on application security reviews. That mix means I see many incidents twice: once when they happen and again when we ask why nothing warned us. The posts here come from that second look. An alert that never fired because the metric disappeared, sampling that dropped exactly the traces we needed, a catch-all that reported success for weeks, a secret recoverable from an image layer, tests that passed against mocks while production failed. Each one covers how the gap was found, what we changed in code or configuration, and how we verified the fix with a test or a drill. Security topics stay defensive and practical: controls you can add to your own code and a way to test each one.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.