Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix for then your pSQL sequences are not standard format #3506

Merged
merged 7 commits into from
Sep 13, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions src/Codeception/Lib/Driver/PostgreSql.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Codeception\Lib\Driver;

use Codeception\Exception\ModuleException;
Expand All @@ -11,6 +12,11 @@ class PostgreSql extends Db

protected $searchPath = null;

/**
* Loads a SQL file.
*
* @param string $sql sql file
*/
public function load($sql)
{
$query = '';
Expand Down Expand Up @@ -47,7 +53,7 @@ public function load($sql)
if (!$dollarsOpen && substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) {
$this->sqlToRun = substr($query, 0, -1 * $delimiterLength);
$this->sqlQuery($this->sqlToRun);
$query = "";
$query = '';
}
}
}
Expand Down Expand Up @@ -95,6 +101,7 @@ public function sqlLine($sql)
} else {
pg_put_line($this->connection, $sql . "\n");
}

return true;
}

Expand Down Expand Up @@ -123,16 +130,39 @@ public function sqlQuery($query)
}
}

/**
* Get the last inserted ID of table.
*/
public function lastInsertId($table)
{
/**
/*
* We make an assumption that the sequence name for this table
* is based on how postgres names sequences for SERIAL columns
*/

$sequenceName = $this->getQuotedName($table . '_id_seq');
return $this->getDbh()->lastInsertId($sequenceName);
$lastSequence = null;

try {
$lastSequence = $this->getDbh()->lastInsertId($sequenceName);
} catch (\PDOException $e) {
// in this case, the sequence name might be combined with the primary key name
}

// here we check if for instance, it's something like table_primary_key_seq instead of table_id_seq
// this could occur when you use some kind of import tool like pgloader
if (!$lastSequence) {
$primaryKeys = $this->getPrimaryKey($table);
$pkName = array_shift($primaryKeys);
$lastSequence = $this->getDbh()->lastInsertId($this->getQuotedName($table . '_' . $pkName . '_seq'));
}

return $lastSequence;
}

/**
* Gets a quoted name of a variable.
*/
public function getQuotedName($name)
{
$name = explode('.', $name);
Expand All @@ -142,10 +172,14 @@ function ($data) {
},
$name
);

return implode('.', $name);
}

/**
* Returns the primary key(s) of the table, based on:
* https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns.
*
* @param string $tableName
*
* @return array[string]
Expand All @@ -162,7 +196,6 @@ public function getPrimaryKey($tableName)
AND i.indisprimary';
$stmt = $this->executeQuery($query, [$tableName]);
$columns = $stmt->fetchAll(\PDO::FETCH_ASSOC);

foreach ($columns as $column) {
$primaryKey []= $column['attname'];
}
Expand Down
46 changes: 46 additions & 0 deletions tests/data/dumps/postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,32 @@ ALTER SEQUENCE users_id_seq OWNED BY users.id;

SET search_path = public, pg_catalog;

--
-- Name: seqnames; Type: TABLE; Schema: public; Owner: -; Tablespace:
--
DROP TABLE IF EXISTS seqnames CASCADE;
CREATE TABLE seqnames (
name character varying(30),
pk_id integer NOT NULL
);


--
-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--

CREATE SEQUENCE seqnames_pk_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;

--
-- Name: seqnames_pk_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--

ALTER SEQUENCE seqnames_pk_id_seq OWNED BY seqnames.pk_id;

--
-- Name: empty_table; Type: TABLE; Schema: public; Owner: -; Tablespace:
Expand Down Expand Up @@ -191,6 +217,13 @@ ALTER TABLE ONLY users ALTER COLUMN id SET DEFAULT nextval('users_id_seq'::regcl

SET search_path = public, pg_catalog;

--
-- Name:pk_id; Type: DEFAULT; Schema: public; Owner: -
--

ALTER TABLE ONLY seqnames ALTER COLUMN pk_id SET DEFAULT nextval('seqnames_pk_id_seq'::regclass);


--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--
Expand Down Expand Up @@ -245,6 +278,12 @@ SET search_path = public, pg_catalog;
COPY empty_table (id, field) FROM stdin;
\.

--
-- Name: seqnames_pk_id_seq; Type: SEQUENCE SET; Schema: public; Owner: -
--

SELECT pg_catalog.setval('seqnames_pk_id_seq', 1, false);


--
-- Name: empty_table_id_seq; Type: SEQUENCE SET; Schema: public; Owner: -
Expand Down Expand Up @@ -324,6 +363,13 @@ SET search_path = public, pg_catalog;
-- Name: g1; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY seqnames
ADD CONSTRAINT s1 PRIMARY KEY (pk_id);

--
-- Name: g1; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--

ALTER TABLE ONLY groups
ADD CONSTRAINT g1 PRIMARY KEY (id);

Expand Down
14 changes: 10 additions & 4 deletions tests/unit/Codeception/Lib/Driver/PostgresTest.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

use \Codeception\Lib\Driver\Db;

/**
Expand All @@ -14,7 +15,7 @@ class PostgresTest extends \PHPUnit_Framework_TestCase

protected static $sql;
protected $postgres;

public static function setUpBeforeClass()
{
if (!function_exists('pg_connect')) {
Expand All @@ -24,7 +25,7 @@ public static function setUpBeforeClass()
self::$config['password'] = 'Password12!';
}
$sql = file_get_contents(\Codeception\Configuration::dataDir() . '/dumps/postgres.sql');
$sql = preg_replace('%/\*(?:(?!\*/).)*\*/%s', "", $sql);
$sql = preg_replace('%/\*(?:(?!\*/).)*\*/%s', '', $sql);
self::$sql = explode("\n", $sql);
try {
$postgres = Db::create(self::$config['dsn'], self::$config['user'], self::$config['password']);
Expand All @@ -42,15 +43,14 @@ public function setUp()
}
$this->postgres->load(self::$sql);
}

public function tearDown()
{
if (isset($this->postgres)) {
$this->postgres->cleanup();
}
}


public function testCleanupDatabase()
{
$this->assertNotEmpty(
Expand Down Expand Up @@ -124,6 +124,12 @@ public function testGetEmptyArrayIfTableHasNoPrimaryKey()
$this->assertEquals([], $this->postgres->getPrimaryKey('no_pk'));
}

public function testLastInsertIdReturnsSequenceValueWhenNonStandardSequenceNameIsUsed()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I replaced your test with a test which actually tests the change in lastInsertId.

{
$this->postgres->executeQuery('INSERT INTO seqnames(name) VALUES(?)',['test']);
$this->assertEquals(1, $this->postgres->lastInsertId('seqnames'));
}

public function testGetPrimaryColumnOfTableUsingReservedWordAsTableName()
{
$this->assertEquals('id', $this->postgres->getPrimaryColumn('order'));
Expand Down