uuidable 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b20ce4ca86027e9695a57d87cef118ec29df028043161a3c3eea836c15fffe27
4
- data.tar.gz: ab4f42a296abbf88ceb0f1318d69ad0e3a02d66427824126f534a19547672109
3
+ metadata.gz: 64eed216cb7c9f07adad0773fcc6bfd57f992d4194fa5a6f45fa9c736a8ce0be
4
+ data.tar.gz: d1388f545158d05d5dbd5df60f9d2b6d1411272f289bbb3e714f3538ebd54cc1
5
5
  SHA512:
6
- metadata.gz: 34ace90af47551e1cff4955586278acfff5a441c621511b00ebb3ccc20e44fccba78ac2adf61a77d8e1145b4e4cb2205984bde36717c751e64f84a9bc07a509a
7
- data.tar.gz: d3651858bea2d6ce7b46c7ec4e6f24b36403dbc1fd68fbddebfec5ad1cd92e482e440edcb5690ee0292f6c7f95d5a66b712772b270aebd7ad72a9edfe30ca1be
6
+ metadata.gz: aec6d70ebf0a611951bab29d3f55fabfba163054e93d6afd2add0c5696482abae211cee9e4d57439e3d63d96bcd3ea0a7ab6cff1a4a42ce14674861c10b944c3
7
+ data.tar.gz: c2455b538b196b7fbfedc080fa745c50bac27418d226f489c07df7788f7e7576eca4ffa67c6dbf9624ae90cdcc39b4ade1e876da4c01c51da5e8709cb5fe33e1
@@ -1,37 +1,74 @@
1
- # This workflow uses actions that are not certified by GitHub.
2
- # They are provided by a third-party and are governed by
3
- # separate terms of service, privacy policy, and support
4
- # documentation.
5
- # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake
6
- # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby
7
-
8
1
  name: Test
9
2
 
10
3
  on:
11
4
  push:
12
- branches: [ '*' ]
5
+ branches: [master]
6
+ pull_request:
7
+ workflow_dispatch:
13
8
 
14
9
  permissions:
15
10
  contents: read
16
11
 
12
+ concurrency:
13
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
14
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
15
+
17
16
  jobs:
18
17
  test:
19
- runs-on: ${{ matrix.os }}-latest
18
+ name: RuboCop and specs without a database
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v7
22
+ - uses: ruby/setup-ruby@v1
23
+ with:
24
+ ruby-version: '2.7'
25
+ bundler-cache: true
26
+ - run: bundle exec rubocop
27
+ - run: bundle exec rake
28
+
29
+ detect:
30
+ name: Detect MySQL specs
31
+ runs-on: ubuntu-latest
32
+ outputs:
33
+ mysql: ${{ steps.check.outputs.mysql }}
34
+ steps:
35
+ - uses: actions/checkout@v7
36
+ - id: check
37
+ run: echo "mysql=$([ -f gemfiles/activerecord.gemfile ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
38
+
39
+ mysql:
40
+ name: MySQL
41
+ needs: detect
42
+ if: needs.detect.outputs.mysql == 'true'
43
+ runs-on: ubuntu-latest
20
44
  strategy:
45
+ fail-fast: false
21
46
  matrix:
22
- os: [ubuntu, macos]
23
- ruby-version: ['2.7', '3.0', '3.1']
24
-
47
+ include:
48
+ - { ruby: '2.7', activerecord: '6.1' }
49
+ - { ruby: '3.2', activerecord: '7.1' }
50
+ - { ruby: '3.4', activerecord: '7.2' }
51
+ - { ruby: '4.0', activerecord: '8.1' }
52
+ services:
53
+ mysql:
54
+ image: mysql:8.4
55
+ env:
56
+ MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
57
+ MYSQL_DATABASE: uuidable_test
58
+ ports: ['127.0.0.1:3306:3306']
59
+ options: >-
60
+ --health-cmd "mysqladmin ping -h 127.0.0.1"
61
+ --health-interval 5s --health-timeout 5s --health-retries 30
62
+ env:
63
+ BUNDLE_GEMFILE: gemfiles/activerecord.gemfile
64
+ ACTIVE_RECORD_VERSION: '~> ${{ matrix.activerecord }}.0'
65
+ UUIDABLE_DATABASE_URL: mysql2://root@127.0.0.1:3306/uuidable_test
25
66
  steps:
26
- - uses: actions/checkout@v3
27
- - name: Set up Ruby
28
- # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby,
29
- # change this to (see https://github.com/ruby/setup-ruby#versioning):
30
- uses: ruby/setup-ruby@v1
31
- with:
32
- ruby-version: ${{ matrix.ruby-version }}
33
- bundler-cache: true # runs 'bundle install' and caches installed gems automatically
34
- - name: Run rubocop
35
- run: bundle exec rubocop
36
- - name: Run tests
37
- run: bundle exec rake
67
+ - uses: actions/checkout@v7
68
+ - uses: ruby/setup-ruby@v1
69
+ with:
70
+ ruby-version: ${{ matrix.ruby }}
71
+ # The gemspec requires Bundler 2.x; Ruby 2.7 ships 2.1 and Ruby 4.0 ships 4.x.
72
+ bundler: '2.4.22'
73
+ bundler-cache: true
74
+ - run: bundle exec rspec
data/.gitignore CHANGED
@@ -8,3 +8,4 @@
8
8
  /tmp/
9
9
  /.history/
10
10
  .idea
