~ubuntu-branches/ubuntu/lucid/python-apsw/lucid

« back to all changes in this revision

Viewing changes to src/util.c

  • Committer: Bazaar Package Importer
  • Author(s): Joel Rosdahl
  • Date: 2010-01-11 20:44:37 UTC
  • mfrom: (1.1.6 upstream) (3.1.4 sid)
  • Revision ID: james.westby@ubuntu.com-20100111204437-iao0rcj1p2m29juy
Tags: 3.6.22-r1-1
* New upstream version.
* Added ${misc:Depends} for binary packages' requirements.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
  Utility macros and functions
 
3
 
 
4
  See the accompanying LICENSE file.
 
5
*/
 
6
 
 
7
/* These macros are to address several issues:
 
8
 
 
9
  - Prevent simultaneous calls on the same object while the GIL is
 
10
  released in one thread.  For example if a Cursor is executing
 
11
  sqlite3_step with the GIL released, we don't want Cursor_execute
 
12
  called on another thread since that will thrash what the first
 
13
  thread is doing.  We use a member of Connection, Blob and Cursor
 
14
  named 'inuse' to provide the simple exclusion.
 
15
 
 
16
  - The GIL has to be released around all SQLite calls that take the
 
17
  database mutex (which is most of them).  If the GIL is kept even for
 
18
  trivial calls then deadlock will arise.  This is because if you have
 
19
  multiple mutexes you must always acquire them in the same order, or
 
20
  never hold more than one at a time.
 
21
 
 
22
  - The SQLite error code is not threadsafe.  This is because the
 
23
  error string is per database connection.  The call to sqlite3_errmsg
 
24
  will return a pointer but that can be replaced by any other thread
 
25
  with an error.  Consequently SQLite added sqlite3_db_mutex (see
 
26
  sqlite-dev mailing list for 4 Nov 2008).  A far better workaround
 
27
  would have been to make the SQLite error stuff be per thread just
 
28
  like errno.  Instead I have had to roll my own thread local storage
 
29
  system for storing the error message.
 
30
*/
 
31
 
 
32
/* call where no error is returned */
 
33
#define _PYSQLITE_CALL_V(x) \
 
34
  do { Py_BEGIN_ALLOW_THREADS { x; } Py_END_ALLOW_THREADS ; } while(0)
 
35
 
 
36
/* Calls where error could be set.  We assume that a variable 'res' is set.  Also need the db to take
 
37
   the mutex on */
 
38
#define _PYSQLITE_CALL_E(db, x)                     \
 
39
do {                                                \
 
40
  Py_BEGIN_ALLOW_THREADS                            \
 
41
    {                                               \
 
42
      sqlite3_mutex_enter(sqlite3_db_mutex(db));    \
 
43
      x;                                            \
 
44
      if(res!=SQLITE_OK && res!=SQLITE_DONE && res!=SQLITE_ROW) \
 
45
        apsw_set_errmsg(sqlite3_errmsg((db)));      \
 
46
      sqlite3_mutex_leave(sqlite3_db_mutex(db));    \
 
47
    }                                               \
 
48
  Py_END_ALLOW_THREADS;                             \
 
49
 } while(0)
 
50
 
 
51
#define INUSE_CALL(x)                               \
 
52
  do {                                              \
 
53
       assert(self->inuse==0); self->inuse=1;       \
 
54
       { x; }                                       \
 
55
       assert(self->inuse==1); self->inuse=0;       \
 
56
  } while(0)
 
57
 
 
58
/* call from blob code */
 
59
#define PYSQLITE_BLOB_CALL(y) INUSE_CALL(_PYSQLITE_CALL_E(self->connection->db, y))
 
60
 
 
61
/* call from connection code */
 
62
#define PYSQLITE_CON_CALL(y)  INUSE_CALL(_PYSQLITE_CALL_E(self->db, y))
 
63
 
 
64
/* call from cursor code - same as blob */
 
65
#define PYSQLITE_CUR_CALL PYSQLITE_BLOB_CALL
 
66
 
 
67
/* from statement cache */
 
