Module: BarkestCore::ConnectionAdapterExtensions

Defined in:
lib/barkest_core/extensions/active_record_extensions.rb

Overview

Adds some helper methods to connection adapters.

Instance Method Summary collapse

Instance Method Details

#exec_sp(stmt) ⇒ Object

Executes a stored procedure.

For MS SQL Server, this will return the return value from the procedure. For other providers, this is the same as execute.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/barkest_core/extensions/active_record_extensions.rb', line 37

def exec_sp(stmt)
  klass = self.class.name
  if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter'
    rex = /^exec(?:ute)?\s+[\["]?(?<PROC>[a-z][a-z0-9_]*)[\]"]?(?<ARGS>\s.*)?$/i
    match = rex.match(stmt)
    if match
      exec_query("DECLARE @RET INTEGER; EXECUTE @RET=[#{match['PROC']}]#{match['ARGS']}; SELECT @RET AS [RET]").first['RET']
    else
      execute stmt
    end
  else
    execute stmt
  end
end

#object_exists?(object_name) ⇒ Boolean

Searches the database to determine if an object with the specified name exists.

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/barkest_core/extensions/active_record_extensions.rb', line 11

def object_exists?(object_name)
  safe_name = "'#{object_name.gsub('\'','\'\'')}'"
  klass = self.class.name

  sql =
      if klass == 'ActiveRecord::ConnectionAdapters::SQLServerAdapter'
        # use sysobjects table.
        "SELECT COUNT(*) AS \"one\" FROM \"sysobjects\" WHERE \"name\"=#{safe_name}"
      elsif klass == 'ActiveRecord::ConnectionAdapters::SQLite3Adapter'
        # use sqlite_master table.
        "SELECT COUNT(*) AS \"one\" FROM \"sqlite_master\" WHERE (\"type\"='table' OR \"type\"='view') AND (\"name\"=#{safe_name})"
      else
        # query the information_schema TABLES and ROUTINES views.
        "SELECT SUM(Z.\"one\") AS \"one\" FROM (SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=#{safe_name} UNION SELECT COUNT(*) AS \"one\" FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME=#{safe_name}) AS Z"
      end

  result = exec_query(sql).first

  result && result['one'] >= 1
end