11
+ /gemfiles/*.lock
data/.rubocop.yml CHANGED
@@ -1,5 +1,6 @@
1
1
  AllCops:
2
2
  NewCops: disable
3
+ TargetRubyVersion: 2.7
3
4
 
4
5
  Layout/LineLength:
5
6
  Max: 140
@@ -15,3 +16,7 @@ Metrics/AbcSize:
15
16
 
16
17
  Style/Documentation:
17
18
  Enabled: False
19
+
20
+ Metrics/BlockLength:
21
+ Exclude:
22
+ - 'spec/**/*'
data/Gemfile.lock CHANGED
@@ -1,8 +1,8 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- uuidable (1.2.0)
5
- activerecord (>= 4.2, < 8.2)
4
+ uuidable (1.3.0)
5
+ activerecord (>= 6.1, < 8.2)
6
6
  mysql-binuuid-rails (>= 1.3, < 2)
7
7
  uuidtools (>= 3.0, < 4)
8
8
 
@@ -25,10 +25,7 @@ GEM
25
25
  minitest (>= 5.1)
26
26
  mutex_m
27
27
  tzinfo (~> 2.0)
28
- addressable (2.8.0)
29
- public_suffix (>= 2.0.2, < 5.0)
30
28
  ast (2.4.2)
31
- backports (3.6.8)
32
29
  base64 (0.2.0)
33
30
  bigdecimal (3.1.6)
34
31
  concurrent-ruby (1.2.3)
@@ -36,41 +33,16 @@ GEM
36
33
  diff-lcs (1.5.0)
37
34
  drb (2.2.0)
38
35
  ruby2_keywords
39
- ethon (0.8.1)
40
- ffi (>= 1.3.0)
41
- faraday (0.9.2)
42
- multipart-post (>= 1.2, < 3)
43
- faraday_middleware (0.10.0)
44
- faraday (>= 0.7.4, < 0.10)
45
- ffi (1.13.1)
46
- gh (0.14.0)
47
- addressable
48
- backports
49
- faraday (~> 0.8)
50
- multi_json (~> 1.0)
51
- net-http-persistent (>= 2.7)
52
- net-http-pipeline
53
- highline (1.7.8)
54
36
  i18n (1.14.1)
55
37
  concurrent-ruby (~> 1.0)
56
38
  json (2.3.1)
57
- launchy (2.4.3)
58
- addressable (~> 2.3)
59
39
  minitest (5.22.2)
60
- multi_json (1.11.2)
61
- multipart-post (2.0.0)
62
40
  mutex_m (0.2.0)
63
41
  mysql-binuuid-rails (1.3.0)
64
42
  activerecord (>= 5)
65
- net-http-persistent (2.9.4)
66
- net-http-pipeline (1.0.1)
67
43
  parallel (1.22.1)
68
44
  parser (3.1.2.0)
69
45
  ast (~> 2.4.1)
70
- public_suffix (4.0.7)
71
- pusher-client (0.6.2)
72
- json
73
- websocket (~> 1.0)
74
46
  rainbow (3.1.1)
75
47
  rake (13.0.6)
76
48
  regexp_parser (2.5.0)
@@ -103,22 +75,10 @@ GEM
103
75
  ruby-progressbar (1.11.0)
104
76
  ruby2_keywords (0.0.5)
105
77
  timeout (0.4.1)
106
- travis (1.8.2)
107
- backports
108
- faraday (~> 0.9)
109
- faraday_middleware (~> 0.9, >= 0.9.1)
110
- gh (~> 0.13)
111
- highline (~> 1.6)
112
- launchy (~> 2.1)
113
- pusher-client (~> 0.4)
114
- typhoeus (~> 0.6, >= 0.6.8)
115
- typhoeus (0.8.0)
116
- ethon (>= 0.8.0)
117
78
  tzinfo (2.0.6)
118
79
  concurrent-ruby (~> 1.0)
119
80
  unicode-display_width (2.2.0)
120
81
  uuidtools (3.0.0)
121
- websocket (1.2.2)
122
82
 
123
83
  PLATFORMS
124
84
  ruby
@@ -128,7 +88,6 @@ DEPENDENCIES
128
88
  rake (~> 13.0)
129
89
  rspec (~> 3.0)
130
90
  rubocop
131
- travis (~> 1.8, >= 1.8.2)
132
91
  uuidable!
133
92
 
134
93
  BUNDLED WITH
data/README.md CHANGED
@@ -46,10 +46,66 @@ class CreateProjects < ActiveRecord::Migration
46
46
  end
