Sha256: fdfe435f092f88ace1510dd0fb5a584cdae0fcdd58a3fd2f305f25496c046fe0

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

module SQLite3
  class Database
    attr_accessor :logging

    def initialize(filename)
      @handle = Pointer.new(::Sqlite3.type)
      @logging = false

      result = sqlite3_open(filename, @handle)
      raise SQLite3Error, sqlite3_errmsg(@handle.value_with_autorelease) if result != SQLITE_OK
    end

    def execute(sql, params = nil, &block)
      raise ArgumentError if sql.nil?

      if @logging
        puts "   SQL: #{sql}"
        puts "Params: #{params}" if params && ! params.empty?
      end

      prepare(sql, params) do |statement|
        results = statement.execute

        if block_given?
          results.each do |result|
            yield result
          end
        else
          rows = []

          results.each do |result|
            rows << result
          end

          rows
        end
      end
    end

    def execute_scalar(*args)
      execute(*args).first.values.first
    end

    def transaction(&block)
      execute("BEGIN TRANSACTION")

      begin
        result = yield
      rescue
        execute("ROLLBACK TRANSACTION")
        raise
      end

      execute("COMMIT TRANSACTION")

      result
    end

    private

    def prepare(sql, params, &block)
      statement = Statement.new(@handle, sql, params)
      result = nil

      begin
        result = yield statement

      ensure
        statement.finalize
      end

      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
motion-sqlite3-2.0.0 lib/motion-sqlite3/database.rb