Module: ActiveRecord::ConnectionHandling

Defined in:
lib/brick/extensions.rb

Overview

Get info on all relations during first database connection

Instance Method Summary collapse

Instance Method Details

#_brick_establish_connectionObject



1626
# File 'lib/brick/extensions.rb', line 1626

alias _brick_establish_connection establish_connection

#_brick_reflect_tablesObject

This is done separately so that during testing it can be called right after a migration in order to make sure everything is good.



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
# File 'lib/brick/extensions.rb', line 1661

def _brick_reflect_tables
  # return if ActiveRecord::Base.connection.current_database == 'postgres'

  initializer_loaded = false
  orig_schema = nil
  if (relations = ::Brick.relations).empty?
    # If there's schema things configured then we only expect our initializer to be named exactly this
    if File.exist?(brick_initializer = ::Rails.root.join('config/initializers/brick.rb'))
      initializer_loaded = load brick_initializer
    end
    # Load the initializer for the Apartment gem a little early so that if .excluded_models and
    # .default_schema are specified then we can work with non-tenanted models more appropriately
    if (apartment = Object.const_defined?('Apartment')) &&
       File.exist?(apartment_initializer = ::Rails.root.join('config/initializers/apartment.rb'))
      unless @_apartment_loaded
        load apartment_initializer
        @_apartment_loaded = true
      end
      apartment_excluded = Apartment.excluded_models
    end
    # Only for Postgres  (Doesn't work in sqlite3 or MySQL)
    # puts ActiveRecord::Base.execute_sql("SELECT current_setting('SEARCH_PATH')").to_a.inspect

    is_postgres = nil
    is_mssql = ActiveRecord::Base.connection.adapter_name == 'SQLServer'
    case ActiveRecord::Base.connection.adapter_name
    when 'PostgreSQL', 'SQLServer'
      is_postgres = !is_mssql
      db_schemas = if is_postgres
                     ActiveRecord::Base.execute_sql('SELECT nspname AS table_schema, MAX(oid) AS dt FROM pg_namespace GROUP BY 1 ORDER BY 1;')
                   else
                     ActiveRecord::Base.execute_sql('SELECT DISTINCT table_schema, NULL AS dt FROM INFORMATION_SCHEMA.tables;')
                   end
      ::Brick.db_schemas = db_schemas.each_with_object({}) do |row, s|
        row = case row
              when Array
                row
              else
                [row['table_schema'], row['dt']]
              end
        # Remove any system schemas
        s[row.first] = { dt: row.last } unless ['information_schema', 'pg_catalog', 'pg_toast', 'heroku_ext',
                                                'INFORMATION_SCHEMA', 'sys'].include?(row.first)
      end
      if (is_multitenant = (multitenancy = ::Brick.config.schema_behavior[:multitenant]) &&
         (sta = multitenancy[:schema_to_analyse]) != 'public') &&
         ::Brick.db_schemas.key?(sta)
        # Take note of the current schema so we can go back to it at the end of all this
        orig_schema = ActiveRecord::Base.execute_sql('SELECT current_schemas(true)').first['current_schemas'][1..-2].split(',')
        ::Brick.default_schema = schema = sta
        ActiveRecord::Base.execute_sql("SET SEARCH_PATH = ?", schema)
      end
    when 'Mysql2'
      ::Brick.default_schema = schema = ActiveRecord::Base.connection.current_database
    when 'OracleEnhanced'
      # ActiveRecord::Base.connection.current_database will be something like "XEPDB1"
      ::Brick.default_schema = schema = ActiveRecord::Base.connection.raw_connection.username
      ::Brick.db_schemas = {}
      ActiveRecord::Base.execute_sql("SELECT username FROM sys.all_users WHERE ORACLE_MAINTAINED != 'Y'").each { |s| ::Brick.db_schemas[s.first] = {} }
    when 'SQLite'
      sql = "SELECT m.name AS relation_name, UPPER(m.type) AS table_type,
        p.name AS column_name, p.type AS data_type,
        CASE p.pk WHEN 1 THEN 'PRIMARY KEY' END AS const
      FROM sqlite_master AS m
        INNER JOIN pragma_table_info(m.name) AS p
      WHERE m.name NOT IN ('sqlite_sequence', ?, ?)
      ORDER BY m.name, p.cid"
    else
      puts "Unfamiliar with connection adapter #{ActiveRecord::Base.connection.adapter_name}"
    end

    ::Brick.db_schemas ||= {}

    if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'
      if (possible_schema = ::Brick.config.schema_behavior&.[](:multitenant)&.[](:schema_to_analyse))
        if ::Brick.db_schemas.key?(possible_schema)
          ::Brick.default_schema = schema = possible_schema
          orig_schema = ActiveRecord::Base.execute_sql('SELECT current_schemas(true)').first['current_schemas'][1..-2].split(',')
          ActiveRecord::Base.execute_sql("SET SEARCH_PATH = ?", schema)
        elsif Rails.env == 'test' # When testing, just find the most recently-created schema
          ::Brick.default_schema = schema = ::Brick.db_schemas.to_a.sort { |a, b| b.last[:dt] <=> a.last[:dt] }.first.first
          puts "While running tests, had noticed in the brick.rb initializer that the line \"::Brick.schema_behavior = ...\" refers to a schema called \"#{possible_schema}\" which does not exist.  Reading table structure from the most recently-created schema, #{schema}."
          orig_schema = ActiveRecord::Base.execute_sql('SELECT current_schemas(true)').first['current_schemas'][1..-2].split(',')
          ActiveRecord::Base.execute_sql("SET SEARCH_PATH = ?", schema)
        else
          puts "*** In the brick.rb initializer the line \"::Brick.schema_behavior = ...\" refers to a schema called \"#{possible_schema}\".  This schema does not exist. ***"
        end
      end
    end

    # %%% Retrieve internal ActiveRecord table names like this:
    # ActiveRecord::Base.internal_metadata_table_name, ActiveRecord::Base.schema_migrations_table_name
    # For if it's not SQLite -- so this is the Postgres and MySQL version
    measures = []
    ::Brick.is_oracle = true if ActiveRecord::Base.connection.adapter_name == 'OracleEnhanced'
    case ActiveRecord::Base.connection.adapter_name
    when 'PostgreSQL', 'SQLite' # These bring back a hash for each row because the query uses column aliases
      # schema ||= 'public' if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'
      ActiveRecord::Base.retrieve_schema_and_tables(sql, is_postgres, is_mssql, schema).each do |r|
        # If Apartment gem lists the table as being associated with a non-tenanted model then use whatever it thinks
        # is the default schema, usually 'public'.
        schema_name = if ::Brick.config.schema_behavior[:multitenant]
                        Apartment.default_schema if apartment_excluded&.include?(r['relation_name'].singularize.camelize)
                      elsif ![schema, 'public'].include?(r['schema'])
                        r['schema']
                      end
        relation_name = schema_name ? "#{schema_name}.#{r['relation_name']}" : r['relation_name']
        # Both uppers and lowers as well as underscores?
        apply_double_underscore_patch if relation_name =~ /[A-Z]/ && relation_name =~ /[a-z]/ && relation_name.index('_')
        relation = relations[relation_name]
        relation[:isView] = true if r['table_type'] == 'VIEW'
        relation[:description] = r['table_description'] if r['table_description']
        col_name = r['column_name']
        key = case r['const']
              when 'PRIMARY KEY'
                relation[:pkey][r['key'] || relation_name] ||= []
              when 'UNIQUE'
                relation[:ukeys][r['key'] || "#{relation_name}.#{col_name}"] ||= []
                # key = (relation[:ukeys] = Hash.new { |h, k| h[k] = [] }) if key.is_a?(Array)
                # key[r['key']]
              end
        key << col_name if key
        cols = relation[:cols] # relation.fetch(:cols) { relation[:cols] = [] }
        cols[col_name] = [r['data_type'], r['max_length'], measures&.include?(col_name), r['is_nullable'] == 'NO']
        # puts "KEY! #{r['relation_name']}.#{col_name} #{r['key']} #{r['const']}" if r['key']
        relation[:col_descrips][col_name] = r['column_description'] if r['column_description']
      end
    else # MySQL2, OracleEnhanced, and MSSQL act a little differently, bringing back an array for each row
      schema_and_tables = case ActiveRecord::Base.connection.adapter_name
                          when 'OracleEnhanced'
                            sql =
