-
Notifications
You must be signed in to change notification settings - Fork 83
/
pg_query.c
113 lines (85 loc) · 2.27 KB
/
pg_query.c
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "pg_query.h"
#include "pg_query_internal.h"
#include <mb/pg_wchar.h>
#include <utils/memutils.h>
#include <utils/memdebug.h>
#ifdef HAVE_PTHREAD
#include <pthread.h>
#endif
#include <signal.h>
const char* progname = "pg_query";
__thread sig_atomic_t pg_query_initialized = 0;
#ifdef HAVE_PTHREAD
static pthread_key_t pg_query_thread_exit_key;
static void pg_query_thread_exit(void *key);
#endif
void pg_query_init(void)
{
if (pg_query_initialized != 0) return;
pg_query_initialized = 1;
MemoryContextInit();
SetDatabaseEncoding(PG_UTF8);
#ifdef HAVE_PTHREAD
pthread_key_create(&pg_query_thread_exit_key, pg_query_thread_exit);
pthread_setspecific(pg_query_thread_exit_key, TopMemoryContext);
#endif
}
void pg_query_free_top_memory_context(MemoryContext context)
{
Assert(MemoryContextIsValid(context));
/*
* After this, no memory contexts are valid anymore, so ensure that
* the current context is the top-level context.
*/
Assert(TopMemoryContext == CurrentMemoryContext);
MemoryContextDeleteChildren(context);
/* Clean up the aset.c freelist, to leave no unused context behind */
AllocSetDeleteFreeList(context);
context->methods->delete_context(context);
VALGRIND_DESTROY_MEMPOOL(context);
/* Without this, Valgrind will complain */
free(context);
/* Reset pointers */
TopMemoryContext = NULL;
CurrentMemoryContext = NULL;
ErrorContext = NULL;
}
#ifdef HAVE_PTHREAD
static void pg_query_thread_exit(void *key)
{
MemoryContext context = (MemoryContext) key;
pg_query_free_top_memory_context(context);
}
#endif
void pg_query_exit(void)
{
pg_query_free_top_memory_context(TopMemoryContext);
}
MemoryContext pg_query_enter_memory_context()
{
MemoryContext ctx = NULL;
pg_query_init();
Assert(CurrentMemoryContext == TopMemoryContext);
ctx = AllocSetContextCreate(TopMemoryContext,
"pg_query",
ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(ctx);
return ctx;
}
void pg_query_exit_memory_context(MemoryContext ctx)
{
// Return to previous PostgreSQL memory context
MemoryContextSwitchTo(TopMemoryContext);
MemoryContextDelete(ctx);
ctx = NULL;
}
void pg_query_free_error(PgQueryError *error)
{
free(error->message);
free(error->funcname);
free(error->filename);
if (error->context) {
free(error->context);
}
free(error);
}