PageRenderTime 14ms CodeModel.GetById 9ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/hdbc-postgresql-helper.c

http://github.com/hdbc/hdbc-postgresql
C | 65 lines | 50 code | 9 blank | 6 comment | 7 complexity | 17e5f4f82069d61f356c8ba7b0019f96 MD5 | raw file
 1#include <libpq-fe.h>
 2#include <stdio.h>
 3#include <stdlib.h>
 4#include "hdbc-postgresql-helper.h"
 5
 6/* Things can't finalize more than once.  
 7We'd like to let people call them from the app.
 8Yet we'd also like to be able to have a ForeignPtr finalize them.
 9
10So, here's a little wrapper for things. */
11
12void PQfinish_conditional_finalizer(finalizeonce *conn);
13
14finalizeonce *wrapobjpg(void *obj, finalizeonce *parentobj) {
15  finalizeonce *newobj;
16  newobj = malloc(sizeof(finalizeonce));
17  if (newobj == NULL) {
18    fprintf(stderr, "HDBC: could not allocate wrapper!\n");
19    return NULL;
20  }
21  newobj->isfinalized = 0;
22  newobj->refcount = 1;
23  newobj->encapobj = obj;
24  newobj->parent = parentobj;
25  if (parentobj != NULL) 
26    parentobj->refcount++;
27  return newobj;
28}
29  
30void PQfinish_app(finalizeonce *conn) {
31  if (conn->isfinalized)
32    return;
33  PQfinish((PGconn *) (conn->encapobj));
34  conn->encapobj = NULL;
35  conn->isfinalized = 1;
36}
37
38void PQfinish_finalizer(finalizeonce *conn) {
39  (conn->refcount)--;
40  PQfinish_conditional_finalizer(conn);
41}
42
43void PQfinish_conditional_finalizer(finalizeonce *conn) {
44  if (conn->refcount < 1) {
45    PQfinish_app(conn);
46    free(conn);
47  }
48}
49
50void PQclear_app(finalizeonce *res) {
51  if (res->isfinalized)
52    return;
53  PQclear((PGresult *) (res->encapobj));
54  res->isfinalized = 1;
55}
56
57void PQclear_finalizer(finalizeonce *res) {
58  PQclear_app(res);
59  (res->refcount)--;            /* Not really important since this is never a 
60                                   parent */
61  (res->parent->refcount)--;
62  PQfinish_conditional_finalizer(res->parent);
63  free(res);
64}
65