Skip to content

Instantly share code, notes, and snippets.

@wconrad
Created February 23, 2016 13:03
Show Gist options
  • Save wconrad/cf2d1fd5782d926313b4 to your computer and use it in GitHub Desktop.
Save wconrad/cf2d1fd5782d926313b4 to your computer and use it in GitHub Desktop.
Example of a monkey patch
# frozen_string_literal: true
require "activerecord-sqlserver-adapter"
# Monkey-patch the SqlServer/ActiveRecord adapter to set
# certain connection options.
#
# --- SET ARITHABORT ON
#
# SqlServer, when a tcp/ip connection is made, sets some default
# options for that connection. One of those options is `SET
# ARITHABORT OFF`. This option has two known effects:
#
# * Performance for certain queries done via TCP/IP becomes very bad.
#
# * The query plan for queries made via TCP/IP differs from queries
# made in Management Studio.
#
# Here is one such query. This query takes a long time (more than a
# minute) when there is a great deal of data in these tables _and_
# `SET ARITHABORT OFF` is in effect:
#
# EXEC sp_executesql N'SELECT COUNT(*) FROM [MigrationSource]
# left outer join MigrationDest on MigrationSource.Id = MigrationSourceId
# WHERE [MigrationSource].[FranchiseNickname] = @0
# AND [MigrationSource].[Table] = @1
# AND [MigrationSource].[Migrate] = @2
# AND [MigrationDest].[MigrationSourceId] IS NULL',
# N'@0 nvarchar(64), @1 nvarchar(64), @2 bit',
# @0 = N'hs', @1 = N'tbl_smartpanel_vendor', @2 = 1"
#
# Turning the ARITHABORT option ON causes the query to succeed
# quickly, exactly as it does in management studio, so monkey-patch
# the SqlServer/ActiveRecord adapter accordingly.
#
# See also:
#
# * https://msdn.microsoft.com/en-us/library/ms190306.aspx
# * http://dba.stackexchange.com/q/9840/42317
# * http://www.sommarskog.se/query-plan-mysteries.html
class ActiveRecord::ConnectionAdapters::SQLServerAdapter
orig_configure_connection = instance_method(:configure_connection)
define_method(:configure_connection) do
orig_configure_connection.bind(self).call
@connection.execute('SET ARITHABORT ON').do
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment