xref: /sqlite-3.40.0/src/test_server.c (revision 2d02a67d)
1*2d02a67dSdrh /*
2*2d02a67dSdrh ** 2006 January 07
3*2d02a67dSdrh **
4*2d02a67dSdrh ** The author disclaims copyright to this source code.  In place of
5*2d02a67dSdrh ** a legal notice, here is a blessing:
6*2d02a67dSdrh **
7*2d02a67dSdrh **    May you do good and not evil.
8*2d02a67dSdrh **    May you find forgiveness for yourself and forgive others.
9*2d02a67dSdrh **    May you share freely, never taking more than you give.
10*2d02a67dSdrh **
11*2d02a67dSdrh ******************************************************************************
12*2d02a67dSdrh **
13*2d02a67dSdrh ** This file contains demonstration code.  Nothing in this file gets compiled
14*2d02a67dSdrh ** or linked into the SQLite library unless you use a non-standard option:
15*2d02a67dSdrh **
16*2d02a67dSdrh **      -DSQLITE_SERVER=1
17*2d02a67dSdrh **
18*2d02a67dSdrh ** The configure script will never generate a Makefile with the option
19*2d02a67dSdrh ** above.  You will need to manually modify the Makefile if you want to
20*2d02a67dSdrh ** include any of the code from this file in your project.  Or, at your
21*2d02a67dSdrh ** option, you may copy and paste the code from this file and
22*2d02a67dSdrh ** thereby avoiding a recompile of SQLite.
23*2d02a67dSdrh **
24*2d02a67dSdrh **
25*2d02a67dSdrh ** This source file demonstrates how to use SQLite to create an SQL database
26*2d02a67dSdrh ** server thread in a multiple-threaded program.  One or more client threads
27*2d02a67dSdrh ** send messages to the server thread and the server thread processes those
28*2d02a67dSdrh ** messages in the order received and returns the results to the client.
29*2d02a67dSdrh **
30*2d02a67dSdrh ** One might ask:  "Why bother?  Why not just let each thread connect
31*2d02a67dSdrh ** to the database directly?"  There are a several of reasons to
32*2d02a67dSdrh ** prefer the client/server approach.
33*2d02a67dSdrh **
34*2d02a67dSdrh **    (1)  Some systems (ex: Redhat9) have broken threading implementations
35*2d02a67dSdrh **         that prevent SQLite database connections from being used in
36*2d02a67dSdrh **         a thread different from the one where they were created.  With
37*2d02a67dSdrh **         the client/server approach, all database connections are created
38*2d02a67dSdrh **         and used within the server thread.  Client calls to the database
39*2d02a67dSdrh **         can be made from multiple threads (though not at the same time!)
40*2d02a67dSdrh **
41*2d02a67dSdrh **    (2)  Beginning with SQLite version 3.3.0, when two or more
42*2d02a67dSdrh **         connections to the same database occur within the same thread,
43*2d02a67dSdrh **         they can optionally share their database cache.  This reduces
44*2d02a67dSdrh **         I/O and memory requirements.  Cache shared is controlled using
45*2d02a67dSdrh **         the sqlite3_enable_shared_cache() API.
46*2d02a67dSdrh **
47*2d02a67dSdrh **    (3)  Database connections on a shared cache use table-level locking
48*2d02a67dSdrh **         instead of file-level locking for improved concurrency.
49*2d02a67dSdrh **
50*2d02a67dSdrh **    (4)  Database connections on a shared cache can by optionally
51*2d02a67dSdrh **         set to READ UNCOMMITTED isolation.  (The default isolation for
52*2d02a67dSdrh **         SQLite is SERIALIZABLE.)  When this occurs, readers will
53*2d02a67dSdrh **         never be blocked by a writer and writers will not be
54*2d02a67dSdrh **         blocked by readers.  There can still only be a single writer
55*2d02a67dSdrh **         at a time, but multiple readers can simultaneously exist with
56*2d02a67dSdrh **         that writer.  This is a huge increase in concurrency.
57*2d02a67dSdrh **
58*2d02a67dSdrh ** To summarize the rational for using a client/server approach: prior
59*2d02a67dSdrh ** to SQLite version 3.3.0 it probably was not worth the trouble.  But
60*2d02a67dSdrh ** with SQLite version 3.3.0 and beyond you can get significant performance
61*2d02a67dSdrh ** and concurrency improvements and memory usage reductions by going
62*2d02a67dSdrh ** client/server.
63*2d02a67dSdrh **
64*2d02a67dSdrh ** Note:  The extra features of version 3.3.0 described by points (2)
65*2d02a67dSdrh ** through (4) above are only available if you compile without the
66*2d02a67dSdrh ** option -DSQLITE_OMIT_SHARED_CACHE.
67*2d02a67dSdrh **
68*2d02a67dSdrh ** Here is how the client/server approach works:  The database server
69*2d02a67dSdrh ** thread is started on this procedure:
70*2d02a67dSdrh **
71*2d02a67dSdrh **       void *sqlite3_server(void *NotUsed);
72*2d02a67dSdrh **
73*2d02a67dSdrh ** The sqlite_server procedure runs as long as the g.serverHalt variable
74*2d02a67dSdrh ** is false.  A mutex is used to make sure no more than one server runs
75*2d02a67dSdrh ** at a time.  The server waits for messages to arrive on a message
76*2d02a67dSdrh ** queue and processes the messages in order.
77*2d02a67dSdrh **
78*2d02a67dSdrh ** Two convenience routines are provided for starting and stopping the
79*2d02a67dSdrh ** server thread:
80*2d02a67dSdrh **
81*2d02a67dSdrh **       void sqlite3_server_start(void);
82*2d02a67dSdrh **       void sqlite3_server_stop(void);
83*2d02a67dSdrh **
84*2d02a67dSdrh ** Both of the convenience routines return immediately.  Neither will
85*2d02a67dSdrh ** ever give an error.  If a server is already started or already halted,
86*2d02a67dSdrh ** then the routines are effectively no-ops.
87*2d02a67dSdrh **
88*2d02a67dSdrh ** Clients use the following interfaces:
89*2d02a67dSdrh **
90*2d02a67dSdrh **       sqlite3_client_open
91*2d02a67dSdrh **       sqlite3_client_prepare
92*2d02a67dSdrh **       sqlite3_client_step
93*2d02a67dSdrh **       sqlite3_client_reset
94*2d02a67dSdrh **       sqlite3_client_finalize
95*2d02a67dSdrh **       sqlite3_client_close
96*2d02a67dSdrh **
97*2d02a67dSdrh ** These interfaces work exactly like the standard core SQLite interfaces
98*2d02a67dSdrh ** having the same names without the "_client_" infix.  Many other SQLite
99*2d02a67dSdrh ** interfaces can be used directly without having to send messages to the
100*2d02a67dSdrh ** server as long as SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined.
101*2d02a67dSdrh ** The following interfaces fall into this second category:
102*2d02a67dSdrh **
103*2d02a67dSdrh **       sqlite3_bind_*
104*2d02a67dSdrh **       sqlite3_changes
105*2d02a67dSdrh **       sqlite3_clear_bindings
106*2d02a67dSdrh **       sqlite3_column_*
107*2d02a67dSdrh **       sqlite3_complete
108*2d02a67dSdrh **       sqlite3_create_collation
109*2d02a67dSdrh **       sqlite3_create_function
110*2d02a67dSdrh **       sqlite3_data_count
111*2d02a67dSdrh **       sqlite3_db_handle
112*2d02a67dSdrh **       sqlite3_errcode
113*2d02a67dSdrh **       sqlite3_errmsg
114*2d02a67dSdrh **       sqlite3_last_insert_rowid
115*2d02a67dSdrh **       sqlite3_total_changes
116*2d02a67dSdrh **       sqlite3_transfer_bindings
117*2d02a67dSdrh **
118*2d02a67dSdrh ** A single SQLite connection (an sqlite3* object) or an SQLite statement
119*2d02a67dSdrh ** (an sqlite3_stmt* object) should only be passed to a single interface
120*2d02a67dSdrh ** function at a time.  The connections and statements can be passed from
121*2d02a67dSdrh ** any thread to any of the functions listed in the second group above as
122*2d02a67dSdrh ** long as the same connection is not in use by two threads at once and
123*2d02a67dSdrh ** as long as SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined.  Additional
124*2d02a67dSdrh ** information about the SQLITE_ENABLE_MEMORY_MANAGEMENT constraint is
125*2d02a67dSdrh ** below.
126*2d02a67dSdrh **
127*2d02a67dSdrh ** The busy handler for all database connections should remain turned
128*2d02a67dSdrh ** off.  That means that any lock contention will cause the associated
129*2d02a67dSdrh ** sqlite3_client_step() call to return immediately with an SQLITE_BUSY
130*2d02a67dSdrh ** error code.  If a busy handler is enabled and lock contention occurs,
131*2d02a67dSdrh ** then the entire server thread will block.  This will cause not only
132*2d02a67dSdrh ** the requesting client to block but every other database client as
133*2d02a67dSdrh ** well.  It is possible to enhance the code below so that lock
134*2d02a67dSdrh ** contention will cause the message to be placed back on the top of
135*2d02a67dSdrh ** the queue to be tried again later.  But such enhanced processing is
136*2d02a67dSdrh ** not included here, in order to keep the example simple.
137*2d02a67dSdrh **
138*2d02a67dSdrh ** This example code assumes the use of pthreads.  Pthreads
139*2d02a67dSdrh ** implementations are available for windows.  (See, for example
140*2d02a67dSdrh ** http://sourceware.org/pthreads-win32/announcement.html.)  Or, you
141*2d02a67dSdrh ** can translate the locking and thread synchronization code to use
142*2d02a67dSdrh ** windows primitives easily enough.  The details are left as an
143*2d02a67dSdrh ** exercise to the reader.
144*2d02a67dSdrh **
145*2d02a67dSdrh **** Restrictions Associated With SQLITE_ENABLE_MEMORY_MANAGEMENT ****
146*2d02a67dSdrh **
147*2d02a67dSdrh ** If you compile with SQLITE_ENABLE_MEMORY_MANAGEMENT defined, then
148*2d02a67dSdrh ** SQLite includes code that tracks how much memory is being used by
149*2d02a67dSdrh ** each thread.  These memory counts can become confused if memory
150*2d02a67dSdrh ** is allocated by one thread and then freed by another.  For that
151*2d02a67dSdrh ** reason, when SQLITE_ENABLE_MEMORY_MANAGEMENT is used, all operations
152*2d02a67dSdrh ** that might allocate or free memory should be performanced in the same
153*2d02a67dSdrh ** thread that originally created the database connection.  In that case,
154*2d02a67dSdrh ** many of the operations that are listed above as safe to be performed
155*2d02a67dSdrh ** in separate threads would need to be sent over to the server to be
156*2d02a67dSdrh ** done there.  If SQLITE_ENABLE_MEMORY_MANAGEMENT is defined, then
157*2d02a67dSdrh ** the following functions can be used safely from different threads
158*2d02a67dSdrh ** without messing up the allocation counts:
159*2d02a67dSdrh **
160*2d02a67dSdrh **       sqlite3_bind_parameter_name
161*2d02a67dSdrh **       sqlite3_bind_parameter_index
162*2d02a67dSdrh **       sqlite3_changes
163*2d02a67dSdrh **       sqlite3_column_blob
164*2d02a67dSdrh **       sqlite3_column_count
165*2d02a67dSdrh **       sqlite3_complete
166*2d02a67dSdrh **       sqlite3_data_count
167*2d02a67dSdrh **       sqlite3_db_handle
168*2d02a67dSdrh **       sqlite3_errcode
169*2d02a67dSdrh **       sqlite3_errmsg
170*2d02a67dSdrh **       sqlite3_last_insert_rowid
171*2d02a67dSdrh **       sqlite3_total_changes
172*2d02a67dSdrh **
173*2d02a67dSdrh ** The remaining functions are not thread-safe when memory management
174*2d02a67dSdrh ** is enabled.  So one would have to define some new interface routines
175*2d02a67dSdrh ** along the following lines:
176*2d02a67dSdrh **
177*2d02a67dSdrh **       sqlite3_client_bind_*
178*2d02a67dSdrh **       sqlite3_client_clear_bindings
179*2d02a67dSdrh **       sqlite3_client_column_*
180*2d02a67dSdrh **       sqlite3_client_create_collation
181*2d02a67dSdrh **       sqlite3_client_create_function
182*2d02a67dSdrh **       sqlite3_client_transfer_bindings
183*2d02a67dSdrh **
184*2d02a67dSdrh ** The example code in this file is intended for use with memory
185*2d02a67dSdrh ** management turned off.  So the implementation of these additional
186*2d02a67dSdrh ** client interfaces is left as an exercise to the reader.
187*2d02a67dSdrh **
188*2d02a67dSdrh ** It may seem surprising to the reader that the list of safe functions
189*2d02a67dSdrh ** above does not include things like sqlite3_bind_int() or
190*2d02a67dSdrh ** sqlite3_column_int().  But those routines might, in fact, allocate
191*2d02a67dSdrh ** or deallocate memory.  In the case of sqlite3_bind_int(), if the
192*2d02a67dSdrh ** parameter was previously bound to a string that string might need
193*2d02a67dSdrh ** to be deallocated before the new integer value is inserted.  In
194*2d02a67dSdrh ** the case of sqlite3_column_int(), the value of the column might be
195*2d02a67dSdrh ** a UTF-16 string which will need to be converted to UTF-8 then into
196*2d02a67dSdrh ** an integer.
197*2d02a67dSdrh */
198*2d02a67dSdrh 
199*2d02a67dSdrh /*
200*2d02a67dSdrh ** Only compile the code in this file on UNIX with a THREADSAFE build
201*2d02a67dSdrh ** and only if the SQLITE_SERVER macro is defined.
202*2d02a67dSdrh */
203*2d02a67dSdrh #ifdef SQLITE_SERVER
204*2d02a67dSdrh #if defined(OS_UNIX) && OS_UNIX && defined(THREADSAFE) && THREADSAFE
205*2d02a67dSdrh 
206*2d02a67dSdrh /*
207*2d02a67dSdrh ** We require only pthreads and the public interface of SQLite.
208*2d02a67dSdrh */
209*2d02a67dSdrh #include <pthread.h>
210*2d02a67dSdrh #include "sqlite3.h"
211*2d02a67dSdrh 
212*2d02a67dSdrh /*
213*2d02a67dSdrh ** Messages are passed from client to server and back again as
214*2d02a67dSdrh ** instances of the following structure.
215*2d02a67dSdrh */
216*2d02a67dSdrh typedef struct SqlMessage SqlMessage;
217*2d02a67dSdrh struct SqlMessage {
218*2d02a67dSdrh   int op;                      /* Opcode for the message */
219*2d02a67dSdrh   sqlite3 *pDb;                /* The SQLite connection */
220*2d02a67dSdrh   sqlite3_stmt *pStmt;         /* A specific statement */
221*2d02a67dSdrh   int errCode;                 /* Error code returned */
222*2d02a67dSdrh   const char *zIn;             /* Input filename or SQL statement */
223*2d02a67dSdrh   int nByte;                   /* Size of the zIn parameter for prepare() */
224*2d02a67dSdrh   const char *zOut;            /* Tail of the SQL statement */
225*2d02a67dSdrh   SqlMessage *pNext;           /* Next message in the queue */
226*2d02a67dSdrh   SqlMessage *pPrev;           /* Previous message in the queue */
227*2d02a67dSdrh   pthread_mutex_t clientMutex; /* Hold this mutex to access the message */
228*2d02a67dSdrh   pthread_cond_t clientWakeup; /* Signal to wake up the client */
229*2d02a67dSdrh };
230*2d02a67dSdrh 
231*2d02a67dSdrh /*
232*2d02a67dSdrh ** Legal values for SqlMessage.op
233*2d02a67dSdrh */
234*2d02a67dSdrh #define MSG_Open       1  /* sqlite3_open(zIn, &pDb) */
235*2d02a67dSdrh #define MSG_Prepare    2  /* sqlite3_prepare(pDb, zIn, nByte, &pStmt, &zOut) */
236*2d02a67dSdrh #define MSG_Step       3  /* sqlite3_step(pStmt) */
237*2d02a67dSdrh #define MSG_Reset      4  /* sqlite3_reset(pStmt) */
238*2d02a67dSdrh #define MSG_Finalize   5  /* sqlite3_finalize(pStmt) */
239*2d02a67dSdrh #define MSG_Close      6  /* sqlite3_close(pDb) */
240*2d02a67dSdrh #define MSG_Done       7  /* Server has finished with this message */
241*2d02a67dSdrh 
242*2d02a67dSdrh 
243*2d02a67dSdrh /*
244*2d02a67dSdrh ** State information about the server is stored in a static variable
245*2d02a67dSdrh ** named "g" as follows:
246*2d02a67dSdrh */
247*2d02a67dSdrh static struct ServerState {
248*2d02a67dSdrh   pthread_mutex_t queueMutex;   /* Hold this mutex to access the msg queue */
249*2d02a67dSdrh   pthread_mutex_t serverMutex;  /* Held by the server while it is running */
250*2d02a67dSdrh   pthread_cond_t serverWakeup;  /* Signal this condvar to wake up the server */
251*2d02a67dSdrh   volatile int serverHalt;      /* Server halts itself when true */
252*2d02a67dSdrh   SqlMessage *pQueueHead;       /* Head of the message queue */
253*2d02a67dSdrh   SqlMessage *pQueueTail;       /* Tail of the message queue */
254*2d02a67dSdrh } g = {
255*2d02a67dSdrh   PTHREAD_MUTEX_INITIALIZER,
256*2d02a67dSdrh   PTHREAD_MUTEX_INITIALIZER,
257*2d02a67dSdrh   PTHREAD_COND_INITIALIZER,
258*2d02a67dSdrh };
259*2d02a67dSdrh 
260*2d02a67dSdrh /*
261*2d02a67dSdrh ** Send a message to the server.  Block until we get a reply.
262*2d02a67dSdrh **
263*2d02a67dSdrh ** The mutex and condition variable in the message are uninitialized
264*2d02a67dSdrh ** when this routine is called.  This routine takes care of
265*2d02a67dSdrh ** initializing them and destroying them when it has finished.
266*2d02a67dSdrh */
267*2d02a67dSdrh static void sendToServer(SqlMessage *pMsg){
268*2d02a67dSdrh   /* Initialize the mutex and condition variable on the message
269*2d02a67dSdrh   */
270*2d02a67dSdrh   pthread_mutex_init(&pMsg->clientMutex, 0);
271*2d02a67dSdrh   pthread_cond_init(&pMsg->clientWakeup, 0);
272*2d02a67dSdrh 
273*2d02a67dSdrh   /* Add the message to the head of the server's message queue.
274*2d02a67dSdrh   */
275*2d02a67dSdrh   pthread_mutex_lock(&g.queueMutex);
276*2d02a67dSdrh   pMsg->pNext = g.pQueueHead;
277*2d02a67dSdrh   if( g.pQueueHead==0 ){
278*2d02a67dSdrh     g.pQueueTail = pMsg;
279*2d02a67dSdrh   }else{
280*2d02a67dSdrh     g.pQueueHead->pPrev = pMsg;
281*2d02a67dSdrh   }
282*2d02a67dSdrh   pMsg->pPrev = 0;
283*2d02a67dSdrh   g.pQueueHead = pMsg;
284*2d02a67dSdrh   pthread_mutex_unlock(&g.queueMutex);
285*2d02a67dSdrh 
286*2d02a67dSdrh   /* Signal the server that the new message has be queued, then
287*2d02a67dSdrh   ** block waiting for the server to process the message.
288*2d02a67dSdrh   */
289*2d02a67dSdrh   pthread_mutex_lock(&pMsg->clientMutex);
290*2d02a67dSdrh   pthread_cond_signal(&g.serverWakeup);
291*2d02a67dSdrh   while( pMsg->op!=MSG_Done ){
292*2d02a67dSdrh     pthread_cond_wait(&pMsg->clientWakeup, &pMsg->clientMutex);
293*2d02a67dSdrh   }
294*2d02a67dSdrh   pthread_mutex_unlock(&pMsg->clientMutex);
295*2d02a67dSdrh 
296*2d02a67dSdrh   /* Destroy the mutex and condition variable of the message.
297*2d02a67dSdrh   */
298*2d02a67dSdrh   pthread_mutex_destroy(&pMsg->clientMutex);
299*2d02a67dSdrh   pthread_cond_destroy(&pMsg->clientWakeup);
300*2d02a67dSdrh }
301*2d02a67dSdrh 
302*2d02a67dSdrh /*
303*2d02a67dSdrh ** The following 6 routines are client-side implementations of the
304*2d02a67dSdrh ** core SQLite interfaces:
305*2d02a67dSdrh **
306*2d02a67dSdrh **        sqlite3_open
307*2d02a67dSdrh **        sqlite3_prepare
308*2d02a67dSdrh **        sqlite3_step
309*2d02a67dSdrh **        sqlite3_reset
310*2d02a67dSdrh **        sqlite3_finalize
311*2d02a67dSdrh **        sqlite3_close
312*2d02a67dSdrh **
313*2d02a67dSdrh ** Clients should use the following client-side routines instead of
314*2d02a67dSdrh ** the core routines above.
315*2d02a67dSdrh **
316*2d02a67dSdrh **        sqlite3_client_open
317*2d02a67dSdrh **        sqlite3_client_prepare
318*2d02a67dSdrh **        sqlite3_client_step
319*2d02a67dSdrh **        sqlite3_client_reset
320*2d02a67dSdrh **        sqlite3_client_finalize
321*2d02a67dSdrh **        sqlite3_client_close
322*2d02a67dSdrh **
323*2d02a67dSdrh ** Each of these routines creates a message for the desired operation,
324*2d02a67dSdrh ** sends that message to the server, waits for the server to process
325*2d02a67dSdrh ** then message and return a response.
326*2d02a67dSdrh */
327*2d02a67dSdrh int sqlite3_client_open(const char *zDatabaseName, sqlite3 **ppDb){
328*2d02a67dSdrh   SqlMessage msg;
329*2d02a67dSdrh   msg.op = MSG_Open;
330*2d02a67dSdrh   msg.zIn = zDatabaseName;
331*2d02a67dSdrh   sendToServer(&msg);
332*2d02a67dSdrh   *ppDb = msg.pDb;
333*2d02a67dSdrh   return msg.errCode;
334*2d02a67dSdrh }
335*2d02a67dSdrh int sqlite3_client_prepare(
336*2d02a67dSdrh   sqlite3 *pDb,
337*2d02a67dSdrh   const char *zSql,
338*2d02a67dSdrh   int nByte,
339*2d02a67dSdrh   sqlite3_stmt **ppStmt,
340*2d02a67dSdrh   const char **pzTail
341*2d02a67dSdrh ){
342*2d02a67dSdrh   SqlMessage msg;
343*2d02a67dSdrh   msg.op = MSG_Prepare;
344*2d02a67dSdrh   msg.pDb = pDb;
345*2d02a67dSdrh   msg.zIn = zSql;
346*2d02a67dSdrh   msg.nByte = nByte;
347*2d02a67dSdrh   sendToServer(&msg);
348*2d02a67dSdrh   *ppStmt = msg.pStmt;
349*2d02a67dSdrh   if( pzTail ) *pzTail = msg.zOut;
350*2d02a67dSdrh   return msg.errCode;
351*2d02a67dSdrh }
352*2d02a67dSdrh int sqlite3_client_step(sqlite3_stmt *pStmt){
353*2d02a67dSdrh   SqlMessage msg;
354*2d02a67dSdrh   msg.op = MSG_Step;
355*2d02a67dSdrh   msg.pStmt = pStmt;
356*2d02a67dSdrh   sendToServer(&msg);
357*2d02a67dSdrh   return msg.errCode;
358*2d02a67dSdrh }
359*2d02a67dSdrh int sqlite3_client_reset(sqlite3_stmt *pStmt){
360*2d02a67dSdrh   SqlMessage msg;
361*2d02a67dSdrh   msg.op = MSG_Reset;
362*2d02a67dSdrh   msg.pStmt = pStmt;
363*2d02a67dSdrh   sendToServer(&msg);
364*2d02a67dSdrh   return msg.errCode;
365*2d02a67dSdrh }
366*2d02a67dSdrh int sqlite3_client_finalize(sqlite3_stmt *pStmt){
367*2d02a67dSdrh   SqlMessage msg;
368*2d02a67dSdrh   msg.op = MSG_Finalize;
369*2d02a67dSdrh   msg.pStmt = pStmt;
370*2d02a67dSdrh   sendToServer(&msg);
371*2d02a67dSdrh   return msg.errCode;
372*2d02a67dSdrh }
373*2d02a67dSdrh int sqlite3_client_close(sqlite3 *pDb){
374*2d02a67dSdrh   SqlMessage msg;
375*2d02a67dSdrh   msg.op = MSG_Close;
376*2d02a67dSdrh   msg.pDb = pDb;
377*2d02a67dSdrh   sendToServer(&msg);
378*2d02a67dSdrh   return msg.errCode;
379*2d02a67dSdrh }
380*2d02a67dSdrh 
381*2d02a67dSdrh /*
382*2d02a67dSdrh ** This routine implements the server.  To start the server, first
383*2d02a67dSdrh ** make sure g.serverHalt is false, then create a new detached thread
384*2d02a67dSdrh ** on this procedure.  See the sqlite3_server_start() routine below
385*2d02a67dSdrh ** for an example.  This procedure loops until g.serverHalt becomes
386*2d02a67dSdrh ** true.
387*2d02a67dSdrh */
388*2d02a67dSdrh void *sqlite3_server(void *NotUsed){
389*2d02a67dSdrh   sqlite3_enable_shared_cache(1);
390*2d02a67dSdrh   if( pthread_mutex_trylock(&g.serverMutex) ){
391*2d02a67dSdrh     sqlite3_enable_shared_cache(0);
392*2d02a67dSdrh     return 0;  /* Another server is already running */
393*2d02a67dSdrh   }
394*2d02a67dSdrh   while( !g.serverHalt ){
395*2d02a67dSdrh     SqlMessage *pMsg;
396*2d02a67dSdrh 
397*2d02a67dSdrh     /* Remove the last message from the message queue.
398*2d02a67dSdrh     */
399*2d02a67dSdrh     pthread_mutex_lock(&g.queueMutex);
400*2d02a67dSdrh     while( g.pQueueTail==0 && g.serverHalt==0 ){
401*2d02a67dSdrh       pthread_cond_wait(&g.serverWakeup, &g.queueMutex);
402*2d02a67dSdrh     }
403*2d02a67dSdrh     pMsg = g.pQueueTail;
404*2d02a67dSdrh     if( pMsg ){
405*2d02a67dSdrh       if( pMsg->pPrev ){
406*2d02a67dSdrh         pMsg->pPrev->pNext = 0;
407*2d02a67dSdrh       }else{
408*2d02a67dSdrh         g.pQueueHead = 0;
409*2d02a67dSdrh       }
410*2d02a67dSdrh       g.pQueueTail = pMsg->pPrev;
411*2d02a67dSdrh     }
412*2d02a67dSdrh     pthread_mutex_unlock(&g.queueMutex);
413*2d02a67dSdrh     if( pMsg==0 ) break;
414*2d02a67dSdrh 
415*2d02a67dSdrh     /* Process the message just removed
416*2d02a67dSdrh     */
417*2d02a67dSdrh     pthread_mutex_lock(&pMsg->clientMutex);
418*2d02a67dSdrh     switch( pMsg->op ){
419*2d02a67dSdrh       case MSG_Open: {
420*2d02a67dSdrh         pMsg->errCode = sqlite3_open(pMsg->zIn, &pMsg->pDb);
421*2d02a67dSdrh         break;
422*2d02a67dSdrh       }
423*2d02a67dSdrh       case MSG_Prepare: {
424*2d02a67dSdrh         pMsg->errCode = sqlite3_prepare(pMsg->pDb, pMsg->zIn, pMsg->nByte,
425*2d02a67dSdrh                                         &pMsg->pStmt, &pMsg->zOut);
426*2d02a67dSdrh         break;
427*2d02a67dSdrh       }
428*2d02a67dSdrh       case MSG_Step: {
429*2d02a67dSdrh         pMsg->errCode = sqlite3_step(pMsg->pStmt);
430*2d02a67dSdrh         break;
431*2d02a67dSdrh       }
432*2d02a67dSdrh       case MSG_Reset: {
433*2d02a67dSdrh         pMsg->errCode = sqlite3_reset(pMsg->pStmt);
434*2d02a67dSdrh         break;
435*2d02a67dSdrh       }
436*2d02a67dSdrh       case MSG_Finalize: {
437*2d02a67dSdrh         pMsg->errCode = sqlite3_finalize(pMsg->pStmt);
438*2d02a67dSdrh         break;
439*2d02a67dSdrh       }
440*2d02a67dSdrh       case MSG_Close: {
441*2d02a67dSdrh         pMsg->errCode = sqlite3_close(pMsg->pDb);
442*2d02a67dSdrh         break;
443*2d02a67dSdrh       }
444*2d02a67dSdrh     }
445*2d02a67dSdrh 
446*2d02a67dSdrh     /* Signal the client that the message has been processed.
447*2d02a67dSdrh     */
448*2d02a67dSdrh     pMsg->op = MSG_Done;
449*2d02a67dSdrh     pthread_mutex_unlock(&pMsg->clientMutex);
450*2d02a67dSdrh     pthread_cond_signal(&pMsg->clientWakeup);
451*2d02a67dSdrh   }
452*2d02a67dSdrh   pthread_mutex_unlock(&g.serverMutex);
453*2d02a67dSdrh   sqlite3_thread_cleanup();
454*2d02a67dSdrh   return 0;
455*2d02a67dSdrh }
456*2d02a67dSdrh 
457*2d02a67dSdrh /*
458*2d02a67dSdrh ** Start a server thread if one is not already running.  If there
459*2d02a67dSdrh ** is aleady a server thread running, the new thread will quickly
460*2d02a67dSdrh ** die and this routine is effectively a no-op.
461*2d02a67dSdrh */
462*2d02a67dSdrh void sqlite3_server_start(void){
463*2d02a67dSdrh   pthread_t x;
464*2d02a67dSdrh   int rc;
465*2d02a67dSdrh   g.serverHalt = 0;
466*2d02a67dSdrh   rc = pthread_create(&x, 0, sqlite3_server, 0);
467*2d02a67dSdrh   if( rc==0 ){
468*2d02a67dSdrh     pthread_detach(x);
469*2d02a67dSdrh   }
470*2d02a67dSdrh }
471*2d02a67dSdrh 
472*2d02a67dSdrh /*
473*2d02a67dSdrh ** If a server thread is running, then stop it.  If no server is
474*2d02a67dSdrh ** running, this routine is effectively a no-op.
475*2d02a67dSdrh **
476*2d02a67dSdrh ** This routine returns immediately without waiting for the server
477*2d02a67dSdrh ** thread to stop.  But be assured that the server will eventually stop.
478*2d02a67dSdrh */
479*2d02a67dSdrh void sqlite3_server_stop(void){
480*2d02a67dSdrh   g.serverHalt = 1;
481*2d02a67dSdrh   pthread_cond_broadcast(&g.serverWakeup);
482*2d02a67dSdrh }
483*2d02a67dSdrh 
484*2d02a67dSdrh #endif /* defined(OS_UNIX) && OS_UNIX && defined(THREADSAFE) && THREADSAFE */
485*2d02a67dSdrh #endif /* defined(SQLITE_SERVER) */
486