daycry/schemas

Database schema management, for CodeIgniter 4

v1.0.1 2024-08-28 13:44 UTC

This package is auto-updated.

Last update: 2025-08-27 07:45:24 UTC


README

Build status Coverage Status Downloads GitHub release (latest by date) GitHub stars GitHub license

🚀 Recently Updated: The library has been modernized with enhanced configuration, comprehensive documentation, and new features while maintaining full backward compatibility.

Quick Start

  1. Install with Composer: > composer require daycry/schemas
  2. Generate a new schema: > php spark schemas

📚 Documentation

✨ Features

  • Database Mapping: View your entire database mapped out in a cascading structure
  • Schema Analysis: Get helpful advice on optimizations to your database structure¹
  • Backup & Restore: Backup, restore, or deploy an entire database structure between servers or environments¹
  • Migration Generation: Generate CodeIgniter 4 migration files from an existing database¹
  • Format Support: Transfer projects to CodeIgniter 4 by reading schema files from other supported formats¹
  • 🆕 Streamlined Caching: Simple, efficient cache control with TTL and prefixes
  • 🆕 Relationship Detection: Polymorphic and many-to-many relationship detection
  • 🆕 Schema Validation: Basic validation with configurable strict mode
  • 🆕 Async Processing: Background processing for large schema operations
  • 🆕 Plugin System: Extensible architecture with event-driven plugins

¹ Some features are still in development. See Handlers > Development for planned future expansion.

🚀 Latest Version - Simplified & Optimized

Streamlined Configuration System

// Simplified, focused configuration
public array $cache = [
    'enabled' => false,
    'handler' => 'file',
    'ttl' => 3600,
    'prefix' => 'schemas_'
];

public array $logging = [
    'enabled' => false,
    'level' => 'info'
];

public array $relationships = [
    'enabled' => true,
    'detect_polymorphic' => true,
    'detect_many_to_many' => true
];

public array $async = [
    'enabled' => false,
    'max_concurrent_jobs' => 3,
    'job_timeout' => 300
];

Backward Compatibility

  • ✅ All existing code continues to work
  • ✅ No breaking changes (except deprecated $ttl property)
  • ✅ Gradual migration - upgrade features as needed

Installation

Install easily via Composer to take advantage of CodeIgniter 4's autoloading capabilities and always be up-to-date:

  • > composer require daycry/schemas

Or, install manually by downloading the source files and adding the directory to app/Config/Autoload.php.

Configuration

The library comes with a modern, structured configuration system. Copy the configuration template: examples/Schemas.php to app/Config/ and customize as needed.

Basic Configuration

public bool $silent = false;           // Control output verbosity

public array $automate = [
    'draft'   => true,                 // Auto-draft when schema missing
    'archive' => true,                 // Auto-archive generated schemas
    'read'    => true,                 // Auto-read from archives
];

Advanced Features

public array $cache = [
    'enabled' => false,               // Enable schema caching
    'ttl' => 3600,                   // Cache lifetime in seconds
    'prefix' => 'schemas_'            // Cache key prefix
];

public array $async = [
    'enabled' => false,               // Enable async processing
    'max_concurrent_jobs' => 3,       // Maximum concurrent jobs
    'job_timeout' => 300              // Job timeout in seconds
];

public array $plugins = [
    'enabled' => true,                // Enable plugin system
    'auto_discovery' => true,         // Auto-discover plugins
    'discovery_paths' => [            // Plugin discovery paths
        APPPATH . 'Plugins/Schemas'
    ]
];

📖 Complete Configuration Guide - See all available options and detailed explanations.

🔄 Migration Guide - Upgrading from older versions with full backward compatibility.

Usage

Schemas has four main functions, each with a variety of handlers available:

  • Draft: Generates a new schema from a variety of sources
  • Archive: Stores a copy of a schema for later use
  • Read: Loads a schema for live access
  • Publish: (not yet available) Modifies environments to match schema specs

The Schemas service is also available to simplify a workflow with convenient wrapper functions. At its most basic (with automation enabled), the service will draft, archive, and return a schema with one simple command:

$schema = service('schemas')->get();

You may want to control when portions of the workflow take place to optimize performance. Here is an example of one common process, mapping the default database group and storing the resulting schema to the cache:

// Map the database and store the schema in cache
$schemas = service('schemas');
$schemas->draft('database')->archive('cache');

// Load the schema from cache, add Model data, and get the updated schema
$schema = $schemas->read('cache')->draft('model')->get();

If you need to deviate from default handler configurations you can inject the handlers yourself:

$db = db_connect('alternate_database');
$databaseHandler = new \Tatter\Schemas\Drafter\Handlers\DatabaseHandler(null, $db);
$schema = $schemas->draft($databaseHandler)->get();

Command

Schemas comes with a spark command for convenient schema generation and display:

`schemas [-draft handler1,handler2,...] [-archive handler1,... | -print]`

Use the command to test and troubleshoot, or add it to your cron for periodic schema caching:

php spark schemas -draft database,model -archive cache

Automation

By default automation is turned on, but this can be configured via the $automate toggles in your config file. Automation will allow the service to fall back on a Reader, or even on a Drafter should it fail to have a schema already loaded. While automation makes using the library very easy, it can come at a performance cost if your application is not configured correctly, since it may draft a schema on every page load. Use automation to help but don't let it become a crutch.

Structure

Schemas uses foreign keys, indexes, and naming convention to detect relationships automatically. Make sure your database is setup using the appropriate keys and foreign keys to assist with the detection. Naming conventions follow the format of {table}_id for foreign keys and {table1}_{table2} for pivot tables. For more examples on relationship naming conventions consult the Rails Guide Active Record Associations (and please excuse the Ruby reference).

Intervention

Should autodetection fail or should you need to deviate from conventions there are a few tools you can use to overwrite or augment the generated schema.

  • Config/Schemas: the Config file includes a variable for $ignoredTables that will let you skip tables entirely. By default this includes the framework's migrations table.
  • app/Schemas/{file}.php: The DirectoryHandler will load any schemas detected in your Schemas directory - this gives you a chance to specify anything you want. See tests/_support/Schemas/Good/Products.php for an example.

Drafting

Currently supported handlers:

  • Database
  • Model
  • PHP
  • Directory (PHP import only)

Archiving/reading

  • Cache

Database Support

All CodeIgniter 4 database drivers work but due to some differences in index handling they may not all report the same results. Example: see skipped tests for SQLite3.

Development

The eventual goal is to support mapping from and deploying to any source. Planned handler implementations include:

  • Publisher\DatabaseHandler: Recreate a live database from its schema
  • MigrationsHandler: Create a schema from migration files, or vice versa
  • FileHandler: A wrapper for importing and exporting from popular schema file formats
  • Lots more...

And the file-specific handlers:

  • PhpHandler->archive(): Create a PHP file with a Schema object in $schema
  • XmlHandler: Support for Doctrine-style XML files
  • More to come...

Want to help out? All code and issues are managed on GitHub