68
#define PYSQLITE_SC_CALL(y)   _PYSQLITE_CALL_E(sc->db, y)
 
69
 
 
70
/* call to sqlite code that doesn't return an error */
 
71
#define PYSQLITE_VOID_CALL(y) INUSE_CALL(_PYSQLITE_CALL_V(y))
 
72
 
 
73
/* call from backup code */
 
74
#define PYSQLITE_BACKUP_CALL(y) INUSE_CALL(_PYSQLITE_CALL_E(self->dest->db, y))
 
75
 
 
76
#ifdef __GNUC__
 
77
#define APSW_ARGUNUSED __attribute__ ((unused))
 
78
#else
 
79
#define APSW_ARGUNUSED
 
80
#endif
 
81
 
 
82
 
 
83
 
 
84
/* used to decide if we will use int (4 bytes) or long long (8 bytes) */
 
85
#define APSW_INT32_MIN (-2147483647-1)
 
86
#define APSW_INT32_MAX 2147483647
 
87
 
 
88
 
 
89
/* 
 
90
   The default Python PyErr_WriteUnraiseable is almost useless.  It
 
91
   only prints the str() of the exception and the str() of the object
 
92
   passed in.  This gives the developer no clue whatsoever where in
 
93
   the code it is happening.  It also does funky things to the passed
 
94
   in object which can cause the destructor to fire twice.
 
95
   Consequently we use our version here.  It makes the traceback
 
96
   complete, and then tries the following, going to the next if
 
97
   the hook isn't found or returns an error:
 
98
 
 
99
   * excepthook of hookobject (if not NULL)
 
100
   * excepthook of sys module
 
101
   * PyErr_Display
 
102
 
 
103
   If any return an error then then the next one is tried.  When we
 
104
   return, any error will be cleared.
 
105
*/
 
106
static void 
 
107
apsw_write_unraiseable(PyObject *hookobject)
 
108
{
 
109
  PyObject *err_type=NULL, *err_value=NULL, *err_traceback=NULL;
 
110
  PyObject *excepthook=NULL;
 
111
  PyObject *result=NULL;
 
112
  PyFrameObject *frame=NULL;
 
113
 
 
114
  /* fill in the rest of the traceback */
 
115
  frame = PyThreadState_GET()->frame;
 
116
  while(frame)
 
117
    {
 
118
      PyTraceBack_Here(frame);
 
119
      frame=frame->f_back;
 
120
    }
 
121
  
 
122
  /* Get the exception details */
 
123
  PyErr_Fetch(&err_type, &err_value, &err_traceback);
 
124
  PyErr_NormalizeException(&err_type, &err_value, &err_traceback);
 
125
 
 
126
  if(hookobject)
 
127
    {
 
128
      excepthook=PyObject_GetAttrString(hookobject, "excepthook");
 
129
      PyErr_Clear();
 
130
      if(excepthook)
 
131
        {
 
132
          result=PyEval_CallFunction(excepthook, "(OOO)", err_type?err_type:Py_None, err_value?err_value:Py_None, err_traceback?err_traceback:Py_None);
 
133
          if(result)
 
134
            goto finally;
 
135
        }
 
136
      Py_XDECREF(excepthook);
 
137
    }
 
138
 
 
139
  excepthook=PySys_GetObject("excepthook");
 
140
  if(excepthook)
 
141
    {
 
142
      Py_INCREF(excepthook); /* borrowed reference from PySys_GetObject so we increment */
 
143
      PyErr_Clear();
 
144
      result=PyEval_CallFunction(excepthook, "(OOO)", err_type?err_type:Py_None, err_value?err_value:Py_None, err_traceback?err_traceback:Py_None);
 
145
      if(result) 
 
146
        goto finally;
 
147
    }
 
148
 
 
149
  /* remove any error from callback failure */
 
150
  PyErr_Clear();
 
151
  PyErr_Display(err_type, err_value, err_traceback);
 
152
 
 
153
  finally:
 
154
  Py_XDECREF(excepthook);
 
155
  Py_XDECREF(result);
 
156
  Py_XDECREF(err_traceback);
 
157
  Py_XDECREF(err_value);
 
158
  Py_XDECREF(err_type);
 
159
  PyErr_Clear(); /* being paranoid - make sure no errors on return */
 
160
}
 
