Module: PgRandomId::Sql

Defined in:
lib/pg_random_id/sql.rb

Class Method Summary collapse

Class Method Details

.apply(table, column, options = {}) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/pg_random_id/sql.rb', line 12

def apply table, column, options = {}
  key = options[:key] || rand(2**15)
  sequence = options[:sequence] || "#{table}_#{column}_seq"
  """
    INSERT INTO pri_keys VALUES ('#{sequence}'::regclass, #{key});
    ALTER TABLE #{table} ALTER COLUMN #{column} SET DEFAULT pri_nextval('#{sequence}'::regclass);
  """
end

.apply_str(table, column, options = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/pg_random_id/sql.rb', line 30

def apply_str table, column, options = {}
  key = options[:key] || rand(2**15)
  sequence = options[:sequence] || "#{table}_#{column}_seq"
  type = options[:type] || "character(6)"
  """
    INSERT INTO pri_keys VALUES ('#{sequence}'::regclass, #{key});
    ALTER TABLE #{table} ALTER COLUMN #{column} SET DATA TYPE #{type};
    ALTER TABLE #{table} ALTER COLUMN #{column} SET DEFAULT pri_nextval_str('#{sequence}'::regclass);
  """
end

.installObject



4
5
6
# File 'lib/pg_random_id/sql.rb', line 4

def install
  FILES.map {|f| read_file f}.join
end

.unapply(table, column, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/pg_random_id/sql.rb', line 21

def unapply table, column, options = {}
  sequence = options[:sequence] || "#{table}_#{column}_seq"
  """
    ALTER TABLE #{table} ALTER COLUMN #{column} SET DEFAULT nextval('#{sequence}'::regclass);
    ALTER TABLE #{table} ALTER COLUMN #{column} SET DATA TYPE integer USING 0;
    DELETE FROM pri_keys WHERE sequence = '#{sequence}'::regclass;
  """
end

.uninstallObject



8
9
10
# File 'lib/pg_random_id/sql.rb', line 8

def uninstall
  read_file 'uninstall.sql'
end