postgresql_adapter.rb 13.2 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3 4 5 6 7
require 'active_record/connection_adapters/abstract_adapter'

module ActiveRecord
  class Base
    # Establishes a connection to the database that's used by all Active Record objects
    def self.postgresql_connection(config) # :nodoc:
      require_library_or_gem 'postgres' unless self.class.const_defined?(:PGconn)
8 9

      config = config.symbolize_keys
D
Initial  
David Heinemeier Hansson 已提交
10 11 12 13 14
      host     = config[:host]
      port     = config[:port]     || 5432 unless host.nil?
      username = config[:username].to_s
      password = config[:password].to_s

15 16
      encoding = config[:encoding]
      min_messages = config[:min_messages]
17

D
Initial  
David Heinemeier Hansson 已提交
18 19 20 21 22 23
      if config.has_key?(:database)
        database = config[:database]
      else
        raise ArgumentError, "No database specified. Missing argument: database."
      end

24
      pga = ConnectionAdapters::PostgreSQLAdapter.new(
D
Initial  
David Heinemeier Hansson 已提交
25 26
        PGconn.connect(host, port, "", "", database, username, password), logger
      )
27

28
      pga.schema_search_path = config[:schema_search_path] || config[:schema_order]
29 30
      pga.execute("SET client_encoding TO '#{encoding}'") if encoding
      pga.execute("SET client_min_messages TO '#{min_messages}'") if min_messages
31 32

      pga
D
Initial  
David Heinemeier Hansson 已提交
33 34 35 36
    end
  end

  module ConnectionAdapters
37 38 39 40 41 42 43 44 45 46
    # The PostgreSQL adapter works both with the C-based (http://www.postgresql.jp/interfaces/ruby/) and the Ruby-base
    # (available both as gem and from http://rubyforge.org/frs/?group_id=234&release_id=1145) drivers.
    #
    # Options:
    #
    # * <tt>:host</tt> -- Defaults to localhost
    # * <tt>:port</tt> -- Defaults to 5432
    # * <tt>:username</tt> -- Defaults to nothing
    # * <tt>:password</tt> -- Defaults to nothing
    # * <tt>:database</tt> -- The name of the database. No default, must be provided.
47
    # * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names.  This is backward-compatible with the :schema_order option.
48 49
    # * <tt>:encoding</tt> -- An optional client encoding that is using in a SET client_encoding TO <encoding> call on connection.
    # * <tt>:min_messages</tt> -- An optional client min messages that is using in a SET client_min_messages TO <min_messages> call on connection.
50
    class PostgreSQLAdapter < AbstractAdapter
51 52 53 54
      def adapter_name
        'PostgreSQL'
      end

55 56 57 58 59 60 61 62 63 64 65 66
      def native_database_types
        {
          :primary_key => "serial primary key",
          :string      => { :name => "character varying", :limit => 255 },
          :text        => { :name => "text" },
          :integer     => { :name => "integer" },
          :float       => { :name => "float" },
          :datetime    => { :name => "timestamp" },
          :timestamp   => { :name => "timestamp" },
          :time        => { :name => "timestamp" },
          :date        => { :name => "date" },
          :binary      => { :name => "bytea" },
67
          :boolean     => { :name => "boolean" }
68 69 70 71 72 73 74
        }
      end
      
      def supports_migrations?
        true
      end      
      
75 76 77 78

      # QUOTING ==================================================

      def quote(value, column = nil)
79
        if value.kind_of?(String) && column && column.type == :binary
80
          "'#{escape_bytea(value)}'"
81 82 83 84 85 86 87 88 89 90 91 92 93
        else
          super
        end
      end

      def quote_column_name(name)
        %("#{name}")
      end


      # DATABASE STATEMENTS ======================================

      def select_all(sql, name = nil) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
94 95 96
        select(sql, name)
      end

97
      def select_one(sql, name = nil) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
98
        result = select(sql, name)
99
        result.first if result
D
Initial  
David Heinemeier Hansson 已提交
100 101
      end

102 103 104
      def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
        execute(sql, name)
        table = sql.split(" ", 4)[2]
105
        id_value || last_insert_id(table, pk)
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
      end

      def query(sql, name = nil) #:nodoc:
        log(sql, name) { @connection.query(sql) }
      end

      def execute(sql, name = nil) #:nodoc:
        log(sql, name) { @connection.exec(sql) }
      end

      def update(sql, name = nil) #:nodoc:
        execute(sql, name).cmdtuples
      end

      alias_method :delete, :update #:nodoc:


      def begin_db_transaction #:nodoc:
        execute "BEGIN"
      end

      def commit_db_transaction #:nodoc:
        execute "COMMIT"
      end
      
      def rollback_db_transaction #:nodoc:
        execute "ROLLBACK"
      end


      # SCHEMA STATEMENTS ========================================