161
 
 
162
 
 
163
 
 
164
/* 
 
165
   Python's handling of Unicode is horrible.  It can use 2 or 4 byte
 
166
   unicode chars and the conversion routines like to put out BOMs
 
167
   which makes life even harder.  These macros are used in pairs to do
 
168
   the right form of conversion and tell us whether to use the plain
 
169
   or -16 version of the SQLite function that is about to be called.
 
170
*/
 
171
 
 
172
#if Py_UNICODE_SIZE==2
 
173
#define UNIDATABEGIN(obj) \
 
174
{                                                        \
 
175
  size_t strbytes=2*PyUnicode_GET_SIZE(obj);             \
 
176
  const void *strdata=PyUnicode_AS_DATA(obj);            
 
177
 
 
178
#define UNIDATAEND(obj)                                  \
 
179
}
 
180
 
 
181
#define USE16(x) x##16
 
182
 
 
183
#else  /* Py_UNICODE_SIZE!=2 */
 
184
 
 
185
#define UNIDATABEGIN(obj) \
 
186
{                                                        \
 
187
  Py_ssize_t strbytes=0;                                 \
 
188
  const char *strdata=NULL;                              \
 
189
  PyObject *_utf8=NULL;                                  \
 
190
  _utf8=PyUnicode_AsUTF8String(obj);                     \
 
191
  if(_utf8)                                              \
 
192
    {                                                    \
 
193
      strbytes=PyBytes_GET_SIZE(_utf8);                  \
 
194
      strdata=PyBytes_AS_STRING(_utf8);                  \
 
195
    } 
 
196
 
 
197
#define UNIDATAEND(obj)                                  \
 
198
  Py_XDECREF(_utf8);                                     \
 
199
}
 
200
 
 
201
#define USE16(x) x
 
202
 
 
203
#endif /* Py_UNICODE_SIZE */
 
204
 
 
205
/* Converts sqlite3_value to PyObject.  Returns a new reference. */
 
206
static PyObject *
 
207
convert_value_to_pyobject(sqlite3_value *value)
 
208
{
 
209
  int coltype=sqlite3_value_type(value);
 
210
 
 
211
  APSW_FAULT_INJECT(UnknownValueType,,coltype=123456);
 
212
 
 
213
  switch(coltype)
 
214
    {
 
215
    case SQLITE_INTEGER:
 
216
      {
 
217
        sqlite3_int64 val=sqlite3_value_int64(value);
 
218
#if PY_MAJOR_VERSION<3
 
219
        if (val>=APSW_INT32_MIN && val<=APSW_INT32_MAX)
 
220
          return PyInt_FromLong((long)val);
 
221
#endif
 
222
        return PyLong_FromLongLong(val);
 
223
      }
 
224
 
 
225
    case SQLITE_FLOAT:
 
226
      return PyFloat_FromDouble(sqlite3_value_double(value));
 
227
      
 
228
    case SQLITE_TEXT:
 
229
      return convertutf8stringsize((const char*)sqlite3_value_text(value), sqlite3_value_bytes(value));
 
230
 
 
231
    case SQLITE_NULL:
 
232
      Py_RETURN_NONE;
 
233
 
 
234
    case SQLITE_BLOB:
 
235
      return converttobytes(sqlite3_value_blob(value), sqlite3_value_bytes(value));
 
236
 
 
237
    default:
 
238
      PyErr_Format(APSWException, "Unknown sqlite column type %d!", coltype);
 
239
      return NULL;
 
240
    }
 
241
  /* can't get here */
 
242
  assert(0);
 
243
  return NULL;
 
244
}
 
245
 
 
246
/* Converts column to PyObject.  Returns a new reference. Almost identical to above 
 
247
   but we cannot just use sqlite3_column_value and then call the above function as 
 
248
   SQLite doesn't allow that ("unprotected values") */
 
