fix docs, add missing "}", fix formatting
[mdref/mdref-pq] / pq / Connection / : General Usage.md
1 # pq\Connection: General Usage
2
3 What is needed to create, check and reset a connection.
4
5 ## Creating a connection:
6
7 Creating a connection to the PostgreSQL server is as simple as:
8
9 <?php
10
11 $connection = new pq\Connection("dbname=test user=test password=test");
12
13 ?>
14
15 The first argument to the Connection constructor is a ***connection string*** as described [in the PostgreSQL documentation](http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING).
16
17 Optional ***flags*** are accepted as second argument. See [connection flag constants](pq/Connection#Connection.Flags:).
18
19 ### Creating a persistent connection:
20
21 <?php
22
23 $connection = new pq\Connection("dbname=test user=test password=test", pq\Connection::PERSISTENT);
24
25 ?>
26
27 ### Creating an asynchronously opened connection:
28
29 <?php
30
31 $connection = new pq\Connection("dbname=test user=test password=test", pq\Connection::ASYNC);
32
33 ?>
34
35 ## Checking the connection status:
36
37 The connection object provides a ***public readonly*** property pq\Connection::$status, which value can be one of the [connection status constants](pq/Connection#Connection.Status:).
38
39 <?php
40
41 switch ($connection->status) {
42 case pq\Connection::OK:
43 // connection complete
44 break;
45 case pq\Connection::BAD:
46 $connection->reset();
47 break;
48 default:
49 // connection in progress
50 break;
51 }
52
53 ?>
54
55 ## Resetting the connection:
56
57 <?php
58
59 $connection->reset();
60
61 ?>
62
63 Attempt to close the connection to the server and reestablish a new connection with the same connection parameters previously used.
64
65 ## Closing the connection:
66
67 <?php
68
69 $connection = NULL;
70
71 ?>
72
73 ### Non-persistent connections:
74
75 A ***non-persistent*** connection will be closed when all references to the pq\Connection object are gone.
76
77 ### Persistent connections:
78
79 A ***persistent*** connection will be recycled, when it is not referenced any longer.
80
81 There is also some cleanup performed, so that subsequent usage is as unimpaired as possible:
82
83 * any active asynchronous queries are canceled
84 * any pending results of asynchronous queries are fetched and cleared
85 * ```ROLLBACK``` if pq\Connection::$transactionStatus is anything but pq\Connection::TRANS_IDLE
86 * ```RESET ALL``` to reset any changed session variables
87 * ```UNLISTEN``` for each listened notification channel