PHPackages                             mouf/schema-analyzer - 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. mouf/schema-analyzer

ActiveLibrary

mouf/schema-analyzer
====================

A package that offers utility tools to analyze database schemas (on top of Doctrine DBAL)

v2.0.1(8mo ago)8215.3k↓12.9%52MITPHPPHP ^7.4 || ^8.0CI passing

Since Sep 24Pushed 8mo ago12 watchersCompare

[ Source](https://github.com/thecodingmachine/schema-analyzer)[ Packagist](https://packagist.org/packages/mouf/schema-analyzer)[ RSS](/packages/mouf-schema-analyzer/feed)WikiDiscussions 2.0 Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (19)Used By (2)

[![Latest Stable Version](https://camo.githubusercontent.com/72171f2a5a58ac9137299a95cd8c4da169ee7d477b72f3130bcb24099ecb9a5a/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f736368656d612d616e616c797a65722f762f737461626c65)](https://packagist.org/packages/mouf/schema-analyzer)[![Latest Unstable Version](https://camo.githubusercontent.com/5954beb9522f708fe80c94ab3d0d2ce81b036ac388e9d36665aeab33cdc97117/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f736368656d612d616e616c797a65722f762f756e737461626c65)](https://packagist.org/packages/mouf/schema-analyzer)[![License](https://camo.githubusercontent.com/f4fc55507adbad5211ed9b76a7f1b0c6068f3180aa0ac98e5e731330d0b452d7/68747470733a2f2f706f7365722e707567782e6f72672f6d6f75662f736368656d612d616e616c797a65722f6c6963656e7365)](https://packagist.org/packages/mouf/schema-analyzer)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/6a48a4934fc8ecc626820f7aa384dfa7564a56eb2a94bc71372669f4df6c41bd/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f746865636f64696e676d616368696e652f736368656d612d616e616c797a65722f6261646765732f7175616c6974792d73636f72652e706e673f623d312e30)](https://scrutinizer-ci.com/g/thecodingmachine/schema-analyzer/?branch=1.0)[![Build Status](https://camo.githubusercontent.com/05bb10cb39e0166cc33b7e999d9e86a805efc0de5b0b3883a10e0e6326a981b5/68747470733a2f2f7472617669732d63692e6f72672f746865636f64696e676d616368696e652f736368656d612d616e616c797a65722e7376673f6272616e63683d312e30)](https://travis-ci.org/thecodingmachine/schema-analyzer)[![Coverage Status](https://camo.githubusercontent.com/bdb994c20fd3d13067a78b324c588007f4b63be47cdfa7813153a2b4125a7a04/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f746865636f64696e676d616368696e652f736368656d612d616e616c797a65722f62616467652e7376673f6272616e63683d312e3026736572766963653d676974687562)](https://coveralls.io/github/thecodingmachine/schema-analyzer?branch=1.0)

Schema analyzer for DBAL
========================

[](#schema-analyzer-for-dbal)

This package offer utility functions to analyze database schemas. It is built on top of Doctrine DBAL.

In this package, you will find:

- Functions to automatically detect **junction tables**
- Functions to compute the shortest path between 2 tables based on the relationships stored in the schema.

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

[](#installation)

You can install this package through Composer:

```
{
    "require": {
        "mouf/schema-analyzer": "^2.0"
    }
}
```

The packages adheres to the [SemVer](http://semver.org/) specification, and there will be full backward compatibility between minor versions.

Detecting junction tables
-------------------------

[](#detecting-junction-tables)

The starting point is always a DBAL Schema. Pass the schema manager to SchemaAnalyzer, and then, simply call the functions.

```
// $conn is the DBAL connection.
$schemaAnalyzer = new SchemaAnalyzer($conn->getSchemaManager());

// Let's detect all junctions tables
$tables = $schemaAnalyzer->detectJunctionTables();
// This will return an array of Doctrine\DBAL\Schema\Table objects
```

A **junction table** is a table:

- that has **exactly 2 foreign keys**
- that has **only 2 columns** (or **3 columns** if the one of those is an *autoincremented primary key*).

There is an optional parameter you can use with `detectJunctionTables` that will automatically ignore any junction table that is referenced by a foreign key of another table.

```
// Get all junction tables except the ones that are references by a foreign key.
$tables = $schemaAnalyzer->detectJunctionTables(true);
```

Detecting inheritance relationship between tables
-------------------------------------------------

[](#detecting-inheritance-relationship-between-tables)

### About inheritance relationships

[](#about-inheritance-relationships)

If a table "user" has a primary key that is also a foreign key pointing on table "contact", then table "user" is considered to be a child of table "contact". This is because you cannot create a row in "user" without having a row with the same ID in "contact".

Therefore, a "user" ID has to match a "contact", but a "contact" has not necessarily a "user" associated.

### Detecting inheritance relationships

[](#detecting-inheritance-relationships)

You can use `SchemaAnalyzer` to detect parent / child relationships.

- `getParentRelationship` takes a table name in parameter and returns the DBAL `ForeignKeyConstraint` representing the relationship between this table and its parent.
- `getChildrenRelationships` takes a table name in parameter and returns an array of DBAL `ForeignKeyConstraint`representing the relationship between this table and its children.

```
$parentKeyConstraint = $schemaAnalyzer->getParentRelationship("user");
/* @var $parentKeyConstraint ForeignKeyConstraint */
$parent = $parentKeyConstraint->getForeignTableName();
// This will return the "contact" table (as a string)

$childrenKeyConstraints = $schemaAnalyzer->getChildrenRelationships("contact");
/* @var $childrenKeyConstraints ForeignKeyConstraint[] */
$children = array_map(function($item) { return $item->getLocalTableName(); }, $childrenKeyConstraints);
// This will return an array of tables whose parent is contact: ["user"]
```

Computing the shortest path between 2 tables
--------------------------------------------

[](#computing-the-shortest-path-between-2-tables)

Following foreign keys, the `getShortestPath` function will try to find the shortest path between 2 tables. It will return the list of foreign keys it used to link the 2 tables.

Internals:

- Each foreign key has a *cost* of 1
- Junction tables have a *cost* of 1.5, instead of 2 (one for each foreign key)
- Foreign keys representing an inheritance relationship (i.e. foreign keys binding the primary keys of 2 tables) have a *cost* of 0.1

```
// $conn is the DBAL connection.
$schemaAnalyzer = new SchemaAnalyzer($conn->getSchemaManager());

// Let's detect the shortest path between 2 tables:
$fks = $schemaAnalyzer->getShortestPath("users", "rights");
// This will return an array of Doctrine\DBAL\Schema\ForeignKeyConstraint objects
```

**Heads up!** The shortest path is based on the *cost* of the foreign keys. It is perfectly possible to have several shortest paths (if several paths have the same total cost). If there are several shortest paths, rather than choosing one path amongst the others, SchemaAnalyzer will throw a `ShortestPathAmbiguityException`. The exception message details all the possible shortest paths.

Caching results
---------------

[](#caching-results)

Analyzing the full data model and looking for shortest paths can take a long time. For anything that should run in a production environment, it is recommended to cache the result. `SchemaAnalyzer` can be passed a Doctrine cache, along a cache prefix. The cache prefix is a string that will be used to prefix all cache keys. It is useful to avoid cache collisions between several databases.

Usage:

```
// $conn is the DBAL connection.
// Let's use the ApcCache (or any other Doctrine cache...)
$cache = new ApcCache();
$schemaAnalyzer = new SchemaAnalyzer($conn->getSchemaManager(), $cache, "my_prefix");
```

Changing the cost of the foreign keys to alter the shortest path
----------------------------------------------------------------

[](#changing-the-cost-of-the-foreign-keys-to-alter-the-shortest-path)

If you are facing an ambiguity exception or if the shortest path simply does not suit you, you can alter the cost of the foreign keys.

```
$schemaAnalyzer->setForeignKeyCost($tableName, $columnName, $cost);
```

The `$cost` can be any number. Remember that the default cost for a foreign key is **1**.

SchemaAnalyzer comes with a set of default constants to help you work with costs:

- `SchemaAnalyzer::WEIGHT_IMPORTANT` (0.75) for foreign keys that should be followed in priority
- `SchemaAnalyzer::WEIGHT_IRRELEVANT` (2) for foreign keys that should be generally avoided
- `SchemaAnalyzer::WEIGHT_IGNORE` (Infinity) for foreign keys that should never be used as part of the shortest path

Another option is to add a cost modifier to a table. This will alter the cost of all foreign keys pointing to or originating from this table.

```
$schemaAnalyzer->setTableCostModifier($tableName, $cost);
```

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance59

Moderate activity, may be stable

Popularity40

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 78.8% 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 ~201 days

Recently: every ~240 days

Total

19

Last Release

263d ago

Major Versions

v0.4.0 → 1.0.x-dev2016-03-04

v1.1.4 → v2.0.0-beta.02020-08-01

v1.1.5 → v2.0.0-beta.12023-01-12

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1104771?v=4)[mouf](/maintainers/mouf)[@Mouf](https://github.com/Mouf)

---

Top Contributors

[![moufmouf](https://avatars.githubusercontent.com/u/1290952?v=4)](https://github.com/moufmouf "moufmouf (41 commits)")[![aszenz](https://avatars.githubusercontent.com/u/25319264?v=4)](https://github.com/aszenz "aszenz (4 commits)")[![dsavina](https://avatars.githubusercontent.com/u/22031211?v=4)](https://github.com/dsavina "dsavina (2 commits)")[![homersimpsons](https://avatars.githubusercontent.com/u/16977446?v=4)](https://github.com/homersimpsons "homersimpsons (2 commits)")[![nguyenk](https://avatars.githubusercontent.com/u/2227554?v=4)](https://github.com/nguyenk "nguyenk (2 commits)")[![xhuberty](https://avatars.githubusercontent.com/u/8350192?v=4)](https://github.com/xhuberty "xhuberty (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mouf-schema-analyzer/health.svg)

```
[![Health](https://phpackages.com/badges/mouf-schema-analyzer/health.svg)](https://phpackages.com/packages/mouf-schema-analyzer)
```

###  Alternatives

[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[sonata-project/entity-audit-bundle

Audit for Doctrine Entities

644989.8k1](/packages/sonata-project-entity-audit-bundle)[overtrue/laravel-versionable

Make Laravel model versionable.

585308.0k5](/packages/overtrue-laravel-versionable)[elgg/elgg

Elgg is an award-winning social networking engine, delivering the building blocks that enable businesses, schools, universities and associations to create their own fully-featured social networks and applications.

1.7k15.7k5](/packages/elgg-elgg)[contao-community-alliance/dc-general

Universal data container for Contao

1578.3k86](/packages/contao-community-alliance-dc-general)[pdir/social-feed-bundle

Social feed extension for Contao CMS

1414.8k](/packages/pdir-social-feed-bundle)

PHPackages © 2026

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