249
static PyObject *
 
250
convert_column_to_pyobject(sqlite3_stmt *stmt, int col)
 
251
{
 
252
  int coltype;
 
253
 
 
254
  _PYSQLITE_CALL_V(coltype=sqlite3_column_type(stmt, col));
 
255
 
 
256
  APSW_FAULT_INJECT(UnknownColumnType,,coltype=12348);
 
257
 
 
258
  switch(coltype)
 
259
    {
 
260
    case SQLITE_INTEGER:
 
261
      {
 
262
        sqlite3_int64 val;
 
263
        _PYSQLITE_CALL_V(val=sqlite3_column_int64(stmt, col));
 
264
#if PY_MAJOR_VERSION<3
 
265
        if (val>=APSW_INT32_MIN && val<=APSW_INT32_MAX)
 
266
          return PyInt_FromLong((long)val);
 
267
#endif
 
268
        return PyLong_FromLongLong(val);
 
269
      }
 
270
 
 
271
    case SQLITE_FLOAT:
 
272
      { 
 
273
        double d;
 
274
        _PYSQLITE_CALL_V(d=sqlite3_column_double(stmt, col));
 
275
        return PyFloat_FromDouble(d);
 
276
      }
 
277
    case SQLITE_TEXT:
 
278
      {
 
279
        const char *data;
 
280
        size_t len;
 
281
        _PYSQLITE_CALL_V( (data=(const char*)sqlite3_column_text(stmt, col), len=sqlite3_column_bytes(stmt, col)) );
 
282
        return convertutf8stringsize(data, len);
 
283
      }
 
284
 
 
285
    case SQLITE_NULL:
 
286
      Py_RETURN_NONE;
 
287
 
 
288
    case SQLITE_BLOB:
 
289
      {
 
290
        const void *data;
 
291
        size_t len;
 
292
        _PYSQLITE_CALL_V( (data=sqlite3_column_blob(stmt, col), len=sqlite3_column_bytes(stmt, col)) );
 
293
        return converttobytes(data, len);
 
294
      }
 
295
 
 
296
    default:
 
297
      PyErr_Format(APSWException, "Unknown sqlite column type %d!", coltype);
 
298
      return NULL;
 
299
    }
 
300
  /* can't get here */
 
301
  assert(0);
 
302
  return NULL;
 
303
}
 
304
 
 
305
 
 
306
/* Some macros used for frequent operations */
 
307
 
 
308
/* used by Connection and Cursor */
 
309
#define CHECK_USE(e)                                                \
 
310
  do \
 
311
  { if(self->inuse)                                                                                 \
 
312
      {    /* raise exception if we aren't already in one */                                                                         \
 
313
           if (!PyErr_Occurred())                                                                                                    \
 
314
             PyErr_Format(ExcThreadingViolation, "You are trying to use the same object concurrently in two threads which is not allowed."); \
 
315
           return e;                                                                                                                 \
 
316
      }                                                                                                                              \
 
317
  } while(0)
 
318
 
 
319
/* used by Connection */
 
320
#define CHECK_CLOSED(connection,e) do \
 
321
    { if(!(connection) || !(connection)->db) { PyErr_Format(ExcConnectionClosed, "The connection has been closed"); return e; } } while(0)
 
322
 
 
323
/* used by cursor */
 
324
#define CHECK_CURSOR_CLOSED(e)                                          \
 
325
  do                                                                    \
 
326
    {                                                                   \
 
327
      if(!self->connection)                                            \
 
328
        { PyErr_Format(ExcCursorClosed, "The cursor has been closed"); return e; } \
 
329
      else if(!self->connection->db)                                    \
 
330
        { PyErr_Format(ExcConnectionClosed, "The connection has been closed"); return e; } \
 
331
    } while(0)
 
332
         
 
333
/* It is 2009 - why do I have to write this? */
 
334
static char *apsw_strdup(const char *source)
 
335
{
 
336
  char *res=PyMem_Malloc(strlen(source)+1);
 
337
  if(res)
 
338
    strcpy(res, source);
 
339
  return res;
 
340
}