: asapien/signet

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "db.h"

static int
scalar(PGconn *pg, const char *sql, int n, const char *const *params)
{
	PGresult *res = db_q(pg, sql, n, params);
	int value;

	assert(res != NULL && PQntuples(res) == 1);
	value = atoi(PQgetvalue(res, 0, 0));
	PQclear(res);
	return value;
}

int
main(int argc, char **argv)
{
	struct conf cf;
	PGconn *pg;
	PGresult *res;
	const char *params[3];
	char *large;
	int pid;

	assert(argc == 2 && conf_load(&cf, argv[1]) == 0);
	pg = db_get(&cf);
	assert(pg != NULL);
	pid = PQbackendPID(pg);
	assert(scalar(pg, "SELECT 1", 0, NULL) == 1);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) == pid);

	assert(db_do(pg, "BEGIN", 0, NULL) == 0);
	res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL);
	assert(res != NULL && PQgetlength(res, 0, 0) == 524288);
	PQclear(res);
	assert(PQtransactionStatus(pg) == PQTRANS_INTRANS);
	assert(PQbackendPID(pg) == pid);
	assert(db_do(pg, "COMMIT", 0, NULL) == 0);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large = malloc(524289);
	assert(large != NULL);
	memset(large, 'x', 524288);
	large[524288] = '\0';
	params[0] = large;
	assert(scalar(pg, "SELECT length($1::text)", 1, params) == 524288);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large[204800] = '\0';
	params[1] = NULL;
	params[2] = large;
	assert(scalar(pg, "SELECT length($1::text) + COALESCE(length($2::text), 0) + length($3::text)",
	    3, params) == 409600);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	pid = PQbackendPID(pg);

	large[204800] = 'x';
	assert(db_q(pg, "SELECT 1/0 WHERE $1::text IS NOT NULL", 1, params) == NULL);
	db_request_done();
	pg = db_get(&cf);
	assert(PQbackendPID(pg) != pid);
	res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL);
	assert(res != NULL);
	PQclear(res);
	db_request_done();
	free(large);
	puts("database cache: small connection reuse, large results/params/errors recycled only at API boundary");
	return 0;
}