-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLiteLog.cs
executable file
·575 lines (498 loc) · 19.1 KB
/
SQLiteLog.cs
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace System.Data.SQLite
{
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
/// <summary>
/// Event data for logging event handlers.
/// </summary>
public class LogEventArgs : EventArgs
{
/// <summary>
/// The error code. The type of this object value should be
/// <see cref="Int32" /> or <see cref="SQLiteErrorCode" />.
/// </summary>
public readonly object ErrorCode;
/// <summary>
/// SQL statement text as the statement first begins executing
/// </summary>
public readonly string Message;
/// <summary>
/// Extra data associated with this event, if any.
/// </summary>
public readonly object Data;
/// <summary>
/// Constructs the object.
/// </summary>
/// <param name="pUserData">Should be null.</param>
/// <param name="errorCode">
/// The error code. The type of this object value should be
/// <see cref="Int32" /> or <see cref="SQLiteErrorCode" />.
/// </param>
/// <param name="message">The error message, if any.</param>
/// <param name="data">The extra data, if any.</param>
internal LogEventArgs(
IntPtr pUserData,
object errorCode,
string message,
object data
)
{
ErrorCode = errorCode;
Message = message;
Data = data;
}
}
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Raised when a log event occurs.
/// </summary>
/// <param name="sender">The current connection</param>
/// <param name="e">Event arguments of the trace</param>
public delegate void SQLiteLogEventHandler(object sender, LogEventArgs e);
///////////////////////////////////////////////////////////////////////////
/// <summary>
/// Manages the SQLite custom logging functionality and the associated
/// callback for the whole process.
/// </summary>
public static class SQLiteLog
{
/// <summary>
/// Object used to synchronize access to the static instance data
/// for this class.
/// </summary>
private static object syncRoot = new object();
///////////////////////////////////////////////////////////////////////
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// Member variable to store the AppDomain.DomainUnload event handler.
/// </summary>
private static EventHandler _domainUnload;
#endif
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Member variable to store the application log handler to call.
/// </summary>
private static event SQLiteLogEventHandler _handlers;
///////////////////////////////////////////////////////////////////////
/// <summary>
/// The default log event handler.
/// </summary>
private static SQLiteLogEventHandler _defaultHandler;
///////////////////////////////////////////////////////////////////////
#if !USE_INTEROP_DLL || !INTEROP_LOG
/// <summary>
/// The log callback passed to native SQLite engine. This must live
/// as long as the SQLite library has a pointer to it.
/// </summary>
private static SQLiteLogCallback _callback;
///////////////////////////////////////////////////////////////////////
/// <summary>
/// The base SQLite object to interop with.
/// </summary>
private static SQLiteBase _sql;
#endif
///////////////////////////////////////////////////////////////////////
/// <summary>
/// This will be non-zero if logging is currently enabled.
/// </summary>
private static bool _enabled;
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Initializes the SQLite logging facilities.
/// </summary>
public static void Initialize()
{
//
// BUFXIX: We cannot initialize the logging interface if the SQLite
// core library has already been initialized anywhere in
// the process (see ticket [2ce0870fad]).
//
if (SQLite3.StaticIsInitialized())
return;
#if !PLATFORM_COMPACTFRAMEWORK
//
// BUGFIX: To avoid nasty situations where multiple AppDomains are
// attempting to initialize and/or shutdown what is really
// a shared native resource (i.e. the SQLite core library
// is loaded per-process and has only one logging callback,
// not one per-AppDomain, which it knows nothing about),
// prevent all non-default AppDomains from registering a
// log handler unless the "Force_SQLiteLog" environment
// variable is used to manually override this safety check.
//
if (!AppDomain.CurrentDomain.IsDefaultAppDomain() &&
UnsafeNativeMethods.GetSettingValue("Force_SQLiteLog", null) == null)
{
return;
}
#endif
lock (syncRoot)
{
#if !PLATFORM_COMPACTFRAMEWORK
//
// NOTE: Add an event handler for the DomainUnload event so
// that we can unhook our logging managed function
// pointer from the native SQLite code prior to it
// being invalidated.
//
// BUGFIX: Make sure this event handler is only added one
// time (per-AppDomain).
//
if (_domainUnload == null)
{
_domainUnload = new EventHandler(DomainUnload);
AppDomain.CurrentDomain.DomainUnload += _domainUnload;
}
#endif
#if !USE_INTEROP_DLL || !INTEROP_LOG
//
// NOTE: Create an instance of the SQLite wrapper class.
//
if (_sql == null)
{
_sql = new SQLite3(
SQLiteDateFormats.Default, DateTimeKind.Unspecified,
null, IntPtr.Zero, null, false);
}
//
// NOTE: Create a single "global" (i.e. per-process) callback
// to register with SQLite. This callback will pass the
// event on to any registered handler. We only want to
// do this once.
//
if (_callback == null)
{
_callback = new SQLiteLogCallback(LogCallback);
SQLiteErrorCode rc = _sql.SetLogCallback(_callback);
if (rc != SQLiteErrorCode.Ok)
throw new SQLiteException(rc,
"Failed to initialize logging.");
}
#endif
//
// NOTE: Logging is enabled by default.
//
_enabled = true;
//
// NOTE: For now, always setup the default log event handler.
//
AddDefaultHandler();
}
}
///////////////////////////////////////////////////////////////////////
#if !PLATFORM_COMPACTFRAMEWORK
/// <summary>
/// Handles the AppDomain being unloaded.
/// </summary>
/// <param name="sender">Should be null.</param>
/// <param name="e">The data associated with this event.</param>
private static void DomainUnload(
object sender,
EventArgs e
)
{
lock (syncRoot)
{
//
// NOTE: Remove the default log event handler.
//
RemoveDefaultHandler();
//
// NOTE: Disable logging. If necessary, it can be re-enabled
// later by the Initialize method.
//
_enabled = false;
#if !USE_INTEROP_DLL || !INTEROP_LOG
//
// BUGBUG: This will cause serious problems if other AppDomains
// have any open SQLite connections; however, there is
// currently no way around this limitation.
//
if (_sql != null)
{
SQLiteErrorCode rc = _sql.Shutdown();
if (rc != SQLiteErrorCode.Ok)
throw new SQLiteException(rc,
"Failed to shutdown interface.");
rc = _sql.SetLogCallback(null);
if (rc != SQLiteErrorCode.Ok)
throw new SQLiteException(rc,
"Failed to shutdown logging.");
}
//
// BUGFIX: Make sure to reset the callback for next time. This
// must be done after it has been succesfully removed
// as logging callback by the SQLite core library as we
// cannot allow native code to refer to a delegate that
// has been garbage collected.
//
if (_callback != null)
{
_callback = null;
}
#endif
//
// NOTE: Remove the event handler for the DomainUnload event
// that we added earlier.
//
if (_domainUnload != null)
{
AppDomain.CurrentDomain.DomainUnload -= _domainUnload;
_domainUnload = null;
}
}
}
#endif
///////////////////////////////////////////////////////////////////////
/// <summary>
/// This event is raised whenever SQLite raises a logging event.
/// Note that this should be set as one of the first things in the
/// application.
/// </summary>
public static event SQLiteLogEventHandler Log
{
add
{
lock (syncRoot)
{
// Remove any copies of this event handler from registered
// list. This essentially means that a handler will be
// called only once no matter how many times it is added.
_handlers -= value;
// Add this to the list of event handlers.
_handlers += value;
}
}
remove
{
lock (syncRoot)
{
_handlers -= value;
}
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// If this property is true, logging is enabled; otherwise, logging is
/// disabled. When logging is disabled, no logging events will fire.
/// </summary>
public static bool Enabled
{
get { lock (syncRoot) { return _enabled; } }
set { lock (syncRoot) { _enabled = value; } }
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Log a message to all the registered log event handlers without going
/// through the SQLite library.
/// </summary>
/// <param name="message">The message to be logged.</param>
public static void LogMessage(
string message
)
{
LogMessage(null, message);
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Log a message to all the registered log event handlers without going
/// through the SQLite library.
/// </summary>
/// <param name="errorCode">The SQLite error code.</param>
/// <param name="message">The message to be logged.</param>
public static void LogMessage(
SQLiteErrorCode errorCode,
string message
)
{
LogMessage((object)errorCode, message);
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Log a message to all the registered log event handlers without going
/// through the SQLite library.
/// </summary>
/// <param name="errorCode">The integer error code.</param>
/// <param name="message">The message to be logged.</param>
public static void LogMessage(
int errorCode,
string message
)
{
LogMessage((object)errorCode, message);
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Log a message to all the registered log event handlers without going
/// through the SQLite library.
/// </summary>
/// <param name="errorCode">
/// The error code. The type of this object value should be
/// System.Int32 or SQLiteErrorCode.
/// </param>
/// <param name="message">The message to be logged.</param>
private static void LogMessage(
object errorCode,
string message
)
{
bool enabled;
SQLiteLogEventHandler handlers;
lock (syncRoot)
{
enabled = _enabled;
if (_handlers != null)
handlers = _handlers.Clone() as SQLiteLogEventHandler;
else
handlers = null;
}
if (enabled && (handlers != null))
handlers(null, new LogEventArgs(
IntPtr.Zero, errorCode, message, null));
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Creates and initializes the default log event handler.
/// </summary>
private static void InitializeDefaultHandler()
{
lock (syncRoot)
{
if (_defaultHandler == null)
_defaultHandler = new SQLiteLogEventHandler(LogEventHandler);
}
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Adds the default log event handler to the list of handlers.
/// </summary>
public static void AddDefaultHandler()
{
InitializeDefaultHandler();
Log += _defaultHandler;
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Removes the default log event handler from the list of handlers.
/// </summary>
public static void RemoveDefaultHandler()
{
InitializeDefaultHandler();
Log -= _defaultHandler;
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Internal proxy function that calls any registered application log
/// event handlers.
///
/// WARNING: This method is used more-or-less directly by native code,
/// do not modify its type signature.
/// </summary>
/// <param name="pUserData">
/// The extra data associated with this message, if any.
/// </param>
/// <param name="errorCode">
/// The error code associated with this message.
/// </param>
/// <param name="pMessage">
/// The message string to be logged.
/// </param>
private static void LogCallback(
IntPtr pUserData,
int errorCode,
IntPtr pMessage
)
{
bool enabled;
SQLiteLogEventHandler handlers;
lock (syncRoot)
{
enabled = _enabled;
if (_handlers != null)
handlers = _handlers.Clone() as SQLiteLogEventHandler;
else
handlers = null;
}
if (enabled && (handlers != null))
handlers(null, new LogEventArgs(pUserData, errorCode,
SQLiteBase.UTF8ToString(pMessage, -1), null));
}
///////////////////////////////////////////////////////////////////////
/// <summary>
/// Default logger. Currently, uses the Trace class (i.e. sends events
/// to the current trace listeners, if any).
/// </summary>
/// <param name="sender">Should be null.</param>
/// <param name="e">The data associated with this event.</param>
private static void LogEventHandler(
object sender,
LogEventArgs e
)
{
#if !NET_COMPACT_20
if (e == null)
return;
string message = e.Message;
if (message == null)
{
message = "<null>";
}
else
{
message = message.Trim();
if (message.Length == 0)
message = "<empty>";
}
object errorCode = e.ErrorCode;
string type = "error";
if ((errorCode is SQLiteErrorCode) || (errorCode is int))
{
SQLiteErrorCode rc = (SQLiteErrorCode)(int)errorCode;
rc &= SQLiteErrorCode.NonExtendedMask;
if (rc == SQLiteErrorCode.Ok)
{
type = "message";
}
else if (rc == SQLiteErrorCode.Notice)
{
type = "notice";
}
else if (rc == SQLiteErrorCode.Warning)
{
type = "warning";
}
else if ((rc == SQLiteErrorCode.Row) ||
(rc == SQLiteErrorCode.Done))
{
type = "data";
}
}
else if (errorCode == null)
{
type = "trace";
}
if ((errorCode != null) &&
!Object.ReferenceEquals(errorCode, String.Empty))
{
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture, "SQLite {0} ({1}): {2}",
type, errorCode, message));
}
else
{
Trace.WriteLine(HelperMethods.StringFormat(
CultureInfo.CurrentCulture, "SQLite {0}: {1}",
type, message));
}
#endif
}
}
}