test_server.c 18 KB

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