sqlite3_adapter.rb 1.4 KB
Newer Older
1
require 'active_record/connection_adapters/sqlite_adapter'
2
require 'sqlite3'
3 4 5 6 7

module ActiveRecord
  class Base
    # sqlite3 adapter reuses sqlite_connection.
    def self.sqlite3_connection(config) # :nodoc:
8 9 10 11 12 13 14 15 16 17 18
      # Require database.
      unless config[:database]
        raise ArgumentError, "No database file specified. Missing argument: database"
      end

      # Allow database path relative to Rails.root, but only if
      # the database path is not the special path that tells
      # Sqlite to build a database only in memory.
      if defined?(Rails.root) && ':memory:' != config[:database]
        config[:database] = File.expand_path(config[:database], Rails.root)
      end
19

20 21 22 23
      unless 'sqlite3' == config[:adapter]
        raise ArgumentError, 'adapter name should be "sqlite3"'
      end

24 25
      db = SQLite3::Database.new(
        config[:database],
26
        :results_as_hash => true
27 28
      )

A
Aaron Patterson 已提交
29
      db.busy_timeout(config[:timeout]) if config[:timeout]
30

31
      ConnectionAdapters::SQLite3Adapter.new(db, logger, config)
32 33 34 35 36
    end
  end

  module ConnectionAdapters #:nodoc:
    class SQLite3Adapter < SQLiteAdapter # :nodoc:
37

38 39 40
      # Returns the current database encoding format as a string, eg: 'UTF-8'
      def encoding
        if @connection.respond_to?(:encoding)
41
          @connection.encoding.to_s
42
        else
43
          encoding = @connection.execute('PRAGMA encoding')
44 45 46 47
          encoding[0]['encoding']
        end
      end

48 49 50
    end
  end
end