47
47
  ```
48
48
 
49
+ ## UUID storage
50
+
51
+ New UUID columns store 16 bytes (`varbinary(16)`). Versions before 1.0 stored the 36-character text form (`varbinary(36)`). Models read both as UUID strings (16-byte columns are recognized by `uuid` in their name), and upgrading the gem does not change existing columns.
52
+
53
+ Choose the format of a new column with `storage:`:
54
+
55
+ ```ruby
56
+ t.uuid storage: :text
57
+ add_uuid_column :projects, :parent_uuid, storage: :binary
58
+ ```
59
+
60
+ An app that keeps its pre-1.0 columns can make text the default, so that new columns match the existing ones:
61
+
62
+ ```ruby
63
+ # config/initializers/uuidable.rb
64
+ Uuidable.default_storage = :text
65
+ ```
66
+
67
+ Migrations read the setting when they run, so set it before the first migration on 1.x runs, and keep it: a database built from scratch with another setting gets other column types. Migrations that pass `storage:` or `limit:` do not depend on it.
68
+
69
+ Columns compared in SQL, for example in a join, must use the same storage: a 16-byte UUID never equals its 36-character text form.
70
+
71
+ ## Converting pre-1.0 columns
72
+
73
+ Converting existing columns is optional. On MySQL 8, include the helpers in a migration:
74
+
75
+ ```ruby
76
+ class ConvertProjectUuids < ActiveRecord::Migration[7.2]
77
+ include Uuidable::V1MigrationHelpers
78
+
79
+ def change
80
+ # Every 36-byte column with `uuid` in its name, or only the listed ones:
81
+ uuidable_migrate_uuid_columns_to_v1 :projects
82
+ uuidable_migrate_uuid_columns_to_v1 :tasks, { 'project_uuid' => {} }
83
+ end
84
+ end
85
+ ```
86
+
87
+ The original values stay in `*__old` columns, which models keep writing while they exist, so the migration can be rolled back. A model callback that sets a converted UUID has to run before that copy: a `before_create` or `before_update` declared after the model's schema has loaded runs after it, so use `before_save` there. When you no longer need the old values, drop them with `uuidable_drop_all_pre_v1_uuid_columns!`: it drops every `*__old` column with `uuid` in its name in all tables, and cannot be undone.
88
+
89
+ - A converted column keeps the nullability and comment of the original; override them with `null:` and `comment:` in its options. Its default is not carried over; a rollback restores it.
90
+ - An empty string becomes `NULL`. A column that ends up `NOT NULL` with empty or `NULL` values is refused.
91
+ - A listed column that is not a 36-byte UUID column raises an error; pass `skip_type_check: true` to convert a column of another type, such as `varchar(36)`. A listed column that is 16 bytes already is skipped, also with `skip_type_check: true`. On Ruby 2.7, use string keys in the list or pass a keyword after it.
92
+ - Each step is a single `ALTER TABLE`. If a call fails, for example on a value that is not a UUID or on two UUIDs that differ only in case under a unique index, its table is left unchanged. Should the cleanup fail as well, drop the remaining `*__new` column before running it again.
93
+ - MySQL commits each step, so a migration with several calls can stop halfway. Fix the data and run it again: the columns it already converted are skipped.
94
+ - Without a column list a call covers the whole table, and so does its rollback: it restores the columns that earlier migrations converted too, even if the call found nothing left to convert. In `change` such a call is refused when the table is already partly converted, even by an earlier call of the same migration, so convert listed columns and then the rest of a table in `up` and `down`. In `change`, list only the columns that migration converts, as its rollback restores every listed one.
95
+ - A rollback written in `change` is reverted by a conversion without options, which without a list takes every remaining 36-byte column; write such rollbacks in `up` and `down`.
96
+ - Rows written during the conversion are converted too, but adding the converted columns rebuilds the table and blocks writes meanwhile. Restart the application afterwards: running processes keep the old column types.
97
+ - Indexes keep their options and expressions; an invisible index comes back visible. Columns that are part of a primary or foreign key are refused; drop the key first. Convert the source of a generated column rather than the column itself, and drop a unique index on a prefix of a UUID before converting it.
98
+ - A rollback is refused if rows changed without the model callbacks, for example with `update_all`, because the `*__old` columns miss those changes. The check runs just before the rollback, so stop such writes while it runs. Inserts that skip callbacks, such as `insert_all`, fail while a `NOT NULL` `*__old` column exists.
99
+
49
100
  ## Development
50
101
 
51
102
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
52
103
 
104
+ Specs that need a database are skipped unless `UUIDABLE_DATABASE_URL` points to a MySQL 8 database whose name ends in `_test`. The specs create and drop their own tables. To run them against a specific Active Record version:
105
+
106
+ BUNDLE_GEMFILE=gemfiles/activerecord.gemfile ACTIVE_RECORD_VERSION='~> 8.1.0' \
107
+ UUIDABLE_DATABASE_URL=mysql2://root@127.0.0.1:3306/uuidable_test bundle exec rake
108
+
53
109
  To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
54
110
 
55
111
  ## Contributing
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Runs the suite against one Active Record version and a MySQL database:
4
+ # BUNDLE_GEMFILE=gemfiles/activerecord.gemfile ACTIVE_RECORD_VERSION='~> 8.1.0' bundle exec rake
5
+ eval_gemfile File.expand_path('../Gemfile', __dir__)
6
+
7
+ gem 'activerecord', ENV.fetch('ACTIVE_RECORD_VERSION')
8
+ gem 'mysql2', '~> 0.5'
9
+
10
+ # Ruby 3.4 no longer ships these as default gems, and Active Record before 7.1 does not declare them.
11
+ gem 'base64'
12
+ gem 'bigdecimal'
13
+ gem 'drb'
14
+ gem 'mutex_m'
@@ -17,24 +17,53 @@ module Uuidable
17
17
  end
18
18
  end
19
19
 
20
+ # Reads 16-byte UUID columns as UUID strings. The types are installed when the
21
+ # model loads its schema, so defining a model needs no database connection.
22
+ module SchemaTypes
23
+ # Rails 7.2 started asking the model for the type of each column.
24
+ def self.type_for_column_hook?
25
+ ::ActiveRecord::ModelSchema::ClassMethods.private_method_defined?(:type_for_column)
26
+ end
27
+
28
+ # Before Rails 7.2: the schema defines each column with `user_provided_default: false`.
29
+ # Swapping the type there lets `attribute`, `serialize` and `enum` wrap or replace it.
30
+ def define_attribute(name, cast_type, **options)
31
+ if options[:user_provided_default] == false && !SchemaTypes.type_for_column_hook? &&
32
+ uuid_type?(connection, name, cast_type.type, cast_type.limit)
33
+ cast_type = MySQLBinUUID::Type.new
34
+ end
35
+ super
36
+ end
37
+
38
+ private
39
+
40
+ def load_schema!
41
+ super
42
+ return unless columns_hash.each_key.any? { |name| V1ModelMigration.old_uuid_column?(name) }
43
+
44
+ include V1ModelMigration if respond_to?(:with_connection) ? with_connection { |c| mysql?(c) } : mysql?(connection)
45
+ end
46
+
47
+ def type_for_column(connection, column)
48
+ uuid_type?(connection, column.name, column.type, column.limit) ? MySQLBinUUID::Type.new : super
49
+ end
50
+
51
+ def uuid_type?(connection, name, type, limit)
52
+ type == :binary && limit == 16 && name.include?('uuid') && mysql?(connection)
53
+ end
54
+
55
+ def mysql?(connection)
56
+ connection.adapter_name.downcase.include?('mysql')
57
+ end
58
+ end
59
+
20
60
  # ClassMethods
21
61
  module ClassMethods
22
62
  include Finder
23
63
 
24
- def uuidable(as_param: true) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
25
- # Configure all uuid columns for MySQL. Database may not be connected (i.e. on assets precompile), so we must supress errors.
26
- conn_config = respond_to?(:connection_db_config) ? connection_db_config.configuration_hash : connection_config
27
-
28
- if conn_config[:adapter].include?('mysql') && connection.data_source_exists?(table_name)
29
- begin
30
- columns.select { |c| c.type == :binary && c.limit == 16 && c.name.include?('uuid') }.each do |column|
31
- attribute column.name.to_sym, MySQLBinUUID::Type.new
32
- end
33
-
34
- include V1ModelMigration if columns.any? { |c| c.name.include?(V1MigrationHelpers::OLD_POSTFIX) }
35
- rescue ::ActiveRecord::ConnectionNotEstablished, Mysql2::Error::ConnectionError, ::ActiveRecord::NoDatabaseError # rubocop:disable Lint/SuppressedException
36
- end
37
- end
64
+ def uuidable(as_param: true) # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
65
+ singleton_class.prepend(SchemaTypes) unless singleton_class.include?(SchemaTypes)
66
+ reload_schema_from_cache if schema_loaded?
38
67
 
39
68
  after_initialize do
40
69
  self.uuid = Uuidable.generate_uuid if attributes.keys.include?('uuid') && uuid.blank?
@@ -5,29 +5,85 @@ module Uuidable
5
5
  COLUMN_TYPE = :binary
6
6
  COLUMN_OPTIONS = { limit: 16, null: false }.freeze
7
7
  INDEX_OPTIONS = { unique: true }.freeze
8
+ STORAGE_LIMITS = { binary: 16, text: 36 }.freeze
9
+
10
+ class << self
11
+ # Name of a new UUID column, given positionally or with the pre-1.0 `column_name:` option.
12
+ def column_name(positional, keyword)
13
+ if positional && keyword && positional.to_s != keyword.to_s
14
+ raise ArgumentError, "UUID column named twice: #{positional.inspect} and column_name: #{keyword.inspect}"
15
+ end
16
+
17
+ positional || keyword || COLUMN_NAME
18
+ end
19
+
20
+ # Storage for new UUID columns that set neither `storage:` nor `limit:`.
21
+ # Apps upgrading from 0.x can set :text so new columns match their 36-byte ones.
22
+ def default_storage
23
+ @default_storage || :binary
24
+ end
25
+
26
+ def default_storage=(storage)
27
+ storage_limit(storage)
28
+ @default_storage = storage
29
+ end
30
+
31
+ # Column options for a new UUID column, resolving `storage:` into a limit.
32
+ def column_options(options)
33
+ options = options.dup
34
+ storage = options.delete(:storage)
35
+ limit = storage_limit(storage || default_storage)
36
+ if storage && options.key?(:limit) && options[:limit] != limit
37
+ raise ArgumentError, "storage: #{storage.inspect} conflicts with limit: #{options[:limit].inspect}"
38
+ end
39
+
40
+ COLUMN_OPTIONS.merge(limit: limit).merge(options)
41
+ end
42
+
43
+ # Splits migration arguments into the column name and its options. Pre-1.0 migrations pass
44
+ # options as a positional hash, which Ruby 3 no longer turns into keywords.
45
+ def column_arguments(name, opts)
46
+ if name.is_a?(Hash)
47
+ opts = name.merge(opts)
48
+ name = nil
49
+ end
50
+
51
+ [name, opts]
52
+ end
53
+
54
+ private
55
+
56
+ def storage_limit(storage)
57
+ STORAGE_LIMITS.fetch(storage) do
58
+ raise ArgumentError, "UUID storage must be one of #{STORAGE_LIMITS.keys.inspect}, got #{storage.inspect}"
59
+ end
60
+ end
61
+ end
8
62
 
9
63
  # Module adds method to table definition
10
64
  module TableDefinition
11
- def uuid(column_name = COLUMN_NAME, **opts)
65
+ def uuid(column_name = nil, **opts)
66
+ column_name, opts = Uuidable.column_arguments(column_name, opts)
12
67
  index_opts = opts.delete(:index)
13
68
  index_opts = {} if index_opts.nil?
14
69
 
15
- column_name ||= opts.delete(:column_name)
70
+ column_name = Uuidable.column_name(column_name, opts.delete(:column_name))
16
71
 
17
- column column_name, COLUMN_TYPE, **COLUMN_OPTIONS.merge(opts)
72
+ column column_name, COLUMN_TYPE, **Uuidable.column_options(opts)
18
73
  index column_name, **INDEX_OPTIONS.merge(index_opts) if index_opts
19
74
  end
20
75
  end
21
76
 
22
77
  # Module adds method to alter table migration
23
78
  module Migration
24
- def add_uuid_column(table_name, column_name = COLUMN_NAME, **opts)
79
+ def add_uuid_column(table_name, column_name = nil, **opts)
80
+ column_name, opts = Uuidable.column_arguments(column_name, opts)
25
81
  index_opts = opts.delete(:index)
26
82
  index_opts = {} if index_opts == true
27
83
 
28
- column_name ||= opts.delete(:column_name)
84
+ column_name = Uuidable.column_name(column_name, opts.delete(:column_name))
29
85
 
30
- add_column table_name, column_name, COLUMN_TYPE, **COLUMN_OPTIONS.merge(opts)
86
+ add_column table_name, column_name, COLUMN_TYPE, **Uuidable.column_options(opts)
31
87
 
32
88
  add_uuid_index(table_name, index_opts.merge(column_name: column_name)) if index_opts
33
89
  end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Uuidable
4
+ # Converts UUID columns from the pre-v1 36-byte text form to 16 bytes and back,
5
+ # keeping the text in *__old columns between the two. Needs MySQL 8.
6
+ #
7
+ # Each step is a single ALTER TABLE, which MySQL applies completely or not at all:
8
+ # 1. add each converted column as a stored generated column, so rows written
9
+ # during the conversion are converted too;
10
+ # 2. in one statement, rename the original to *__old, turn the generated column
11
+ # into a regular one under the original name and rebuild the indexes.
12
+ class V1Conversion # rubocop:disable Metrics/ClassLength
13
+ class Error < StandardError; end
14
+
15
+ INDEX_ATTRIBUTES = { length: :lengths, order: :orders, type: :type, using: :using, comment: :comment }.freeze
16
+
17
+ def initialize(connection, table_name)
18
+ @connection = connection
19
+ @table_name = table_name.to_s
20
+ @quoted_table = connection.quote_table_name(@table_name)
21
+ end
22
+
23
+ # @param columns [Array<ActiveRecord::ConnectionAdapters::Column>] 36-byte UUID columns
24
+ # @param columns_options [Hash{String => Hash}] :null and :comment for converted columns
25
+ def migrate(columns, columns_options = {})
26
+ return if columns.empty?
27
+
28
+ options = columns.to_h { |column| [column.name, column_options(column, columns_options[column.name])] }
29
+ refuse_keys!(columns)
30
+ refuse_empty_values!(columns.reject { |column| options[column.name][:null] })
31
+ add_converted_columns(columns)
32
+ remove_converted_columns_on_failure(columns) do
33
+ alter_table(indexes_on(columns)) { columns.flat_map { |column| convert_clauses(column, options[column.name]) } }
34
+ end
35
+ end
36
+
37
+ # @param columns [Array<ActiveRecord::ConnectionAdapters::Column>] converted columns that have an *__old column
38
+ def rollback(columns)
39
+ return if columns.empty?
40
+
41
+ refuse_keys!(columns)
42
+ refuse_stale_old_values!(columns)
43
+ alter_table(indexes_on(columns)) do
44
+ columns.flat_map do |column|
45
+ ["DROP COLUMN #{quote(column.name)}", "RENAME COLUMN #{quote(old_name(column))} TO #{quote(column.name)}"]
46
+ end
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ # Renaming a column moves its keys to the *__old column, which would silently drop them from the converted one.
53
+ def refuse_keys!(columns)
54
+ keyed = @connection.select_values(<<~SQL) & columns.map(&:name)
55
+ SELECT COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE
56
+ WHERE #{table_condition} AND (REFERENCED_TABLE_NAME IS NOT NULL OR CONSTRAINT_NAME = 'PRIMARY')
57
+ UNION
58
+ SELECT REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE #{table_condition('REFERENCED_')}
59
+ SQL
60
+ raise Error, "#{keyed.join(', ')} in #{@table_name}: part of a primary or foreign key; drop the key first" if keyed.any?
61
+ end
62
+
63
+ # information_schema keeps the database of a qualified table name, such as app.projects, in a column of its own.
64
+ def table_condition(prefix = '')
65
+ *database, table = @table_name.split('.', 2)
66
+ database = database.empty? ? 'DATABASE()' : @connection.quote(database.first)
67
+ "#{prefix}TABLE_SCHEMA = #{database} AND #{prefix}TABLE_NAME = #{@connection.quote(table)}"
68
+ end
69
+
70
+ # A rollback restores *__old, so it would lose rows written without the V1ModelMigration callbacks.
71
+ def refuse_stale_old_values!(columns)
72
+ old_columns = @connection.columns(@table_name).index_by(&:name)
73
+ columns.each do |column|
74
+ old_value = converted_value(old_columns.fetch(old_name(column)))
75
+ stale = @connection.select_value(<<~SQL).to_i
76
+ SELECT COUNT(*) FROM #{@quoted_table} WHERE NOT (#{quote(column.name)} <=> #{old_value})
77
+ SQL
78
+ raise Error, "#{stale} rows of #{@table_name}.#{column.name} differ from #{old_name(column)}; copy them first" unless stale.zero?
79
+ end
80
+ end
81
+
82
+ # An empty string converts to NULL, which a NOT NULL column cannot take.
83
+ def refuse_empty_values!(columns)
84
+ columns.each do |column|
85
+ empty = @connection.select_value("SELECT COUNT(*) FROM #{@quoted_table} WHERE #{converted_value(column)} IS NULL").to_i
86
+ raise Error, "#{empty} rows of #{@table_name}.#{column.name} are empty or NULL; fill them or pass null: true" unless empty.zero?
87
+ end
88
+ end
89
+
90
+ def convert_clauses(column, options)
91
+ ["RENAME COLUMN #{quote(column.name)} TO #{quote(old_name(column))}",
92
+ "CHANGE COLUMN #{quote(new_name(column))} #{quote(column.name)} #{definition(options)}"]
93
+ end
94
+
95
+ def add_converted_columns(columns)
96
+ @connection.change_table(@table_name, bulk: true) do |table|
97
+ columns.each do |column|
98
+ table.virtual new_name(column), type: :binary, limit: 16, as: converted_value(column), stored: true, after: column.name
99
+ end
100
+ end
101
+ end
102
+
103
+ def remove_converted_columns_on_failure(columns)
104
+ yield
105
+ rescue StandardError => e
106
+ begin
107
+ @connection.remove_columns(@table_name, *columns.map { |column| new_name(column) })
108
+ rescue StandardError => cleanup_error
109
+ warn "uuidable: could not remove the converted columns of #{@table_name}: #{cleanup_error.message}; " \
110
+ "drop the *#{V1MigrationHelpers::NEW_POSTFIX} columns before running the migration again"
111
+ end
112
+ raise e
113
+ end
114
+
115
+ # An empty string means no UUID, and 16 bytes in a binary column are a UUID already. Anything
116
+ # else that is not a UUID makes UUID_TO_BIN fail the ALTER.
117
+ def converted_value(column)
118
+ name = quote(column.name)
119
+ converted = "UUID_TO_BIN(NULLIF(#{name}, ''))"
120
+ column.type == :binary ? "IF(OCTET_LENGTH(#{name}) = 16, #{name}, #{converted})" : converted
121
+ end
122
+
123
+ # Released versions passed the options to the new column, so existing migrations may give `default: nil`,
124
+ # which a converted column has anyway.
125
+ def column_options(column, options)
126
+ options = (options || {}).transform_keys(&:to_sym)
127
+ options.delete(:default) if options[:default].nil?
128
+ options = { null: column.null, comment: column.comment }.merge(options)
129
+ unknown = options.keys - %i[null comment]
130
+ raise ArgumentError, "Unsupported options for #{column.name}: #{unknown.join(', ')}" if unknown.any?
131
+
132
+ options
133
+ end
134
+
135
+ def definition(options)
136
+ [@connection.type_to_sql(:binary, limit: 16), ('NOT NULL' unless options[:null]),
137
+ ("COMMENT #{@connection.quote(options[:comment])}" if options[:comment])].compact.join(' ')
138
+ end
139
+
140
+ def indexes_on(columns)
141
+ names = columns.map(&:name)
142
+ @connection.indexes(@table_name).select do |index|
143
+ # Rails gives the parts of an index with an expression as one SQL string.
144
+ index.columns.is_a?(String) ? names.any? { |name| index.columns.include?(quote(name)) } : (index.columns & names).any?
145
+ end
146
+ end
147
+
148
+ # Drops the indexes, applies the column changes and adds the indexes back in one statement.
149
+ def alter_table(indexes)
150
+ clauses = indexes.map { |index| "DROP INDEX #{quote(index.name)}" } + yield + indexes.map { |index| add_index_clause(index) }
151
+ @connection.execute("ALTER TABLE #{@quoted_table} #{clauses.join(', ')}")
152
+ end
153
+
154
+ # Rails builds the clause it would use in change_table(bulk: true); its public API cannot be
155
+ # combined with CHANGE COLUMN in a single statement.
156
+ def add_index_clause(index)
157
+ options = INDEX_ATTRIBUTES.transform_values { |reader| index.public_send(reader) }.reject { |_, value| value.nil? || value == {} }
158
+ @connection.send(:add_index_for_alter, @table_name, index.columns, name: index.name, unique: index.unique, **options)
159
+ end
160
+
161
+ def new_name(column)
162
+ "#{column.name}#{V1MigrationHelpers::NEW_POSTFIX}"
163
+ end
164
+
165
+ def old_name(column)
166
+ "#{column.name}#{V1MigrationHelpers::OLD_POSTFIX}"
167
+ end
168
+
169
+ def quote(name)
170
+ @connection.quote_column_name(name)
171
+ end
172
+ end
173
+ end
@@ -1,95 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # rubocop:disable all
3
+ require 'uuidable/v1_conversion'
4
+
4
5
  module Uuidable
6
+ # Migration helpers that convert pre-v1 36-byte UUID columns to 16 bytes. Needs MySQL 8.
7
+ # Converting and rolling back are each other's inverse, so either works inside `change`.
5
8
  module V1MigrationHelpers
6
9
  NEW_POSTFIX = '__new'
7
10
  OLD_POSTFIX = '__old'
8
11
 
9
- # Will create uuid columns with new type, move data from pre-v1 column and then move pre-v1 to *__old.
10
- # WARNING: will only work on MySQL 8+.
12
+ # Converts UUID columns to 16 bytes and keeps the original values in *__old columns.
13
+ # @param columns_options [Hash{String, Symbol => Hash}] columns to convert, with :null or :comment overrides
14
+ # @param opts [Hash] :limit and :skip_type_check for selecting columns, see #valid_column_for_migration?
11
15
  def uuidable_migrate_uuid_columns_to_v1(table_name, columns_options = {}, **opts)
12
- columns_options.stringify_keys!
13
- uuid_columns = connection.columns(table_name).select do |column|
14
- (columns_options.blank? || columns_options.key?(column.name)) &&
15
- valid_column_for_migration?(column, **opts)
16
- end
17
-
18
- return if uuid_columns.blank?
19
-
20
- indexes = indexes_with_columns(table_name, uuid_columns)
21
-
22
- change_table table_name, bulk: true do |t|
23
- uuid_columns.each do |column|
24
- options = columns_options[column.name] || { null: column.null }
25
- t.column :"#{column.name}#{NEW_POSTFIX}", :binary, **COLUMN_OPTIONS.merge(options).merge(after: column.name)
26
- end
27
- end
28
-
29
- update = uuid_columns.map do |column, _opts|
30
- <<~SQL
31
- `#{table_name}`.`#{column.name}#{NEW_POSTFIX}` = IF(
32
- IS_UUID(`#{table_name}`.`#{column.name}`),
33
- UUID_TO_BIN(`#{table_name}`.`#{column.name}`),
34
- `#{table_name}`.`#{column.name}`
35
- )
36
- SQL
37
- end.join(', ')
38
-
39
- execute "UPDATE `#{table_name}` SET #{update}"
40
-
41
- change_table table_name, bulk: true do |t|
42
- uuid_columns.each do |column|
43
- t.rename column.name, :"#{column.name}#{OLD_POSTFIX}"
44
- t.rename :"#{column.name}#{NEW_POSTFIX}", column.name
45
- end
46
-
47
- indexes.each do |ind|
48
- t.remove_index name: ind.name
49
- end
50
- end
51
-
52
- # recreate indexes with new column
53
- change_table table_name, bulk: true do |t|
54
- indexes.each do |ind|
55
- t.index ind.columns, name: ind.name, unique: ind.unique
56
- end
16
+ columns_options = columns_options.transform_keys(&:to_s)
17
+ reversible do |direction|
18
+ direction.up { uuidable_convert_to_v1(table_name, columns_options, opts) }
19
+ direction.down { uuidable_restore_from_v1(table_name, columns_options.keys) }
57
20
  end
