Skip to content

Commit

Permalink
Test with PDO instead
Browse files Browse the repository at this point in the history
  • Loading branch information
theodorejb committed Oct 13, 2024
1 parent 3ae243c commit 4a73920
Showing 1 changed file with 21 additions and 37 deletions.
58 changes: 21 additions & 37 deletions test.php
Original file line number Diff line number Diff line change
@@ -1,56 +1,40 @@
<?php

use PeachySQL\Test\src\App;
use PgSql\Connection;

require 'test/bootstrap.php';

$conn = getPgsqlConn();

$sql = "INSERT INTO Users (name, dob, weight, isDisabled)
VALUES ($1, $2, $3, $4)";
VALUES (?, ?, ?, ?)";

$result = pg_query_params($conn, $sql, ['George McFly', '1938-04-01', 133.8, true]);
$stmt = $conn->prepare($sql);
$stmt->execute(['George McFly', '1938-04-01', 133.8, true]);
echo "Successfully inserted row!\n";

if (!$result) {
echo 'Failed to insert row: ' . pg_last_error($conn) . "\n";
} else {
echo "Successfully inserted row!\n";
}
$conn->query("DROP TABLE Users");
echo "Successfully dropped test table\n";

if (!pg_query($conn, "DROP TABLE Users")) {
throw new Exception('Failed to drop PostgreSQL test table: ' . pg_last_error($conn));
} else {
echo "Successfully dropped test table\n";
}

function getPgsqlConn(): Connection
function getPgsqlConn(): PDO
{
$c = App::$config;
$connStr = "host={$c->getPgsqlHost()} dbname={$c->getPgsqlDatabase()} "
. "user={$c->getPgsqlUser()} password={$c->getPgsqlPassword()}";
$conn = pg_connect($connStr);

if (!$conn) {
throw new Exception('Failed to connect to PostgreSQL');
}
$dsn = "pgsql:host={$c->getPgsqlHost()};dbname={$c->getPgsqlDatabase()}";

createPgsqlTestTable($conn);
return $conn;
$pdo = new PDO($dsn, $c->getPgsqlUser(), $c->getPgsqlPassword());
createPgsqlTestTable($pdo);
return $pdo;
}

function createPgsqlTestTable(Connection $conn): void
function createPgsqlTestTable(PDO $pdo): void
{
$sql = "CREATE TABLE Users (
user_id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
dob DATE NOT NULL,
weight REAL NOT NULL,
isDisabled BOOLEAN NOT NULL,
uuid bytea NULL
)";

if (!pg_query($conn, $sql)) {
throw new Exception('Failed to create PostgreSQL test table: ' . pg_last_error($conn));
}
user_id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
dob DATE NOT NULL,
weight REAL NOT NULL,
isDisabled BOOLEAN NOT NULL,
uuid bytea NULL
)";

$pdo->query($sql);
}

0 comments on commit 4a73920

Please sign in to comment.