Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/arfi/extensions/active_record/base.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.function_exists?(function_name) ⇒ Boolean

ActiveRecord::Base.function_exists? -> bool

This method checks if a custom SQL function exists in the database.

Examples:

ActiveRecord::Base.function_exists?('my_function') #=> true
ActiveRecord::Base.function_exists?('my_function123') #=> false

Parameters:

  • function_name (String)

    The name of the function to check.

Returns:

  • (Boolean)

    Returns true if the function exists, false otherwise.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/arfi/extensions/active_record/base.rb', line 16

def self.function_exists?(function_name) # rubocop:disable Metrics/MethodLength
  case connection
  when ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
    connection.execute("SELECT * FROM pg_proc WHERE proname = '#{function_name}'").any?
  when ActiveRecord::ConnectionAdapters::Mysql2Adapter
    sql = <<~SQL
      SELECT 1
      FROM information_schema.ROUTINES
      WHERE ROUTINE_TYPE = 'FUNCTION'
        AND ROUTINE_SCHEMA = '#{connection.current_database}'
        AND ROUTINE_NAME = '#{function_name}'
      LIMIT 1;
    SQL

    !!connection.execute(sql).first
  else
    raise ActiveRecord::AdapterNotFound, "adapter #{connection.class.name} is not supported"
  end
end