Skip to content

Create method on model returning wrong primary key value (SQLSRV) #32883

Closed

Description

@kadevland
  • Laravel Version: 7
  • PHP Version: 7.4
  • Database Driver & Version: PDP_SQLSRV

Description:

When creating records of a model using create the returned record will have a wrong value for primary key if the table has a trigger on it which itself creates (inserts) a record in another table.

Steps To Reproduce:

Create a table (with an auto incrementing primary key) and add a trigger to it which inserts another record in another table). Then calling the create method on the model will return the just created record with the wrong value for the primary key field.

Note

it is the same issue as #27452, close for lack of activity but the problem is still valid

The fix staudenmeir@b4a8f81 solves the problem but is not integrated into Laravel.

Activity

  1. joelharkes commented on May 19, 2020

    @joelharkes
    Contributor

    @kadevland i dont think this is a laravel bug.

    it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity

    Its php Doctrine package that adds: ;SELECT SCOPE_IDENTITY() AS LastInsertId; to the query for SqlServer when query starts with 'INSERT INTO '

    see class: Doctrine\DBAL\Driver\SQLSrv\SQLSrvStatement

  2. joelharkes commented on May 19, 2020

    @joelharkes
    Contributor

    @kadevland I would advise using Laravel Eloquent events instead of database triggers for your logic.

  3. kadevland commented on May 19, 2020

    @kadevland
    Author

    @kadevland i dont think this is a laravel bug.

    it seems more like a mssql bug: https://stackoverflow.com/questions/15883304/stop-trigger-changing-scope-identity

    Its php Doctrine package that adds: ;SELECT SCOPE_IDENTITY() AS LastInsertId; to the query for SqlServer when query starts with 'INSERT INTO '

    see class: Doctrine\DBAL\Driver\SQLSrv\SQLSrvStatement

    You see Doctrine fix by append but laravel not append so that my purpose of issu.
    It's Bug of Eloquent can not return write value of ID ( doctrine can, and if do the same in eleoquent )

    You can't not replace trigger logical by php.

    It possible to integrete same logical witch use in doctrice and all ready use un driver pgsql in laravel

    for exemple :

    Illuminate\Database\Query\Grammars\PostgresGrammar

     public function compileInsertGetId(Builder $query, $values, $sequence)
        {
            return $this->compileInsert($query, $values).' returning '.$this->wrap($sequence ?: 'id');
        }
    

    Illuminate\Database\Query\Processors\PostgresProcessor

     public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
        {
            $result = $query->getConnection()->selectFromWriteConnection($sql, $values)[0];
    
            $sequence = $sequence ?: 'id';
    
            $id = is_object($result) ? $result->{$sequence} : $result[$sequence];
    
            return is_numeric($id) ? (int) $id : $id;
        }
    
  4. taylorotwell commented on May 19, 2020

    @taylorotwell
    Member

    Anyone is welcome to PR a fix. I do not use SQL Server nor can I test it easily.

  5. joelharkes commented on May 19, 2020

    @joelharkes
    Contributor

    @taylorotwell Can i add a docker-compose file to test sql-server (Unit)Tests and can this be integrated in the CI build process or not possible?

  6. kadevland commented on May 19, 2020

    @kadevland
    Author

    @joelharkes i can post DDL table and trigger, make the fixe on sqlsrvGrammar and procces
    but for CI/test i'm not good at all

  7. joelharkes commented on May 20, 2020

    @joelharkes
    Contributor

    I Got a working docker-compose setup for SQL server unit tests.

    Now I have to add the test case and discuss with Laravel team how/where to put my files.

    It got:

    • dockerfile to make php with SQL server drivers
    • compose file
    • docker entry point file to wait for host & port
    • PHP script to create a database in SQL server (it starts without database)

    Where do I put these files?
    What do I do with phpunit tests that should only be executed in this container?

  8. joelharkes commented on May 21, 2020

    @joelharkes
    Contributor

    update: I've got a working unit test, working on fix this week.

  9. joelharkes commented on May 21, 2020

    @joelharkes
    Contributor

    Got a fix working on finalizing PR.

  10. kadevland commented on May 22, 2020

    @kadevland
    Author

    THX.
    When you finalizing PR, i will test on my project

  11. joelharkes commented on May 25, 2020

    @joelharkes
    Contributor

    @kadevland fixed it on master, lets see what they say :) you can upvote the PR if you like.

  12. driesvints commented on Jun 25, 2020

    @driesvints
    Member

    #32957 was closed pending inactivity but we welcome any help with resurrecting it.

  13. 9 remaining items

  14. stevebauman commented on Jul 15, 2020

    @stevebauman
    Contributor

    Amazing work on that PR @rodrigopedra! 🙌

    Is there any possibility we could have a flag inside the developers sqlsrv configuration that enables / swaps compatibility with FreeTDS, while the MSSQL driver is supported by default?

    We would of course have to create separate grammars or grammar methods to compile the insert statement. But then instead of dropping support completely, users can set the flag to true (maybe 'freetds' => true).

    What are your thoughts?

    Since we have access to the configuration in the SqlServerConnection we could, we could retrieve this option and apply it to the Grammar instance:

    /**
    * Get the default query grammar instance.
    *
    * @return \Illuminate\Database\Query\Grammars\SqlServerGrammar
    */
    protected function getDefaultQueryGrammar()
    {
    return $this->withTablePrefix(new QueryGrammar);
    }

    Example:

    /**
     * Get the default query grammar instance.
     *
     * @return \Illuminate\Database\Query\Grammars\SqlServerGrammar
     */
    protected function getDefaultQueryGrammar()
    {
        $grammar = new QueryGrammar;
        
        if ($this->getConfig('freetds') === true) {
            $grammar->usingFreeTds();
        }
        
        return $this->withTablePrefix($grammar);
    }

    Or, even better, if we have the ability to detect which Sqlsrv driver is being used, then can enable the Grammar option without breaking backwards compatibility. Not sure if this is doable though...

  15. rodrigopedra commented on Jul 15, 2020

    @rodrigopedra
    Contributor

    Thanks @stevebauman !

    One of the suggestions I made in here:

    #33430 (comment)

    Was having some feature detection in place for that.

    Laravel already does that for the ODBC driver:

    if ($connection->getConfig('odbc') === true) {
    $id = $this->processInsertGetIdForOdbc($connection);
    } else {
    $id = $connection->getPdo()->lastInsertId();
    }

    But I fear adding more branches to that if should be a reason to drop SQL Server support altogether.

    I still think that adding the requirement to use the official driver is a better way to go, as it would simplify code and make maintenance easier. Support for alternative drivers could be added by third-party packages.

  16. driesvints commented on Jul 16, 2020

    @driesvints
    Member

    How much drivers are there for SQL Server and how popular are they?

  17. stevebauman commented on Jul 16, 2020

    @stevebauman
    Contributor

    @driesvints All I know of is the official SQL Server drivers and FreeTDS, but I haven't touched FreeTDS since PHP 5.4. Unsure why anyone would use FreeTDS over the official drivers to be honest, maybe for legacy Ubuntu servers?

    @rodrigopedra You're right, if it gets too complicated then it's probably best to support only the official SQL Server driver from Microsoft. However, if it's only one additional if statement to offer a fix and backwards compatibility, I'm not sure if that's a large maintenance overhead (imho).

  18. driesvints commented on Jul 16, 2020

    @driesvints
    Member

    @stevebauman well, if it's really one if statement I suspect we would have resolved this issue much sooner. I also don't think it's reasonable to support every driver out there. But I want to figure out how much there are and how popular they are first.

  19. stevebauman commented on Jul 16, 2020

    @stevebauman
    Contributor

    Apologies @driesvints, I wasn't intending to oversimplify the issue. I was referring to the need to extract both the PR's logic, and the in-place working logic (that is already working with FreeTDS) into two separate method calls and adding an if to simply check if the server is using the FreeTDS driver, or the Microsoft SQL Driver -- then execute the compatible insert.

  20. driesvints commented on Jul 16, 2020

    @driesvints
    Member

    No need to apologize :)

  21. taylorotwell commented on Sep 23, 2020

    @taylorotwell
    Member

    Since this issue has only been raised by a single person and @stevebauman has since posted a fix in the trigger itself (no response from OP) I'm going to close this.

  22. peter-olom commented on Sep 10, 2021

    @peter-olom

    This is still an issue in 2021

    $post = Post::create([ 'author_id' => $request->author, 'series_id' => $request->series, 'content' => $request->content, ]);
    After calling create method, $post->id will have a wrong value.

  23. stevebauman commented on Sep 10, 2021

    @stevebauman
    Contributor

    Hi @peter-olom, do you have any insert SQL triggers tied to your posts DB table?

    If you're going to say this is still an issue, then you have to create a programmatic test illustrating such. Saying it's still an issue provides maintainers nothing to work with.

    You can utilize Azure SQL Server for free in GitHub actions if you'd like to take on the task: https://docs.microsoft.com/en-us/azure/azure-sql/database/connect-github-actions-sql-db

  24. rodrigopedra commented on Sep 10, 2021

    @rodrigopedra
    Contributor

    This is still an issue in 2021

    Of course it is, the fix was reverted to avoid breaking apps that were using different drivers, as described in the thread above.

    If you read all the thread you will see no changes were made, as there is a workaround one can make to their own database server to circumvent this.

    By the way, have you tried adding the trigger workaround by @stevebauman above?

    If you think the framework should drop support for other SQL Servers drivers that didn't work out with the fix sent in 2020, without requiring developers to use the trigger workaround available in this thread, I would suggest you to:

    • send a PR re-submitting the fix, or better yet with an improved fix that might work with users using the FreeTDS driver
    • If a fix cannot accommodate FreeTDS applications, discuss with the maintainers if only the drivers from Microsoft should be supported
    • If they agree, send a PR to the docs clarifying this new requirement and noting it in the upgrade docs

    Until an alternative fix that works for both Microsoft drivers and FreeTDS drivers, or an agreement on only supporting Microsoft official drivers and using the then proposed fix sent in 2020, or an improved one, please try using the trigger workaround as discussed in the thread.

  25. joelharkes commented on Oct 9, 2021

    @joelharkes
    Contributor

    This is still an issue in 2021

    $post = Post::create([ 'author_id' => $request->author, 'series_id' => $request->series, 'content' => $request->content, ]); After calling create method, $post->id will have a wrong value.

    We have no issues using the official SQL server drivers. I would suggest swapping, since the official drivers work on all platforms nowadays.

  26. developerdino commented on Mar 5, 2024

    @developerdino

    I know this is an old bug, but it is still an issue. So I thought I'd make a package that will override the connection to enhance the SQL Server driver with the fix provided by @rodrigopedra in his PR.

    I choose this method as the triggers applied on our database are from a replication system that I don't want to maintain manually as every table in the database will eventually have a trigger for replication purposes making the suggested fix via the database triggers unmaintainable.

    The package can be found here https://packagist.org/packages/verifiedit/laravel-sqlsrv-driver-enhanced and installed by composer like so.

    composer require verifiedit/laravel-sqlsrv-driver-enhanced
    

    FYI: if you are using freeTDS driver this will not work for you as per the discussions above.

  27. renzovil commented on May 5, 2026

    @renzovil

    I know this is an old bug, but it is still an issue. So I thought I'd make a package that will override the connection to enhance the SQL Server driver with the fix provided by @rodrigopedra in his PR.

    I choose this method as the triggers applied on our database are from a replication system that I don't want to maintain manually as every table in the database will eventually have a trigger for replication purposes making the suggested fix via the database triggers unmaintainable.

    The package can be found here https://packagist.org/packages/verifiedit/laravel-sqlsrv-driver-enhanced and installed by composer like so.

    composer require verifiedit/laravel-sqlsrv-driver-enhanced
    

    FYI: if you are using freeTDS driver this will not work for you as per the discussions above.

    Hi @developerdino so many thanks for this big fix (it was a nightmare for me). Just a quick comment, I wanted to update my laravel version from 12 to 13, but the code/package is not supported. I guess it has some validation in the code that only allows to install it with laravel 12. I'm not that advanced to resolve this on my own (I get the idea of the solution but can't replicate it on my own). Please, I'd appreciate if you could tell us how to update it for laravel 13.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions