datatable.directory codebase https://datatable.directory/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
datatable.directory/database/migrations/2018_08_01_204822_add_row_s...

54 lines
1.9 KiB

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddRowSequenceGenerator extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// https://www.depesz.com/2008/03/20/getting-multiple-values-from-sequences/
DB::unprepared(/** @lang PostgreSQL */
<<<PGSQL
CREATE OR REPLACE FUNCTION multi_nextval(use_seqname TEXT, use_increment INT4) RETURNS INT4 AS $$
DECLARE
reply int4;
BEGIN
perform pg_advisory_lock(20180801);
execute 'ALTER SEQUENCE ' || quote_ident(use_seqname) || ' INCREMENT BY ' || use_increment::text;
reply := nextval(use_seqname);
execute 'ALTER SEQUENCE ' || quote_ident(use_seqname) || ' INCREMENT BY 1';
perform pg_advisory_unlock(20180801);
return reply;
END;
$$ LANGUAGE 'plpgsql';
PGSQL
);
DB::unprepared('CREATE SEQUENCE IF NOT EXISTS global_row_id_seq START 0 MINVALUE 0;');
// We have to increment manually once before the above function can be used - that is because
// nextval will return the initial value the first time it's called, so it would not advance by
// the given step at all. This would give us negative values - not a problem in postgres without unsigned
// types, but it loooks bad.
DB::select("SELECT nextval('global_row_id_seq') as nv;");
// The multi_nextval() is concurrency-safe, except it can sometimes happen that
// nextval in other connection also increments by the bigger step. The only downside is "wasted IDs".
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::unprepared('DROP FUNCTION IF EXISTS multi_nextval(TEXT, INT4);');
DB::unprepared('DROP SEQUENCE IF EXISTS global_row_id_seq;');
}
}