| 92 | } |
| 93 | |
| 94 | PGconn *Connect(const DatabaseInfo *info, char *error, size_t maxlength) |
| 95 | { |
| 96 | const char *keywords[7]; |
| 97 | const char *values[7]; |
| 98 | unsigned int count = 0; |
| 99 | |
| 100 | char port[16]; |
| 101 | char timeout[16]; |
| 102 | |
| 103 | keywords[count] = "host"; |
| 104 | values[count++] = info->host; |
| 105 | |
| 106 | keywords[count] = "dbname"; |
| 107 | values[count++] = info->database; |
| 108 | |
| 109 | if (info->port > 0) |
| 110 | { |
| 111 | snprintf(port, sizeof(port), "%u", info->port); |
| 112 | keywords[count] = "port"; |
| 113 | values[count++] = port; |
| 114 | } |
| 115 | |
| 116 | if (info->user[0] != '\0') |
| 117 | { |
| 118 | keywords[count] = "user"; |
| 119 | values[count++] = info->user; |
| 120 | } |
| 121 | if (info->pass[0] != '\0') |
| 122 | { |
| 123 | keywords[count] = "password"; |
| 124 | values[count++] = info->pass; |
| 125 | } |
| 126 | |
| 127 | if (info->maxTimeout > 0) |
| 128 | { |
| 129 | snprintf(timeout, sizeof(timeout), "%u", info->maxTimeout); |
| 130 | keywords[count] = "connect_timeout"; |
| 131 | values[count++] = timeout; |
| 132 | } |
| 133 | |
| 134 | keywords[count] = NULL; |
| 135 | values[count] = NULL; |
| 136 | |
| 137 | /* Make a connection to the database */ |
| 138 | PGconn *conn = PQconnectdbParams(keywords, values, 0); |
| 139 | if (!conn) |
| 140 | { |
| 141 | snprintf(error, maxlength, "Failed to allocate memory for connection"); |
| 142 | return NULL; |
| 143 | } |
| 144 | |
| 145 | /* Check to see that the backend connection was successfully made */ |
| 146 | if (PQstatus(conn) != CONNECTION_OK) |
| 147 | { |
| 148 | /* :TODO: expose UTIL_Format from smutil! */ |
| 149 | snprintf(error, maxlength, "%s", PQerrorMessage(conn)); |
| 150 | PQfinish(conn); |
| 151 | return NULL; |