58
21
  end
59
22
 
60
- # WARNING: will only work until *__old columns is not deleted!
23
+ # Restores the original values from *__old columns. Refuses to run if rows changed
24
+ # without the V1ModelMigration callbacks, because the old columns would not have them.
61
25
  def uuidable_rollback_uuid_columns_from_v1(table_name, *columns)
62
- columns.map!(&:to_s)
63
- indexes = indexes(table_name)
64
-
65
- uuid_columns = connection.columns(table_name).select do |column|
66
- (columns.blank? || columns.include?(column.name)) &&
67
- valid_column_for_migration?(column, limit: 16)
68
- end
69
-
70
- return if uuid_columns.blank?
71
-
72
- indexes = indexes_with_columns(table_name, uuid_columns)
73
-
74
- change_table table_name, bulk: true do |t|
75
- uuid_columns.each do |column|
76
- t.rename column.name, :"#{column.name}#{NEW_POSTFIX}"
77
- t.rename :"#{column.name}#{OLD_POSTFIX}", column.name
78
- end
79
-
80
- indexes.each do |ind|
81
- t.remove_index name: ind.name
82
- end
83
- end
84
-
85
- change_table table_name, bulk: true do |t|
86
- uuid_columns.each do |column|
87
- t.remove :"#{column.name}#{NEW_POSTFIX}"
88
- end
89
-
90
- indexes.each do |ind|
91
- t.index ind.columns, name: ind.name, unique: ind.unique
92
- end
26
+ columns = columns.map(&:to_s)
27
+ reversible do |direction|
28
+ direction.up { uuidable_restore_from_v1(table_name, columns) }
29
+ # Listed columns had *__old pairs, so they are UUID columns whatever type they are restored to.
30
+ direction.down { uuidable_convert_to_v1(table_name, columns.to_h { |name| [name, {}] }, { skip_type_check: columns.any? }) }
93
31
  end
