-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsweepea.pyx
3041 lines (2462 loc) · 91.3 KB
/
sweepea.pyx
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from cpython cimport datetime
from cpython.bytes cimport PyBytes_Check
from cpython.mem cimport PyMem_Free
from cpython.object cimport PyObject
from cpython.ref cimport Py_INCREF, Py_DECREF
from cpython.unicode cimport PyUnicode_AsUTF8String
from cpython.unicode cimport PyUnicode_Check
from libc.float cimport DBL_MAX
from libc.math cimport log, sqrt
from libc.stdint cimport uint8_t
from libc.stdint cimport uint32_t
from libc.stdlib cimport free, malloc, rand
from libc.string cimport memcpy, memset
from collections import namedtuple
from contextlib import contextmanager
from functools import partial
try:
from functools import reduce
except ImportError:
pass
from random import randint
import decimal
import hashlib
import itertools
import logging
import operator
import re
import sqlite3 as pysqlite
import struct
import threading
import uuid
import zlib
from sqlite3 import DatabaseError
from sqlite3 import InterfaceError
from sqlite3 import OperationalError
from sweepea cimport *
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logger = logging.getLogger('sweepea')
logger.addHandler(NullHandler())
# We define an xConnect function, but leave xCreate NULL so that the
# table-function can be called eponymously.
cdef int pwConnect(sqlite3 *db, void *pAux, int argc, char **argv,
sqlite3_vtab **ppVtab, char **pzErr) noexcept with gil:
cdef:
int rc
object table_func_cls = <object>pAux
sweepea_vtab *pNew
rc = sqlite3_declare_vtab(
db,
encode('CREATE TABLE x(%s);' %
table_func_cls.get_table_columns_declaration()))
if rc == SQLITE_OK:
pNew = <sweepea_vtab *>sqlite3_malloc(sizeof(pNew[0]))
memset(<char *>pNew, 0, sizeof(pNew[0]))
ppVtab[0] = &(pNew.base)
pNew.table_func_cls = <void *>table_func_cls
Py_INCREF(table_func_cls)
return rc
cdef int pwDisconnect(sqlite3_vtab *pBase) noexcept with gil:
cdef:
sweepea_vtab *pVtab = <sweepea_vtab *>pBase
object table_func_cls = <object>(pVtab.table_func_cls)
Py_DECREF(table_func_cls)
sqlite3_free(pVtab)
return SQLITE_OK
# The xOpen method is used to initialize a cursor. In this method we
# instantiate the TableFunction class and zero out a new cursor for iteration.
cdef int pwOpen(sqlite3_vtab *pBase, sqlite3_vtab_cursor **ppCursor) noexcept with gil:
cdef:
sweepea_vtab *pVtab = <sweepea_vtab *>pBase
sweepea_cursor *pCur
object table_func_cls = <object>pVtab.table_func_cls
pCur = <sweepea_cursor *>sqlite3_malloc(sizeof(pCur[0]))
memset(<char *>pCur, 0, sizeof(pCur[0]))
ppCursor[0] = &(pCur.base)
pCur.idx = 0
table_func = table_func_cls()
Py_INCREF(table_func)
pCur.table_func = <void *>table_func
pCur.stopped = False
return SQLITE_OK
cdef int pwClose(sqlite3_vtab_cursor *pBase) noexcept with gil:
cdef:
sweepea_cursor *pCur = <sweepea_cursor *>pBase
object table_func = <object>pCur.table_func
Py_DECREF(table_func)
sqlite3_free(pCur)
return SQLITE_OK
# Iterate once, advancing the cursor's index and assigning the row data to the
# `row_data` field on the sweepea_cursor struct.
cdef int pwNext(sqlite3_vtab_cursor *pBase) noexcept with gil:
cdef:
sweepea_cursor *pCur = <sweepea_cursor *>pBase
object table_func = <object>pCur.table_func
tuple result
if pCur.row_data:
Py_DECREF(<tuple>pCur.row_data)
try:
result = table_func.iterate(pCur.idx)
except StopIteration:
pCur.stopped = True
except:
return SQLITE_ERROR
else:
Py_INCREF(result)
pCur.row_data = <void *>result
pCur.idx += 1
pCur.stopped = False
return SQLITE_OK
# Return the requested column from the current row.
cdef int pwColumn(sqlite3_vtab_cursor *pBase, sqlite3_context *ctx,
int iCol) noexcept with gil:
cdef:
bytes bval
sweepea_cursor *pCur = <sweepea_cursor *>pBase
sqlite3_int64 x = 0
tuple row_data
if iCol == -1:
sqlite3_result_int64(ctx, <sqlite3_int64>pCur.idx)
return SQLITE_OK
row_data = <tuple>pCur.row_data
value = row_data[iCol]
if value is None:
sqlite3_result_null(ctx)
elif isinstance(value, (int, long)):
sqlite3_result_int64(ctx, <sqlite3_int64>value)
elif isinstance(value, float):
sqlite3_result_double(ctx, <double>value)
elif isinstance(value, basestring):
bval = encode(value)
sqlite3_result_text(
ctx,
<const char *>bval,
-1,
<sqlite3_destructor_type>-1)
elif isinstance(value, bool):
sqlite3_result_int(ctx, int(value))
else:
sqlite3_result_error(
ctx,
encode('Unsupported type %s' % type(value)),
-1)
return SQLITE_ERROR
return SQLITE_OK
cdef int pwRowid(sqlite3_vtab_cursor *pBase, sqlite3_int64 *pRowid) noexcept:
cdef:
sweepea_cursor *pCur = <sweepea_cursor *>pBase
pRowid[0] = <sqlite3_int64>pCur.idx
return SQLITE_OK
# Return a boolean indicating whether the cursor has been consumed.
cdef int pwEof(sqlite3_vtab_cursor *pBase) noexcept:
cdef:
sweepea_cursor *pCur = <sweepea_cursor *>pBase
if pCur.stopped:
return 1
return 0
# The filter method is called on the first iteration. This method is where we
# get access to the parameters that the function was called with, and call the
# TableFunction's `initialize()` function.
cdef int pwFilter(sqlite3_vtab_cursor *pBase, int idxNum,
const char *idxStr, int argc, sqlite3_value **argv) noexcept with gil:
cdef:
sweepea_cursor *pCur = <sweepea_cursor *>pBase
object table_func = <object>pCur.table_func
dict query = {}
int idx
int value_type
tuple row_data
void *row_data_raw
if not idxStr or argc == 0 and len(table_func.params):
return SQLITE_ERROR
elif idxStr:
params = decode(idxStr).split(',')
else:
params = []
for idx, param in enumerate(params):
value = argv[idx]
if not value:
query[param] = None
continue
value_type = sqlite3_value_type(value)
if value_type == SQLITE_INTEGER:
query[param] = sqlite3_value_int(value)
elif value_type == SQLITE_FLOAT:
query[param] = sqlite3_value_double(value)
elif value_type == SQLITE_TEXT:
query[param] = decode(sqlite3_value_text(value))
elif value_type == SQLITE_BLOB:
query[param] = <bytes>sqlite3_value_blob(value)
elif value_type == SQLITE_NULL:
query[param] = None
else:
query[param] = None
table_func.initialize(**query)
pCur.stopped = False
try:
row_data = table_func.iterate(0)
except StopIteration:
pCur.stopped = True
else:
Py_INCREF(row_data)
pCur.row_data = <void *>row_data
pCur.idx += 1
return SQLITE_OK
# SQLite will (in some cases, repeatedly) call the xBestIndex method to try and
# find the best query plan.
cdef int pwBestIndex(sqlite3_vtab *pBase, sqlite3_index_info *pIdxInfo) \
noexcept with gil:
cdef:
int i
int idxNum = 0, nArg = 0
sweepea_vtab *pVtab = <sweepea_vtab *>pBase
object table_func_cls = <object>pVtab.table_func_cls
sqlite3_index_constraint *pConstraint
list columns = []
char *idxStr
int nParams = len(table_func_cls.params)
pConstraint = <sqlite3_index_constraint*>0
for i in range(pIdxInfo.nConstraint):
pConstraint = &pIdxInfo.aConstraint[i]
if not pConstraint.usable:
continue
if pConstraint.op != SQLITE_INDEX_CONSTRAINT_EQ:
continue
columns.append(table_func_cls.params[pConstraint.iColumn -
table_func_cls._ncols])
nArg += 1
pIdxInfo.aConstraintUsage[i].argvIndex = nArg
pIdxInfo.aConstraintUsage[i].omit = 1
if nArg > 0:
if nArg == nParams:
# All parameters are present, this is ideal.
pIdxInfo.estimatedCost = <double>1
pIdxInfo.estimatedRows = 10
else:
# Penalize score based on number of missing params.
pIdxInfo.estimatedCost = <double>10000000000000 * <double>(nParams - nArg)
pIdxInfo.estimatedRows = 10 * (nParams - nArg)
# Store a reference to the columns in the index info structure.
joinedCols = encode(','.join(columns))
idxStr = <char *>sqlite3_malloc((len(joinedCols) + 1) * sizeof(char))
memcpy(idxStr, <char *>joinedCols, len(joinedCols))
idxStr[len(joinedCols)] = '\x00'
pIdxInfo.idxStr = idxStr
pIdxInfo.needToFreeIdxStr = 0
else:
pIdxInfo.estimatedCost = DBL_MAX
pIdxInfo.estimatedRows = 100000
return SQLITE_OK
cdef class _TableFunctionImpl(object):
cdef:
sqlite3_module module
object table_function
def __cinit__(self, table_function):
self.table_function = table_function
cdef create_module(self, pysqlite_Connection* sqlite_conn):
cdef:
bytes name = encode(self.table_function.name)
sqlite3 *db = sqlite_conn.db
int rc
# Populate the SQLite module struct members.
self.module.iVersion = 0
self.module.xCreate = NULL
self.module.xConnect = pwConnect
self.module.xBestIndex = pwBestIndex
self.module.xDisconnect = pwDisconnect
self.module.xDestroy = NULL
self.module.xOpen = pwOpen
self.module.xClose = pwClose
self.module.xFilter = pwFilter
self.module.xNext = pwNext
self.module.xEof = pwEof
self.module.xColumn = pwColumn
self.module.xRowid = pwRowid
self.module.xUpdate = NULL
self.module.xBegin = NULL
self.module.xSync = NULL
self.module.xCommit = NULL
self.module.xRollback = NULL
self.module.xFindFunction = NULL
self.module.xRename = NULL
# Create the SQLite virtual table.
rc = sqlite3_create_module(
db,
<const char *>name,
&self.module,
<void *>(self.table_function))
Py_INCREF(self)
return rc == SQLITE_OK
class TableFunction(object):
columns = None
params = None
name = None
_ncols = None
@classmethod
def register(cls, conn):
cdef _TableFunctionImpl impl = _TableFunctionImpl(cls)
impl.create_module(<pysqlite_Connection *>conn)
cls._ncols = len(cls.columns)
def initialize(self, **filters):
raise NotImplementedError
def iterate(self, idx):
raise NotImplementedError
@classmethod
def get_table_columns_declaration(cls):
cdef list accum = []
for column in cls.columns:
if isinstance(column, tuple):
if len(column) != 2:
raise ValueError('Column must be either a string or a '
'2-tuple of name, type')
accum.append('%s %s' % column)
else:
accum.append(column)
for param in cls.params:
accum.append('%s HIDDEN' % param)
return ', '.join(accum)
cdef double *get_weights(int ncol, tuple raw_weights):
cdef:
int argc = len(raw_weights)
int icol
double *weights = <double *>malloc(sizeof(double) * ncol)
for icol in range(ncol):
if argc == 0:
weights[icol] = 1.0
elif icol < argc:
weights[icol] = <double>raw_weights[icol]
else:
weights[icol] = 0.0
return weights
def rank(py_match_info, *raw_weights):
cdef:
unsigned int *match_info
unsigned int *phrase_info
bytes _match_info_buf = bytes(py_match_info)
char *match_info_buf = _match_info_buf
int nphrase, ncol, icol, iphrase, hits, global_hits
int P_O = 0, C_O = 1, X_O = 2
double score = 0.0, weight
double *weights
match_info = <unsigned int *>match_info_buf
nphrase = match_info[P_O]
ncol = match_info[C_O]
weights = get_weights(ncol, raw_weights)
# matchinfo X value corresponds to, for each phrase in the search query, a
# list of 3 values for each column in the search table.
# So if we have a two-phrase search query and three columns of data, the
# following would be the layout:
# p0 : c0=[0, 1, 2], c1=[3, 4, 5], c2=[6, 7, 8]
# p1 : c0=[9, 10, 11], c1=[12, 13, 14], c2=[15, 16, 17]
for iphrase in range(nphrase):
phrase_info = &match_info[X_O + iphrase * ncol * 3]
for icol in range(ncol):
weight = weights[icol]
if weight == 0:
continue
# The idea is that we count the number of times the phrase appears
# in this column of the current row, compared to how many times it
# appears in this column across all rows. The ratio of these values
# provides a rough way to score based on "high value" terms.
hits = phrase_info[3 * icol]
global_hits = phrase_info[3 * icol + 1]
if hits > 0:
score += weight * (<double>hits / <double>global_hits)
free(weights)
return -1 * score
def lucene(py_match_info, *raw_weights):
# Usage: peewee_lucene(matchinfo(table, 'pcnalx'), 1)
cdef:
unsigned int *match_info
bytes _match_info_buf = bytes(py_match_info)
char *match_info_buf = _match_info_buf
int nphrase, ncol
double total_docs, term_frequency
double doc_length, docs_with_term, avg_length
double idf, weight, rhs, denom
double *weights
int P_O = 0, C_O = 1, N_O = 2, L_O, X_O
int iphrase, icol, x
double score = 0.0
match_info = <unsigned int *>match_info_buf
nphrase = match_info[P_O]
ncol = match_info[C_O]
total_docs = match_info[N_O]
L_O = 3 + ncol
X_O = L_O + ncol
weights = get_weights(ncol, raw_weights)
for iphrase in range(nphrase):
for icol in range(ncol):
weight = weights[icol]
if weight == 0:
continue
doc_length = match_info[L_O + icol]
x = X_O + (3 * (icol + iphrase * ncol))
term_frequency = match_info[x] # f(qi)
docs_with_term = match_info[x + 2] or 1. # n(qi)
idf = log(total_docs / (docs_with_term + 1.))
tf = sqrt(term_frequency)
fieldNorms = 1.0 / sqrt(doc_length)
score += (idf * tf * fieldNorms)
free(weights)
return -1 * score
def bm25(py_match_info, *raw_weights):
# Usage: peewee_bm25(matchinfo(table, 'pcnalx'), 1)
# where the second parameter is the index of the column and
# the 3rd and 4th specify k and b.
cdef:
unsigned int *match_info
bytes _match_info_buf = bytes(py_match_info)
char *match_info_buf = _match_info_buf
int nphrase, ncol
double B = 0.75, K = 1.2
double total_docs, term_frequency
double doc_length, docs_with_term, avg_length
double idf, weight, ratio, num, b_part, denom, pc_score
double *weights
int P_O = 0, C_O = 1, N_O = 2, A_O = 3, L_O, X_O
int iphrase, icol, x
double score = 0.0
match_info = <unsigned int *>match_info_buf
# PCNALX = matchinfo format.
# P = 1 = phrase count within query.
# C = 1 = searchable columns in table.
# N = 1 = total rows in table.
# A = c = for each column, avg number of tokens
# L = c = for each column, length of current row (in tokens)
# X = 3 * c * p = for each phrase and table column,
# * phrase count within column for current row.
# * phrase count within column for all rows.
# * total rows for which column contains phrase.
nphrase = match_info[P_O] # n
ncol = match_info[C_O]
total_docs = match_info[N_O] # N
L_O = A_O + ncol
X_O = L_O + ncol
weights = get_weights(ncol, raw_weights)
for iphrase in range(nphrase):
for icol in range(ncol):
weight = weights[icol]
if weight == 0:
continue
x = X_O + (3 * (icol + iphrase * ncol))
term_frequency = match_info[x] # f(qi, D)
docs_with_term = match_info[x + 2] # n(qi)
# log( (N - n(qi) + 0.5) / (n(qi) + 0.5) )
idf = log(
(total_docs - docs_with_term + 0.5) /
(docs_with_term + 0.5))
if idf <= 0.0:
idf = 1e-6
doc_length = match_info[L_O + icol] # |D|
avg_length = match_info[A_O + icol] # avgdl
if avg_length == 0:
avg_length = 1
ratio = doc_length / avg_length
num = term_frequency * (K + 1)
b_part = 1 - B + (B * ratio)
denom = term_frequency + (K * b_part)
pc_score = idf * (num / denom)
score += (pc_score * weight)
free(weights)
return -1 * score
cdef uint32_t murmurhash2(const unsigned char *key, ssize_t nlen,
uint32_t seed):
cdef:
uint32_t m = 0x5bd1e995
int r = 24
const unsigned char *data = key
uint32_t h = seed ^ nlen
uint32_t k
while nlen >= 4:
k = <uint32_t>((<uint32_t *>data)[0])
k *= m
k = k ^ (k >> r)
k *= m
h *= m
h = h ^ k
data += 4
nlen -= 4
if nlen == 3:
h = h ^ (data[2] << 16)
if nlen >= 2:
h = h ^ (data[1] << 8)
if nlen >= 1:
h = h ^ (data[0])
h *= m
h = h ^ (h >> 13)
h *= m
h = h ^ (h >> 15)
return h
def murmurhash(key, seed=None):
if key is None:
return
cdef:
bytes bkey
int nseed = seed or 0
if isinstance(key, unicode):
bkey = <bytes>key.encode('utf-8')
else:
bkey = <bytes>key
if key:
return murmurhash2(<unsigned char *>bkey, len(bkey), nseed)
return 0
cdef bint regexp(basestring value, basestring regex):
# Expose regular expression matching in SQLite.
return re.search(regex, value, re.I) is not None
def make_hash(hash_impl):
def inner(*items):
state = hash_impl()
for item in items:
state.update(encode(item))
return state.hexdigest()
return inner
hash_md5 = make_hash(hashlib.md5)
hash_sha1 = make_hash(hashlib.sha1)
hash_sha256 = make_hash(hashlib.sha256)
cdef class median(object):
cdef:
int ct
list items
def __init__(self):
self.ct = 0
self.items = []
cdef selectKth(self, int k, int s=0, int e=-1):
cdef:
int idx
if e < 0:
e = len(self.items)
idx = randint(s, e-1)
idx = self.partition_k(idx, s, e)
if idx > k:
return self.selectKth(k, s, idx)
elif idx < k:
return self.selectKth(k, idx + 1, e)
else:
return self.items[idx]
cdef int partition_k(self, int pi, int s, int e):
cdef:
int i, x
val = self.items[pi]
# Swap pivot w/last item.
self.items[e - 1], self.items[pi] = self.items[pi], self.items[e - 1]
x = s
for i in range(s, e):
if self.items[i] < val:
self.items[i], self.items[x] = self.items[x], self.items[i]
x += 1
self.items[x], self.items[e-1] = self.items[e-1], self.items[x]
return x
def step(self, item):
self.items.append(item)
self.ct += 1
def finalize(self):
if self.ct == 0:
return None
elif self.ct < 3:
return self.items[0]
else:
return self.selectKth(self.ct // 2)
def _register_functions(database, pairs):
for func, name in pairs:
database.func(name)(func)
def register_hash_functions(database):
_register_functions(database, (
(murmurhash, 'murmurhash'),
(hash_md5, 'md5'),
(hash_sha1, 'sha1'),
(hash_sha256, 'sha256'),
(zlib.adler32, 'adler32'),
(zlib.crc32, 'crc32')))
def register_rank_functions(database):
_register_functions(database, (
(bm25, 'fts_bm25'),
(lucene, 'fts_lucene'),
(rank, 'fts_rank')))
class DateSeries(TableFunction):
params = ['start', 'stop', 'step_seconds']
columns = ['date']
name = 'date_series'
def initialize(self, start, stop, step_seconds=86400):
self.start = format_datetime(start)
self.stop = format_datetime(stop)
self.step_seconds_i = int(step_seconds)
self.step_seconds = datetime.timedelta(seconds=self.step_seconds_i)
self.format = self.get_format()
def get_format(self):
if self.is_zero_time(self.start) and self.step_seconds_i >= 86400:
return '%Y-%m-%d'
elif self.is_zero_date(self.start) and self.is_zero_date(self.stop) \
and self.step_seconds_i < 86400:
return '%H:%M:%S'
else:
return '%Y-%m-%d %H:%M:%S'
def is_zero_time(self, dt):
return dt.hour == dt.minute == dt.second == 0
def is_zero_date(self, dt):
return (dt.year, dt.month, dt.day) == (1900, 1, 1)
def iterate(self, idx):
if self.start > self.stop:
raise StopIteration
current = self.start
self.start += self.step_seconds
return (current.strftime(self.format),)
cdef int _aggressive_busy_handler(void *ptr, int n) noexcept nogil:
# In concurrent environments, it often seems that if multiple queries are
# kicked off at around the same time, they proceed in lock-step to check
# for the availability of the lock. By introducing some "jitter" we can
# ensure that this doesn't happen. Furthermore, this function makes more
# attempts in the same time period than the default handler.
cdef:
int busyTimeout = <int>ptr
int current, total
if n < 20:
current = 25 - (rand() % 10) # ~20ms
total = n * 20
elif n < 40:
current = 50 - (rand() % 20) # ~40ms
total = 400 + ((n - 20) * 40)
else:
current = 120 - (rand() % 40) # ~100ms
total = 1200 + ((n - 40) * 100) # Estimate the amount of time slept.
if total + current > busyTimeout:
current = busyTimeout - total
if current > 0:
sqlite3_sleep(current)
return 1
return 0
class DoesNotExist(Exception): pass
cdef class CursorWrapper(object) # Forward declaration.
cdef class ResultIterator(object):
cdef:
CursorWrapper cursor_wrapper
int index
def __init__(self, cursor_wrapper):
self.cursor_wrapper = cursor_wrapper
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < self.cursor_wrapper.count:
obj = self.cursor_wrapper.result_cache[self.index]
elif not self.cursor_wrapper.is_populated:
self.cursor_wrapper.iterate()
obj = self.cursor_wrapper.result_cache[self.index]
else:
raise StopIteration
self.index += 1
return obj
next = __next__
cdef class CursorWrapper(object):
cdef:
bint is_initialized, is_populated
int count
list columns, result_cache
object cursor
def __init__(self, cursor):
self.cursor = cursor
self.count = 0
self.is_initialized = False
self.is_populated = False
self.result_cache = []
def __iter__(self):
if self.is_populated:
return iter(self.result_cache)
return ResultIterator(self)
def __getitem__(self, item):
if isinstance(item, slice):
stop = item.stop
if stop is None or stop < 0:
self.fill_cache()
else:
self.fill_cache(stop)
return self.result_cache[item]
elif isinstance(item, int):
fill_line = item + 1 if item >= 0 else item
self.fill_cache(fill_line)
return self.result_cache[item]
else:
raise ValueError('CursorWrapper only supports integer and slice '
'indexes.')
def __len__(self):
self.fill_cache()
return self.count
cdef initialize(self):
self.columns = [col[0][col[0].find('.') + 1:]
for col in self.cursor.description]
def iterate(self, cache=True):
cdef:
tuple row = self.cursor.fetchone()
if row is None:
self.is_populated = True
self.cursor.close()
raise StopIteration
elif not self.is_initialized:
self.initialize() # Lazy initialization.
self.is_initialized = True
self.count += 1
result = self.transform(row)
if cache:
self.result_cache.append(result)
return result
cdef transform(self, tuple row):
return row
def iterator(self):
while True:
yield self.iterate(cache=False)
cpdef fill_cache(self, n=None):
cdef:
int counter = -1 if n is None else <int>n
ResultIterator iterator = ResultIterator(self)
iterator.index = self.count
while not self.is_populated and (counter < 0 or counter > self.count):
try:
iterator.next()
except StopIteration:
break
cpdef first(self):
if not self.is_populated:
self.fill_cache(1)
if self.result_cache:
return self.result_cache[0]
cpdef get(self):
obj = self.first()
if obj is None:
raise DoesNotExist('No objects found matching this query.')
else:
return obj
cpdef scalar(self):
return self.get()[0]
cdef class DictCursorWrapper(CursorWrapper):
cdef transform(self, tuple row):
cdef:
basestring column
dict accum = {}
int i
for i, column in enumerate(self.columns):
accum[column] = row[i]
return accum
cdef class NamedTupleCursorWrapper(CursorWrapper):
cdef:
object tuple_class
cdef initialize(self):
CursorWrapper.initialize(self)
self.tuple_class = namedtuple('Row', self.columns)
cdef transform(self, tuple row):
return self.tuple_class(*row)
cdef class ObjectCursorWrapper(DictCursorWrapper):
cdef:
public object constructor
def __init__(self, cursor, constructor):
super(ObjectCursorWrapper, self).__init__(cursor)
self.constructor = constructor
cdef transform(self, tuple row):
cdef:
dict accum = DictCursorWrapper.transform(self, row)
return self.constructor(**accum)
cdef class _callable_context_manager(object):
def __call__(self, fn):
def inner(*args, **kwargs):
with self:
return fn(*args, **kwargs)
return inner
__sentinel__ = object()
def __status__(flag, return_highwater=False):
"""
Expose a sqlite3_status() call for a particular flag as a property of the
Database object.
"""
def getter(self):
cdef int current, highwater
cdef int rc = sqlite3_status(flag, ¤t, &highwater, 0)
if rc == SQLITE_OK:
if return_highwater:
return highwater
else:
return (current, highwater)
else:
raise Exception('Error requesting status: %s' % rc)
return property(getter)
def __dbstatus__(flag, return_highwater=False, return_current=False):
"""
Expose a sqlite3_dbstatus() call for a particular flag as a property of the
Database instance. Unlike sqlite3_status(), the dbstatus properties pertain
to the current connection.
"""
def getter(Database self):
cdef:
int current, hi
pysqlite_Connection *conn = <pysqlite_Connection *>(self._local.conn)
int rc = sqlite3_db_status(conn.db, flag, ¤t, &hi, 0)
if rc != SQLITE_OK:
raise Exception('Error requesting db status: %s' % rc)
if return_highwater:
return hi
elif return_current:
return current
else:
return (current, hi)
return property(getter)
def __pragma__(name):
"""
Expose a SQLite PRAGMA operation as a property of the Database, with a
getter and setter.
"""
def __get__(self):
return self.pragma(name)
def __set__(self, value):
return self.pragma(name, value)
return property(__get__, __set__)
cdef inline int _check_connection(pysqlite_Connection *conn) except -1:
"""
Check that the underlying SQLite database connection is usable. Raises an
InterfaceError if the connection is either uninitialized or closed.
"""
if not conn.initialized: