rails-uuid-pk 0.10.0 → 0.12.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: 5c8d9367ce6e034ff5ecc94e41e482b38e56f0886fd7cbbcb73a43bd948e3f96
4
- data.tar.gz: 972cf5ee47c2c0ca1120decb6f35e16da2e62d9b2e2d2cee8b171fb883bdc003
3
+ metadata.gz: 0ef202d7fd8ed44687383011c2306cdafc16fc9a05505270c270a753d4fd4a33
4
+ data.tar.gz: fd9416e86ae299c7d693fcba9bc0e71d179940cd4e1e29dbd4bfc892e30e0248
5
5
  SHA512:
6
- metadata.gz: fd95a444a62a9b337c0c6033530fe75db6e0873750bb8e43f1ac47a6bfdee4443b5139c9f79aa4b432752fcfdd54a32adfca598e6a1dfe5669b8085c2eb2b7cf
7
- data.tar.gz: ad6c1eb9f0fed6a62b15930fca2a1e67b09d0c4940314f5fca8032e130637619105159b49f5dd37e96ceb2ccff7ad057ff30b81ae044a2d864e752dec748dde3
6
+ metadata.gz: 4f675cb556f985b0060cc34297182d5dbe1860a05cce42ce1b8de62e4b5f4ea89b07ae84669615dbb109d6f4c4bc0779c6a90bcaf9b0af3cc1b8d42b8588f8cc
7
+ data.tar.gz: 9ac0c2032a0036bc9a5a7441391f30b3991c0557446605ac1bb9b35a100e8fdb9cad565443536ef4b833f3c7c0793ff085b51996e1d75a5e018472ff4edd92af
data/CHANGELOG.md CHANGED
@@ -5,6 +5,55 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v1.0.0.html).
7
7
 
8
+ ## [0.12.0] - 2026-01-17
9
+
10
+ ### Changed
11
+ - **Refactored Database Adapter Extensions**: Eliminated 152 lines of duplicated code (97% similarity) between MySQL and SQLite adapter extensions by introducing a shared `UuidAdapterExtension` module
12
+ - Created `lib/rails_uuid_pk/uuid_adapter_extension.rb` with common UUID type support functionality
13
+ - Refactored `Mysql2AdapterExtension` and `Sqlite3AdapterExtension` to include the shared module
14
+ - Maintained SQLite-specific transaction-aware connection configuration while standardizing all other UUID handling logic
15
+ - Improved code maintainability and reduced duplication from 156 lines to 99 lines total (37% reduction)
16
+
17
+ ### Technical Details
18
+ - Added shared `UuidAdapterExtension` module containing `native_database_types`, `valid_type?`, `register_uuid_types`, `initialize_type_map`, `configure_connection`, and `type_to_dump` methods
19
+ - Updated `Mysql2AdapterExtension` to include shared module with minimal override for `configure_connection`
20
+ - Updated `Sqlite3AdapterExtension` to include shared module while preserving transaction-aware `configure_connection` implementation
21
+ - Added require statement for new shared module in main library file
22
+ - All existing functionality preserved with identical test suite results (119 tests, 0 failures, 0 errors)
23
+
24
+ ## [0.11.0] - 2026-01-16
25
+
26
+ ### Added
27
+ - **`use_integer_primary_key` opt-out functionality**: Added ability to opt out of automatic UUIDv7 primary key generation for specific models
28
+ - New `use_integer_primary_key` class method allows models to use traditional integer auto-incrementing primary keys
29
+ - **Important**: When opting out, developers must modify the generated migration to change `id: :uuid` to `id: :integer` for the table schema
30
+ - Migration helpers automatically detect mixed primary key types and set appropriate foreign key types
31
+ - Comprehensive test coverage for opt-out behavior and mixed primary key scenarios
32
+ - Full interoperability between UUID and integer primary key models
33
+ - Updated documentation with opt-out usage examples
34
+
35
+ ### Documentation
36
+ - **README Minimization**: Streamlined README.md from ~250 to 112 lines (55% reduction) by moving development content to dedicated DEVELOPMENT.md
37
+ - **DEVELOPMENT.md**: Created comprehensive development guide covering setup, testing, contribution guidelines, and project structure
38
+ - **AGENTS.md Enhancement**: Added prominent "Documentation Maintenance" section with critical instructions for keeping all documentation files (AGENTS.md, ARCHITECTURE.md, CHANGELOG.md, DEVELOPMENT.md, PERFORMANCE.md, README.md, SECURITY.md) up-to-date
39
+ - **Improved Documentation Organization**: Better separation of user-facing and developer-facing content with proper cross-references
40
+
41
+ ### Technical Details
42
+ - Added `ClassMethods` module to `RailsUuidPk::HasUuidv7PrimaryKey` with `use_integer_primary_key` and `uses_uuid_primary_key?` methods
43
+ - Modified callback condition to check `self.class.uses_uuid_primary_key?` for opt-out support
44
+ - Enhanced migration helpers to handle mixed UUID/integer primary key environments
45
+ - **Refactored logger initialization**: Simplified `RailsUuidPk.logger` method from multiple redundant assignments to single `||=` expression for improved readability and maintainability
46
+ - Added comprehensive unit tests in `test/uuid/opt_out_test.rb` covering:
47
+ - Opt-out method functionality and flag setting
48
+ - Callback skipping for opted-out models
49
+ - Mixed primary key scenarios with proper foreign key type detection
50
+ - Inheritance behavior and subclass overrides
51
+ - Added integration tests for mixed primary key scenarios in migration helpers
52
+ - Updated configuration tests to verify opt-out functionality
53
+
54
+ ### Fixed
55
+ - **Documentation URI**: Updated documentation URI in gemspec to include version number for proper RubyDoc.info linking
56
+
8
57
  ## [0.10.0] - 2026-01-15
9
58
 
10
59
  ### Added
data/README.md CHANGED
@@ -13,13 +13,8 @@ Automatically use UUID v7 for **all primary keys** in Rails applications. Works
13
13
 
14
14
  - Uses **native** `SecureRandom.uuid_v7` (Ruby 3.3+)
15
15
  - Automatically sets `:uuid` as default primary key type
16
- - Adds reliable `before_create` callback for UUIDv7 generation
17
- - Works perfectly on **PostgreSQL 18+**, **MySQL 8.0+**, and **SQLite** (and older versions too)
18
- - **PostgreSQL**: Uses native `UUID` column types with full database support
19
- - **MySQL**: Uses `VARCHAR(36)` with custom ActiveRecord type handling
20
- - **SQLite**: Uses `VARCHAR(36)` with custom ActiveRecord type handling
16
+ - Works perfectly on PostgreSQL, MySQL, and SQLite
21
17
  - Zero database extensions needed
22
- - Minimal and maintainable — no monkey-patching hell
23
18
  - Production-ready logging for debugging and monitoring
24
19
 
25
20
  ## Installation
@@ -27,7 +22,7 @@ Automatically use UUID v7 for **all primary keys** in Rails applications. Works
27
22
  Add to your `Gemfile`:
28
23
 
29
24
  ```ruby
30
- gem "rails-uuid-pk", "~> 0.10"
25
+ gem "rails-uuid-pk", "~> 0.12"
31
26
  ```
32
27
 
33
28
  Then run:
@@ -40,198 +35,78 @@ That's it! The gem automatically enables UUIDv7 primary keys for all your models
40
35
 
41
36
  ## Usage
42
37
 
43
- After installation, **every new model** you generate will get a `uuid` primary key with automatic UUIDv7 values:
38
+ After installation, **every new model** automatically gets a `uuid` primary key with UUIDv7 values:
44
39
 
45
40
  ```bash
46
41
  rails g model User name:string email:string
47
42
  # → creates id: :uuid with automatic uuidv7 generation
48
43
  ```
49
44
 
50
- That's it! No changes needed in your models.
51
-
52
45
  ```ruby
53
46
  # This works out of the box:
54
47
  User.create!(name: "Alice") # ← id is automatically a proper UUIDv7
55
48
  ```
56
49
 
57
- ## Important Compatibility Notes
50
+ ### Opting Out of UUID Primary Keys
58
51
 
59
- ### Action Text & Active Storage
52
+ For specific models, you can opt out:
60
53
 
61
- When you install Action Text or Active Storage:
54
+ ```ruby
55
+ class LegacyModel < ApplicationRecord
56
+ use_integer_primary_key
57
+ # Uses integer auto-incrementing primary key instead of UUIDv7
58
+ end
62
59
 
63
- ```bash
64
- rails action_text:install
65
- rails active_storage:install
60
+ # Migration must also use :integer
61
+ create_table :legacy_models, id: :integer do |t|
62
+ t.string :name
63
+ end
66
64
  ```
67
65
 
68
- The generated migrations seamlessly integrate with UUID primary keys. Rails-uuid-pk's smart migration helpers automatically detect UUID primary keys in referenced tables and set the appropriate `type: :uuid` for foreign keys.
69
-
70
- ### Polymorphic associations
71
-
72
- Polymorphic associations work seamlessly with UUID primary keys. Whether you're using Action Text's `record` references or custom polymorphic associations, the migration helpers automatically detect the parent table's primary key type and set the correct foreign key type.
73
-
74
- For example, this migration will automatically use `type: :uuid` when the parent models have UUID primary keys:
66
+ Migration helpers automatically detect mixed primary key types and set appropriate foreign key types:
75
67
 
76
68
  ```ruby
77
- create_table :comments do |t|
78
- t.references :commentable, polymorphic: true
69
+ # Rails will automatically use integer foreign keys when referencing LegacyModel
70
+ create_table :related_records do |t|
71
+ t.references :legacy_model, null: false # → integer foreign key
72
+ t.references :user, null: false # → UUID foreign key (User uses UUIDs)
79
73
  end
