Skip to content
New issue

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

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

Already on GitHub? # to your account

Fix computed columns mapping to wrong tables #51009

Merged
merged 1 commit into from
Apr 10, 2024
Merged

Fix computed columns mapping to wrong tables #51009

merged 1 commit into from
Apr 10, 2024

Conversation

maddhatter
Copy link
Contributor

If at least one table contains a computed column, Schema::getColumns() would show the computed column for other tables as well.

The query created by \Illuminate\Database\Schema\Grammars\SqlServerGrammar::compileColumns is missing a join predicate between sys.columns and sys.computed_columns:

select col.name, type.name as type_name, 
col.max_length as length, col.precision as precision, col.scale as places, 
col.is_nullable as nullable, def.definition as [default], 
col.is_identity as autoincrement, col.collation_name as collation, 
com.definition as [expression], is_persisted as [persisted], 
cast(prop.value as nvarchar(max)) as comment 
from sys.columns as col 
join sys.types as type on col.user_type_id = type.user_type_id 
join sys.objects as obj on col.object_id = obj.object_id 
join sys.schemas as scm on obj.schema_id = scm.schema_id 
left join sys.default_constraints def on col.default_object_id = def.object_id and col.object_id = def.parent_object_id 
left join sys.extended_properties as prop on obj.object_id = prop.major_id and col.column_id = prop.minor_id and prop.name = 'MS_Description' 
left join sys.computed_columns as com on col.column_id = com.column_id and col.object_id = com.object_id 
--                                                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
where obj.type in ('U', 'V') and obj.name = %s and scm.name = %s 
order by col.column_id'

This adds the predicate to ensure only computed columns that belong to the current table are returned.

Tested on SQL Server 2019.

@taylorotwell
Copy link
Member

@hafezdivandari what do you think?

@hafezdivandari
Copy link
Contributor

hafezdivandari commented Apr 10, 2024

@taylorotwell The changes are valid, we can merge this, thanks.

@maddhatter thanks!

For ref: The column_id is unique within the object but not within the schema!

@taylorotwell taylorotwell merged commit 4e3b785 into laravel:11.x Apr 10, 2024
30 checks passed
@maddhatter maddhatter deleted the mssql-computed branch April 11, 2024 11:03
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants