sqlite3_adapter.rb 1.6 KB
Newer Older
1
require 'active_record/connection_adapters/sqlite_adapter'
2

A
Arun Agrawal 已提交
3
gem 'sqlite3', '~> 1.3.5'
4
require 'sqlite3'
5 6 7 8 9

module ActiveRecord
  class Base
    # sqlite3 adapter reuses sqlite_connection.
    def self.sqlite3_connection(config) # :nodoc:
10 11 12 13 14 15 16 17 18 19 20
      # 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
21

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

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

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

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

  module ConnectionAdapters #:nodoc:
    class SQLite3Adapter < SQLiteAdapter # :nodoc:
39 40 41 42 43 44 45 46
      def quote(value, column = nil)
        if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
          s = column.class.string_to_binary(value).unpack("H*")[0]
          "x'#{s}'"
        else
          super
        end
      end
47

48 49
      # Returns the current database encoding format as a string, eg: 'UTF-8'
      def encoding
50
        @connection.encoding.to_s
51 52
      end

53 54 55
    end
  end
end