94
32
  end
95
33
 
@@ -107,11 +45,13 @@ module Uuidable
107
45
 
108
46
  # WARNING: this is irreversible migration! It will drop all *uuid__old columns and their indexes in all tables!
109
47
  def uuidable_drop_all_pre_v1_uuid_columns!
48
+ raise ::ActiveRecord::IrreversibleMigration, 'the dropped *__old columns cannot be restored' if reverting?
49
+
110
50
  tables.each do |table_name|
111
51
  indexes = indexes(table_name)
112
52
  change_table table_name, bulk: true do |t|
113
53
  connection.columns(table_name).each do |column|
114
- next unless column.name.include?(OLD_POSTFIX)
54
+ next unless column.name.include?('uuid') && column.name.end_with?(OLD_POSTFIX)
115
55
 
116
56
  indexes.each do |ind|
117
57
  next unless ind.columns.include?(column.name)
@@ -129,15 +69,59 @@ module Uuidable
129
69
  column.name.include?('uuid') &&
130
70
  !column.name.include?(NEW_POSTFIX) &&
131
71
  !column.name.include?(OLD_POSTFIX) &&
132
- (skip_type_check || (
133
- column.type == :binary &&
134
- column.limit == limit
135
- ))
72
+ (skip_type_check || (column.type == :binary && column.limit == limit))
136
73
  end
