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

Check if a SQL function exists in the database, dispatching to the correct adapter method.

Parameters:

  • function_name (String)

    Function name to check

Returns:

  • (Boolean)

    Whether the function exists

Raises:

  • (ActiveRecord::AdapterNotFound)

    If adapter is not supported



12
13
14
15
16
17
18
19
20
21
# File 'lib/arfi/extensions/active_record/base.rb', line 12

def self.function_exists?(function_name)
  case connection.class.name
  when 'ActiveRecord::ConnectionAdapters::PostgreSQLAdapter'
    pg_function_exists?(function_name)
  when 'ActiveRecord::ConnectionAdapters::Mysql2Adapter', 'ActiveRecord::ConnectionAdapters::TrilogyAdapter'
    mysql_function_exists?(function_name)
  else
    raise ActiveRecord::AdapterNotFound, "adapter #{connection.class.name} is not supported"
  end
end

.mysql_function_exists?(function_name) ⇒ Boolean

Check if a function exists in MySQL/MariaDB via information_schema.ROUTINES.

Parameters:

  • function_name (String)

    Function name to check

Returns:

  • (Boolean)

    Whether the function exists



36
37
38
39
40
41
42
43
44
# File 'lib/arfi/extensions/active_record/base.rb', line 36

def self.mysql_function_exists?(function_name)
  !connection.select_value(<<~SQL).nil?
    SELECT 1 FROM information_schema.ROUTINES
    WHERE ROUTINE_TYPE = 'FUNCTION'
      AND ROUTINE_SCHEMA = #{connection.quote(connection.current_database)}
      AND ROUTINE_NAME = #{connection.quote(function_name)}
    LIMIT 1;
  SQL
end

.pg_function_exists?(function_name) ⇒ Boolean

Check if a function exists in PostgreSQL via pg_proc catalog table.

Parameters:

  • function_name (String)

    Function name to check

Returns:

  • (Boolean)

    Whether the function exists



27
28
29
30
# File 'lib/arfi/extensions/active_record/base.rb', line 27

def self.pg_function_exists?(function_name)
  sql = "SELECT 1 FROM pg_proc WHERE proname = #{connection.quote(function_name)} LIMIT 1"
  !connection.select_value(sql).nil?
end