xref: /PHP-7.2/ext/pgsql/tests/08escape.phpt (revision c6662392)
1--TEST--
2PostgreSQL escape functions
3--SKIPIF--
4<?php include("skipif.inc"); ?>
5--FILE--
6<?php
7
8include 'config.inc';
9define('FILE_NAME', dirname(__FILE__) . '/php.gif');
10
11// pg_escape_string() test
12$before = "ABC\\ABC\'";
13$expect  = "ABC\\\\ABC\\'";
14$expect2  = "ABC\\\\ABC\\\\''"; //the way escape string differs from PostgreSQL 9.0
15$after = pg_escape_string($before);
16if ($expect === $after || $expect2 === $after) {
17	echo "pg_escape_string() is Ok\n";
18}
19else {
20	echo "pg_escape_string() is NOT Ok\n";
21	var_dump($before);
22	var_dump($after);
23	var_dump($expect);
24}
25
26// pg_escape_bytea() test
27$before = "ABC\\ABC";
28$expect  = "ABC\\\\\\\\ABC";
29$after  = pg_escape_bytea($before);
30if ($expect === $after) {
31	echo "pg_escape_bytea() is Ok\n";
32}
33else {
34	echo "pg_escape_byte() is NOT Ok\n";
35	var_dump($before);
36	var_dump($after);
37	var_dump($expect);
38}
39
40// Test using database
41$data = file_get_contents(FILE_NAME);
42$db   = pg_connect($conn_str);
43
44// Insert binary to DB
45$escaped_data = pg_escape_bytea($data);
46pg_query("DELETE FROM ".$table_name." WHERE num = -9999;");
47$sql = "INSERT INTO ".$table_name." (num, bin) VALUES (-9999, CAST ('".$escaped_data."' AS BYTEA));";
48pg_query($db, $sql);
49
50// Retrieve binary from DB
51for ($i = 0; $i < 2; $i++) {
52	$sql = "SELECT bin::bytea FROM ".$table_name." WHERE num = -9999";
53	$result = pg_query($db, $sql);
54	$row = pg_fetch_array($result, 0, PGSQL_ASSOC);
55
56	if ($data === pg_unescape_bytea($row['bin'])) {
57		echo "pg_escape_bytea() actually works with database\n";
58		break;
59	}
60	elseif (!$i) {
61		// Force bytea escaping and retry
62		@pg_query($db, "SET bytea_output = 'escape'");
63	}
64	else {
65		$result = pg_query($db, $sql);
66		echo "pg_escape_bytea() is broken\n";
67		break;
68	}
69}
70
71// pg_escape_literal/pg_escape_identifier
72$before = "ABC\\ABC\'";
73$expect	 = " E'ABC\\\\ABC\\\\'''";
74$after = pg_escape_literal($before);
75if ($expect === $after) {
76	echo "pg_escape_literal() is Ok\n";
77}
78else {
79	echo "pg_escape_literal() is NOT Ok\n";
80	var_dump($before);
81	var_dump($after);
82	var_dump($expect);
83}
84
85$before = "ABC\\ABC\'";
86$expect	 = "\"ABC\ABC\'\"";
87$after = pg_escape_identifier($before);
88if ($expect === $after) {
89	echo "pg_escape_identifier() is Ok\n";
90}
91else {
92	echo "pg_escape_identifier() is NOT Ok\n";
93	var_dump($before);
94	var_dump($after);
95	var_dump($expect);
96}
97
98?>
99--EXPECT--
100pg_escape_string() is Ok
101pg_escape_bytea() is Ok
102pg_escape_bytea() actually works with database
103pg_escape_literal() is Ok
104pg_escape_identifier() is Ok
105