Skip to content

Add documentation for database transaction handling with Sequel #242

@bethesque

Description

@bethesque

I'm currently using Rack/Webmachine/Sequel together. Sequel will only allow you to create transactions with a block - there is no API to start and end a transaction manually. This doesn't play nicely with the way a Webmachine resource is "executed" via multiple separate methods, so the best way I've found to handle database transactions is to create some rack middleware that wraps around the entire call to Webmachine. I'd like to add an example of this to the documentation, but I thought I'd just check to see if anyone had a better/another way before I do this.

@seancribbs @lgierth @Asmod4n

module Rack
  module Middleware
    class DatabaseTransaction

      REQUEST_METHOD = "REQUEST_METHOD".freeze
      GET = "GET".freeze
      HEAD = "HEAD".freeze

      def initialize app, database_connection
        @app = app
        @database_connection = database_connection
      end

      def call env
        if env[REQUEST_METHOD] != GET && env[REQUEST_METHOD] != HEAD
          call_with_transaction env
        else
          call_without_transaction env
        end
      end

      def call_without_transaction env
        @app.call(env)
      end

      def call_with_transaction env
        response = nil
        @database_connection.transaction do
          response = @app.call(env)
          raise Sequel::Rollback if response.first == 500
        end
        response
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions