activerecord-enhancedsqlite3-adapter 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2f3c0a5d2a1ceae77db506215c35aa217521e43d152a1ca312e7b2f52887b803
4
+ data.tar.gz: c5d6f2ac4e34b9181ac7dc6417176fbd5b5dfd5d20376ba6b91731faca73093a
5
+ SHA512:
6
+ metadata.gz: c26a1f83ede20d480687b01a8d1ab39b7d5c854e16fe7d3c3a6c5c984bd23812f3c5d40c531c3a964e032bc0dba1bc33f8de43a3d85c3b4eade0bd30a251f091
7
+ data.tar.gz: fdf1d73eaa883f932f0cbb5cb6c4defc6addcfbbf4a8059a634a08f0b773a7b854b1e85c719e2b978a5708c1263dec3901a6c7d6e289eabe8421fdbdfc55bdb6
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 2.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-09-28
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Stephen Margheim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Activerecord::Enhanced::Sqlite3::Adapter
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/activerecord/enhanced/sqlite3/adapter`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/activerecord-enhancedsqlite3-adapter.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
@@ -0,0 +1,3 @@
1
+ require "active_record"
2
+ require "enhanced_sqlite3/version"
3
+ require "enhanced_sqlite3/railtie"
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ # supports concatenation in default functions: https://github.com/rails/rails/pull/49287
4
+ # supports insert returning values: https://github.com/rails/rails/pull/49290
5
+ # supports configuring busy_handler: https://github.com/rails/rails/pull/49352
6
+
7
+ require "active_record/connection_adapters/sqlite3_adapter"
8
+ require "enhanced_sqlite3/supports_virtual_columns"
9
+
10
+ module EnhancedSQLite3
11
+ module Adapter
12
+ # Perform any necessary initialization upon the newly-established
13
+ # @raw_connection -- this is the place to modify the adapter's
14
+ # connection settings, run queries to configure any application-global
15
+ # "session" variables, etc.
16
+ #
17
+ # Implementations may assume this method will only be called while
18
+ # holding @lock (or from #initialize).
19
+ #
20
+ # extends https://github.com/rails/rails/blob/main/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb#L691
21
+ def configure_connection
22
+ configure_busy_handler
23
+
24
+ super
25
+
26
+ configure_pragmas
27
+ configure_extensions
28
+
29
+ EnhancedSQLite3::SupportsVirtualColumns.apply!
30
+ end
31
+
32
+ private
33
+
34
+ def configure_busy_handler
35
+ if @config[:timeout] && @config[:retries]
36
+ raise ArgumentError, "Cannot specify both timeout and retries arguments"
37
+ elsif @config[:retries]
38
+ # see: https://www.sqlite.org/c3ref/busy_handler.html
39
+ @raw_connection.busy_handler do |count|
40
+ count <= @config[:retries]
41
+ end
42
+ end
43
+ end
44
+
45
+ def configure_pragmas
46
+ @config.fetch(:pragmas, []).each do |key, value|
47
+ execute("PRAGMA #{key} = #{value}", "SCHEMA")
48
+ end
49
+ end
50
+
51
+ def configure_extensions
52
+ @raw_connection.enable_load_extension(true)
53
+ @config.fetch(:extensions, []).each do |extension_name|
54
+ require extension_name
55
+ extension_classname = extension_name.camelize
56
+ extension_class = extension_classname.constantize
57
+ extension_class.load(@raw_connection)
58
+ rescue LoadError
59
+ Rails.logger.error("Failed to find the SQLite extension gem: #{extension_name}. Skipping...")
60
+ rescue NameError
61
+ Rails.logger.error("Failed to find the SQLite extension class: #{extension_classname}. Skipping...")
62
+ end
63
+ @raw_connection.enable_load_extension(false)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+ require "enhanced_sqlite3/adapter"
5
+
6
+ module EnhancedSQLite3
7
+ class Railtie < ::Rails::Railtie
8
+ # Enhance the SQLite3 ActiveRecord adapter with optimized defaults
9
+ initializer "enhanced_sqlite3.enhance_active_record_sqlite3adapter" do |app|
10
+ ActiveSupport.on_load(:active_record_sqlite3adapter) do
11
+ # self refers to `SQLite3Adapter` here,
12
+ # so we can call .prepend
13
+ prepend EnhancedSQLite3::Adapter
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ # see: https://github.com/rails/rails/pull/49346
4
+ module EnhancedSQLite3
5
+ module SupportsVirtualColumns
6
+ def self.apply!
7
+ EnhancedSQLite3::Adapter.include(Adapter)
8
+ ActiveRecord::ConnectionAdapters::SQLite3::Column.include(Column)
9
+ ActiveRecord::ConnectionAdapters::SQLite3::SchemaCreation.include(SchemaCreation)
10
+ ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition.include(TableDefinition)
11
+ ActiveRecord::ConnectionAdapters::SQLite3::SchemaDumper.include(SchemaDumper)
12
+ end
13
+
14
+ module Adapter
15
+ def supports_virtual_columns?
16
+ database_version >= "3.31.0"
17
+ end
18
+
19
+ def new_column_from_field(table_name, field, definitions)
20
+ default = field["dflt_value"]
21
+
22
+ type_metadata = fetch_type_metadata(field["type"])
23
+ default_value = extract_value_from_default(default)
24
+ generated_type = extract_generated_type(field)
25
+
26
+ default_function = if generated_type.present?
27
+ default
28
+ else
29
+ extract_default_function(default_value, default)
30
+ end
31
+
32
+ rowid = is_column_the_rowid?(field, definitions) if definitions
33
+
34
+ ActiveRecord::ConnectionAdapters::SQLite3::Column.new(
35
+ field["name"],
36
+ default_value,
37
+ type_metadata,
38
+ field["notnull"].to_i == 0,
39
+ default_function,
40
+ collation: field["collation"],
41
+ auto_increment: field["auto_increment"],
42
+ rowid: rowid,
43
+ generated_type: generated_type
44
+ )
45
+ end
46
+
47
+ def table_structure(table_name)
48
+ structure = if supports_virtual_columns?
49
+ internal_exec_query("PRAGMA table_xinfo(#{quote_table_name(table_name)})", "SCHEMA")
50
+ else
51
+ internal_exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", "SCHEMA")
52
+ end
53
+ raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
54
+ table_structure_with_collation(table_name, structure)
55
+ end
56
+ alias_method :column_definitions, :table_structure
57
+
58
+ def invalid_alter_table_type?(type, options)
59
+ type.to_sym == :primary_key || options[:primary_key] ||
60
+ options[:null] == false && options[:default].nil?
61
+ options[:null] == false && options[:default].nil? ||
62
+ (type.to_sym == :virtual && options[:stored])
63
+ end
64
+
65
+ GENERATED_ALWAYS_AS_REGEX = /.*"(\w+)".+GENERATED ALWAYS AS \((.+)\) (?:STORED|VIRTUAL)/i
66
+ def table_structure_with_collation(table_name, basic_structure)
67
+ collation_hash = {}
68
+ auto_increments = {}
69
+ generated_columns = {}
70
+ sql = <<~SQL
71
+ SELECT sql FROM
72
+ (SELECT * FROM sqlite_master UNION ALL
73
+ SELECT * FROM sqlite_temp_master)
74
+ WHERE type = 'table' AND name = #{quote(table_name)}
75
+ SQL
76
+
77
+ # Result will have following sample string
78
+ # CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
79
+ # "password_digest" varchar COLLATE "NOCASE");
80
+ result = query_value(sql, "SCHEMA")
81
+
82
+ if result
83
+ # Splitting with left parentheses and discarding the first part will return all
84
+ # columns separated with comma(,).
85
+ columns_string = result.split("(", 2).last
86
+
87
+ columns_string.split(",").each do |column_string|
88
+ # This regex will match the column name and collation type and will save
89
+ # the value in $1 and $2 respectively.
90
+ collation_hash[$1] = $2 if ActiveRecord::ConnectionAdapters::SQLite3Adapter::COLLATE_REGEX =~ column_string
91
+ auto_increments[$1] = true if ActiveRecord::ConnectionAdapters::SQLite3Adapter::PRIMARY_KEY_AUTOINCREMENT_REGEX =~ column_string
92
+ generated_columns[$1] = $2 if GENERATED_ALWAYS_AS_REGEX =~ column_string
93
+ end
94
+
95
+ basic_structure.map do |column|
96
+ column_name = column["name"]
97
+
98
+ if collation_hash.has_key? column_name
99
+ column["collation"] = collation_hash[column_name]
100
+ end
101
+
102
+ if auto_increments.has_key?(column_name)
103
+ column["auto_increment"] = true
104
+ end
105
+
106
+ if generated_columns.has_key?(column_name)
107
+ column["dflt_value"] = generated_columns[column_name]
108
+ end
109
+
110
+ column
111
+ end
112
+ else
113
+ basic_structure.to_a
114
+ end
115
+ end
116
+
117
+ def extract_generated_type(field)
118
+ case field["hidden"]
119
+ when 2 then :virtual
120
+ when 3 then :stored
121
+ end
122
+ end
123
+ end
124
+
125
+ module Column
126
+ def initialize(*, auto_increment: nil, rowid: false, generated_type: nil, **)
127
+ super
128
+ @generated_type = generated_type
129
+ end
130
+
131
+ def virtual?
132
+ @generated_type.present?
133
+ end
134
+
135
+ def virtual_stored?
136
+ virtual? && @generated_type == :stored
137
+ end
138
+
139
+ def has_default?
140
+ super && !virtual?
141
+ end
142
+ end
143
+
144
+ module SchemaCreation
145
+ def add_column_options!(sql, options)
146
+ if options[:collation]
147
+ sql << " COLLATE \"#{options[:collation]}\""
148
+ end
149
+
150
+ if (as = options[:as])
151
+ sql << " GENERATED ALWAYS AS (#{as})"
152
+
153
+ sql << if options[:stored]
154
+ " STORED"
155
+ else
156
+ " VIRTUAL"
157
+ end
158
+ end
159
+ super
160
+ end
161
+ end
162
+
163
+ module TableDefinition
164
+ def new_column_definition(name, type, **options) # :nodoc:
165
+ case type
166
+ when :virtual
167
+ type = options[:type]
168
+ end
169
+
170
+ super
171
+ end
172
+
173
+ def valid_column_definition_options
174
+ super + [:as, :type, :stored]
175
+ end
176
+ end
177
+
178
+ module SchemaDumper
179
+ def prepare_column_options(column)
180
+ spec = super
181
+
182
+ if @connection.supports_virtual_columns? && column.virtual?
183
+ spec[:as] = extract_expression_for_virtual_column(column)
184
+ spec[:stored] = column.virtual_stored?
185
+ spec = {type: schema_type(column).inspect}.merge!(spec)
186
+ end
187
+
188
+ spec
189
+ end
190
+
191
+ def extract_expression_for_virtual_column(column)
192
+ column.default_function.inspect
193
+ end
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnhancedSQLite3
4
+ VERSION = "0.1.0"
5
+ end
metadata ADDED
@@ -0,0 +1,143 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: activerecord-enhancedsqlite3-adapter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Stephen Margheim
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-10-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '7.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: sqlite3
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.6'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.6'
41
+ - !ruby/object:Gem::Dependency
42
+ name: combustion
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.3'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.3'
55
+ - !ruby/object:Gem::Dependency
56
+ name: railties
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: Back-ports generated column support, deferred foreign key support, custom
98
+ foreign key support, improved default configuration, and adds support for pragma
99
+ tuning and extension loading
100
+ email:
101
+ - stephen.margheim@gmail.com
102
+ executables: []
103
+ extensions: []
104
+ extra_rdoc_files: []
105
+ files:
106
+ - ".standard.yml"
107
+ - CHANGELOG.md
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - lib/activerecord-enhancedsqlite3-adapter.rb
112
+ - lib/enhanced_sqlite3/adapter.rb
113
+ - lib/enhanced_sqlite3/railtie.rb
114
+ - lib/enhanced_sqlite3/supports_virtual_columns.rb
115
+ - lib/enhanced_sqlite3/version.rb
116
+ homepage: https://github.com/fractaledmind/activerecord-enhancedsqlite3-adapter
117
+ licenses:
118
+ - MIT
119
+ metadata:
120
+ allowed_push_host: https://rubygems.org
121
+ homepage_uri: https://github.com/fractaledmind/activerecord-enhancedsqlite3-adapter
122
+ source_code_uri: https://github.com/fractaledmind/activerecord-enhancedsqlite3-adapter
123
+ changelog_uri: https://github.com/fractaledmind/activerecord-enhancedsqlite3-adapter/CHANGELOG.md
124
+ post_install_message:
125
+ rdoc_options: []
126
+ require_paths:
127
+ - lib
128
+ required_ruby_version: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - ">="
131
+ - !ruby/object:Gem::Version
132
+ version: 2.6.0
133
+ required_rubygems_version: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - ">="
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ requirements: []
139
+ rubygems_version: 3.4.19
140
+ signing_key:
141
+ specification_version: 4
142
+ summary: ActiveRecord adapter for SQLite that enhances the default.
143
+ test_files: []