137
74
 
138
75
  def indexes_with_columns(table_name, columns)
139
76
  indexes(table_name).select { |ind| (ind.columns & columns.map(&:name)).any? }
140
77
  end
78
+
79
+ private
80
+
81
+ # Columns that are 16 bytes already are skipped, even with skip_type_check: those an earlier run converted,
82
+ # so a migration that stopped halfway can run again, and those created on 1.x, as in a database built by
83
+ # running the migrations there.
84
+ def uuidable_convert_to_v1(table_name, columns_options, opts)
85
+ all_columns = connection.columns(table_name)
86
+ binary = all_columns.select { |column| valid_column_for_migration?(column, limit: 16) }.map(&:name)
87
+ columns = all_columns.select { |column| convertible?(column, columns_options, binary, opts) }
88
+ refuse_missing!(table_name, columns_options.keys - binary - columns.map(&:name),
89
+ 'not a pre-v1 UUID column; check the name, or pass skip_type_check: true for a column of another type')
90
+ refuse_partly_converted!(table_name, converted_column_names(table_name)) if columns_options.empty? && columns.any?
91
+ V1Conversion.new(connection, table_name).migrate(columns, columns_options)
92
+ end
93
+
94
+ def convertible?(column, columns_options, binary, opts)
95
+ (columns_options.empty? || columns_options.key?(column.name)) && !binary.include?(column.name) &&
96
+ valid_column_for_migration?(column, **opts)
97
+ end
98
+
99
+ def uuidable_restore_from_v1(table_name, names)
100
+ converted = converted_column_names(table_name)
101
+ columns = connection.columns(table_name)
102
+ refuse_missing!(table_name, names - columns.map(&:name), 'no such column')
103
+ columns = columns.select { |column| converted.include?(column.name) && (names.empty? || names.include?(column.name)) }
104
+ V1Conversion.new(connection, table_name).rollback(columns)
105
+ end
106
+
107
+ # 16-byte UUID columns that have an *__old pair.
108
+ def converted_column_names(table_name)
109
+ columns = connection.columns(table_name)
110
+ names = columns.map(&:name)
111
+ columns.select { |column| valid_column_for_migration?(column, limit: 16) && names.include?("#{column.name}#{OLD_POSTFIX}") }
112
+ .map(&:name)
113
+ end
114
+
115
+ def refuse_missing!(table_name, names, reason)
116
+ raise V1Conversion::Error, "#{names.join(', ')} in #{table_name}: #{reason}" if names.any?
117
+ end
118
+
119
+ # In `change`, a call without a list is reverted by a rollback without a list, which would also
120
+ # restore the columns that earlier migrations converted.
121
+ def refuse_partly_converted!(table_name, converted)
122
+ return unless converted.any? && respond_to?(:change)
123
+
124
+ raise V1Conversion::Error, "#{table_name} is partly converted (#{converted.join(', ')}); list the columns to convert in change"
125
+ end
141
126
  end
