spadefoot / kohana-orm-leap

An ORM module for the Kohana PHP framework that is designed to work with all major databases.
http://spadefoot.github.io/kohana-orm-leap/
100 stars 25 forks source link

Error from last_insert_id() in PostgreSQL (pg_last_oid()) #44

Closed taai closed 12 years ago

taai commented 12 years ago

The last_insert_id() isn't working for PostgreSQL 9.1, because in PostgreSQL 9.1 (already since version 8.1) the OIDS are turned off by default ( http://www.postgresql.org/docs/8.4/interactive/runtime-config-compatible.html#GUC-DEFAULT-WITH-OIDS ). So, if you don't turn on OIDS, you can't get the last insert id with Kohana Leap ORM. :(

The query is:

INSERT INTO "food" ("name") VALUES ('hamburger');

The error is:

ErrorException [ Warning ]: pg_last_oid(): supplied resource is not a valid PostgreSQL result resource
MODPATH\leap\classes\base\db\postgresql\connection\standard.php [ 151 ]
$insert_id = pg_last_oid($this->resource_id);

But the RETURNING could be the solution!

The query:

INSERT INTO "food" ("name") VALUES ('hamburger') RETURNING id;

The PHP:

<?php
$result = pg_query($connection, $query);
$insert_row = pg_fetch_row($result);
$insert_id = $insert_row[0];

And (!) the cool thing is that the RETURNING id returns all id's, so I can get all id's for inserted rows:

INSERT INTO "food" ("name") VALUES ('hamburger'), ('cheeseburger'), ('french fries') RETURNING id;

I can immagine that in model's there could be some function that defined wich columns to return (RETURNING can return values from multiple columns), for example like this:

<?php
public static function returns()
{
    return array('id');
}

Can you resolve this, please?

taai commented 12 years ago

The simplest way to resolve this problem without modifying too many files was to query the last insert id from database:

SELECT lastval();

In the future I will try to figure out how to implement RETURNING , but for now this fix is just fine.