forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cs
More file actions
595 lines (492 loc) · 22.5 KB
/
Connection.cs
File metadata and controls
595 lines (492 loc) · 22.5 KB
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// Copyright (c) Jeff Hardy 2010-2012.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using Community.CsharpSqlite;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using sqlite3_stmt = Community.CsharpSqlite.Sqlite3.Vdbe;
using sqlite3_value = Community.CsharpSqlite.Sqlite3.Mem;
namespace IronPython.SQLite
{
public static partial class PythonSQLite
{
[PythonType]
public class Connection
{
public bool autocommit = false;
public int total_changes { get { return Sqlite3.sqlite3_total_changes(this.db); } }
public int detect_types { get; set; }
public bool check_same_thread { get; set; }
private double _timeout;
public double timeout
{
get { return _timeout; }
set { _timeout = value; Sqlite3.sqlite3_busy_timeout(this.db, (int)(_timeout * 1000)); }
}
private string _isolation_level;
public string isolation_level
{
get { return _isolation_level; }
set { setIsolationLevel(value); }
}
public string begin_statement { get; private set; }
public object row_factory { get; set; }
public object text_factory { get; set; }
public IDictionary collations = new PythonDictionary();
private List<WeakReference> statements = new List<WeakReference>();
private int created_statements = 0;
private Dictionary<object, object> function_pinboard = new Dictionary<object, object>();
internal Sqlite3.sqlite3 db;
internal bool inTransaction = false;
internal int thread_ident = Thread.CurrentThread.ManagedThreadId;
private static readonly Dictionary<object, object> emptyKwargs= new Dictionary<object, object>();
public PythonType Warning = PythonSQLite.Warning;
public PythonType Error = PythonSQLite.Error;
public PythonType InterfaceError = PythonSQLite.InterfaceError;
public PythonType DataError = PythonSQLite.DataError;
public PythonType DatabaseError = PythonSQLite.DatabaseError;
public PythonType OperationalError = PythonSQLite.OperationalError;
public PythonType InternalError = PythonSQLite.InternalError;
public PythonType IntegrityError = PythonSQLite.IntegrityError;
public PythonType ProgrammingError = PythonSQLite.ProgrammingError;
public PythonType NotSupportedError = PythonSQLite.NotSupportedError;
private enum AllStatmentsAction
{
Reset, Finalize
}
public Connection(string database,
double timeout=0.0,
int detect_types=0,
string isolation_level=null,
bool check_same_thread=true,
object factory=null,
int cached_statements=0)
{
this.text_factory = typeof(string);
int rc = Sqlite3.sqlite3_open(database, out this.db);
if(rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
setIsolationLevel(isolation_level ?? "");
this.detect_types = detect_types;
this.timeout = timeout;
this.check_same_thread = check_same_thread;
}
~Connection()
{
if(this.db != null)
Sqlite3.sqlite3_close(this.db);
}
[Documentation("Closes the connection.")]
public void close()
{
checkThread();
doAllStatements(AllStatmentsAction.Finalize);
if(this.db != null)
{
int rc = Sqlite3.SQLITE_OK, i = 0;
do
{
rc = Sqlite3.sqlite3_close(this.db);
if(rc == Sqlite3.SQLITE_BUSY)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
} while(rc == Sqlite3.SQLITE_BUSY && i++ < 3);
if(rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
this.db = null;
}
}
internal void begin()
{
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, this.begin_statement, -1, ref statement, ref tail);
if(rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, statement);
rc = Util.Step(statement);
if(rc == Sqlite3.SQLITE_DONE)
this.inTransaction = true;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
if(rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
[Documentation("Commit the current transaction.")]
public void commit()
{
checkThread(); checkConnection();
if(inTransaction)
{
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, "COMMIT", -1, ref statement, ref tail);
if(rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
rc = Util.Step(statement);
if(rc == Sqlite3.SQLITE_DONE)
this.inTransaction = false;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
if(rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
}
[Documentation("Roll back the current transaction.")]
public void rollback()
{
checkThread(); checkConnection();
if(inTransaction)
{
doAllStatements(AllStatmentsAction.Reset);
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, "ROLLBACK", -1, ref statement, ref tail);
if(rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
rc = Util.Step(statement);
if(rc == Sqlite3.SQLITE_DONE)
this.inTransaction = false;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
if(rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
}
[Documentation("Return a cursor for the connection.")]
public object cursor(CodeContext context, object factory=null)
{
checkThread(); checkConnection();
object cursor = factory == null ? new Cursor(context, this) : PythonCalls.Call(context, factory, this);
if(this.row_factory != null)
context.LanguageContext.Operations.SetMember(cursor, "row_factory", this.row_factory);
return cursor;
}
[Documentation("Executes a SQL statement. Non-standard.")]
public object execute(CodeContext context, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args)
{
object c = cursor(context, null);
object execute = context.LanguageContext.Operations.GetMember(c, "execute");
return PythonCalls.CallWithKeywordArgs(context, execute, args, kwargs);
}
[Documentation("Repeatedly executes a SQL statement. Non-standard.")]
public object executemany(CodeContext context, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args)
{
object c = cursor(context, null);
object executemany = context.LanguageContext.Operations.GetMember(c, "executemany");
return PythonCalls.CallWithKeywordArgs(context, executemany, args, kwargs);
}
[Documentation("Executes a multiple SQL statements at once. Non-standard.")]
public object executescript(CodeContext context, [ParamDictionary]IDictionary<object, object> kwargs, params object[] args)
{
object c = cursor(context, null);
object executescript = context.LanguageContext.Operations.GetMember(c, "executescript");
return PythonCalls.CallWithKeywordArgs(context, executescript, args, kwargs);
}
public object __call__(string sql)
{
dropUnusedStatementReferences();
Statement statement = new Statement(this, sql);
this.statements.Add(new WeakReference(statement));
return statement;
}
private void dropUnusedStatementReferences()
{
if(this.created_statements++ < 200)
return;
this.created_statements = 0;
List<WeakReference> new_list = new List<WeakReference>();
foreach(WeakReference weakref in this.statements)
if(weakref.IsAlive)
new_list.Add(weakref);
this.statements = new_list;
}
#region User functions
[Documentation("Creates a new function. Non-standard.")]
public void create_function(CodeContext context, string name, int narg, object func)
{
int rc = Sqlite3.sqlite3_create_function(this.db,
name, narg,
Sqlite3.SQLITE_ANY,
new object[] { context, func },
callUserFunction,
null, null);
if(rc != Sqlite3.SQLITE_OK)
throw MakeOperationalError("Error creating function");
else
this.function_pinboard[func] = null;
}
private static void callUserFunction(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv)
{
object[] data = (object[])Sqlite3.sqlite3_user_data(ctx);
CodeContext context = (CodeContext)data[0];
object func = data[1];
object[] args = buildPyParams(context, ctx, argc, argv);
try
{
object result = PythonCalls.CallWithKeywordArgs(context, func, args, emptyKwargs);
setResult(ctx, result);
}
catch(Exception)
{
Sqlite3.sqlite3_result_error(ctx, "user-defined function raised exception", -1);
}
}
private static object[] buildPyParams(CodeContext context, Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv)
{
object[] args = new object[argc];
for(int i = 0; i < argc; ++i)
{
sqlite3_value cur_value = argv[i];
object cur_py_value = null;
switch(Sqlite3.sqlite3_value_type(cur_value))
{
case Sqlite3.SQLITE_INTEGER:
cur_py_value = (int)Sqlite3.sqlite3_value_int64(cur_value);
break;
case Sqlite3.SQLITE_FLOAT:
cur_py_value = Sqlite3.sqlite3_value_double(cur_value);
break;
case Sqlite3.SQLITE_TEXT:
cur_py_value = Sqlite3.sqlite3_value_text(cur_value);
break;
case Sqlite3.SQLITE_BLOB:
cur_py_value = new Bytes(Sqlite3.sqlite3_value_blob(cur_value)); // TODO: avoid creating a copy
break;
case Sqlite3.SQLITE_NULL:
default:
cur_py_value = null;
break;
}
args[i] = cur_py_value;
}
return args;
}
private static void setResult(Sqlite3.sqlite3_context ctx, object result)
{
if(result == null)
Sqlite3.sqlite3_result_null(ctx);
else if(result is bool)
Sqlite3.sqlite3_result_int64(ctx, ((bool)result) ? 1 : 0);
else if(result is int)
Sqlite3.sqlite3_result_int64(ctx, (int)result);
else if(result is long)
Sqlite3.sqlite3_result_int64(ctx, (long)result);
else if (result is System.Numerics.BigInteger)
Sqlite3.sqlite3_result_int64(ctx, (long)(System.Numerics.BigInteger)result);
else if(result is float)
Sqlite3.sqlite3_result_double(ctx, (float)result);
else if(result is double)
Sqlite3.sqlite3_result_double(ctx, (double)result);
else if(result is string)
Sqlite3.sqlite3_result_text(ctx, (string)result, -1, Sqlite3.SQLITE_TRANSIENT);
else if(result is byte[])
{
byte[] b = (byte[])result;
string s = Latin1.GetString(b, 0, b.Length);
Sqlite3.sqlite3_result_blob(ctx, s, s.Length, Sqlite3.SQLITE_TRANSIENT);
}
else
{
// TODO raise error
}
}
#endregion
#region User aggregates
private class UserAggregateThunk
{
public UserAggregateThunk(CodeContext context, string name, object aggregate_class)
{
this.context = context;
this.aggregate_class = aggregate_class;
this.name = name;
}
public void stepCallback(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] param)
{
if(instance == null)
{
try
{
instance = PythonCalls.Call(context, aggregate_class);
}
catch(Exception)
{
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's '__init__' method raised error", -1);
return;
}
}
try
{
object step = context.LanguageContext.Operations.GetMember(instance, "step");
object[] args = buildPyParams(context, ctx, argc, param);
PythonCalls.CallWithKeywordArgs(context, step, args, new Dictionary<object, object>());
}
catch(Exception e)
{
if(e is MissingMemberException)
throw;
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's 'step' method raised error", -1);
}
}
public void finalCallback(Sqlite3.sqlite3_context ctx)
{
if(instance == null)
return;
try
{
object function_result = context.LanguageContext.Operations.InvokeMember(instance, "finalize");
setResult(ctx, function_result);
}
catch(Exception)
{
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's 'finalize' method raised error", -1);
}
}
private CodeContext context;
private string name;
private object aggregate_class;
private object instance;
}
[Documentation("Creates a new aggregate. Non-standard.")]
public void create_aggregate(CodeContext context, string name, int n_arg, object aggregate_class)
{
UserAggregateThunk thunk = new UserAggregateThunk(context, name, aggregate_class);
int rc = Sqlite3.sqlite3_create_function(this.db,
name, n_arg,
Sqlite3.SQLITE_ANY,
thunk,
null,
thunk.stepCallback,
thunk.finalCallback);
if(rc != Sqlite3.SQLITE_OK)
throw MakeOperationalError("Error creating aggregate");
else
this.function_pinboard[aggregate_class] = null;
}
#endregion
[Documentation("Creates a collation function. Non-standard.")]
public void create_collation(params object[] args)
{
throw new NotImplementedException();
}
[Documentation("Sets progress handler callback. Non-standard.")]
public void set_progress_handler(params object[] args)
{
throw new NotImplementedException();
}
[Documentation("Sets authorizer callback. Non-standard.")]
public void set_authorizer(params object[] args)
{
throw new NotImplementedException();
}
[Documentation("For context manager. Non-standard.")]
public object __enter__()
{
return this;
}
[Documentation("For context manager. Non-standard.")]
public object __exit__(CodeContext context, object exc_type, object exc_value, object exc_tb)
{
DynamicOperations ops = context.LanguageContext.Operations;
if(exc_type == null && exc_value == null && exc_tb == null)
{
object commitfn;
if(ops.TryGetMember(this, "commit", out commitfn))
ops.Invoke(commitfn);
else
commit();
}
else
{
object rollbackfn;
if(ops.TryGetMember(this, "rollback", out rollbackfn))
ops.Invoke(rollbackfn);
else
rollback();
}
return false;
}
public object iterdump(CodeContext context)
{
throw new NotImplementedException("Not supported with C#-sqlite for unknown reasons.");
//var ops = context.LanguageContext.Operations;
//PythonModule sqlite3 = Importer.ImportModule(context, context.GlobalScope, "sqlite3", false, -1) as PythonModule;
//PythonModule dump = Importer.ImportFrom(context, sqlite3, "dump") as PythonModule;
//object _iterdump = ops.GetMember(dump, "_iterdump");
//object result = ops.Invoke(_iterdump, this);
//return result;
}
internal void checkConnection()
{
if(this.db == null)
throw MakeProgrammingError("Cannot operate on a closed database.");
}
internal void checkThread()
{
if(this.check_same_thread)
if(this.thread_ident != System.Threading.Thread.CurrentThread.ManagedThreadId)
throw MakeProgrammingError("SQLite objects created in a thread can only be used in that same thread." +
"The object was created in thread id {0} and this is thread id {1}".Format(
this.thread_ident, System.Threading.Thread.CurrentThread.ManagedThreadId));
}
internal static void verify(Connection connection)
{
verify(connection, false);
}
internal static void verify(Connection connection, bool closed)
{
if(!closed && (connection == null || connection.db == null))
throw MakeProgrammingError("Cannot operate on a closed database.");
connection.checkThread();
}
private void setIsolationLevel(string isolation_level)
{
this.begin_statement = null;
if(isolation_level == null)
{
this._isolation_level = null;
this.commit();
this.inTransaction = false;
}
else
{
this._isolation_level = isolation_level;
this.begin_statement = "BEGIN " + isolation_level;
}
}
private void doAllStatements(AllStatmentsAction action)
{
foreach(WeakReference weakref in this.statements)
{
if(weakref.IsAlive)
{
Statement statement = weakref.Target as Statement;
if(statement != null)
{
if(action == AllStatmentsAction.Reset)
statement.Reset();
else
statement.SqliteFinalize();
}
}
}
}
}
}
}