Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Truncated varchars in Stored Procedures #496

Open
mrcook opened this issue Jul 18, 2016 · 1 comment
Open

Truncated varchars in Stored Procedures #496

mrcook opened this issue Jul 18, 2016 · 1 comment
Labels

Comments

@mrcook
Copy link

mrcook commented Jul 18, 2016

SQL statements are generated using stored procedures, but SQL Server will truncate varchar values to the limit as given in the column. As an example, I create a migration like so:

create_table :users do |t|
  t.string :code, unique: true, limit: 5
end

And then then create a new record giving code the value ABCDE.

A typical SQL query generated by the gem would be:

EXEC sp_executesql N'SELECT  [users].* FROM [users] WHERE [users].[code] = @0  ORDER BY [users].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY', N'@0 nvarchar(5)', @0 = N'ABCDEFGH'

If I execute this directly on MSSQL the value ABCDEFGH would be truncated down to ABCDE because of the nvarchar(5) casting, and so we get the record back. This happens while fetching records as well as inserting, and likely other actions too. ActiveRecord validations will not catch these behaviours.

Here's an SO post with some more details on this known MSSQL behaviour: http://stackoverflow.com/questions/4628140/sql-server-silently-truncates-varchars-in-stored-procedures

A proposed solution is to use nvarchar(max), even though there would be a small performance hit.

If I hack the gem to make this change (.sub(/nvarchar\(\d+\)/, 'nvarchar(max)')) then an insert will no longer truncate (desired behaviour), a .where would fail to return the record (as expected), and ActiveRecord validations on length would kick in.

@metaskills
Copy link
Contributor

Thanks. I'll take a look at this once (perf too) once I get the Rails v5 work done.

@wpolicarpo wpolicarpo added the bug label May 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants