schema added withoutForeignKeyConstraints()

Added shortcut method which disables foreign key constraints during the
execution of a callback.

 - updated docs
This commit is contained in:
silverqx
2023-02-21 12:52:20 +01:00
parent 505badde4c
commit 66f278d180
5 changed files with 26 additions and 0 deletions

View File

@@ -1267,6 +1267,11 @@ You may enable or disable foreign key constraints within your migrations by usin
Schema::disableForeignKeyConstraints();
Schema::withoutForeignKeyConstraints([]
{
// Constraints disabled within this lambda expression...
});
:::caution
The SQLite disables foreign key constraints by default. When using SQLite, make sure to [enable foreign key support](database/getting-started.mdx#sqlite-configuration) in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports creating foreign keys when creating tables and [not when tables are altered](https://www.sqlite.org/omitted.html).
:::

View File

@@ -85,6 +85,9 @@ namespace Orm
static SqlQuery enableForeignKeyConstraints(const QString &connection = "");
/*! Disable foreign key constraints. */
static SqlQuery disableForeignKeyConstraints(const QString &connection = "");
/*! Disable foreign key constraints during the execution of a callback. */
static void withoutForeignKeyConstraints(const std::function<void()> &callback,
const QString &connection = "");
/*! Get the column listing for a given table. */
static QStringList getColumnListing(const QString &table,

View File

@@ -86,6 +86,8 @@ namespace Grammars
SqlQuery enableForeignKeyConstraints() const;
/*! Disable foreign key constraints. */
SqlQuery disableForeignKeyConstraints() const;
/*! Disable foreign key constraints during the execution of a callback. */
void withoutForeignKeyConstraints(const std::function<void()> &callback) const;
/*! Get the column listing for a given table. */
virtual QStringList getColumnListing(const QString &table) const;

View File

@@ -110,6 +110,12 @@ SqlQuery Schema::disableForeignKeyConstraints(const QString &connection)
return schemaBuilder(connection).disableForeignKeyConstraints();
}
void Schema::withoutForeignKeyConstraints(const std::function<void()> &callback,
const QString &connection)
{
schemaBuilder(connection).withoutForeignKeyConstraints(callback);
}
QStringList Schema::getColumnListing(const QString &table, const QString &connection)
{
return schemaBuilder(connection).getColumnListing(table);

View File

@@ -152,6 +152,16 @@ SqlQuery SchemaBuilder::disableForeignKeyConstraints() const
return m_connection.statement(m_grammar.compileDisableForeignKeyConstraints());
}
void
SchemaBuilder::withoutForeignKeyConstraints(const std::function<void()> &callback) const
{
disableForeignKeyConstraints();
std::invoke(callback);
enableForeignKeyConstraints();
}
QStringList SchemaBuilder::getColumnListing(const QString &table) const
{
auto query = m_connection.selectFromWriteConnection(