138
      # Return the list of all tables in the schema search path.
139
      def tables(name = nil) #:nodoc:
140 141 142 143 144 145 146 147
        schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
        query(<<-SQL, name).map { |row| row[0] }
          SELECT tablename
            FROM pg_tables
           WHERE schemaname IN (#{schemas})
        SQL
      end

148
      def indexes(table_name, name = nil) #:nodoc:
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        result = query(<<-SQL, name)
          SELECT i.relname, d.indisunique, a.attname
            FROM pg_class t, pg_class i, pg_index d, pg_attribute a
           WHERE i.relkind = 'i'
             AND d.indexrelid = i.oid
             AND d.indisprimary = 'f'
             AND t.oid = d.indrelid
             AND t.relname = '#{table_name}'
             AND a.attrelid = t.oid
             AND ( d.indkey[0]=a.attnum OR d.indkey[1]=a.attnum
                OR d.indkey[2]=a.attnum OR d.indkey[3]=a.attnum
                OR d.indkey[4]=a.attnum OR d.indkey[5]=a.attnum
                OR d.indkey[6]=a.attnum OR d.indkey[7]=a.attnum
                OR d.indkey[8]=a.attnum OR d.indkey[9]=a.attnum )
          ORDER BY i.relname
        SQL

        current_index = nil
        indexes = []

        result.each do |row|
          if current_index != row[0]
            indexes << IndexDefinition.new(table_name, row[0], row[1] == "t", [])
            current_index = row[0]
          end

          indexes.last.columns << row[2]
        end

        indexes
      end

181
      def columns(table_name, name = nil) #:nodoc:
182 183 184
        column_definitions(table_name).collect do |name, type, default, notnull|
          Column.new(name, default_value(default), translate_field_type(type),
            notnull == "f")
D
Initial  
David Heinemeier Hansson 已提交
185 186 187
        end
      end

188 189 190 191 192 193 194 195
      # Set the schema search path to a string of comma-separated schema names.
      # Names beginning with $ are quoted (e.g. $user => '$user')
      # See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html
      def schema_search_path=(schema_csv) #:nodoc:
        if schema_csv
          execute "SET search_path TO #{schema_csv}"
          @schema_search_path = nil
        end
D
Initial  
David Heinemeier Hansson 已提交
196 197
      end

198 199
      def schema_search_path #:nodoc:
        @schema_search_path ||= query('SHOW search_path')[0][0]
200
      end
201 202 203 204
      
      def rename_table(name, new_name)
        execute "ALTER TABLE #{name} RENAME TO #{new_name}"
      end
205
            
S
Scott Barron 已提交
206 207 208 209 210 211 212 213 214 215 216
      def add_column(table_name, column_name, type, options = {})
        native_type = native_database_types[type]
        sql_commands = ["ALTER TABLE #{table_name} ADD #{column_name} #{type_to_sql(type, options[:limit])}"]
        if options[:default]
          sql_commands << "ALTER TABLE #{table_name} ALTER #{column_name} SET DEFAULT '#{options[:default]}'"
        end
        if options[:null] == false
          sql_commands << "ALTER TABLE #{table_name} ALTER #{column_name} SET NOT NULL"
        end
        sql_commands.each { |cmd| execute(cmd) }
      end
D
Initial  
David Heinemeier Hansson 已提交
217

218
      def change_column(table_name, column_name, type, options = {}) #:nodoc:
219 220
        execute = "ALTER TABLE #{table_name} ALTER  #{column_name} TYPE #{type}"
        change_column_default(table_name, column_name, options[:default]) unless options[:default].nil?
221
      end      
222

223
      def change_column_default(table_name, column_name, default) #:nodoc:
224 225
        execute "ALTER TABLE #{table_name} ALTER COLUMN #{column_name} SET DEFAULT '#{default}'"
      end
226
      
227
      def rename_column(table_name, column_name, new_column_name) #:nodoc:
228 229
        execute "ALTER TABLE #{table_name} RENAME COLUMN #{column_name} TO #{new_column_name}"
      end
230

231
      def remove_index(table_name, options) #:nodoc:
232 233 234 235 236 237 238
        if Hash === options
          index_name = options[:name]
        else
          index_name = "#{table_name}_#{options}_index"
        end

        execute "DROP INDEX #{index_name}"
239
      end      
240

241
      
D
Initial  
David Heinemeier Hansson 已提交
242
      private
243 244
        BYTEA_COLUMN_TYPE_OID = 17

245
        def last_insert_id(table, column = nil)
D
Initial  
David Heinemeier Hansson 已提交
246 247 248 249 250
          sequence_name = "#{table}_#{column || 'id'}_seq"
          @connection.exec("SELECT currval('#{sequence_name}')")[0][0].to_i
        end

        def select(sql, name = nil)
251
          res = execute(sql, name)
D
Initial  
David Heinemeier Hansson 已提交
252 253 254 255 256 257
          results = res.result           
          rows = []
          if results.length > 0
            fields = res.fields
            results.each do |row|
              hashed_row = {}
258 259
              row.each_index do |cel_index|
                column = row[cel_index]
260
                if res.type(cel_index) == BYTEA_COLUMN_TYPE_OID
261 262 263 264
                  column = unescape_bytea(column)
                end
                hashed_row[fields[cel_index]] = column
              end
D
Initial  
David Heinemeier Hansson 已提交
265 266 267 268 269 270
              rows << hashed_row
            end
          end
          return rows
        end

271
        def escape_bytea(s)
272 273 274 275 276 277 278 279 280 281 282 283 284 285
          if PGconn.respond_to? :escape_bytea
            self.class.send(:define_method, :escape_bytea) do |s|
              PGconn.escape_bytea(s) if s
            end
          else
            self.class.send(:define_method, :escape_bytea) do |s|
              if s
                result = ''
                s.each_byte { |c| result << sprintf('\\\\%03o', c) }
                result
              end
            end
          end
          escape_bytea(s)
286 287 288
        end

        def unescape_bytea(s)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
          if PGconn.respond_to? :unescape_bytea
            self.class.send(:define_method, :unescape_bytea) do |s|
              PGconn.unescape_bytea(s) if s
            end
          else
            self.class.send(:define_method, :unescape_bytea) do |s|
              if s
                result = ''
                i, max = 0, s.size
                while i < max
                  char = s[i]
                  if char == ?\\
                    if s[i+1] == ?\\
                      char = ?\\
                      i += 1
                    else
                      char = s[i+1..i+3].oct
                      i += 3
                    end
                  end
                  result << char
                  i += 1
                end
                result
              end
            end
          end
          unescape_bytea(s)
317
        end
318
        
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        # Query a table's column names, default values, and types.
        #
        # The underlying query is roughly:
        #  SELECT column.name, column.type, default.value
        #    FROM column LEFT JOIN default
        #      ON column.table_id = default.table_id
        #     AND column.num = default.column_num
        #   WHERE column.table_id = get_table_id('table_name')
        #     AND column.num > 0
        #     AND NOT column.is_dropped
        #   ORDER BY column.num
        #
        # If the table name is not prefixed with a schema, the database will
        # take the first match from the schema search path.
        #
        # Query implementation notes:
        #  - format_type includes the column size constraint, e.g. varchar(50)
        #  - ::regclass is a function that gives the id for a table name
        def column_definitions(table_name)
          query <<-end_sql
339
            SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
340 341 342 343 344 345
              FROM pg_attribute a LEFT JOIN pg_attrdef d
                ON a.attrelid = d.adrelid AND a.attnum = d.adnum
             WHERE a.attrelid = '#{table_name}'::regclass
               AND a.attnum > 0 AND NOT a.attisdropped
             ORDER BY a.attnum
          end_sql
D
Initial  
David Heinemeier Hansson 已提交
346 347
        end

348 349 350 351 352 353 354 355 356
        # Translate PostgreSQL-specific types into simplified SQL types.
        # These are special cases; standard types are handled by
        # ConnectionAdapters::Column#simplified_type.
        def translate_field_type(field_type)
          # Match the beginning of field_type since it may have a size constraint on the end.
          case field_type
            when /^timestamp/i    then 'datetime'
            when /^real|^money/i  then 'float'
            when /^interval/i     then 'string'
357 358
            # geometric types (the line type is currently not implemented in postgresql)
            when /^point|lseg|box|path|polygon|circle/i  then 'string' 
359 360
            when /^bytea/i        then 'binary'
            else field_type       # Pass through standard types.
D
Initial  
David Heinemeier Hansson 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
          end
        end

        def default_value(value)
          # Boolean types
          return "t" if value =~ /true/i
          return "f" if value =~ /false/i
          
          # Char/String type values
          return $1 if value =~ /^'(.*)'::(bpchar|text|character varying)$/
          
          # Numeric values
          return value if value =~ /^[0-9]+(\.[0-9]*)?/

          # Date / Time magic values
376
          return Time.now.to_s if value =~ /^now\(\)|^\('now'::text\)::(date|timestamp)/i
D
Initial  
David Heinemeier Hansson 已提交
377 378 379 380 381 382 383 384 385 386 387

          # Fixed dates / times
          return $1 if value =~ /^'(.+)'::(date|timestamp)/
          
          # Anything else is blank, some user type, or some function
          # and we can't know the value of that, so return nil.
          return nil
        end
    end
  end
end