Is it possible to call an .sql file in a migration class?
I could not find anything on that topic.
Is it possible to call an .sql file in a migration class?
I could not find anything on that topic.
Yes, just put that .sql file and refer it from you migration class.
$this->addSql(file_get_contents(__DIR__ . '/sql-dump.sql'));
I know it's an old question, but it is still the only real hit when I googled for it. The above answer can be slightly improved. It's a simple thing, but you might not think of it. If you have a sql file that contains multiple queries divided by semicolon, you can explode the contents on semicolon.
<?php
foreach (explode(';', file_get_contents(__DIR__ . '/sql-dump.sql')) as $sql) {
$this->addSql($sql);
}
If you are using SQLite and want to execute a .sql file which cointains multiple statements separated by semicolon, I suggest using this code:
$this->connection->exec(file_get_contents(__DIR__ . '/sql-dump.sql'));
This beacuse if you use addSql() method, Doctrine will call the query() method, which doesn't support multiple statements in a single string, and will execute only the first one. Multiple statements are supported only with the exec() method. See: php.net/manual/en/function.sqlite-query.php
For MySQLi I used:
$this->connection->getWrappedConnection()->getWrappedResourceHandle()->multi_query($sql);
After doing some research this works for me
I am using
doctrine-migrations-bundle: "^3.0"
symfony version: 5.4.12
PostgreSQL version: 14.5
Procedure
pq_dump:
pg_dump --column-inserts --data-only -U postgres -h localhost db_name > file_name.sql
Migrations:
public function up(Schema $schema): void
{
$this->connection->getNativeConnection()->exec(file_get_contents(__DIR__.'./../Sql/file_name.sql'));
}
Note: Make sure this line is comment out in your sql file.
SELECT pg_catalog.set_config('search_path', '', false);