1 /*	$Id: trace.c,v 1.3 2018/12/17 15:14:15 kristaps Exp $ */
2 /*
3  * Copyright (c) 2016--2018 Kristaps Dzonsons <kristaps@bsd.lv>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include "config.h"
18 
19 #if HAVE_SYS_QUEUE
20 # include <sys/queue.h>
21 #endif
22 
23 #include <assert.h>
24 #include <stdlib.h>
25 
26 #include <sqlite3.h>
27 
28 #include "ksql.h"
29 #include "extern.h"
30 
31 /*
32  * Used by SQLite when tracing events.
33  * Passes right through to ksql_err_noexit().
34  */
35 static void
ksql_tracemsg(void * pArg,int iErrCode,const char * zMsg)36 ksql_tracemsg(void *pArg, int iErrCode, const char *zMsg)
37 {
38 	struct ksql	*p = pArg;
39 
40 	(void)iErrCode;
41 
42 	ksql_err_noexit(p, KSQL_OK, zMsg);
43 }
44 
45 enum ksqlc
ksql_trace(struct ksql * p)46 ksql_trace(struct ksql *p)
47 {
48 	enum ksqlc	 c, cc;
49 	int		 rc;
50 
51 	if (KSQLSRV_ISPARENT(p)) {
52 		ksql_writeop(p, KSQLOP_TRACE);
53 		if (KSQL_OK != (c = ksql_readcode(p, &cc)))
54 			return(c);
55 		return(cc);
56 	}
57 
58 	rc = sqlite3_config
59 		(SQLITE_CONFIG_LOG, ksql_tracemsg, p);
60 
61 	if (SQLITE_MISUSE == rc)
62 		cc = KSQL_ALREADYOPEN;
63 	else if (SQLITE_OK != rc)
64 		cc = KSQL_SYSTEM;
65 	else
66 		cc = KSQL_OK;
67 
68 	return(ksql_writecode(p, cc));
69 }
70 
71 enum ksqlc
ksql_untrace(struct ksql * p)72 ksql_untrace(struct ksql *p)
73 {
74 	enum ksqlc	 c, cc;
75 	int		 rc;
76 
77 	if (KSQLSRV_ISPARENT(p)) {
78 		ksql_writeop(p, KSQLOP_UNTRACE);
79 		if (KSQL_OK != (c = ksql_readcode(p, &cc)))
80 			return(c);
81 		return(cc);
82 	}
83 
84 	rc = sqlite3_config
85 		(SQLITE_CONFIG_LOG, NULL, NULL);
86 
87 	if (SQLITE_MISUSE == rc)
88 		cc = KSQL_ALREADYOPEN;
89 	else if (SQLITE_OK != rc)
90 		cc = KSQL_SYSTEM;
91 	else
92 		cc = KSQL_OK;
93 
94 	return(ksql_writecode(p, cc));
95 }
96