Skip to content

Fix table name parsing for INSERT INTO <table> WITH (<hints>) - #1424

Merged
aidanharan merged 2 commits into
rails-sqlserver:mainfrom
justindell:fix-insert-table-hint-parsing
Oct 26, 2026
Merged

aidanharan merged 2 commits into
rails-sqlserver:mainfrom
justindell:fix-insert-table-hint-parsing

Conversation

@justindell

Copy link
Copy Markdown
Contributor

Any INSERT with a table hint between the table name and the column list fails before it reaches the server:

connection.execute("INSERT INTO books WITH (TABLOCK) (title) SELECT title FROM old_books")
# => ActiveRecord::StatementInvalid: Table 'books WITH' doesn't exist

get_raw_table_name takes everything up to the first (, so the parsed name is books WITH. query_requires_identity_insert? runs on every insert and looks that name up, which raises. WITH (TABLOCK) is the documented way to get a minimally logged INSERT ... SELECT, so right now the only workaround is to go around Active Record.

I fixed it in two places:

  • get_raw_table_name strips a WITH (...) hint before reading the table name.
  • query_requires_identity_insert? skips past the hint when it looks for the identity column. Without this, an insert with an explicit id still fails with "IDENTITY_INSERT is set to OFF".

INSERT books ... without INTO still isn't handled (it falls through to the FROM branch). I left that out of this PR.

Would you want this backported to 8-1-stable? Happy to open that PR too.

@aidanharan
aidanharan merged commit 1c44234 into rails-sqlserver:main Oct 26, 2026
2 of 5 checks passed
@aidanharan

Copy link
Copy Markdown
Contributor

Please backport to 8-1. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants