We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Issues with Transaction object

I'm having an issue using Transactions, here is some code example:

//Doing values insertion try { $transactionManager = new Phalcon\Mvc\Model\Transaction\Manager();

    $transaction = $transactionManager->get();

    $user = Users::findFirst("uid='".$userId."'");

    if ($user == false) {
        $user = new Users();
    }

    $user->setTransaction($transaction);
    $user->uid = $userId;
    $user->status = 'active';
    $user->created = date('Y-m-d H:i:s');

    $ipAddress = explode(',', $app->request->getClientAddress(true));

    if ($user->save() == true) {
        $toolbar = new Toolbars_Install();
        $toolbar->setTransaction($transaction);
        $toolbar->ip_address = $ipAddress[0];
        $toolbar->created = date('Y-m-d H:i:s');
        $toolbar->uid = $user->id;

        if ($toolbar->save() == true) {
            $user->toolbar_install_id = $toolbar->id;
            $user->save();
        } else {
            $transaction->rollback('Unable to save model [toolbar], error: '.$errors);
        }
    } else {
        $transaction->rollback('Unable to save model [user], error: '.$errors);
    }

    $transaction->commit();

} catch(Phalcon\Mvc\Model\Transaction\Failed $e) {
    \Classes\Utils\Log::exception($app->config->logs->toolbars->install, $e);
} catch (Exception $e) {
    \Classes\Utils\Log::exception($app->config->logs->toolbars->install, $e);
}

doing this I'm getting an exception

Line: 120, Code: 23000, Message: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2-c749b72fda4299b64363cab38dfb280d' for key 'PRIMARY'

Line 120 in my file is the line related to: $user->save();

Looking into the generated queries, Phalcon is generating a sencond INSERT for the Users model.

If I do:

$user->update(array( 'toolbar_install_id' => $toolbar->id ));

The update query is not getting generated.

I'm using Phalcon 0.8.0



98.9k

Could you post the table structure for table Users?



12.1k

I can't.

If I do this after the transaction commit;

$user = Users::findFirst("uid='".$userId."'");

    if ($user != false) {
        $user->update(array('toolbar_install_id' => $toolbar->id));
    }

then the users tablet is updated properly.



98.9k

The SQL table structure? show create table users?



12.1k

Yes I know what you mean, but my company don't allow me to do that.

@Odiel

Make two tables of your own (not the ones you use in your company). Use similar primary key->foreign key linking but show say Robots and Parts. That should allow us to have a look at it and perhaps find where the issue lies.



98.9k

ok, The error says that primary key has two fields 2-c749b72fda4299b64363cab38dfb280d, I assume the primary key on that table is a compound primary key, but you get the record using $user = Users::findFirst("uid='".$userId."'");, maybe are you missing a field there?



12.1k

Yes as you said Phalcon, the table has two fields for the primary key.

One is 'id' which is auto increment, and the other one is some I insert.

$user = Users::findFirst("uid='".$userId."'");

This is only to check if the user exist, but the error I got was having no users in the table, so the code:

if ($user == false) { $user = new Users(); }

was executed for sure, creating a new instance of User model.



12.1k

Tables structure:

CREATE TABLE users ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, uid varchar(32) NOT NULL, status varchar(50) NOT NULL DEFAULT 'active', created datetime NOT NULL DEFAULT '0000-00-00 00:00:00', toolbar_install_id int(10) unsigned DEFAULT NULL, PRIMARY KEY (id,uid), UNIQUE KEY uid (uid) USING BTREE, KEY created (created) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1

CREATE TABLE toolbars_install ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, uid bigint(20) NOT NULL, ip_address varchar(15) NOT NULL, created datetime NOT NULL, PRIMARY KEY (id), KEY uid (uid), KEY ip_address (ip_address) USING BTREE, KEY created (created) ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1

I did a test with the same code I put here, and change my tables structure, still having the same error.