80
74
  ```
81
75
 
82
- ## Features / Trade-offs
83
-
84
- | Feature | Status | Notes |
85
- |--------------------------------------|-----------------|-----------------------------------------------------------------------|
86
- | UUIDv7 generation | Automatic | Uses `SecureRandom.uuid_v7` (very good randomness + monotonicity) |
87
- | PostgreSQL 18+ native `uuidv7()` | Not used | Fallback approach — more universal, no extensions needed |
88
- | PostgreSQL support | Full | Native `UUID` column types with full database support |
89
- | MySQL 8.0+ support | Full | Uses `VARCHAR(36)` with custom ActiveRecord type handling |
90
- | SQLite support | Full | Uses `VARCHAR(36)` with custom ActiveRecord type handling |
91
- | Index locality / performance | Very good | UUIDv7 is monotonic → almost as good as sequential IDs |
92
- | Zero config after install | Yes | Migration helpers automatically handle foreign key types |
93
- | Works with Rails 7.1 – 8+ | Yes | Tested conceptually up to Rails 8.1+ |
94
-
95
- ## Performance Overview
96
-
97
- **Generation**: ~800,000 UUIDs/second with cryptographic security and monotonic ordering
98
-
99
- | Database | Storage | Index Performance | Notes |
100
- |----------|---------|-------------------|--------|
101
- | **PostgreSQL** | Native UUID (16B) | Excellent | Optimal performance |
102
- | **MySQL** | VARCHAR(36) (36B) | Good | 2.25x storage overhead |
103
- | **SQLite** | VARCHAR(36) (36B) | Good | Good for development |
76
+ ## Important Compatibility Notes
104
77
 
105
- **Key Advantages**:
106
- - **UUIDv7 outperforms UUIDv4** in most scenarios due to monotonic ordering
107
- - **Better index locality** than random UUIDs with reduced fragmentation
108
- - **Efficient range queries** for time-based data access
109
- - **Production-ready scaling** with proper indexing and monitoring
78
+ ### Action Text & Active Storage
110
79
 
111
- For comprehensive performance analysis, scaling strategies, and optimization guides, see [PERFORMANCE.md](PERFORMANCE.md).
80
+ When installing Action Text or Active Storage, migrations automatically integrate with UUID primary keys - no changes needed.
112
81
 
113
- ## Bulk Operations
82
+ ### Polymorphic associations
114
83
 
115
- **Important**: Bulk operations like `Model.import` bypass ActiveRecord callbacks, so UUIDs won't be automatically generated for bulk-inserted records. Use explicit UUID assignment or a custom bulk import method if needed.
84
+ Polymorphic associations work seamlessly with UUID primary keys. Foreign key types are automatically detected.
116
85
 
117
- ```ruby
118
- # Manual UUID assignment for bulk operations
119
- users = [{ name: "Alice", id: SecureRandom.uuid_v7 }, { name: "Bob", id: SecureRandom.uuid_v7 }]
120
- User.insert_all(users) # Bypasses callbacks, requires explicit IDs
121
- ```
86
+ ## Performance & Architecture
122
87
 
123
- ## Why not use native PostgreSQL `uuidv7()`?
88
+ UUIDv7 provides excellent performance with monotonic ordering and reduced index fragmentation compared to UUIDv4.
124
89
 
125
- While PostgreSQL 18+ has excellent native `uuidv7()` support, the **fallback approach** was chosen for maximum compatibility:
90
+ - **Generation**: ~800,000 UUIDs/second with cryptographic security
91
+ - **Storage**: Native UUID (16B) on PostgreSQL, VARCHAR(36) on MySQL/SQLite
92
+ - **Index Performance**: Better locality than random UUIDs
126
93
 
127
- - Works on SQLite without changes
128
- - Works on older PostgreSQL versions
129
- - No need to manage database extensions
130
- - Zero risk when switching databases or in CI/test environments
94
+ For detailed performance analysis and optimization guides, see [PERFORMANCE.md](PERFORMANCE.md).
131
95
 
132
- You can still add native PostgreSQL defaults manually if you want maximum performance — the gem's fallback is safe and will simply be ignored.
96
+ For architecture decisions and design rationale, see [ARCHITECTURE.md](ARCHITECTURE.md).
133
97
 
134
98
  ## Development
135
99
 
136
- ### Devcontainer Setup
137
-
138
- This project includes a devcontainer configuration for VS Code (highly recommended, as it automatically sets up Ruby 3.3, Rails, PostgreSQL, MySQL, and SQLite in an isolated environment). To get started:
139
-
140
- 1. Open the project in VS Code
141
- 2. When prompted, click "Reopen in Container" (or run `Dev Containers: Reopen in Container` from the command palette)
142
- 3. The devcontainer will set up Ruby 3.3, Rails, and all dependencies automatically
100
+ See [DEVELOPMENT.md](DEVELOPMENT.md) for setup instructions, testing, and contribution guidelines.
143
101
 
144
- #### Devcontainer CLI
145
-
146
- For terminal-based development or automation, you can use the Devcontainer CLI. The devcontainer will be built and started automatically when you run the exec commands.
147
-
148
- ##### Installation
149
-
150
- - **MacOS**: `brew install devcontainer`
151
- - **Other systems**: `npm install -g @devcontainers/cli`
152
-
153
- ##### Usage
154
-
155
- Run commands inside the devcontainer:
156
-
157
- ```bash
158
- # Install dependencies
159
- devcontainer exec --workspace-folder . bundle install
102
+ ## Security
160
103
 
161
- # Run tests
162
- devcontainer exec --workspace-folder . ./bin/test
163
-
164
- # Run code quality checks
165
- devcontainer exec --workspace-folder . ./bin/rubocop
166
-
167
- # Interactive shell
168
- devcontainer exec --workspace-folder . bash
169
- ```
170
-
171
- ### Running Tests
172
-
173
- The project includes a comprehensive test suite that runs against SQLite, PostgreSQL, and MySQL.
174
-
175
- ```bash
176
- # Run all tests (SQLite + PostgreSQL + MySQL)
177
- ./bin/test
178
-
179
- # Run tests with coverage reporting
180
- ./bin/coverage
181
-
182
- # Run performance benchmarks
183
- ./bin/benchmark
184
-
185
- # Run tests for specific database
186
- DB=sqlite ./bin/test # SQLite only
187
- DB=postgres ./bin/test # PostgreSQL only
188
- DB=mysql ./bin/test # MySQL only
189
-
190
- # Run specific test file
191
- ./bin/test test/uuid/generation_test.rb
192
-
193
- # Run specific test file with specific database
194
- DB=sqlite ./bin/test test/uuid/type_test.rb
195
-
196
- # Run multiple specific test files
197
- ./bin/test test/uuid/generation_test.rb test/uuid/type_test.rb
198
- ```
199
-
200
- ### Code Quality
201
-
202
- ```bash
203
- # Run RuboCop for style checking
204
- ./bin/rubocop
205
-
206
- # Auto-fix RuboCop offenses
207
- ./bin/rubocop -a
208
- ```
209
-
210
- ### Building the Gem
211
-
212
- ```bash
213
- # Build the gem
214
- gem build rails_uuid_pk.gemspec
215
-
216
- # Install locally for testing
217
- gem install rails-uuid-pk-0.10.0.gem
218
- ```
219
-
220
- ### Database Setup
221
-
222
- For database testing, ensure the respective databases are running and accessible. The test suite uses these environment variables:
223
- - `DB_HOST` (defaults to localhost)
224
- - `RAILS_ENV=test_postgresql` for PostgreSQL tests
225
- - `RAILS_ENV=test_mysql` for MySQL tests
104
+ For security considerations and vulnerability reporting, see [SECURITY.md](SECURITY.md).
226
105
 
227
106
  ## Contributing
228
107
 
229
- Bug reports and pull requests are welcome on GitHub at https://github.com/seouri/rails-uuid-pk.
230
-
231
- Please see our [Security Policy](SECURITY.md) for information about reporting security vulnerabilities.
232
-
233
- For detailed architecture documentation, design decisions, and technical rationale, see [ARCHITECTURE.md](ARCHITECTURE.md).
108
+ Bug reports and pull requests welcome on GitHub. See [DEVELOPMENT.md](DEVELOPMENT.md) for contribution guidelines.
234
109
 
235
110
  ## License
236
111
 
237
- The gem is available as open source under the terms of the [MIT License](MIT-LICENSE).
112
+ MIT License - see [MIT-LICENSE](MIT-LICENSE) for details.
@@ -20,14 +20,49 @@ module RailsUuidPk
20
20
  # user = User.new(id: "custom-uuid")
21
21
  # user.save # Uses the custom UUID, not auto-generated
22
22
  #
23
- # @note UUIDs are only assigned when id is nil to allow manual ID assignment
23
+ # @example Opting out of UUID primary keys
24
+ # class LegacyModel < ApplicationRecord
25
+ # use_integer_primary_key
26
+ # # Uses integer auto-incrementing primary key instead of UUIDv7
27
+ # end
28
+ #
29
+ # @note UUIDs are only assigned when id is nil and the model uses UUID primary keys
24
30
  # @see RailsUuidPk::Railtie
25
31
  # @see https://www.rfc-editor.org/rfc/rfc9562.html RFC 9562 (UUIDv7)
26
32
  module HasUuidv7PrimaryKey
27
33
  extend ActiveSupport::Concern
28
34
 
29
35
  included do
30
- before_create :assign_uuidv7_if_needed, if: -> { id.nil? }
36
+ before_create :assign_uuidv7_if_needed, if: -> { id.nil? && self.class.uses_uuid_primary_key? }
37
+ end
38
+
39
+ # Class methods for models using HasUuidv7PrimaryKey.
40
+ module ClassMethods
41
+ # Opt out of automatic UUIDv7 primary key generation for this model.
42
+ #
43
+ # When called, the model will use Rails' default primary key behavior
44
+ # (typically integer auto-incrementing) instead of UUIDv7 generation.
45
+ #
46
+ # @example
47
+ # class LegacyModel < ApplicationRecord
48
+ # use_integer_primary_key
49
+ # end
50
+ #
51
+ # @note Subclasses do NOT inherit this setting. Each class must explicitly opt out.
52
+ # @return [void]
53
+ def use_integer_primary_key
54
+ singleton_class.instance_variable_set(:@uses_integer_primary_key, true)
55
+ end
56
+
57
+ # Check if this model uses UUID primary keys.
58
+ #
59
+ # Returns false if the model has opted out via use_integer_primary_key,
60
+ # true otherwise (default behavior).
61
+ #
62
+ # @return [Boolean] true if model uses UUID primary keys, false otherwise
63
+ def uses_uuid_primary_key?
64
+ !singleton_class.instance_variable_get(:@uses_integer_primary_key)
65
+ end
31
66
  end
32
67
 
33
68
  private
@@ -4,8 +4,8 @@ module RailsUuidPk
4
4
  # MySQL adapter extension for UUID type support.
5
5
  #
6
6
  # This module extends ActiveRecord's MySQL2 adapter to provide native UUID
7
- # type support. Since MySQL doesn't have a native UUID type, it maps UUIDs
8
- # to VARCHAR(36) columns and registers the custom UUID type handlers.
7
+ # type support. It includes the shared UUID adapter extension functionality
8
+ # and provides MySQL-specific connection configuration.
9
9
  #
10
10
  # @example Automatic type mapping
11
11
  # # MySQL tables with VARCHAR(36) columns are automatically treated as UUIDs
@@ -13,65 +13,17 @@ module RailsUuidPk
13
13
  # t.column :id, :uuid # Maps to VARCHAR(36) in MySQL
14
14
  # end
15
15
  #
16
+ # @see RailsUuidPk::UuidAdapterExtension
16
17
  # @see RailsUuidPk::Type::Uuid
17
18
  # @see https://dev.mysql.com/doc/refman/8.0/en/data-types.html
18
19
  module Mysql2AdapterExtension
19
- # Defines native database types for MySQL UUID support.
20
- #
21
- # @return [Hash] Database type definitions including UUID mapping
22
- def native_database_types
23
- super.merge(
24
- uuid: { name: "varchar", limit: 36 }
25
- )
26
- end
27
-
28
- # Checks if a type is valid for this adapter.
29
- #
30
- # Overrides ActiveRecord's valid_type? to recognize the custom UUID type.
31
- #
32
- # @param type [Symbol] The type to check
33
- # @return [Boolean] true if the type is valid
34
- def valid_type?(type)
35
- return true if type == :uuid
36
- super
37
- end
38
-
39
- # Registers UUID type handlers in the adapter's type map.
40
- #
41
- # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to register with
42
- # @return [void]
43
- def register_uuid_types(m = type_map)
44
- RailsUuidPk.log(:debug, "Registering UUID types on #{m.class}")
45
- m.register_type(/varchar\(36\)/i) { RailsUuidPk::Type::Uuid.new }
46
- m.register_type("uuid") { RailsUuidPk::Type::Uuid.new }
47
- end
48
-
49
- # Initializes the type map with UUID type registrations.
50
- #
51
- # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to initialize
52
- # @return [void]
53
- def initialize_type_map(m = type_map)
54
- super
55
- register_uuid_types(m)
56
- end
20
+ include UuidAdapterExtension
57
21
 
58
22
  # Configures the database connection with UUID type support.
59
23
  #
60
24
  # @return [void]
61
25
  def configure_connection
62
26
  super
63
- register_uuid_types
64
- end
65
-
66
- # Overrides type dumping to properly handle UUID columns.
67
- #
68
- # @param column [ActiveRecord::ConnectionAdapters::Column] The column to dump
69
- # @return [Array] The type and options for the schema dump
70
- def type_to_dump(column)
71
- if column.type == :uuid
72
- return [ :uuid, {} ]
73
- end
74
- super
75
27
  end
76
28
  end
77
29
  end
@@ -4,8 +4,9 @@ module RailsUuidPk
4
4
  # SQLite adapter extension for UUID type support.
5
5
  #
6
6
  # This module extends ActiveRecord's SQLite3 adapter to provide native UUID
7
- # type support. Since SQLite doesn't have a native UUID type, it maps UUIDs
8
- # to VARCHAR(36) columns and registers the custom UUID type handlers.
7
+ # type support. It includes the shared UUID adapter extension functionality
8
+ # and provides SQLite-specific connection configuration, including transaction-aware
9
+ # connection setup.
9
10
  #
10
11
  # @example Automatic type mapping
11
12
  # # SQLite tables with VARCHAR(36) columns are automatically treated as UUIDs
@@ -13,67 +14,22 @@ module RailsUuidPk
13
14
  # t.column :id, :uuid # Maps to VARCHAR(36) in SQLite
14
15
  # end
15
16
  #
17
+ # @see RailsUuidPk::UuidAdapterExtension
16
18
  # @see RailsUuidPk::Type::Uuid
17
19
  # @see https://www.sqlite.org/datatype3.html
18
20
  module Sqlite3AdapterExtension
19
- # Defines native database types for SQLite UUID support.
20
- #
21
- # @return [Hash] Database type definitions including UUID mapping
22
- def native_database_types
23
- super.merge(
24
- uuid: { name: "varchar", limit: 36 }
25
- )
26
- end
27
-
28
- # Checks if a type is valid for this adapter.
29
- #
30
- # Overrides ActiveRecord's valid_type? to recognize the custom UUID type.
31
- #
32
- # @param type [Symbol] The type to check
33
- # @return [Boolean] true if the type is valid
34
- def valid_type?(type)
35
- return true if type == :uuid
36
- super
37
- end
38
-
39
- # Registers UUID type handlers in the adapter's type map.
40
- #
41
- # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to register with
42
- # @return [void]
43
- def register_uuid_types(m = type_map)
44
- RailsUuidPk.log(:debug, "Registering UUID types on #{m.class}")
45
- m.register_type(/varchar\(36\)/i) { RailsUuidPk::Type::Uuid.new }
46
- m.register_type("uuid") { RailsUuidPk::Type::Uuid.new }
47
- end
48
-
49
- # Initializes the type map with UUID type registrations.
50
- #
51
- # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to initialize
52
- # @return [void]
53
- def initialize_type_map(m = type_map)
54
- super
55
- register_uuid_types(m)
56
- end
21
+ include UuidAdapterExtension
57
22
 
58
23
  # Configures the database connection with UUID type support.
59
24
  #
25
+ # SQLite-specific implementation that avoids calling super inside transactions,
26
+ # as PRAGMA statements cannot be executed inside transactions in SQLite.
27
+ #
60
28
  # @return [void]
61
29
  def configure_connection
62
30
  # Only call super if not inside a transaction, as PRAGMA statements
63
31
  # cannot be executed inside transactions in SQLite
64
32
  super unless open_transactions > 0
65
- register_uuid_types
66
- end
67
-
68
- # Overrides type dumping to properly handle UUID columns.
69
- #
70
- # @param column [ActiveRecord::ConnectionAdapters::Column] The column to dump
71
- # @return [Array] The type and options for the schema dump
72
- def type_to_dump(column)
73
- if column.type == :uuid
74
- return [ :uuid, {} ]
75
- end
76
- super
77
33
  end
78
34
  end
79
35
  end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RailsUuidPk
4
+ # Shared UUID adapter extension for database adapters.
5
+ #
6
+ # This module provides common UUID type support functionality that can be
7
+ # included by specific database adapter extensions (MySQL, SQLite, etc.).
8
+ # Since most databases don't have native UUID types, it maps UUIDs to
9
+ # VARCHAR(36) columns and registers the custom UUID type handlers.
10
+ #
11
+ # @example Automatic type mapping
12
+ # # Database tables with VARCHAR(36) columns are automatically treated as UUIDs
13
+ # create_table :users do |t|
14
+ # t.column :id, :uuid # Maps to VARCHAR(36) in supported databases
15
+ # end
16
+ #
17
+ # @see RailsUuidPk::Type::Uuid
18
+ module UuidAdapterExtension
19
+ # Defines native database types for UUID support.
20
+ #
21
+ # @return [Hash] Database type definitions including UUID mapping
22
+ def native_database_types
23
+ super.merge(
24
+ uuid: { name: "varchar", limit: 36 }
25
+ )
26
+ end
27
+
28
+ # Checks if a type is valid for this adapter.
29
+ #
30
+ # Overrides ActiveRecord's valid_type? to recognize the custom UUID type.
31
+ #
32
+ # @param type [Symbol] The type to check
33
+ # @return [Boolean] true if the type is valid
34
+ def valid_type?(type)
35
+ return true if type == :uuid
36
+ super
37
+ end
38
+
39
+ # Registers UUID type handlers in the adapter's type map.
40
+ #
41
+ # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to register with
42
+ # @return [void]
43
+ def register_uuid_types(m = type_map)
44
+ RailsUuidPk.log(:debug, "Registering UUID types on #{m.class}")
45
+ m.register_type(/varchar\(36\)/i) { RailsUuidPk::Type::Uuid.new }
46
+ m.register_type("uuid") { RailsUuidPk::Type::Uuid.new }
47
+ end
48
+
49
+ # Initializes the type map with UUID type registrations.
50
+ #
51
+ # @param m [ActiveRecord::ConnectionAdapters::AbstractAdapter::TypeMap] The type map to initialize
52
+ # @return [void]
53
+ def initialize_type_map(m = type_map)
54
+ super
55
+ register_uuid_types(m)
56
+ end
57
+
58
+ # Configures the database connection with UUID type support.
59
+ #
60
+ # This method should be overridden by including adapters to handle
61
+ # database-specific connection configuration requirements.
62
+ #
63
+ # @return [void]
64
+ def configure_connection
65
+ super
66
+ register_uuid_types
67
+ end
68
+
69
+ # Overrides type dumping to properly handle UUID columns.
70
+ #
71
+ # @param column [ActiveRecord::ConnectionAdapters::Column] The column to dump
72
+ # @return [Array] The type and options for the schema dump
73
+ def type_to_dump(column)
74
+ if column.type == :uuid
75
+ return [ :uuid, {} ]
76
+ end
77
+ super
78
+ end
79
+ end
80
+ end
@@ -7,6 +7,6 @@ module RailsUuidPk
7
7
  #
8
8
  # @return [String] The current version
9
9
  # @example
10
- # RailsUuidPk::VERSION # => "0.10.0"
11
- VERSION = "0.10.0"
10
+ # RailsUuidPk::VERSION # => "0.12.0"
11
+ VERSION = "0.12.0"
12
12
  end
data/lib/rails_uuid_pk.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require "rails_uuid_pk/version"
4
4
  require "rails_uuid_pk/concern"
5
5
  require "rails_uuid_pk/type"
6
+ require "rails_uuid_pk/uuid_adapter_extension"
6
7
  require "rails_uuid_pk/sqlite3_adapter_extension"
7
8
  require "rails_uuid_pk/mysql2_adapter_extension"
8
9
  require "rails_uuid_pk/railtie"
@@ -46,10 +47,7 @@ module RailsUuidPk
46
47
  # @example
47
48
  # RailsUuidPk.logger.info("Custom message")
48
49
  def self.logger
49
- return @logger if @logger
50
-
51
- rails_logger = defined?(Rails.logger) && Rails.logger
52
- @logger = rails_logger || Logger.new($stdout)
50
+ @logger ||= ((defined?(Rails.logger) && Rails.logger) || Logger.new($stdout))
53
51
  @logger = Logger.new($stdout) unless @logger.is_a?(Logger)
54
52
  @logger
55
53
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails-uuid-pk
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.10.0
4
+ version: 0.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Joon Lee
@@ -154,6 +154,7 @@ files:
154
154
  - lib/rails_uuid_pk/railtie.rb
155
155
  - lib/rails_uuid_pk/sqlite3_adapter_extension.rb
156
156
  - lib/rails_uuid_pk/type.rb
157
+ - lib/rails_uuid_pk/uuid_adapter_extension.rb
157
158
  - lib/rails_uuid_pk/version.rb
158
159
  - lib/tasks/rails_uuid_pk_tasks.rake
159
160
  homepage: https://github.com/seouri/rails-uuid-pk
@@ -163,7 +164,7 @@ metadata:
163
164
  homepage_uri: https://github.com/seouri/rails-uuid-pk
164
165
  source_code_uri: https://github.com/seouri/rails-uuid-pk
165
166
  changelog_uri: https://github.com/seouri/rails-uuid-pk/blob/main/CHANGELOG.md
166
- documentation_uri: https://www.rubydoc.info/gems/rails-uuid-pk
167
+ documentation_uri: https://www.rubydoc.info/gems/rails-uuid-pk/0.12.0
167
168
  rdoc_options: []
168
169
  require_paths:
169
170
  - lib