17

Is there a way to generate stored MYSQL procedures in a Laravel 4 migration?

For example, here's a simple procedure generation query stored as a string (via a Heredoc)

    $query = <<<SQL
DELIMITER $$
DROP PROCEDURE IF EXISTS test$$
CREATE PROCEDURE test()
BEGIN
    INSERT INTO `test_table`(`name`) VALUES('test');
END$$
DELIMITER ;
SQL;

    DB:statement(DB::RAW($query));

When Running this in a migration's up() function I get this error:

enter image description here

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
Johannes
  • 6,232
  • 9
  • 43
  • 59

2 Answers2

32

There are two major problems with your code

  1. DELIMITER is not a valid sql statement. It's just a MySql client command. So just don't use it. BTW the error you get tells you exactly that.
  2. You can't use DB::statement to execute CREATE PROCEDURE code because it uses prepared statement source code for Connection. You can use PDO exec() DB::connection()->getPdo()->exec() instead

That being said a sample migration for imaginary tags table might look like this

class CreateTagsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function($table){
            $table->increments('id');
            $table->string('name')->unique();
        });
$sql = <<<SQL
DROP PROCEDURE IF EXISTS sp_insert_tag;
CREATE PROCEDURE sp_insert_tag(IN _name VARCHAR(32))
BEGIN
    INSERT INTO `tags`(`name`) VALUES(_name);
END
SQL;
        DB::connection()->getPdo()->exec($sql);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $sql = "DROP PROCEDURE IF EXISTS sp_insert_tag";
        DB::connection()->getPdo()->exec($sql);
        Schema::drop('tags');
    }
}
peterm
  • 91,357
  • 15
  • 148
  • 157
  • 8
    Just wanted to mention, someone on the Laravel forums pointed out that you don't even need to use the PDO object, you can just call `DB::unprepared($sql)` and it will work just as well. Sure it probably boils down to the same thing in the end, but less code :) – Johannes Aug 26 '13 at 11:55
13

For fellow dev looking for the link in laravel mentioned by @Johannes.

Any way to create MYSQL Procedures in Migrations? answered by @aheissenberger.

I use this and it works well for me:

public function up() {            
    DB::unprepared('CREATE PROCEDURE get_highscore() BEGIN SET time_zone = \'Europe/Berlin\'; SET @refscore :=0; SELECT * FROM test; END');
}

public function down() {
    DB::unprepared('DROP PROCEDURE IF EXISTS get_highscore');
}

To call a procedure in your code:

DB::unprepared('CALL get_highscore()');

if you expect a resulting table:

DB::statement('CALL update_highscore()');

if you expect variables:

DB::statement('CALL update_ranking(3,10,@olduser,@newuser)');
$dberg = DB::select('select @olduser as old, @newuser as new');
Vainglory07
  • 5,073
  • 10
  • 43
  • 77