142
127
  end
143
- # rubocop:enable all
@@ -5,14 +5,32 @@ module Uuidable
5
5
  module V1ModelMigration
6
6
  extend ActiveSupport::Concern
7
7
 
8
+ def self.old_uuid_column?(name)
9
+ name.end_with?(V1MigrationHelpers::OLD_POSTFIX) && name.include?('uuid')
10
+ end
11
+
12
+ # Saves that skip validation, such as save!(validate: false), still copy. The module is included
13
+ # when the schema loads, so these run after the model's before_save callbacks and after its
14
+ # before_create and before_update callbacks declared before that.
8
15
  included do
9
- before_validation do
10
- attributes.each_key do |attr_name|
11
- next unless attr_name.include?(V1MigrationHelpers::OLD_POSTFIX)
16
+ before_create :uuidable_copy_uuids_to_old_columns
17
+ before_update :uuidable_copy_uuids_to_old_columns
18
+ end
19
+
20
+ private
21
+
22
+ # Copies only UUIDs that are written, so other saves keep the original text for a rollback.
23
+ # An old column that was not loaded is written as well.
24
+ def uuidable_copy_uuids_to_old_columns
25
+ self.class.columns_hash.each_value do |old_column|
26
+ next unless V1ModelMigration.old_uuid_column?(old_column.name)
27
+
28
+ source = old_column.name.delete_suffix(V1MigrationHelpers::OLD_POSTFIX)
29
+ next unless self.class.columns_hash.key?(source) && (new_record? || will_save_change_to_attribute?(source))
12
30
 