98.9k

I created this gist, is this ok? https://gist.github.com/phalcon/4718070

You can see it running at https://test.phalcon.io/tx.php

Current data on tables:

mysql> select * from users;
+----+----------------------------------+--------+---------------------+--------------------+
| id | uid                              | status | created             | toolbar_install_id |
+----+----------------------------------+--------+---------------------+--------------------+
| 12 | 5d41402abc4b2a76b9719d911017c592 | active | 2013-02-05 16:52:42 |                 17 |
+----+----------------------------------+--------+---------------------+--------------------+
1 row in set (0.00 sec)
mysql> select * from toolbars_install;
+----+-----+------------+---------------------+
| id | uid | ip_address | created             |
+----+-----+------------+---------------------+
| 14 |  12 | 1          | 2013-02-05 16:52:11 |
| 15 |  12 | 1          | 2013-02-05 16:52:38 |
| 16 |  12 | 1          | 2013-02-05 16:52:40 |
| 17 |  12 | 1          | 2013-02-05 16:52:42 |
+----+-----+------------+---------------------+
4 rows in set (0.00 sec)


12.1k

Yes your example looks perfect.

But even that I'm still having the issue, I double checked your code with me, to see if I have any error or something.

I switch Phalcon version to 090 Beta2

The code this time don't trigger an exception but the field toolbar_install_id is not getting populated.

This are the generated queries:

[Tue, 05 Feb 13 22:39:58 +0000][INFO] SET NAMES UTF8; [Tue, 05 Feb 13 22:39:58 +0000][INFO] SELECT users.id, users.uid, users.status, users.created, users.toolbar_install_id FROM users WHERE users.uid = 'c749b72fda4299b64363cab38dfb280d' LIMIT 1 [Tue, 05 Feb 13 22:39:58 +0000][INFO] SELECT COUNT(*) AS rowcount FROM users WHERE id = ? AND uid = ? [Tue, 05 Feb 13 22:39:58 +0000][INFO] INSERT INTO users (uid, status, created, toolbar_install_id, id) VALUES (?, ?, ?, null, null) [Tue, 05 Feb 13 22:39:58 +0000][INFO] INSERT INTO toolbars_install (uid, ip_address, created, id) VALUES (?, ?, ?, null) [Tue, 05 Feb 13 22:39:58 +0000][INFO] UPDATE users SET status = ?, created = ?, toolbar_install_id = ? WHERE id = ? AND uid = ?



98.9k

Are you using manual meta-data on model Users?



12.1k

No the models are empty, only have the getSource definition.

BTW, can you truncate the tables you have, and run only once the code, then check if the field toolbar_install_id is being populated?



12.1k

I ran it in my local computer, and got same behavior I described before, values are inserted in the tables, but the field toolbar_install_id don't have value first time the script run.



98.9k

I added some truncate before execute the script, also you can pass a userId with https://test.phalcon.io/tx.php?userId=x the x is passed to md5



98.9k

The second user update is not being done

mysql> select * from users;
+----+----------------------------------+--------+---------------------+--------------------+
| id | uid                              | status | created             | toolbar_install_id |
+----+----------------------------------+--------+---------------------+--------------------+
|  1 | 6d865d85813b1261953b3e79cdb04716 | active | 2013-02-05 18:27:53 |               NULL |
+----+----------------------------------+--------+---------------------+--------------------+
1 row in set (0.00 sec)
mysql> select * from toolbars_install;
+----+-----+------------+---------------------+
| id | uid | ip_address | created             |
+----+-----+------------+---------------------+
|  1 |   1 | 127.0.0.1  | 2013-02-05 18:27:53 |
+----+-----+------------+---------------------+
1 row in set (0.00 sec)


12.1k

Exactly, so?



98.9k

I added a fix for this in 0.9.0 stable, could you reinstall/install that version?



12.1k

So far, so good with this, everything looks great and working, thanks.