PHPackages                             k-kinzal/sql-fixture - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. k-kinzal/sql-fixture

ActiveLibrary

k-kinzal/sql-fixture
====================

Generate PHP-Faker based fixtures from SQL schemas

v0.1.1(2w ago)01↓100%1MITPHPPHP ^8.1

Since Mar 6Pushed 2w agoCompare

[ Source](https://github.com/k-kinzal/sql-fixture)[ Packagist](https://packagist.org/packages/k-kinzal/sql-fixture)[ RSS](/packages/k-kinzal-sql-fixture/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (11)Versions (3)Used By (1)

SQL Fixture
===========

[](#sql-fixture)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/7535257ca228724c93658bd52583d4e47a9bab02c356abf6e54c1d575f2151e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c75652e737667)](https://www.php.net/)

A [FakerPHP](https://github.com/FakerPHP/Faker) provider for generating test fixture data from SQL schemas. Parses CREATE TABLE statements and generates type-appropriate fake data.

Overview
--------

[](#overview)

SQL Fixture reads your database schema (CREATE TABLE) and automatically generates realistic fixture data with correct types, lengths, and constraints. It supports MySQL and SQLite with three usage modes:

- **`FixtureProvider`** - Generate fixtures from CREATE TABLE SQL strings
- **`DatabaseFixtureProvider`** - Generate fixtures from a live database connection (PDO)
- **`FileFixtureProvider`** - Generate fixtures from a directory of DDL files

All modes support object hydration via `ReflectionHydrator`, converting generated data directly into typed PHP objects.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- [fakerphp/faker](https://github.com/FakerPHP/Faker) ^1.23
- [phpmyadmin/sql-parser](https://github.com/phpmyadmin/sql-parser) ^5.11

Installation
------------

[](#installation)

```
composer require --dev k-kinzal/sql-fixture
```

Usage
-----

[](#usage)

### From SQL Strings

[](#from-sql-strings)

Use `FixtureProvider` when you have CREATE TABLE SQL available:

```
use Faker\Factory;
use SqlFixture\FixtureProvider;

$faker = Factory::create();
$faker->addProvider(new FixtureProvider($faker));

$fixture = $faker->fixture(
    'CREATE TABLE users (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(100) NOT NULL,
        age INT UNSIGNED,
        status ENUM("active", "inactive"),
        balance DECIMAL(10, 2),
        created_at DATETIME
    )'
);
// Returns: ['name' => 'John Doe', 'email' => 'john@example.com', 'age' => 28, ...]
// Note: auto_increment columns (id) are skipped by default
```

### From Database Connection

[](#from-database-connection)

Use `DatabaseFixtureProvider` with a PDO connection to generate fixtures from your actual database schema:

```
use Faker\Factory;
use SqlFixture\DatabaseFixtureProvider;

$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'password');
$faker = Factory::create();
$faker->addProvider(new DatabaseFixtureProvider($faker, $pdo));

// Generate fixture by table name
$fixture = $faker->fixture('users');
// Schema is fetched via SHOW CREATE TABLE and cached
```

### From DDL Files

[](#from-ddl-files)

Use `FileFixtureProvider` with a directory containing `.sql` files:

```
use Faker\Factory;
use SqlFixture\FileFixtureProvider;

// Directory contains: users.sql, posts.sql, comments.sql
$faker = Factory::create();
$faker->addProvider(new FileFixtureProvider($faker, '/path/to/ddl/'));

$fixture = $faker->fixture('users');

// List available tables
$tables = $faker->getTableNames(); // ['users', 'posts', 'comments']

// Register additional schemas at runtime
$faker->registerSchema('CREATE TABLE tags (id INT PRIMARY KEY, name VARCHAR(50))');
```

### Overriding Values

[](#overriding-values)

Pass specific values to override generated data:

```
$fixture = $faker->fixture(
    'CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))',
    ['id' => 1, 'name' => 'Alice']
);
// Returns: ['id' => 1, 'name' => 'Alice', 'email' => '']
```

### Object Hydration

[](#object-hydration)

Generate typed PHP objects directly using `ReflectionHydrator`:

```
class User
{
    public function __construct(
        public readonly int $id,
        public readonly string $userName,
        public readonly string $email,
    ) {}
}

$user = $faker->fixture(
    'CREATE TABLE users (id INT PRIMARY KEY, user_name VARCHAR(255), email VARCHAR(255))',
    ['id' => 1],
    User::class
);
// Returns: User(id: 1, userName: 'generated_name', email: 'generated@example.com')
```

The hydrator handles:

- Constructor parameter matching (exact name or snake\_case to camelCase conversion)
- Type casting (string to int/float/bool, JSON decode for arrays)
- Default values and nullable parameters
- Property-based hydration for classes without constructors

### SQLite Support

[](#sqlite-support)

```
use SqlFixture\FixtureProvider;
use SqlFixture\Platform\PlatformFactory;

// Specify dialect explicitly
$faker->addProvider(new FixtureProvider($faker, dialect: PlatformFactory::DRIVER_SQLITE));

$fixture = $faker->fixture(
    'CREATE TABLE users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        score REAL
    )'
);

// DatabaseFixtureProvider auto-detects dialect from PDO driver
$pdo = new PDO('sqlite::memory:');
$faker->addProvider(new DatabaseFixtureProvider($faker, $pdo));
// SQLite dialect is automatically detected
```

Supported Types
---------------

[](#supported-types)

### MySQL

[](#mysql)

CategoryTypesIntegerTINYINT, SMALLINT, MEDIUMINT, INT, BIGINTDecimalFLOAT, DOUBLE, REAL, DECIMAL, NUMERICStringCHAR, VARCHAR, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXTBinaryBINARY, VARBINARY, TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOBEnum/SetENUM, SETDate/TimeDATE, TIME, DATETIME, TIMESTAMP, YEARJSONJSONBooleanBOOL, BOOLEANBitBITSpatialPOINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING, MULTIPOLYGON, GEOMETRYCOLLECTION### SQLite

[](#sqlite)

AffinityMapped TypesINTEGERINT, INTEGER, TINYINT, SMALLINT, MEDIUMINT, BIGINT, INT2, INT8TEXTCHAR, VARCHAR, TEXT, CLOB, TINYTEXT, MEDIUMTEXT, LONGTEXTREALFLOAT, DOUBLE, REALBLOBBLOB, BINARY, VARBINARYNUMERICBOOLEAN, DATE, DATETIME, TIMESTAMP, DECIMALColumn Handling
---------------

[](#column-handling)

- **AUTO\_INCREMENT / AUTOINCREMENT** columns are skipped (not generated)
- **Generated columns** (`AS` expressions) are skipped
- **Nullable columns** have a 10% chance of returning null/default
- **UNSIGNED** constraint is respected for numeric types
- **Length/precision/scale** are respected for string and decimal types
- **ENUM/SET** values are randomly selected from the declared options
- **DEFAULT** values are used when a nullable column generates null

Extensibility
-------------

[](#extensibility)

Customize behavior by providing your own implementations:

```
use SqlFixture\FixtureProvider;
use SqlFixture\TypeMapper\TypeMapperInterface;
use SqlFixture\Schema\SchemaParserInterface;
use SqlFixture\Hydrator\HydratorInterface;

$provider = new FixtureProvider(
    $faker,
    typeMapper: $customTypeMapper,      // Custom type-to-value mapping
    hydrator: $customHydrator,          // Custom object hydration
    schemaParser: $customSchemaParser,  // Custom CREATE TABLE parsing
    dialect: 'mysql',
);
```

Development
-----------

[](#development)

```
# Run unit tests
composer test:unit

# Run all tests
composer test

# Run linter (PHP-CS-Fixer + PHPStan level max)
composer lint

# Run fuzz tests
composer fuzz:create-table
composer fuzz:insert-select

# Fix code style
composer format
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

36

—

LowBetter than 83% of packages

Maintenance97

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

16d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4458a22db62c885006248e08715301bcb73e78c1057e2bbf686af001729165d5?d=identicon)[kinzal](/maintainers/kinzal)

---

Top Contributors

[![k-kinzal](https://avatars.githubusercontent.com/u/1281825?v=4)](https://github.com/k-kinzal "k-kinzal (5 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/k-kinzal-sql-fixture/health.svg)

```
[![Health](https://phpackages.com/badges/k-kinzal-sql-fixture/health.svg)](https://phpackages.com/packages/k-kinzal-sql-fixture)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.5M599](/packages/sylius-sylius)[nelmio/alice

Expressive fixtures generator

2.5k42.8M126](/packages/nelmio-alice)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k38.0M27.4k](/packages/orchestra-testbench)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k11.6M37](/packages/knuckleswtf-scribe)[jgrossi/corcel

Use WordPress backend with Laravel or any PHP framework

4.8k1.8M26](/packages/jgrossi-corcel)[zenstruck/foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.

78011.3M80](/packages/zenstruck-foundry)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
