Module: UuidV7::Patches::Mysql::FxMigration

Defined in:
lib/uuid_v7/patches/mysql/fx_migration.rb

Instance Method Summary collapse

Instance Method Details

#populate_uuid_field(table_name:, column_name:) ⇒ Object

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/uuid_v7/patches/mysql/fx_migration.rb', line 7

def populate_uuid_field(table_name:, column_name:)
  table_name  = table_name.to_s.to_sym
  column_name = column_name.to_s.to_sym

  raise ArgumentError, "Column #{column_name} does not exist on table #{table_name}" unless column_exists?(table_name, column_name)

  connection.execute "    DROP FUNCTION IF EXISTS uuid_v7;\n  SQL\n\n  connection.exec_query <<~SQL.squish\n    CREATE FUNCTION uuid_v7 (time_of_creation DATETIME)\n    RETURNS BINARY(16)\n    LANGUAGE SQL\n    NOT DETERMINISTIC\n    NO SQL\n    SQL SECURITY DEFINER\n    BEGIN\n      DECLARE uuid          CHAR(36);\n      DECLARE undashed_uuid CHAR(32);\n      DECLARE currentTime   BIGINT;\n      DECLARE buuid         BINARY(16);\n\n      SET currentTime = UNIX_TIMESTAMP(time_of_creation) * 1000 + FLOOR(MICROSECOND(NOW(6)) / 1000);\n\n      SET uuid = LOWER(\n        CONCAT(\n          LPAD(HEX(currentTime), 12, '0'), '-7',\n          LPAD(HEX(FLOOR(RAND() * 0x1000)), 3, '0'), '-',\n          HEX(0x8000 | FLOOR(RAND() * 0x4000)), '-',\n          LPAD(HEX(FLOOR(RAND() * 0x1000000000000)), 12, '0')\n        )\n      );\n\n      SET undashed_uuid = REPLACE(uuid, '-', '');\n      SET buuid = UNHEX(undashed_uuid);\n\n      RETURN buuid;\n    END\n  SQL\n\n  # Check for NULL created_at values\n  result = connection.exec_query(<<~SQL)\n    SELECT COUNT(*) AS count FROM \#{table_name} WHERE created_at IS NULL;\n  SQL\n\n  raise ActiveRecord::RecordInvalid, \"There are records with NULL created_at in \#{table_name}\" if (result.rows[0][0]).positive?\n\n  connection.execute <<~SQL\n    UPDATE \#{table_name} SET \#{column_name} = uuid_v7(created_at) WHERE \#{column_name} IS NULL;\n  SQL\n\n  connection.execute <<~SQL\n    DROP FUNCTION IF EXISTS uuid_v7;\n  SQL\nend\n"