I've been writing my own PHP model system that offers basic ORM and DBAL support as merely a learning lesson. It allowed me to write things I've never done before and use databases like SQLite and PostgreSQL that I've never used.
Model package: https://github.com/titon/Model PgSQL package: https://github.com/titon/Model.PostgreSQL
The problem I am having is unit testing the PgSQL driver (I have MySQL and SQLite working). Any time a unit test is run, I receive the following error:
PDOException : SQLSTATE[55000]: Object not in prerequisite state: 7 ERROR: currval of sequence "users_id_seq" is not yet defined in this session
I know what this problem is, but nothing I seem to do fixes it. It doesn't even reach my unit tests, it fails on the fixture setup portion. Here are the steps taken during each unit test:
- Driver is initialized and connected during
setUp()
- Unit test method is called
- Fixtures are loaded
- CREATE TABLE statement is called
- CREATE INDEX statements are called
- INSERT records are called
- Unit test is ran
tearDown()
is called which unloads fixtures (DROP TABLE and INDEX) and disconnects the driver
The error occurs during step 3.3 while inserting the fixture records. It inserts the 1st record (out of 10) and fails trying to fetch the last insert ID (the sequence error above). When I check PGAdmin, the tables and the sequences DO exist, so I am confused.
- Are the sequences not fully created yet by the time the inserts are being called?
- Does my connection session die too early?
- How can I solve this?
I'm very new to PgSQL so any help would be appreciated. For the record, the code is using PHP PDO and calls lastInsertId('table_column_seq') to retrieve the last ID.
Here's the fixture setUp SQL if you are interested.
CREATE TABLE IF NOT EXISTS "users" (
"id" serial NOT NULL,
"country_id" integer NULL DEFAULT NULL,
"username" varchar(255) NULL,
"password" varchar(255) NULL,
"email" varchar(255) NULL,
"firstName" varchar(255) NULL,
"lastName" varchar(255) NULL,
"age" smallint NULL,
"created" timestamp NULL DEFAULT NULL,
"modified" timestamp NULL DEFAULT NULL,
UNIQUE ("username")
);
CREATE INDEX "country_id" ON "users" ("country_id");
INSERT INTO "users" ("id", "country_id", "username", "firstName", "lastName", "password", "email", "age", "created") VALUES ('1', 1, 'miles', 'Miles', 'Johnson', '1Z5895jf72yL77h', '[email protected]', 25, '1988-02-26 21:22:34');
# Fails right after this insert