Sha256: 1953b9a2207efb5d06fc97c547396910081af027ff8b0fdd08810eac851bc5c7

Contents?: true

Size: 1.41 KB

Versions: 3

Compression:

Stored size: 1.41 KB

Contents

module SQLite3
  class Database
    def initialize(filename)
      @handle = Pointer.new(::Sqlite3.type)

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

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

      #puts "*** #{sql}"
      #puts "    #{params.inspect}" if params

      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_debug(*args, &block)
      puts "*** #{args[0]}"
      puts "    #{args[1].inspect}" if args[1]

      execute(*args, &block)
    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

3 entries across 3 versions & 1 rubygems

Version Path
motion-sqlite3-0.4.2 lib/motion-sqlite3/database.rb
motion-sqlite3-0.4.1 lib/motion-sqlite3/database.rb
motion-sqlite3-0.4.0 lib/motion-sqlite3/database.rb