13
- new_attr_name = attr_name.gsub(V1MigrationHelpers::OLD_POSTFIX, '')
14
- public_send("#{attr_name}=", attributes[new_attr_name].to_s)
15
- end
31
+ value = self[source]
32
+ # A NOT NULL old column keeps an empty string for no UUID, which converts to NULL.
33
+ self[old_column.name] = value.nil? && !old_column.null ? '' : value
16
34
  end
17
35
  end
18
36
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Uuidable
4
- VERSION = '1.2.0'
4
+ VERSION = '1.3.0'
5
5
  end
data/uuidable.gemspec CHANGED
@@ -25,9 +25,8 @@ Gem::Specification.new do |spec|
25
25
  spec.add_development_dependency 'bundler', '~> 2.4'
26
26
  spec.add_development_dependency 'rake', '~> 13.0'
27
27
  spec.add_development_dependency 'rspec', '~> 3.0'
28
- spec.add_development_dependency 'travis', '~> 1.8', '>= 1.8.2'
29
28
 
30
- spec.add_dependency 'activerecord', '>= 4.2', '< 8.2'
29
+ spec.add_dependency 'activerecord', '>= 6.1', '< 8.2'
31
30
  spec.add_dependency 'mysql-binuuid-rails', '>= 1.3', '< 2'
32
31
  spec.add_dependency 'uuidtools', '>= 3.0', '< 4'
33
32
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: uuidable
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.0
4
+ version: 1.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sergey Gnuskov
@@ -51,33 +51,13 @@ dependencies:
51
51
  - - "~>"
52
52
  - !ruby/object:Gem::Version
53
53
  version: '3.0'
54
- - !ruby/object:Gem::Dependency
55
- name: travis
56
- requirement: !ruby/object:Gem::Requirement
57
- requirements:
58
- - - "~>"
59
- - !ruby/object:Gem::Version
60
- version: '1.8'
61
- - - ">="
62
- - !ruby/object:Gem::Version
63
- version: 1.8.2
64
- type: :development
65
- prerelease: false
66
- version_requirements: !ruby/object:Gem::Requirement
67
- requirements:
68
- - - "~>"
69
- - !ruby/object:Gem::Version
70
- version: '1.8'
71
- - - ">="
72
- - !ruby/object:Gem::Version
73
- version: 1.8.2
74
54
  - !ruby/object:Gem::Dependency
75
55
  name: activerecord
76
56
  requirement: !ruby/object:Gem::Requirement
77
57
  requirements:
78
58
  - - ">="
79
59
  - !ruby/object:Gem::Version
80
- version: '4.2'
60
+ version: '6.1'
81
61
  - - "<"
82
62
  - !ruby/object:Gem::Version
83
63
  version: '8.2'
@@ -87,7 +67,7 @@ dependencies:
87
67
  requirements:
88
68
  - - ">="
89
69
  - !ruby/object:Gem::Version
90
- version: '4.2'
70
+ version: '6.1'
91
71
  - - "<"
92
72
  - !ruby/object:Gem::Version
93
73
  version: '8.2'
@@ -151,9 +131,11 @@ files:
151
131
  - Rakefile
152
132
  - bin/console
153
133
  - bin/setup
134
+ - gemfiles/activerecord.gemfile
154
135
  - lib/uuidable.rb
155
136
  - lib/uuidable/active_record.rb
156
137
  - lib/uuidable/migration.rb
138
+ - lib/uuidable/v1_conversion.rb
157
139
  - lib/uuidable/v1_migration_helpers.rb
158
140
  - lib/uuidable/v1_model_migration.rb
159
141
  - lib/uuidable/version.rb