-
Notifications
You must be signed in to change notification settings - Fork 5
/
y_serial_dev.py
executable file
·2072 lines (1772 loc) · 91.1 KB
/
y_serial_dev.py
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
# y_serial Python module Version 0.70.0 Date : 2015-04-22
# vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=python : per Python PEP 0263
#
# Origin https://github.com/rsvp/yserial
# HOWTO http://yserial.sourceforge.net
'''
_______________ y_serial :: warehouse compressed Python objects with SQLite
Dependencies: at least Python v2.5 because it includes the sqlite3 module.
Database itself and all other modules used are standard issue.
_____ PREFACE (in reStructured Text format for our site)
Intro and quick example
-----------------------
*In about ten minutes, you should be able to simply give some
labels to any Python object and save it to a database file; then
get back a set of objects by specifying portion of their labels.*
Here's a quick EXAMPLE for a typical situation. After downloading
the y_serial module, create an instance which is associated with a
regular file::
import y_serial_v060 as y_serial
demo = y_serial.Main( '/tmp/agency.sqlite' )
# ^instance ^include suitable path for database file
# ... now we do some work producing an object obj, e.g.
obj = 911
That object could have been a dictionary with a complex structure,
but let's continue on for the insert::
demo.insert( obj, "#plan agent007 #london", 'goldfinger' )
# ^notes ^table
We label each object with "notes" which can be arbitrarily long
text (or UTF-8), containing keywords or tags, but excluding commas.
Within that file we specify a "table" (merely an organizational
subsector). Some time later, perhaps in another script, we will
want to select some object::
eg1 = demo.select( "agent00[1-7],#plan", 'goldfinger' )
# ^search values are space-sensitive
# and comma separated;
# arbitrarily many permitted in string.
print "Example 1: ", eg1
# That reveals the _latest_ goldfinger plan
# which involves any one of the top seven agents
# anywhere in the world including London.
That's it... **only a few lines of Python code to store compressed
serialized objects in a database, and to selectively retrieve
them** (with optional regular expression, and remarkably, *without
writing any SQL commands*). DEAD SIMPLE -- *with only one module
imported*. Hopefully you see how widely this is applicable...
Installation and license
------------------------
Sole requirement: Python version 2.x where x is 5 or greater.
Download the latest version of the module at
`http://sourceforge.net/projects/yserial
<http://sourceforge.net/projects/yserial/>`_ and put it where your
Python can find it. No tar.gz or eggs here ;-) The module includes
the tutorial documentation within itself. You are free to use
*y_serial* under the BSD license. No monetary charge at all;
however, if you are a developer, please critically review the code.
More eyeballs lead to increased scrutiny, and thus greater
reliability.
Overview
--------
The purpose of y_serial is to keep data persistent. It is based on
key/value where the conceptual key is
- filename + table_name + primary_key + timestamp + notes
and the value is some object. (Ironically this is implemented using
a SQL database. ;-) **Our goal is to have the simplest possible
user interface in the foreground, yet have near optimal computing
in the background.**
By "objects" we generally mean Python objects, but we include
support for files (binary, image, etc.) and URL content (e.g.
webpages). Python objects are strings, dictionaries, lists,
tuples, classes, and instances. Objects are inserted into a
hierarchy: database file, table within that database, row within
table. Moreover, each object is annotated for reference by "notes"
and automatically timestamped.
*So what is happening in the background?* To minimize storage size,
each object is compressed. But before compression, we serialize the
object. The processing between y_serial and the database is handled
by the sqlite3 module **(all dependencies are standard issue
modules)**. Your program's interaction with y_serial normally will
not require writing SQL, although subqueries can be customized.
y_serial is written as a single Python module which reads like a
working tutorial and includes many tips and references. It's
instructive in the way it unifies the standard batteries:
- sqlite3 (as of Python v2.5)
- zlib (for compression)
- cPickle (for serializing objects)
- ["re" module is not used, instead we access much faster
SQLite functions for regular expressions]
Technicalities aside, you are spared from explicitly spelling out
many of the difficult protocol details: cursor/connection,
SQL/DB-API implementation, serialization, compression, search
algorithm, etc. -- for these are optimized to interact with speed,
security, and concurrency -- yet handled transparently.
Our module is faster than comparable approaches under PostgreSQL.
Among serialization methods, we found cPickle to be one of the
fastest, and so we have used it in a secure manner. Try y_serial
with a few million objects.
We recommend SQLite because it requires neither separate
installation nor a server process; also, it uses single normal
files (easy to backup or send), not an elaborate filesystem.
Moreover, in comparison to similar applications with MySQL or
PostgreSQL, SQLite is extremely fast and suits most purposes
wonderfully. Should you later decide to migrate out of SQLite,
y_serial can help port your objects elsewhere including other NoSQL
implementations.
*The means for insertion, organization by annotation, and finally
retrieval are designed to be* **simple to use**. The notes
effectively label the objects placed into the database. We can
then later query the database, for example, by *regex* (regular
expression) searching on notes, and placing the qualified objects
in a dictionary. The keys of this dictionary correspond to the
unique primary keys used in the database. If necessary we can
access the timestamp for each object. We can thus use Python code
to process the contents of the qualified dictionary, in effect, a
data subset. If the objects in that dictionary are themselves
dictionaries we are essentially dealing with *schema-less data*
(see the compelling Friendfeed case study in the module's
Endnotes).
To illustrate, let's continue our example by adding an object for
agent006::
obj = 411
demo.insert( obj, "agent006 #paris #plan", 'goldfinger' )
# We now can get a dictionary of objects
# which matches our search values:
#
eg2 = demo.selectdic( "agent00[1-7],#plan", 'goldfinger' )
print "Example 2: ", eg2
#
# which should look like:
# {1: [1257874696, u'#plan agent007 #london', 411],
# 2: [1257874696, u'agent006 #paris #plan', 911] }
Notice that we used a different method called *selectdic* which
produces a dictionary whose keys are the unique primary keys
automatically assigned in the database. Inside the list are the
(unix) epoch timestamp, followed by (unicode) notes, then object.
This means that we can *work with flexible data subsets using
Python code rather than cumbersome SQL.*
Other features
--------------
Instead of using comma-separated values, as in our example so far,
we could have crafted a custom subquery and used a method called
*dicsub*.
Or we could just skip any subquery altogether. Here we pick out the
most recent n-th entry::
eg3 = demo.select( 0, 'goldfinger' )
print "Example 3: ", eg3
The method called "*view*" will verbosely pretty-print deeply
nested structures::
demo.view( 5, 'goldfinger' )
# ^last m inserts (or use search string argument).
y_serial can also act like a persistent *QUEUE*. Whatever that is
retrieved can be deleted thereafter by appending "POP=True" at the
end of any applicable method::
eg4 = demo.select( 0, 'goldfinger', POP=True )
Object(s) can of course be deleted directly::
demo.delete( "agent00?", 'goldfinger' )
# ^where notes mention any single digit agent.
To get rid of stale data we could freshen a table and vacuum the
entire database via *clean*::
demo.clean( 365.5 , 'goldfinger' )
# ^retain one year-old or less prior to last insert.
To delete the entire table::
demo.droptable( 'goldfinger' )
Other useful methods are available:
- insert any external file (via *infile*). This is handy for
working with thousands of image files.
- insert anything on the web by URL (via *inweb*).
- insert in batches by generator (via *ingenerator*). This can
be used to rapidly store a series of computationally intense
results for quick retrieval at a later time.
For concurrency we can easily code for a farm of databases using
the module's copy functions. In general, your program can have
multiple interacting instances which control distinct database
files.
[*What's in beta?* In heavy concurrent situations (say, hundreds
of near-simultaneous writes per second), SQLite has a problem
because of the way it locks the database. We can alleviate the
problem by diffusing such operations across many databases (called
"barns" via class *Farm*), and then writing back to the target
database as a batch (which is far more efficient than single
writes) over time. The harvest time to reap the batch is
stochastic (see the "plant" method). That introduces some latency
in accessing the newest objects -- the cost for scaling up
concurrency.]
The class *Main* should be stable for all practical purposes.
If you run across any bugs, please kindly report them to the
`Tracker
<https://sourceforge.net/tracker/?group_id=277002&atid=1176411>`_.
For group discussions, check out the SourceForge link in the
left sidebar.
For other specialized features, please RTM "read the module" for
tips on usage.
Summary
-------
**y_serial = serialization + persistance. In a few lines of code,
compress and annotate Python objects into SQLite; then later
retrieve them chronologically by keywords without any SQL. Highly
useful NoSQL "standard" module for a database to store schema-less
data.**
_______________ TABLE OF CONTENTS:
- Preface with quick example
- Usage with SUMMARY of CLASSES, METHODS, and FUNCTIONS:
Base:
_______________ Attributes and methods for database setup.
Set path to database for all instances; db0 is default.
Connection and execution methods.
Insertion( Base ):
_______________ INSERT pz BLOB into DATABASE
inbatch( self, objseq, table=Base.tab0 ):
Pickle and compress sequence of annotated objects; insert.
* ingenerator( self, generate_objnotes, table=Base.tab0 ):
Pickle and compress via generator function, then insert.
** insert( self, obj, notes='#0notes', table=Base.tab0 ):
Pickle and compress single object; insert with annotation.
Annex( Insertion ):
_______________ Add macro-objects (files, URL content) to DATABASE
inweb( self, URL, notes='', table=Base.tab0 ):
Pickle and compress URL content, then insert into table.
* infile( self, filename, notes='', table=Base.tab0 ):
Pickle and compress any file, then insert contents into table.
Answer( Base ):
_______________ Single item answer shouted out.
shout( self, question, table=Base.tab0 ):
Shout a question; get a short answer.
** lastkid( self, table=Base.tab0 ):
Get primary key ID of the last insert.
lastsec( self, table=Base.tab0 ):
Get time in unix seconds of the last insert.
lastdate( self, table=Base.tab0 ):
Get local date/time of the last insert.
Util:
_______________ Utility methods for keys, subquery, comma
comma2list( self, csvstr, wild=True ):
Convert comma separated values to a parameter list.
Deletion( Base, Util ):
_______________ Deletion methods; also used for queue POP
deletesub( self, subquery, parlist=[], table=Base.tab0 ):
Delete row(s) matching the subquery.
deletekid( self, kid, table=Base.tab0 ):
Delete single row with primary key kid.
deletecomma( self, csvstr, table=Base.tab0, wild=True ):
Delete row(s): notes match comma separated values in string.
* delete( self, dual, table=Base.tab0, wild=True ):
Alias "delete": deletekid OR deletecomma.
droptable( self, table=Base.tab0 ):
Delete a table: destroys its structure, indexes, data.
Subquery( Util, Answer, Deletion ):
_______________ SUBQUERY table, get dictionary. POP QUEUE.
dicsub(self, subquery='', parlist=[], table=Base.tab0, POP=False):
Subquery table to get objects into response dictionary.
diclast( self, m=1, table=Base.tab0, POP=False ):
Get dictionary with last m consecutive kids in table.
diccomma( self, csvstr, table=Base.tab0, wild=True, POP=False ):
Get dictionary where notes match comma separated values.
* selectdic( self, dual=1, table=Base.tab0, POP=False ):
Alias "selectdic": diclast OR diccomma.
Display( Subquery ):
_______________ View subquery via pretty print
viewsub(self, subquery='', parlist=[], table=Base.tab0, POP=False):
Subquery, order keys, and print qualified dictionary.
viewlast( self, m=1, table=Base.tab0, POP=False ):
Print last m consecutive kids in table.
viewcomma(self, csvstr='', table=Base.tab0, wild=True, POP=False):
Print dictionary where notes match comma separated values.
* view( self, dual=1, table=Base.tab0, POP=False ):
Alias "view": viewlast OR viewcomma.
Latest( Display ):
_______________ Retrieve the latest qualified object "omax"
omaxsub(self, subquery='', parlist=[], table=Base.tab0, POP=False):
Get the latest object omax which matches subquery.
omaxlast( self, n=0, table=Base.tab0, POP=False ):
Most quickly get the latest n-th object using key index.
omaxcomma( self, csvstr, table=Base.tab0, wild=True, POP=False ):
Get latest object where notes match comma separated values.
** select( self, dual=0, table=Base.tab0, POP=False ):
Alias "select": omaxlast OR omaxcomma.
* getkid( self, kid, table=Base.tab0, POP=False ):
Retrieve a row given primary key kid, POP optional.
Oldest( Latest ):
_______________ Retrieve the oldest qualified object "omin"
ominfirst( self, n=0, table=Base.tab0, POP=False ):
Most quickly get the oldest n-th object using key index.
* fifo( self, table=Base.tab0 ):
FIFO queue: return oldest object, then POP (delete) it.
Care( Answer, Deletion ):
_______________ Maintenance methods
freshen( self, freshdays=None, table=Base.tab0 ):
Delete rows in table over freshdays-old since last insert.
vacuum( self ):
Defrag entire database, i.e. all tables therein.
- why VACUUM?
* clean( self, freshdays=None, table=Base.tab0 ):
Delete stale rows after freshdays; vacuum/defrag database.
Main( Annex, Oldest, Care ):
_______________ Summary for use of a single database.
copysub( subquery, parlist, tablex, tabley, dbx=Base.db0, dby=Base.db0 ):
Subselect from tablex, then copy to tabley (in another database).
copylast( m, tablex, tabley, dbx=Base.db0, dby=Base.db0 ):
Copy last m consecutive kids in tablex over to tabley.
* comma( *string_args ):
Join string-type arguments with comma (cf. csvstr, comma2list).
copycomma( csvstr, tablex, tabley, dbx=Base.db0, dby=Base.db0, wild=True ):
Subselect by comma separated values from tablex, then copy to tabley.
** copy( dual, tablex, tabley, dbx=Base.db0, dby=Base.db0, wild=True ):
Alias "copy": copylast OR copycomma
Farm:
_______________ Start a farm of databases for concurrency and scale.
__init__( self, dir=dir0, maxbarns=barns0 ):
Set directory for the farm of maxbarns database files.
farmin( self, obj, notes='#0notes', table=Base.tab0, n=0 ):
Insert an object with notes into barn(n).
harvest(self, dual, tablex,tabley, n, dby=Base.db0, wild=True, size=10):
After farmin, reap dual under tablex barn(n) by size expectation.
cleanfarm( self, freshdays=None, table=Base.tab0 ):
Delete stale rows after freshdays; vacuum/defrag barns.
* plant( self, obj, notes='#0notes', table=Base.tab0, dby=Base.db0 ):
FARM SUMMARY: farmin insert with generic self-cleaning harvest.
- Change log
- TODO list
- ENDNOTES: operational tips and commentary with references
- pz Functions for FILE.gz
- Database versus FILE.gz
- tester( database=Base.db0 ):
Test class Main for bugs.
- testfarm( dir=Farm.dir0, maxbarns=Farm.barns0 ):
Test class Farm for bugs. Include path for directory.
- Acknowledgements and Revised BSD LICENCE
_______________ CHANGE LOG
2015-04-22 v0.70: Code review to fix tester.
Default database db0 in class Base now uses /tmp.
Character set change from iso-8859-1 to utf-8.
Certified to run under Python 2.7.8 and IPython 2.30.
2010-08-20 v0.60: Certified to run under Python 2.6 series.
Edited the preface (also used for welcome page).
Added getkid. Cosmetic touch-up for view method.
2010-04-25 v0.53: Be sure to assign default database db0 in class Base.
2009-11-22 v0.52: Added plant (insert) method summarizing class Farm.
2009-11-19 v0.51: Added fifo (queue) method to class Oldest.
Added beta Farm (of databases!) for concurrency.
!! 2009-11-11 v0.50: TOTAL TOP-DOWN GENERALIZED CLASS REWRITE
of the final bottom-up all-function revision 28.
- Python objects now are warehoused among various database files
by design. Each instance of the class Main is associated with
a particular database file.
- Dropped *glob functions in favor of the *comma form (see
comma2list to see how this works exactly).
- Simplified the names of many functions since most of them
are now methods within some class.
- LIFO has been renamed as POP to reflect queue generlization.
2009-10-26 Revision 28: final bottom-up all-function version
which also archives prior change log.
!! = indicates change(s) which broke backward compatibility.
pz = pickled zlib compressed binary format.
_______________ TODO List
The sqlite3 module, maintained by Gerhard Haering, has been updated
from version 2.3.2 in Python 2.5 to version 2.4.1 in Python 2.6.
[ ] - update code for threads when the following becomes public:
Contrary to popular belief, newer versions of sqlite3 do support
access from multiple threads. This can be enabled via optional
keyword argument "check_same_thread":
sqlite.connect(":memory:", check_same_thread = False)
However, their docs omit this option. --Noted 2010-05-24
[ ] - update code for Python version 3.x
When we run y_serial.tester() with the "-3" flag under Python 2.6,
there is only one message:
"DeprecationWarning: buffer() not supported in 3.x"
This actually is about how BLOBs are handled in the sqlite3 module,
and is being resolved by Gerhard Haering,
see http://bugs.python.org/issue7723
Thereafter, we expect an easy transition to Python 3.
'''
# _______________ Variable settings with imports
DEBUG = False
# Here's how to EXECUTE TESTS. First, be sure to change the default
# database file to suit yourself; see assignment db0 in class Base.
#
# import y_serial_dev as y_serial
# y_serial.tester()
# # ^for the principal class Main
# y_serial.testfarm( directory, maxbarns )
# ^for the beta version, not yet in Main.
import sqlite3 as ysql
# ^ for portability to another SQL database.
import pprint
# pretty print to Display nested arbitrary Python data structures.
# __________ pz FUNCTIONS for pickled compression
import cPickle as yPickle
# ^ written in C, compatible with pickle but thousand times faster.
# But some situations may only allow pure-Python pickle module.
# The data stream produced by pickle and cPickle are identical.
# So take your pick for yPickle.
# [Future note: pickle in Python v3 will integrate cPickle.]
pickle_protocol = 2
# 0 = original ASCII protocol and is backwards compatible.
# 1 = old binary format which is also backwards compatible.
# 2 = introduced in Python 2.3, more efficient pickling of new-style classes.
# 3 = for Python 3 with explicit support for bytes objects and byte arrays,
# but it is not backward compatible with protocol 2.
# So use that since Python 3 will still understand what to do.
import zlib
# ^zlib compression for pickled items.
compress_level = 7
# 1 to 9 controlling the level of compression;
# 1 is fastest and produces the least compression,
# 9 is slowest and produces the greatest compression.
def pzdumps( obj ):
'''Pickle object, then compress the pickled.'''
return zlib.compress( yPickle.dumps(obj, pickle_protocol), compress_level)
# as binary string.
def pzloads( pzob ):
'''Inverse of pzdumps: decompress pz object, then unpickle.'''
return yPickle.loads( zlib.decompress( pzob ) )
# ^auto-detects pickle protocol.
class Base:
'''_______________ Essential attributes and methods for database setup.'''
db0 = '/tmp/y_serial-db0-tmp.sqlite'
# ========================================================== ***
# ^ be sure to specify an absolute path to the database file.
# This is just your convenient DEFAULT DATABASE FILE.
# Specify other such files explicitly when creating instances.
#
# [ Using an in-memory database ':memory:' will not work here
# because we go in and out of connection as needed. ]
tab0 = 'tmptable'
# ^default SQL table for storing objects temporarily.
TRANSACT = 'IMMEDIATE'
# among: None (autocommit), 'DEFERRED' (default), 'IMMEDIATE', 'EXCLUSIVE'.
#
# We want to support transactions among multiple concurrent sessions, and
# to AVOID DEADLOCK. For our purposes, such sessions should start out by:
# "BEGIN IMMEDIATE TRANSACTION;"
# to guarantee a (reserved) write lock while allowing others to read.
# See _The Definitive Guide to SQLite_, chapters 4 and 5,
# by Michael Owens (2006, Apress) for the clearest explanation.
TIMEOUT = 14
# ^ in seconds (default: 5)
# During multiple concurrent sessions, writing creates a certain type
# of lock until a transaction is committed. TIMEOUT specifies how long
# a connection should wait for that lock to be released until raising
# an exception. Increase the wait if a very large amount of objects
# is routinely inserted during a single session.
def __init__( self, db=db0 ):
'''Set path to database for all instances; db0 is default.'''
self.db = db
def proceed( self, sql, parlist=[[]] ):
'''Connect, executemany, commit, then finally close.'''
try:
con = ysql.connect( self.db, timeout = self.TIMEOUT,
isolation_level = self.TRANSACT )
cur = con.cursor()
cur.executemany( sql, parlist )
# for an empty ^parameter list, use [[]].
con.commit()
# ^MUST remember to commit! else the data is rolled back!
except:
a = " !! Base.proceed did not commit. [Check db path.] \n"
b = " Suspect busy after TIMEOUT, \n"
c = " tried this sql and parameter list: \n"
raise IOError, "%s%s%s%s\n%s" % ( a, b, c, sql, parlist )
finally:
cur.close()
con.close()
# ^ very important to release lock for concurrency.
def respond( self, klass, sql, parlist=[] ):
'''Connect, execute select sql, get response dictionary.'''
try:
con = ysql.connect( self.db, timeout = self.TIMEOUT,
isolation_level = self.TRANSACT )
cur = con.cursor()
response = {}
for tupler in cur.execute( sql, parlist ):
self.responder( klass, tupler, response )
# ^ to be defined in a subclass
# (mostly to process output from subqueries).
# con.commit() intentionally omitted.
except:
a = " !! Base.respond choked, probably because \n"
b = " object feels out of context. \n"
c = " Tried this sql and parameter list: \n"
raise IOError, "%s%s%s%s\n%s" % (a, b, c, sql, parlist)
finally:
cur.close()
con.close()
return response
def createtable( self, table=tab0 ):
'''Columns created: key ID, unix time, notes, and pzblob.'''
a = 'CREATE TABLE IF NOT EXISTS %s' % table
b = '(kid INTEGER PRIMARY KEY, tunix INTEGER,'
c = 'notes TEXT, pzblob BLOB)'
sql = ' '.join( [a, b, c] )
try:
self.proceed( sql )
# try construct is useful for portability in standard
# cases where clause "IF NOT EXISTS" is not implemented.
except IOError:
if DEBUG:
print " :: createtable: table exists."
# createtable is designed to be harmless if it
# left sitting in your script.
class Insertion( Base ):
'''_______________ INSERT pz BLOB into DATABASE'''
# For inbatch we shall assume that the "objseq" is a sequence
# (tuple or list) of objnotes. An "objnotes" consists of a sequence
# pairing of an object and its annotation. Example:
# objseq = [ (obj1, 'First thing'), (obj2, 'Second thing') ]
# Use an empty string like "" to explicitly blank out annotation.
def inbatch( self, objseq, table=Base.tab0 ):
'''Pickle and compress sequence of annotated objects; insert.'''
self.createtable( table )
# ^ serves also to check table's existence.
s = "INSERT INTO %s " % table
v = "VALUES (null, strftime('%s','now'), ?, ?)"
# ^SQLite's function for unix epoch time.
sql = ' '.join([s, v])
def generate_parlist():
for i in objseq:
obj, notes = i
parlist = [ notes, ysql.Binary(pzdumps(obj)) ]
yield parlist
# ^ using generator for parameter list.
self.proceed( sql, generate_parlist() )
# inserting 100,000 rows takes about 10 seconds.
# objseq can be generated on the fly. Just write a generator function,
# and pass it along to pzgenerator [for illustration, see copy].
def ingenerator( self, generate_objnotes, table=Base.tab0 ):
'''Pickle and compress via generator function, then insert.'''
# generator should yield an objseq element like this: (obj, notes)
self.inbatch( [x for x in generate_objnotes], table )
# TIP: generate computationally intense results, then
# pass them to ingenerator which will warehouse them. Instantly
# access those pre-computed results later by subquery on notes.
def insert( self, obj, notes='#0notes', table=Base.tab0 ):
'''Pickle and compress single object; insert with annotation.'''
self.inbatch( [(obj, notes)], table )
# CAVEAT: if you have *lots* of objects to insert individually
# this repeatedly will be slow because it commits after every
# insert which causes sqlite to sync the inserted data to disk.
# REMEDY: prepare your annotated objects in objseq form,
# then use inbatch or ingenerator instead.
class Annex( Insertion ):
'''_______________ Add macro-objects (files, URL content) to DATABASE'''
def inweb( self, URL, notes='', table=Base.tab0 ):
'''Pickle and compress URL content, then insert into table.'''
# put URL address in quotes including the http portion.
if not notes:
# let notes be an empty string if you want the URL noted,
# else notes will be that supplied by argument.
notes = URL
import urllib2
webpage = urllib2.urlopen( URL )
webobj = webpage.read()
self.insert( webobj, notes, table )
def file2string( self, filename ):
'''Convert any file, text or binary, into a string object.'''
# put filename in quotes including the path.
f = open( filename, 'rb' )
# 'read binary' but also works here for text;
# line-end conversions are suppressed.
strobj = f.read()
f.close()
return strobj
# ^ Note: even if the file originally was iterable.
# that STRING OBJECT will NOT be iterable.
# If the file was text, one could regain iteration by writing
# back to a disk file, or by doing something in-memory, e.g.
# import cStringIO as yString
# # or StringIO
# inmemoryfile = yString.StringIO( strobj )
# for line in inmemoryfile:
# ... process the line ...
# inmemoryfile.close()
# Iteration is not necessary if the string object is
# to be used in its entirety, e.g. some boilerplate text.
# Getting text snippets from a database is generally
# faster than reading equivalent text files from disk.
def infile( self, filename, notes='', table=Base.tab0 ):
'''Pickle and compress any file, then insert contents into table.'''
# put filename in quotes including any needed path.
# file can be binary or text, including image.
if not notes:
# let notes be an empty string if you want filename noted,
# else notes will be that supplied by argument.
notes = filename
self.insert( self.file2string( filename ), notes, table )
class Answer( Base ):
'''_______________ Single item answer shouted out.'''
# see class Selection for reading and retrieval.
def responder( self, klass, tupler, response ):
'''(see def respond in abstract superclass Base.)'''
# different behavior depending on subclass...
if klass == 'Answer':
response[0] = tupler
# ^ we only expect a single answer.
if klass == 'Subquery':
kid, tunix, notes, pzblob = tupler
obj = pzloads( pzblob )
response[kid] = [ tunix, notes, obj ]
# each item in response DICTIONARY has a key kid <=
# (same as in the table), and it is a list consisting of <=
# timestamp, notes, and original object <=
# (decompressed and unpickled). <=
def shout( self, question, table=Base.tab0 ):
'''Shout a question; get a short answer.'''
sql = "SELECT ( %s ) FROM %s" % (question, table)
response = self.respond( 'Answer', sql )
return response[0][0]
# None, if the table is empty.
def lastkid( self, table=Base.tab0 ):
'''Get primary key ID of the last insert.'''
maxkid = self.shout( "MAX( kid )", table )
if maxkid == None:
maxkid = 0
return maxkid
def lastsec( self, table=Base.tab0 ):
'''Get time in unix seconds of the last insert.'''
tmax = self.shout( "MAX( tunix )", table )
if tmax == None:
tmax = 0
return tmax
# e.g. 1256856209
# seconds ^ elapsed since 00:00 UTC, 1 January 1970
# _____ Automatic timestamp ("tunix")
# As each object enters the database we also add an
# epoch timestamp. Rather than import another Python
# module for that purpose, we use SQLite's (faster)
# functions: strftime and datetime.
def lastdate( self, table=Base.tab0 ):
'''Get local date/time of the last insert.'''
tmax = self.lastsec( table )
q = "datetime( %s, 'unixepoch', 'localtime')" % tmax
if not tmax:
return ' :: lastdate not applicable.'
else:
return self.shout( q, table )
# e.g. u'2009-10-29 15:43:29'
class Util:
'''_______________ Utility methods for keys, subquery, comma'''
def reverse_dickeys( self, dictionary, recentfirst=True ):
'''List dictionary keys: sorted reverse (chronological) order.'''
dickeys = dictionary.keys()
dickeys.sort()
if recentfirst:
dickeys.reverse()
return dickeys
# _____ SUBQUERY regex style for LIKE
#
# Here we want the dictionary to consist of items which have
# notes containing " gold " (using LIKE):
#
# dic = I.dicsub("WHERE notes LIKE '% gold %'")
#
# Percent % in LIKE is the regex equivalent of star "*"
# ^wildcard for 0 or more characters
# Underscore _ in LIKE is the regex equivalent of period "."
# ^single character
# Escape ! in LIKE is the regex equivalent of backslash "\"
# (or one can specify an escape character
# by appending, for example, "ESCAPE '\'"
# at the end of the subquery.)
# [a-c] same in LIKE for character ranges, exclude by "^"
# _____ SUBQUERY regex style for GLOB
#
# For SQLite: the GLOB operator is similar to LIKE but uses the
# Unix file globbing [dissimilar to grep] syntax for its wildcards.
# ? in GLOB is the regex equivalent of period "."
#
# GLOB is case sensitive, unlike LIKE. <=
# But LIKE is case sensitive for unicode characters beyond ASCII.
# Both GLOB and LIKE may be preceded by the NOT keyword
# to invert the sense of the test.
def notesglob( self, parlist ):
'''Create a CONJUNCTIVE subquery using GLOB with placeholder.'''
# ^i.e. each term in parlist is an "AND" search term.
s = ""
for i in parlist:
s += "AND notes GLOB ? "
# use placeholder ^ rather than i for security!
return s.replace('AND', 'WHERE', 1)
# replace only the first occurrence
# Everyone is going to have a unique style of writing out their notes
# so that it can be efficiently searched. Tags are helpful, but they
# are optional within notes. Tags are useful for creating indexes.
# Define a "TAG" to be text in notes prefixed by "#"
def comma2list( self, csvstr, wild=True ):
'''Convert comma separated values within string to a parameter list
>>> # !! white spaces within string are significant !!
>>> print comma2list('#paris, agent007 ,#scheme')
['*#paris*', '* agent007 *', '*#scheme*']
Empty or single entry (without comma) csvstr is acceptable.
Empty string '' will select everything if wild is True.
Unlike official csv, internal quotes should not be used;
for simplicity, comma itself is not meant to be escaped.
'''
# wild will conveniently include stars on both ends...
if wild:
parlist = [ '*%s*' % i for i in csvstr.split(',') ]
else:
parlist = [ '%s' % i for i in csvstr.split(',') ]
# manually add wildcards as needed to csvstr for faster regex.
return parlist
#
# TIP: for faster execution, list most discriminating values first;
# use wild=False for exact search wherever possible.
#
# To form csvstr out of string variables a, b, c:
# csvstr = ','.join( [a, b, c] )
# See function comma after Main class.
class Deletion( Base, Util ):
'''_______________ Deletion methods; also used for queue POP'''
def deletesub( self, subquery, parlist=[], table=Base.tab0 ):
'''Delete row(s) matching the subquery.'''
sql = 'DELETE FROM %s %s' % ( table, subquery )
# use ? placeholder(s) for security^
self.proceed( sql, [ parlist ] )
def deletekid( self, kid, table=Base.tab0 ):
'''Delete single row with primary key kid.'''
subquery = 'WHERE kid = ?'
self.deletesub( subquery, [ kid ], table )
def deletecomma( self, csvstr, table=Base.tab0, wild=True ):
'''Delete row(s): notes match comma separated values in string.'''
parlist = self.comma2list( csvstr, wild )
self.deletesub( self.notesglob(parlist), parlist, table )
def delete( self, dual, table=Base.tab0, wild=True ):
'''Alias "delete": deletekid OR deletecomma.'''
# assuming dual is either an ^integer OR ^csvstr string...
if isinstance( dual, int ):
self.deletekid( dual, table )
else:
self.deletecomma( dual, table, wild )
def droptable( self, table=Base.tab0 ):
'''Delete a table: destroys its structure, indexes, data.'''
sql = 'DROP TABLE %s' % table
try:
self.proceed( sql )
except:
if DEBUG:
print " ?? droptable: no table to delete."
return " :: droptable: done."
# Delete a SQLite database file like a normal file at OS level.
class Subquery( Util, Answer, Deletion ):
'''_______________ SUBQUERY table, get dictionary. POP QUEUE.'''
# "kid" serves as key for both retrieved dictionaries and database.
#
# _____ SUBQUERY : SECURITY NOTICE.
# Per the DB-API recommendations,
# subquery should use ? as parameter placeholder
# to prevent SQL injection attacks; see Endnotes.
# Such a placeholder does not take a clause, simply values.
# Obscured fact: table names cannot be parametized.
# parlist shall be the parameter list which sequentially
# corresponds to the placeholder(s).
# parlist should be empty [] if no placeholders are used.
def dicsub(self, subquery='', parlist=[], table=Base.tab0, POP=False):
'''Subquery table to get objects into response dictionary.'''
a = 'SELECT kid, tunix, notes, pzblob FROM %s %s'
sql = a % ( table, subquery )
response = self.respond( 'Subquery', sql, parlist )
if POP:
self.deletesub( subquery, parlist, table )
return response
# __________ Using POP for QUEUE purposes ___ATTN___
#
# After y_serial retrieves entities that match a subquery pattern,
# it can optionally delete them.
#
# POP = True, herein means "Treat as queue" <=!!!
# whereby objects matching a subquery are
# retrieved and then DELETED.
#
# POP = False, means "retrieve but DO NOT delete." <=!
def diclast( self, m=1, table=Base.tab0, POP=False ):
'''Get dictionary with last m consecutive kids in table.'''
kid = self.lastkid( table ) - m
return self.dicsub('WHERE kid > ?', [kid], table, POP )
def diccomma( self, csvstr, table=Base.tab0, wild=True, POP=False ):
'''Get dictionary where notes match comma separated values.'''
parlist = self.comma2list( csvstr, wild )
subquery = self.notesglob( parlist )
return self.dicsub( subquery, parlist, table, POP )
def selectdic( self, dual=1, table=Base.tab0, POP=False ):
'''Alias "selectdic": diclast OR diccomma.'''
# assuming dual is either an ^integer OR ^csvstr string...
if isinstance( dual, int ):
return self.diclast( dual, table, POP )
else:
wild = True
# ^constrained for dual usage
return self.diccomma( dual, table, wild, POP )
class Display( Subquery ):
'''_______________ View subquery via pretty print'''
def viewsub(self, subquery='', parlist=[], table=Base.tab0, POP=False):
'''Subquery, order keys, and print qualified dictionary.'''
dic = self.dicsub( subquery, parlist, table, POP )
dickeylist = self.reverse_dickeys( dic )
diclen = len( dickeylist )
print "\n :: View in reverse chronological order :: "
print " :: ----------------------------------------"
# ^^^^ "grep -v '^ :: '" to get rid of labels.
if diclen:
for kid in dickeylist:
[ tunix, notes, obj ] = dic[ kid ]
print " :: kid: %s (%s secs)" % (kid, tunix)
print " :: notes: ", notes
if isinstance( obj, str ):
if len( obj ) > 1000:
end = '[... Display limited ...]'
obj = ' '.join( [obj[0:1000], end] )
print obj
else:
try:
pprint.pprint( obj )
except:
print " !! Display: object not printable."
print " :: ----------------------------------------"
print " :: Display: MATCHED %s objects." % diclen
if POP:
print " and POP deleted them."
else:
print " !! Display: NOTHING matched subquery !!"
def viewlast( self, m=1, table=Base.tab0, POP=False ):
'''Print last m consecutive kids in table.'''
kid = self.lastkid( table ) - m
self.viewsub('WHERE kid > ?', [kid], table, POP )
def viewcomma(self, csvstr='', table=Base.tab0, wild=True, POP=False):
'''Print dictionary where notes match comma separated values.'''
parlist = self.comma2list( csvstr, wild )
subquery = self.notesglob( parlist )
self.viewsub( subquery, parlist, table, POP )