Skip to content

Commit

Permalink
add an sqlite config option to enable foreign key constraints
Browse files Browse the repository at this point in the history
For Sqlite, foreign key constraints need to be explicitly enabled for
every database connection. So enabling them in the migrations (as suggested
by the documentation) does not work.

This PR enables the contraints for every connection to an sqlite database
that has the config option `foreign_key_constraints` set to `true`.

If the option is not set, nothing changes, so no breaking change is
introduced.

As foreign key constraints are the default behavior for all other databases
I suggest switching this around for the next release and enable foreign
keys unless this is set to `false`.

If this is accepted I'll submit two more PRs for documentation and
laravel/laravel.
  • Loading branch information
dakira committed Oct 29, 2018
1 parent c30a784 commit 56a62cb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/Illuminate/Database/SQLiteConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@

class SQLiteConnection extends Connection
{
/**
* Create a new database connection instance.
*
* @param \PDO|\Closure $pdo
* @param string $database
* @param string $tablePrefix
* @param array $config
* @return void
*/
public function __construct($pdo, $database = '', $tablePrefix = '', array $config = [])
{
parent::__construct($pdo, $database, $tablePrefix, $config);

if ($this->getForeignKeyConstraintsSetting() == true) {
$this->getSchemaBuilder()->enableForeignKeyConstraints();
}
}
/**
* Get the default query grammar instance.
*
Expand Down Expand Up @@ -63,4 +80,14 @@ protected function getDoctrineDriver()
{
return new DoctrineDriver;
}

/**
* Get the database connection foreign_key_constraints setting.
*
* @return boolean|null
*/
protected function getForeignKeyConstraintsSetting()
{
return $this->getConfig('foreign_key_constraints');
}
}
13 changes: 13 additions & 0 deletions tests/Database/DatabaseConnectionFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,17 @@ public function testCustomConnectorsCanBeResolvedViaContainer()

$this->assertEquals('connector', $factory->createConnector(['driver' => 'foo']));
}

public function testSqliteForeignKeyConstraints()
{
$this->db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'foreign_key_constraints' => true,
], 'constraints_set');

$this->assertEquals(0, $this->db->connection()->select('PRAGMA foreign_keys')[0]->foreign_keys);

$this->assertEquals(1, $this->db->connection('constraints_set')->select('PRAGMA foreign_keys')[0]->foreign_keys);
}
}

0 comments on commit 56a62cb

Please sign in to comment.