File: internal_metadata.rb

package info (click to toggle)
rails 2%3A6.1.7.10%2Bdfsg-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 39,756 kB
  • sloc: ruby: 290,662; javascript: 19,241; yacc: 46; sql: 43; makefile: 32; sh: 18
file content (64 lines) | stat: -rw-r--r-- 1,590 bytes parent folder | download
1
2
3
4
5
6
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
63
64
# frozen_string_literal: true

require "active_record/scoping/default"
require "active_record/scoping/named"

module ActiveRecord
  # This class is used to create a table that keeps track of values and keys such
  # as which environment migrations were run in.
  #
  # This is enabled by default. To disable this functionality set
  # `use_metadata_table` to false in your database configuration.
  class InternalMetadata < ActiveRecord::Base # :nodoc:
    self.record_timestamps = true

    class << self
      def enabled?
        ActiveRecord::Base.connection.use_metadata_table?
      end

      def _internal?
        true
      end

      def primary_key
        "key"
      end

      def table_name
        "#{table_name_prefix}#{internal_metadata_table_name}#{table_name_suffix}"
      end

      def []=(key, value)
        return unless enabled?

        find_or_initialize_by(key: key).update!(value: value)
      end

      def [](key)
        return unless enabled?

        where(key: key).pluck(:value).first
      end

      # Creates an internal metadata table with columns +key+ and +value+
      def create_table
        return unless enabled?

        unless connection.table_exists?(table_name)
          connection.create_table(table_name, id: false) do |t|
            t.string :key, **connection.internal_string_options_for_primary_key
            t.string :value
            t.timestamps
          end
        end
      end

      def drop_table
        return unless enabled?

        connection.drop_table table_name, if_exists: true
      end
    end
  end
end