"SELECT c.owner AS schema, c.table_name AS relation_name,
CASE WHEN v.owner IS NULL THEN 'BASE_TABLE' ELSE 'VIEW' END AS table_type,
c.column_name, c.data_type,
COALESCE(c.data_length, c.data_precision) AS max_length,
CASE ac.constraint_type WHEN 'P' THEN 'PRIMARY KEY' END AS const,
ac.constraint_name AS \"key\",
CASE c.nullable WHEN 'Y' THEN 'YES' ELSE 'NO' END AS is_nullable
FROM all_tab_cols c
LEFT OUTER JOIN all_cons_columns acc ON acc.owner = c.owner AND acc.table_name = c.table_name AND acc.column_name = c.column_name
LEFT OUTER JOIN all_constraints ac ON ac.owner = acc.owner AND ac.table_name = acc.table_name AND ac.constraint_name = acc.constraint_name AND constraint_type = 'P'
LEFT OUTER JOIN all_views v ON c.owner = v.owner AND c.table_name = v.view_name
WHERE c.owner IN (#{::Brick.db_schemas.keys.map { |s| "'#{s}'" }.join(', ')})
AND c.table_name NOT IN (?, ?)
ORDER BY 1, 2, c.internal_column_id, acc.position"
                            ActiveRecord::Base.execute_sql(sql, *ar_tables)
                          else
                            ActiveRecord::Base.retrieve_schema_and_tables(sql)
                          end

      schema_and_tables.each do |r|
        next if r[1].index('$') # Oracle can have goofy table names with $

        if (relation_name = r[1]) =~ /^[A-Z0-9_]+$/
          relation_name.downcase!
        # Both uppers and lowers as well as underscores?
        elsif relation_name =~ /[A-Z]/ && relation_name =~ /[a-z]/ && relation_name.index('_')
          apply_double_underscore_patch
        end
        # Expect the default schema for SQL Server to be 'dbo'.
        if (::Brick.is_oracle && r[0] != schema) || (is_mssql && r[0] != 'dbo')
          relation_name = "#{r[0]}.#{relation_name}"
        end

        relation = relations[relation_name] # here relation represents a table or view from the database
        relation[:isView] = true if r[2] == 'VIEW' # table_type
        col_name = ::Brick.is_oracle ? connection.send(:oracle_downcase, r[3]) : r[3]
        key = case r[6] # constraint type
              when 'PRIMARY KEY'
                # key
                relation[:pkey][r[7] || relation_name] ||= []
              when 'UNIQUE'
                relation[:ukeys][r[7] || "#{relation_name}.#{col_name}"] ||= []
                # key = (relation[:ukeys] = Hash.new { |h, k| h[k] = [] }) if key.is_a?(Array)
                # key[r['key']]
              end
        key << col_name if key
        cols = relation[:cols] # relation.fetch(:cols) { relation[:cols] = [] }
        # 'data_type', 'max_length', measure, 'is_nullable'
        cols[col_name] = [r[4], r[5], measures&.include?(col_name), r[8] == 'NO']
        # puts "KEY! #{r['relation_name']}.#{col_name} #{r['key']} #{r['const']}" if r['key']
      end
    end

    # # Add unique OIDs
    # if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'
    #   ActiveRecord::Base.execute_sql(
    #     "SELECT c.oid, n.nspname, c.relname
    #     FROM pg_catalog.pg_namespace AS n
    #       INNER JOIN pg_catalog.pg_class AS c ON n.oid = c.relnamespace
    #     WHERE c.relkind IN ('r', 'v')"
    #   ).each do |r|
    #     next if ['pg_catalog', 'information_schema', ''].include?(r['nspname']) ||
    #       ['ar_internal_metadata', 'schema_migrations'].include?(r['relname'])
    #     relation = relations.fetch(r['relname'], nil)
    #     if relation
    #       (relation[:oid] ||= {})[r['nspname']] = r['oid']
    #     else
    #       puts "Where is #{r['nspname']} #{r['relname']} ?"
    #     end
    #   end
    # end
    # schema = ::Brick.default_schema # Reset back for this next round of fun
    case ActiveRecord::Base.connection.adapter_name
    when 'PostgreSQL', 'Mysql2', 'SQLServer'
      sql = "SELECT kcu1.CONSTRAINT_SCHEMA, kcu1.TABLE_NAME, kcu1.COLUMN_NAME,
          kcu2.CONSTRAINT_SCHEMA AS primary_schema, kcu2.TABLE_NAME AS primary_table, kcu1.CONSTRAINT_NAME AS CONSTRAINT_SCHEMA_FK
        FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc
          INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu1
            ON kcu1.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG
            AND kcu1.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
            AND kcu1.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
          INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu2
            ON kcu2.CONSTRAINT_CATALOG = rc.UNIQUE_CONSTRAINT_CATALOG
            AND kcu2.CONSTRAINT_SCHEMA = rc.UNIQUE_CONSTRAINT_SCHEMA
            AND kcu2.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME#{"
            AND kcu2.TABLE_NAME = kcu1.REFERENCED_TABLE_NAME
            AND kcu2.COLUMN_NAME = kcu1.REFERENCED_COLUMN_NAME" unless is_postgres || is_mssql }
            AND kcu2.ORDINAL_POSITION = kcu1.ORDINAL_POSITION#{"
        WHERE kcu1.CONSTRAINT_SCHEMA = COALESCE(current_setting('SEARCH_PATH'), 'public')" if is_postgres && schema }"
        # AND kcu2.TABLE_NAME = ?;", Apartment::Tenant.current, table_name
      fk_references = ActiveRecord::Base.execute_sql(sql)
    when 'SQLite'
      sql = "SELECT m.name, fkl.\"from\", fkl.\"table\", m.name || '_' || fkl.\"from\" AS constraint_name
      FROM sqlite_master m
        INNER JOIN pragma_foreign_key_list(m.name) fkl ON m.type = 'table'
      ORDER BY m.name, fkl.seq"
      fk_references = ActiveRecord::Base.execute_sql(sql)
    when 'OracleEnhanced'
      schemas = ::Brick.db_schemas.keys.map { |s| "'#{s}'" }.join(', ')
      sql =
      "SELECT -- fk
             ac.owner AS constraint_schema, acc_fk.table_name, acc_fk.column_name,
             -- referenced pk
             ac.r_owner AS primary_schema, acc_pk.table_name AS primary_table, acc_fk.constraint_name AS constraint_schema_fk
             -- , acc_pk.column_name
      FROM all_cons_columns acc_fk
        INNER JOIN all_constraints ac ON acc_fk.owner = ac.owner
          AND acc_fk.constraint_name = ac.constraint_name
        INNER JOIN all_cons_columns acc_pk ON ac.r_owner = acc_pk.owner
          AND ac.r_constraint_name = acc_pk.constraint_name
      WHERE ac.constraint_type = 'R'
        AND ac.owner IN (#{schemas})
        AND ac.r_owner IN (#{schemas})"
      fk_references = ActiveRecord::Base.execute_sql(sql)
    end
    ::Brick.is_oracle = true if ActiveRecord::Base.connection.adapter_name == 'OracleEnhanced'
    # ::Brick.default_schema ||= schema ||= 'public' if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'
    fk_references&.each do |fk|
      fk = fk.values unless fk.is_a?(Array)
      # Multitenancy makes things a little more general overall, except for non-tenanted tables
      if apartment_excluded&.include?(::Brick.namify(fk[1]).singularize.camelize)
        fk[0] = Apartment.default_schema
      elsif (is_postgres && (fk[0] == 'public' || (is_multitenant && fk[0] == schema))) ||
            (::Brick.is_oracle && fk[0] == schema) ||
            (is_mssql && fk[0] == 'dbo') ||
            (!is_postgres && !::Brick.is_oracle && !is_mssql && ['mysql', 'performance_schema', 'sys'].exclude?(fk[0]))
        fk[0] = nil
      end
      if apartment_excluded&.include?(fk[4].singularize.camelize)
        fk[3] = Apartment.default_schema
      elsif (is_postgres && (fk[3] == 'public' || (is_multitenant && fk[3] == schema))) ||
            (::Brick.is_oracle && fk[3] == schema) ||
            (is_mssql && fk[3] == 'dbo') ||
            (!is_postgres && !::Brick.is_oracle && !is_mssql && ['mysql', 'performance_schema', 'sys'].exclude?(fk[3]))
        fk[3] = nil
      end
      if ::Brick.is_oracle
        fk[1].downcase! if fk[1] =~ /^[A-Z0-9_]+$/
        fk[4].downcase! if fk[4] =~ /^[A-Z0-9_]+$/
        fk[2] = connection.send(:oracle_downcase, fk[2])
      end
      ::Brick._add_bt_and_hm(fk, relations)
    end
  end

  relations.each do |k, v|
    rel_name = k.split('.').map { |rel_part| ::Brick.namify(rel_part, :underscore) }
    schema_names = rel_name[0..-2]
    schema_names.shift if ::Brick.apartment_multitenant && schema_names.first == Apartment.default_schema
    v[:schema] = schema_names.join('.') unless schema_names.empty?
    # %%% If more than one schema has the same table name, will need to add a schema name prefix to have uniqueness
    v[:resource] = rel_name.last
    if (singular = rel_name.last.singularize).blank?
      singular = rel_name.last
    end
    v[:class_name] = (schema_names + [singular]).map(&:camelize).join('::')
  end
  ::Brick.load_additional_references if initializer_loaded

  if orig_schema && (orig_schema = (orig_schema - ['pg_catalog', 'heroku_ext']).first)
    puts "Now switching back to \"#{orig_schema}\" schema."
    ActiveRecord::Base.execute_sql("SET SEARCH_PATH = ?", orig_schema)
  end
end

#apply_double_underscore_patchObject



2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
# File 'lib/brick/extensions.rb', line 2010

def apply_double_underscore_patch
  unless @double_underscore_applied
    # Same as normal #camelize and #underscore, just that double-underscores turn into a single underscore
    ActiveSupport::Inflector.class_eval do
      def camelize(term, uppercase_first_letter = true)
        strings = term.to_s.split('__').map do |string|
          # String#camelize takes a symbol (:upper or :lower), so here we also support :lower to keep the methods consistent.
          if !uppercase_first_letter || uppercase_first_letter == :lower
            string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase! || match }
          else
            string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize! || match }
          end
          string.gsub!(/(?:_|(\/))([a-z\d]*)/i) do
            word = $2
            substituted = inflections.acronyms[word] || word.capitalize! || word
            $1 ? "::#{substituted}" : substituted
          end
          string
        end
        strings.join('_')
      end

      def underscore(camel_cased_word)
        return camel_cased_word.to_s unless /[A-Z-]|::/.match?(camel_cased_word)
        camel_cased_word.to_s.gsub("::", "/").split('_').map do |word|
          word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
          word.gsub!(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) { ($1 || $2) << "_" }
          word.tr!("-", "_")
          word.downcase!
          word
        end.join('__')
      end
    end
    @double_underscore_applied = true
  end
end

#ar_tablesObject



2000
2001
2002
2003
2004
2005
2006
2007
2008
# File 'lib/brick/extensions.rb', line 2000

def ar_tables
  ar_smtn = if ActiveRecord::Base.respond_to?(:schema_migrations_table_name)
              ActiveRecord::Base.schema_migrations_table_name
            else
              'schema_migrations'
            end
  ar_imtn = ActiveRecord.version >= ::Gem::Version.new('5.0') ? ActiveRecord::Base. : ''
  [ar_smtn, ar_imtn]
end

#establish_connection(*args) ⇒ Object



1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
# File 'lib/brick/extensions.rb', line 1627

def establish_connection(*args)
  conn = _brick_establish_connection(*args)
  begin
    # Overwrite SQLite's #begin_db_transaction so it opens in IMMEDIATE mode instead of
    # the default DEFERRED mode.
    #   https://discuss.rubyonrails.org/t/failed-write-transaction-upgrades-in-sqlite3/81480/2
    if ActiveRecord::Base.connection.adapter_name == 'SQLite'
      arca = ::ActiveRecord::ConnectionAdapters
      db_statements = arca::SQLite3::DatabaseStatements
      # Rails 7.1 and later
      if arca::AbstractAdapter.private_instance_methods.include?(:with_raw_connection)
        db_statements.define_method(:begin_db_transaction) do
          log("begin immediate transaction", "TRANSACTION") do
            with_raw_connection(allow_retry: true, uses_transaction: false) do |conn|
              conn.transaction(:immediate)
            end
          end
        end
      else # Rails < 7.1
        db_statements.define_method(:begin_db_transaction) do
          log('begin immediate transaction', 'TRANSACTION') { @connection.transaction(:immediate) }
        end
      end
    end
    # ::Brick.is_db_present = true
    _brick_reflect_tables
  rescue ActiveRecord::NoDatabaseError
    # ::Brick.is_db_present = false
  end
  conn
end

#retrieve_schema_and_tables(sql = nil, is_postgres = nil, is_mssql = nil, schema = nil) ⇒ Object



1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
# File 'lib/brick/extensions.rb', line 1957

def retrieve_schema_and_tables(sql = nil, is_postgres = nil, is_mssql = nil, schema = nil)
  is_mssql = ActiveRecord::Base.connection.adapter_name == 'SQLServer' if is_mssql.nil?
  sql ||= "SELECT t.table_schema AS \"schema\", t.table_name AS relation_name, t.table_type,#{"
    pg_catalog.obj_description(
      ('\"' || t.table_schema || '\".\"' || t.table_name || '\"')::regclass::oid, 'pg_class'
    ) AS table_description,
    pg_catalog.col_description(
      ('\"' || t.table_schema || '\".\"' || t.table_name || '\"')::regclass::oid, c.ordinal_position
    ) AS column_description," if is_postgres}
    c.column_name, c.data_type,
    COALESCE(c.character_maximum_length, c.numeric_precision) AS max_length,
    kcu.constraint_type AS const, kcu.constraint_name AS \"key\",
    c.is_nullable
  FROM INFORMATION_SCHEMA.tables AS t
    LEFT OUTER JOIN INFORMATION_SCHEMA.columns AS c ON t.table_schema = c.table_schema
      AND t.table_name = c.table_name
      LEFT OUTER JOIN
      (SELECT kcu1.constraint_schema, kcu1.table_name, kcu1.column_name, kcu1.ordinal_position,
      tc.constraint_type, kcu1.constraint_name
      FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu1
      INNER JOIN INFORMATION_SCHEMA.table_constraints AS tc
        ON kcu1.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
        AND kcu1.TABLE_NAME = tc.TABLE_NAME
        AND kcu1.CONSTRAINT_NAME = tc.constraint_name
        AND tc.constraint_type != 'FOREIGN KEY' -- For MSSQL
      ) AS kcu ON
      -- kcu.CONSTRAINT_CATALOG = t.table_catalog AND
      kcu.CONSTRAINT_SCHEMA = c.table_schema
      AND kcu.TABLE_NAME = c.table_name
      AND kcu.column_name = c.column_name#{"
  --    AND kcu.position_in_unique_constraint IS NULL" unless is_mssql}
  WHERE t.table_schema #{is_postgres || is_mssql ?
      "NOT IN ('information_schema', 'pg_catalog',
               'INFORMATION_SCHEMA', 'sys')"
      :
      "= '#{ActiveRecord::Base.connection.current_database.tr("'", "''")}'"}#{"
    AND t.table_schema = COALESCE(current_setting('SEARCH_PATH'), 'public')" if is_postgres && schema }
--          AND t.table_type IN ('VIEW') -- 'BASE TABLE', 'FOREIGN TABLE'
    AND t.table_name NOT IN ('pg_stat_statements', ?, ?)
  ORDER BY 1, t.table_type DESC, 2, kcu.ordinal_position"
  ActiveRecord::Base.execute_sql(sql, *ar_tables)
end