Your IP : 216.73.216.60


Current Path : /opt/alt/python35/lib64/python3.5/site-packages/playhouse/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib64/python3.5/site-packages/playhouse/__pycache__/sqlite_ext.cpython-35.pyc



R6�W‹�&@s�dZddlZddlZddlZddlZddlZddlZddlZyddlZ	Wne
k
r�ddl	Z	YnXyddlmZWne
k
r�YnXddl
Tddl
mZddl
mZddl
mZddl
mZdd	l
mZdd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZddl
mZyddlmZWne
k
r�dZYnXejddkr�eZdZ dZ!ej"dd�dddfko�dp�dZ#dddfZ$Gdd�de�Z%Gdd�de�Z&Gdd�de'�Z(Gd d!�d!e)�Z*Gd"d#�d#e+�Z,Gd$d%�d%e-�Z.Gd&d'�d'e.e+�Z/Gd(d)�d)e.e0�Z1Gd*d+�d+e.e2�Z3Gd,d-�d-e.e4�Z5Gd.d/�d/e6�Z7Gd0d1�d1e7�Z8Gd2d3�d3e8�Z9d4Z:e;d5d6d7d8e<d9�d:d;d<d=d>d?d@dAg
�e;dB�Be;e:�Be;e:j=��BZ>e;dCdD�e?dE�D��Z@ejAdF�ZBGdGdH�dHe8�ZCddIdJ�ZDGdKdL�dLe�ZEejFdMdN�dOdP��ZGGdQdR�dReH�ZIGdSdT�dTe�ZJdUe_KeIjLejKdVi�dWdU�ZMdXdY�ZNdZd[�ZOd\d]�ZPdS)^a�
Sqlite3 extensions
==================

* Define custom aggregates, collations and functions
* Basic support for virtual tables
* Basic support for FTS3/4
* Specify isolation level in transactions

Example usage of the Full-text search:

class Document(FTSModel):
    title = TextField()  # type affinities are ignored in FTS
    content = TextField()

Document.create_table(tokenize='porter')  # use the porter stemmer

# populate the documents using normal operations.
for doc in documents:
    Document.create(title=doc['title'], content=doc['content'])

# use the "match" operation for FTS queries.
matching_docs = Document.select().where(match(Document.title, 'some query'))

# to sort by best match, use the custom "rank" function.
best_docs = (Document
             .select(Document, Document.rank('score'))
             .where(match(Document.title, 'some query'))
             .order_by(SQL('score')))

# or use the shortcut method.
best_docs = Document.match('some phrase')
�N)�
TableFunction)�*)�EnclosedClause)�Entity)�
Expression)�Node)�OP)�SqliteQueryCompiler)�_AutoPrimaryKeyField)�sqlite3)�transaction)�_sqlite_date_part)�_sqlite_date_trunc)�_sqlite_regexp)�_sqlite_ext�ZpcnalxZpcx��ZFTS4ZFTS3�	c@seZdZdZdZdS)�
RowIDFieldz�
    Field used to access hidden primary key on FTS5 or any other SQLite
    table that does not have a separately-defined primary key.
    �rowidN)�__name__�
__module__�__qualname__�__doc__�_column_name�rr�G/opt/alt/python35/lib64/python3.5/site-packages/playhouse/sqlite_ext.pyrOsrc@seZdZdZdZdS)�
DocIDFieldz9Field used to access hidden primary key on FTS3/4 tables.�docidN)rrrrrrrrrrWsrcs(eZdZdZ�fdd�Z�S)�PrimaryKeyAutoIncrementFielda
    SQLite by default uses MAX(primary key) + 1 to set the ID on a new row.
    Using the `AUTOINCREMENT` field, the IDs will increase monotonically
    even if rows are deleted. Use this if you need to guarantee IDs are not
    re-used in the event of deletion.
    cs)tt|�j|�}|td�gS)NZ
AUTOINCREMENT)�superr �__ddl__�SQL)�self�column_type�ddl)�	__class__rrr"csz$PrimaryKeyAutoIncrementField.__ddl__)rrrrr"rr)r'rr \sr c@s�eZdZdd�Zdd�Zdd�Zddd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
ddd�Zddd�Zddd�ZdS)�	JSONFieldcCs@|dk	r<ytj|�SWnttfk
r;|SYnXdS)N)�json�loads�	TypeError�
ValueError)r$�valuerrr�python_valueis
zJSONField.python_valuecCs|dk	rtj|�SdS)N)r)�dumps)r$r-rrr�db_valuepszJSONField.db_valuecCs&|jd�s|rd|Sd|S)N�[z$%sz$.%s)�
startswith)r$�pathrrr�
clean_pathtszJSONField.clean_pathNcCs,|rtj||j|��Stj|�S)N)�fnZjson_array_lengthr4)r$r3rrr�lengthyszJSONField.lengthcCstj||j|��S)N)r5Zjson_extractr4)r$r3rrr�extract~szJSONField.extractcCs2t|tttf�r.tjtj|��S|S)N)�
isinstance�list�tuple�dictr5r)r/)r$r-rrr�_value_for_insertion�szJSONField._value_for_insertioncCs�t|�}|ddkr(td��g}xRtd|d�D]>}|j|j||��|j|j||d��qAW|||�S)N�rz%Mismatched path and value parameters.�)�lenr,�range�appendr4r<)r$r5�pairsZnpairs�accum�irrr�_insert_like�s"zJSONField._insert_likecGs|jtj|�S)N)rEr5Zjson_insert)r$rBrrr�insert�szJSONField.insertcGs|jtj|�S)N)rEr5Zjson_replace)r$rBrrr�replace�szJSONField.replacecGs|jtj|�S)N)rEr5Zjson_set)r$rBrrr�set�sz
JSONField.setcs#tj��fdd�|D��S)Ncsg|]}�j|��qSr)r4)�.0r3)r$rr�
<listcomp>�s	z$JSONField.remove.<locals>.<listcomp>)r5Zjson_remove)r$�pathsr)r$r�remove�szJSONField.removecCs,|rtj||j|��Stj|�S)N)r5�	json_typer4)r$r3rrrrM�szJSONField.json_typecCs,|rtj||j|��Stj|�S)a?
        Schema of `json_each` and `json_tree`:

        key,
        value,
        type TEXT (object, array, string, etc),
        atom (value for primitive/scalar types, NULL for array and object)
        id INTEGER (unique identifier for element)
        parent INTEGER (unique identifier of parent element or NULL)
        fullkey TEXT (full path describing element)
        path TEXT (path to the container of the current element)
        json JSON hidden (1st input parameter to function)
        root TEXT hidden (2nd input parameter, path at which to start)
        )r5Z	json_eachr4)r$r3rrr�children�szJSONField.childrencCs,|rtj||j|��Stj|�S)N)r5Z	json_treer4)r$r3rrr�tree�szJSONField.tree)rrrr.r0r4r6r7r<rErFrGrHrLrMrNrOrrrrr(hs
r(csCeZdZdZddd�fdd�Z�fdd�Z�S)�SearchFielda-
    Field class to be used with full-text search extension. Since the FTS
    extensions do not support any field types besides `TEXT`, and furthermore
    do not support secondary indexes, using this field will prevent you
    from mistakenly creating the wrong kind of field on your FTS table.
    FNcsTddd|d|i}||_|r:td�g|d<tt|�j|�dS)N�nullT�	db_column�coerceZ	UNINDEXED�constraints)�
_unindexedr#r!rP�__init__)r$Z	unindexedrRrS�_�kwargs)r'rrrV�s
	zSearchField.__init__cs(tt|�j|�}|j|_|S)N)r!rP�
clone_baserU)r$rX�clone)r'rrrY�szSearchField.clone_base)rrrrrVrYrr)r'rrP�srPcs(eZdZdZ�fdd�Z�S)�_VirtualFieldMixinzx
    Field mixin to support virtual table attributes that may not correspond
    to actual columns in the database.
    cs-tt|�j||�|jj|�dS)N)r!r[�add_to_class�_meta�remove_field)r$�model_class�name)r'rrr\�sz_VirtualFieldMixin.add_to_class)rrrrr\rr)r'rr[�sr[c@seZdZdS)�VirtualFieldN)rrrrrrrra�srac@seZdZdS)�VirtualIntegerFieldN)rrrrrrrrb�srbc@seZdZdS)�VirtualCharFieldN)rrrrrrrrc�srcc@seZdZdS)�VirtualFloatFieldN)rrrrrrrrd�srdc@sJeZdZGdd�d�Zedd��Zeddd��ZdS)	�VirtualModelc@s"eZdZdZdZiZdS)zVirtualModel.MetaTN)rrrZ
virtual_table�extension_module�extension_optionsrrrr�Meta�srhcKs|S)Nr)�cls�optionsrrr�
clean_options�szVirtualModel.clean_optionsFcKs=|r|j�rdS|jjj|d|�|j�dS)Nrj)�table_existsr]�database�create_table�_create_indexes)ri�
fail_silentlyrjrrrrn�szVirtualModel.create_tableN)rrrrh�classmethodrkrnrrrrre�srec@s"eZdZedd��ZdS)�BaseFTSModelcKs[|jd�}|jd�}|r2d||d<t|t�rW|dkrWd|d<|S)N�tokenize�contentz"%s"�z'')�getr8�
basestring)rirjrsrtrrrrk�s
zBaseFTSModel.clean_optionsN)rrrrqrkrrrrrr�srrc@smeZdZdZe�ZGdd�d�Zedd��Zedd��Z	edd	��Z
ed
d��Zedd
��Zedddd��Z
eddd��Zedd��Zedd��Zedd��Zedd��Zedd��Zedd d!d d"d#��Zedd d!d d$d%��Zedd d!d d&d'��ZdS)(�FTSModela_
    VirtualModel class for creating tables that use either the FTS3 or FTS4
    search extensions. Peewee automatically determines which version of the
    FTS extension is supported and will use FTS4 if possible.

    Note: because FTS5 is significantly different from FTS3 and FTS4, there is
    a separate model class for FTS5 virtual tables.
    c@seZdZeZdS)z
FTSModel.MetaN)rrr�FTS_VERrfrrrrrhsrhcCs%|jjjdkr!td��dS)Nrz:FTSModel classes must use the default `docid` primary key.)r]�primary_keyr`�ImproperlyConfigured)rirrr�validate_modelszFTSModel.validate_modelcCs8|jj}|jjjd|||f�}|j�S)Nz INSERT INTO %s(%s) VALUES('%s');)r]�db_tablerm�execute_sql�fetchone)ri�cmd�tbl�resrrr�_fts_cmdszFTSModel._fts_cmdcCs
|jd�S)N�optimize)r�)rirrrr�$szFTSModel.optimizecCs
|jd�S)N�rebuild)r�)rirrrr�(szFTSModel.rebuildcCs
|jd�S)Nzintegrity-check)r�)rirrr�integrity_check,szFTSModel.integrity_check���cCs|jd||f�S)Nzmerge=%s,%s)r�)riZblocksZsegmentsrrr�merge0szFTSModel.mergeTcCs|jd|rdpd�S)Nzautomerge=%s�1�0)r�)ri�staterrr�	automerge4szFTSModel.automergecCst|j�|�S)zU
        Generate a `MATCH` expression appropriate for searching this table.
        )�match�	as_entity)ri�termrrrr�8szFTSModel.matchcGs"tjtj|j�t�|�S)N)r5�fts_rank�	matchinfor��FTS_MATCHINFO_FORMAT_SIMPLE)ri�weightsrrr�rank?sz
FTSModel.rankcGs(tj|j�t�}tj||�S)N)r5r�r��FTS_MATCHINFO_FORMAT�fts_bm25)rir��
match_inforrr�bm25Dsz
FTSModel.bm25cGs(tj|j�t�}tj||�S)N)r5r�r�r��
fts_lucene)rir�r�rrr�luceneIszFTSModel.lucenecCs�|s|�}not|t�rug}x<|jjD].}	|j|j|	|j|	jd���q4W||�}n||�}f}
|}|r�||j|�f}
|r�|r�t|�}|j	|
�j
|j|��j|�S)Ng�?)
r8r;r]�declared_fieldsrArvr`�aliasr#�select�wherer��order_by)rir�r��
with_score�score_aliasZscore_fn�explicit_orderingr��weight_args�field�	selectionr�rrr�_searchNs&&
	zFTSModel._searchNF�scorecCs|j|||||j|�S)z'Full-text search using selected `term`.)r�r�)rir�r�r�r�r�rrr�searchhszFTSModel.searchcCs|j|||||j|�S)z:Full-text search for selected `term` using BM25 algorithm.)r�r�)rir�r�r�r�r�rrr�search_bm25tszFTSModel.search_bm25cCs|j|||||j|�S)z:Full-text search for selected `term` using BM25 algorithm.)r�r�)rir�r�r�r�r�rrr�
search_lucene�szFTSModel.search_lucene)rrrrrrrhrqr|r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrxs4		

rx�abcdefghijklmnopqrstuvwxyz�	� �,�"��(�)�{�}r�:rW�+�
0123456789cCs.g|]$}t|�tkrt|��qSr)�chr�	_alphanum)rI�prrrrJ�s	rJ�z(?:[^\s"]|"(?:\.|[^"])*")+c@s�eZdZdZe�ZGdd�d�Zdddddd	iZed
d��Z	edd
��Z
edd��Zee
d�dd��Zedd��Zedd��Zedd��Zedddddd��Zedddddd��Zed d!��Zed"d#��Zed$d%��Zed&d'��Zed(d)��Zed*d+��Zed,dd-d.��ZdS)/�	FTS5Modelan
    Requires SQLite >= 3.9.0.

    Table options:

    content: table name of external content, or empty string for "contentless"
    content_rowid: column name of external content primary key
    prefix: integer(s). Ex: '2' or '2 3 4'
    tokenize: porter, unicode61, ascii. Ex: 'porter unicode61'

    The unicode tokenizer supports the following parameters:

    * remove_diacritics (1 or 0, default is 1)
    * tokenchars (string of characters, e.g. '-_'
    * separators (string of characters)

    Parameters are passed as alternating parameter name and value, so:

    {'tokenize': "unicode61 remove_diacritics 0 tokenchars '-_'"}

    Content-less tables:

    If you don't need the full-text content in it's original form, you can
    specify a content-less table. Searches and auxiliary functions will work
    as usual, but the only values returned when SELECT-ing can be rowid. Also
    content-less tables do not support UPDATE or DELETE.

    External content tables:

    You can set up triggers to sync these, e.g.

    -- Create a table. And an external content fts5 table to index it.
    CREATE TABLE tbl(a INTEGER PRIMARY KEY, b);
    CREATE VIRTUAL TABLE ft USING fts5(b, content='tbl', content_rowid='a');

    -- Triggers to keep the FTS index up to date.
    CREATE TRIGGER tbl_ai AFTER INSERT ON tbl BEGIN
      INSERT INTO ft(rowid, b) VALUES (new.a, new.b);
    END;
    CREATE TRIGGER tbl_ad AFTER DELETE ON tbl BEGIN
      INSERT INTO ft(fts_idx, rowid, b) VALUES('delete', old.a, old.b);
    END;
    CREATE TRIGGER tbl_au AFTER UPDATE ON tbl BEGIN
      INSERT INTO ft(fts_idx, rowid, b) VALUES('delete', old.a, old.b);
      INSERT INTO ft(rowid, b) VALUES (new.a, new.b);
    END;

    Built-in auxiliary functions:

    * bm25(tbl[, weight_0, ... weight_n])
    * highlight(tbl, col_idx, prefix, suffix)
    * snippet(tbl, col_idx, prefix, suffix, ?, max_tokens)
    c@seZdZdZdS)zFTS5Model.Meta�fts5N)rrrrfrrrrrh�srh�
field_typezQBesides the implicit `rowid` column, all columns must be instances of SearchField�indexz3Secondary indexes are not supported for FTS5 models�pkz4FTS5 models must use the default `rowid` primary keycCs�|jjjdkr(t|jd��xB|jjj�D].}t|tt	f�s;t|jd��q;W|jj
r�t|jd��dS)Nrr�r�r�)r]rzr`r{�_error_messages�fields�valuesr8rPr�indexes)rir�rrrr|�szFTS5Model.validate_modelcCs�tjdd�tkrdStjd�}z`y|jd�WnHytjd�tjd�WndSYnX|jjjd�YnXWd|j	�XdS)NrFz:memory:z0CREATE VIRTUAL TABLE fts5test USING fts5 (data);Tr�)
r�sqlite_version_info�FTS5_MIN_VERSION�connect�execute�enable_load_extension�load_extensionr]rm�close)riZtmp_dbrrr�fts5_installed�s
	zFTS5Model.fts5_installedcCsYtj|�}xC|D];}|jd�r=|jd�r=qt|�t@rdSqWdS)z�
        Simple helper function to indicate whether a search query is a
        valid FTS5 query. Note: this simply looks at the characters being
        used, and is not guaranteed to catch all problematic queries.
        r�FT)�	_quote_re�findallr2�endswithrH�_invalid_ascii)�query�tokens�tokenrrr�validate_query�s
zFTS5Model.validate_queryr�c	Cs�g}d}tj|�}x�|D]�}|jd�rV|jd�rV|j|�q"t|�}|t@}|r�d}x |D]}|j||�}qW|j|�q"W|r�dj|�S|S)z2
        Clean a query of invalid tokens.
        Fr�Tr�)	r�r�r2r�rArHr�rG�join)	r�rGrCZany_invalidr�r�Z	token_setZinvalid_for_token�crrr�clean_querys"




zFTS5Model.clean_querycCst|j�|�S)zU
        Generate a `MATCH` expression appropriate for searching this table.
        )r�r�)rir�rrrr�$szFTS5Model.matchcGs!|r|j|�Std�SdS)Nr�)r�r#)ri�argsrrrr�+s
zFTS5Model.rankcGstj|j�|�S)N)r5r�r�)rir�rrrr�2szFTS5Model.bm25NFr�cCs"|jtj|�||||�S)z'Full-text search using selected `term`.)r�r�r�)rir�r�r�r�r�rrrr�6szFTS5Model.searchcCs
|std�}n�t|t�r�g}x<|jjD].}|j|j||j|jd���q7Wtj	|j
�|�}ntj	|j
�|�}f}	|}
|r�||j|�f}	|r�|r�t|�}
|j|	�j
|jtj|���j|
�S)z'Full-text search using selected `term`.r�g�?)r#r8r;r]r�rArvr`r5r�r�r�r�r�r�r�r�r�)rir�r�r�r�r�r�r�r�r�r�rrrr�As&&
	zFTS5Model.search_bm25c
Ks�|j�}|g}|g}x:|j�D],\}}|jt|��|j|�q+Wt|�}ttd�|j�t|�td�t|��}	|jjj	|	�S)NzINSERT INTO�VALUES)
r��itemsrArr�Clauser#r]rmr�)
rir�Zextra_paramsr��columnsr��keyr-Zinner_clause�clauserrrr�\s						zFTS5Model._fts_cmdcCs;d|kodkns(td��|jdd|�S)Nr�zlevel must be between 0 and 16r�r�)r,r�)ri�levelrrrr�nszFTS5Model.automergecCs|jdd|�S)Nr�r�)r�)riZnpagesrrrr�tszFTS5Model.mergecCs|jdd|�S)N�pgszr�)r�)rir�rrr�set_pgszxszFTS5Model.set_pgszcCs|jdd|�S)Nr�)r�)riZrank_expressionrrr�set_rank|szFTS5Model.set_rankcCs
|jd�S)Nz
delete-all)r�)rirrr�
delete_all�szFTS5Model.delete_all�rowc
s��dkrtd��d�}t�|�s�G���fdd�d�}dt�dt�d	t�d
t�d|i}�dkr�t�|d<d�j}t�|t|tf|��t	�|�S)
Nr��colz)table_type must be either "row" or "col".z_vocab_model_%scsPeZdZ�jjZ�p+�jjdZej�j�e	���Z
dS)z"FTS5Model.VocabModel.<locals>.MetaZ_vN)rrrr]rmr}r5Z	fts5vocabr�r#rfr)ri�
table_name�
table_typerrrh�s
	rhr��docZcntrz%sVocab)r�r�)
r,�hasattr�	BareField�IntegerFieldrr�setattr�typere�getattr)rir�r��attrrh�attrs�
class_namer)rir�r�r�
VocabModel�s
				

zFTS5Model.VocabModel)rrrrrrrhr�rqr|r��staticmethodr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrr��s85			r�cs��dkrKx<�jjj�D]}|j�kr|�PqWtd���jj�G���fdd�dt�}G��fdd�d�}d�j}t||fd|i�S)z3Model factory for the transitive closure extension.Nz,Unable to find self-referential foreign key.cs�eZdZe�Ze�Ze�Ze�Ze�Ze	�Z
Gdd�d�Zedd��fdd��Z
edd��fdd��Zed���fd	d
��ZdS)z&ClosureTable.<locals>.BaseClosureTablec@seZdZdZdS)z+ClosureTable.<locals>.BaseClosureTable.MetaZtransitive_closureN)rrrrfrrrrrh�srhNFcs��j�|jjd��j|d�|jk�j|j|k�}|dk	ro|j|j|k�}n|s�|j|jdk�}|S)N�depth�onr)r�r�r�r��idr��root)ri�noder��include_noder�)r_rzrr�descendants�sz2ClosureTable.<locals>.BaseClosureTable.descendantscs��j�|jjd��j|d�|jk�j|j|k�}|ri|j|j|k�}n|s�|j|jdk�}|S)Nr�r�r)r�r�r�r�r�r�r�)rir�r�r�r�)r_rzrr�	ancestors�sz0ClosureTable.<locals>.BaseClosureTable.ancestorscsO|jj�j�}�j�j�|k�}|sK|j�|k�}|S)N)�_datarvr`r�r�)rir�r�Zfk_valuer�)�foreign_keyr_rzrr�siblings�s
z/ClosureTable.<locals>.BaseClosureTable.siblings)rrrrbr�r��idcolumn�parentcolumnr�rc�	tablenamerhrqr�r�rr)r�r_rzrr�BaseClosureTable�s						rcsLeZdZ�jjZd�jjd�jjjd�jiZdZdS)zClosureTable.<locals>.MetarrrFN)	rrrr]rmr}rzrRrgr)r�r_rrrh�s
rhz	%sClosure)	r]�relr��	rel_modelr,rzrerr�)r_r��	field_objrrhr`r)r�r_rzr�ClosureTable�s"+
rcsLeZdZdZdd�fdd�Zdd�Zdddd	�Z�S)
�SqliteExtQueryCompilerzQ
    Subclass of QueryCompiler that can be used to construct virtual tables.
    FNc
stt|�j|d|�}t|t�r�d}|jj}t|t�r�|j	dd�t
d�|g}t|�}q�|j	jdt
d|��nd}|r�|d7}t
|�|j	d<|j
|||�}|r�|j	d}	x�t|j��D]�\}
}t|t�r7|j|d
k�}n�tj|�rdt|t�rd|j�}nUt|ttf�r�t
ddjtt|���}nt|t�s�t
|�}tt
|
�|�}d
|_|	j	j|�qWt|jdd�r|j	jt
d��|S)N�safezCREATE VIRTUAL TABLEr=ZUSINGzUSING %szCREATE TABLEz IF NOT EXISTSrr>r�z'%s'r��=Z
without_rowidz
WITHOUT ROWID���)r!r	�
_create_table�
issubclassrer]rfr8r�nodesr#r�rFrk�sortedr��Fieldr��inspect�isclass�Modelr9r:r��map�str�gluerAr�)
r$r_r
rjr��	statement�	extension�partsZ
table_optionsZcolumns_constraints�k�v�option)r'rrr
�s># 

%	z$SqliteExtQueryCompiler._create_tablecCsSt|jdd�}|r-|j|�}ni}|rO|j|j|��|S)Nrg)r�r]rk�update)r$r_r�Z
extra_optionsZ
model_optionsrjrrrrk sz$SqliteExtQueryCompiler.clean_optionscCs|j|j|||��S)N)�
parse_noder
)r$r_r
rjrrrrn*sz#SqliteExtQueryCompiler.create_table)rrrrr
rkrnrr)r'rr	�s6
r	rZFcCstd|dd�S)Nr�rru)r�)r$rrr�
disqualify.sr csceZdZdZeZd�fdd�Zedd��Zdd�Z	d	d
�Z
dd�Zd
d�Zdd�Z
dd3dd�Zdd4dd�Zddd�Zddd�Zdd5dd�Zdd6dd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+dd,d-�Zd+�fd.d/�Zd0d1d2�Z�S)7�SqliteExtDatabasez�
    Database class which provides additional Sqlite-specific functionality:

    * Register custom aggregates, collations and functions
    * Specify a row factory
    * Advanced transactions (specify isolation level)
    Tcsmtt|�j|||�i|_i|_i|_tg�|_d|_t	r|rd|_
|jt	jdd�|jt	j
dd�|jt	jdd�|jt	jdd�|jt	jdd
�|jt	jd	d�|jt	jd
d�nhd|_
|jtdd�|jtdd�|jtdd�|jtdd�|jtd	d�dS)NT�	date_partr=�
date_trunc�regexpr�r>r�r�Z
murmurhashFrrrrr)r!r!rV�_aggregates�_collations�
_functionsrH�_extensions�_row_factory�_c_ext�_using_c_extensions�register_functionZpeewee_date_partZpeewee_date_truncZ
peewee_regexpZpeewee_rankZ
peewee_luceneZpeewee_bm25Zpeewee_murmurhashr
rrr�r�)r$rmZc_extensionsr�rX)r'rrrV?s*						zSqliteExtDatabase.__init__cCs|jS)N)r+)r$rrr�using_c_extensionsWsz$SqliteExtDatabase.using_c_extensionscCsc|j|�|j|�|j|�|j|�|jrI|j|_|jr_|j|�dS)N)�_set_pragmas�_load_aggregates�_load_collations�_load_functionsr)�row_factoryr(�_load_extensions)r$�connrrr�_add_conn_hooks[s



		z!SqliteExtDatabase._add_conn_hookscCs=x6|jj�D]%\}\}}|j|||�qWdS)N)r%r��create_aggregate)r$r4r`�klass�
num_paramsrrrr/es"z"SqliteExtDatabase._load_aggregatescCs4x-|jj�D]\}}|j||�qWdS)N)r&r��create_collation)r$r4r`r5rrrr0isz"SqliteExtDatabase._load_collationscCs=x6|jj�D]%\}\}}|j|||�qWdS)N)r'r��create_function)r$r4r`r5r8rrrr1ms"z!SqliteExtDatabase._load_functionscCs2|jd�x|jD]}|j|�qWdS)NT)r�r(r�)r$r4rrrrr3qs
z"SqliteExtDatabase._load_extensionsNr>cCsE||f|j|p!|jj�<|j�sA|j|j��dS)N)r%r�lower�	is_closedr/�get_conn)r$r7r`r8rrr�register_aggregatevs"z$SqliteExtDatabase.register_aggregatecs���fdd�}|S)Ncs�j|���|S)N)r>)r7)r`r8r$rr�	decorator|sz.SqliteExtDatabase.aggregate.<locals>.decoratorr)r$r`r8r?r)r`r8r$r�	aggregate{szSqliteExtDatabase.aggregatecsZ�p|j��fdd�}||_||j�<|j�sV|j|j��dS)Ncs!|td��f}t|�S)Nz
collate %s)r#r�)r��expressions)r`rr�
_collation�sz8SqliteExtDatabase.register_collation.<locals>._collation)r�	collationr&r<r0r=)r$r5r`rBr)r`r�register_collation�s	
z$SqliteExtDatabase.register_collationcs��fdd�}|S)Ncs�j|��|S)N)rD)r5)r`r$rrr?�sz.SqliteExtDatabase.collation.<locals>.decoratorr)r$r`r?r)r`r$rrC�szSqliteExtDatabase.collationcCs?||f|j|p|j<|j�s;|j|j��dS)N)r'rr<r1r=)r$r5r`r8rrrr,�sz#SqliteExtDatabase.register_functioncs���fdd�}|S)Ncs�j|���|S)N)r,)r5)r`r8r$rrr?�sz)SqliteExtDatabase.func.<locals>.decoratorr)r$r`r8r?r)r`r8r$r�func�szSqliteExtDatabase.funccCsF|jj|�|j�sB|j�}|jd�|j|�dS)NT)r(�addr<r=r�r�)r$rr4rrrr��s

z SqliteExtDatabase.load_extensioncCs|j|=dS)N)r%)r$r`rrr�unregister_aggregate�sz&SqliteExtDatabase.unregister_aggregatecCs|j|=dS)N)r&)r$r`rrr�unregister_collation�sz&SqliteExtDatabase.unregister_collationcCs|j|=dS)N)r')r$r`rrr�unregister_function�sz%SqliteExtDatabase.unregister_functioncCs|jj|�dS)N)r(rL)r$rrrr�unload_extension�sz"SqliteExtDatabase.unload_extensioncCs
||_dS)N)r))r$r5rrrr2�szSqliteExtDatabase.row_factoryFcCs1|j�j|||�\}}|j||�S)N)�compilerrnr~)r$r_r
rj�sql�paramsrrrrn�s!zSqliteExtDatabase.create_tablecs/t|t�rdStt|�j|||�S)N)rrxr!r!�create_index)r$r_�
field_name�unique)r'rrrN�szSqliteExtDatabase.create_index�deferredcCs%|j�dkst�t||�S)NrQ�	immediate�	exclusive)rQrRrS)r;�AssertionError�granular_transaction)r$�	lock_typerrrrU�sz&SqliteExtDatabase.granular_transactionrrrr)rrrrr	�compiler_classrV�propertyr-r5r/r0r1r3r>r@rDrCr,rEr�rGrHrIrJr2rnrNrUrr)r'rr!5s0

r!c@s+eZdZddd�Zdd�ZdS)rUrQcCs(||_|jj�|_||_dS)N)�dbr=r4rV)r$rYrVrrrrV�s	zgranular_transaction.__init__cCs|jj|j�dS)N)rY�beginrV)r$rrr�_begin�szgranular_transaction._beginN)rrrrVr[rrrrrU�srUr��MATCHcCst|tj|�S)N)rrr\)�lhs�rhsrrrr��scs/t��}�fdd�td|d�D�S)Ncs4g|]*}tjd�||d��d�qS)z@Irr)�struct�unpack)rIrD)�bufrrrJ�s	z%_parse_match_info.<locals>.<listcomp>rr)r?r@)ra�bufsizer)rar�_parse_match_info�srccGst|�}d}|dd�\}}|s>dg|}n4dg|}x$t|�D]\}}|||<qXWx�t|�D]�}d||d}	xst|�D]e}
||
}|s�q�|	|
d}|||d�\}}
|dkr�||t|�|
7}q�WqW|S)Ngr=r>rr)rc�	enumerater@�float)�raw_match_infor�r�r�r�r�rD�weightZ
phrase_numZphrase_info_idxZcol_numZcol_idx�x1Zx2rrrr��s&

 r�cGs�t|�}d}d}d}td�\}}}}	||}
||}||}|	|}
|
|}|s~dg|}n8dg|}x(t|�D]\}}||||<q�Wx@t|
�D]2}x)t|�D]}||}|dkr�q�t||	|�}t||
|�}|dkr2d}nd||||}|d||d}t||�}t||d�}ttj||d	|d	�d�}|||}|dkr�d}n||d|}||||7}q�Wq�W|S)
z�
    Usage:

        # Format string *must* be pcnalx
        # Second parameter to bm25 specifies the index of the column, on
        # the table being queries.
        bm25(matchinfo(document_tbl, 'pcnalx'), 1) AS rank
    g333333�?g�?grr>rrr=g�?)rcr@rdre�max�math�log)rfr�r��K�Br�ZP_OZC_OZN_OZA_OZ
term_countZ	col_countZ
total_docsZL_OZX_Or�rDrg�jZ
avg_lengthZ
doc_length�D�xZterm_frequencyZdocs_with_termZidfZdenomr^rrrr��sN	






			r�)QrZglobrrj�os�rer_�sysZ
simplejsonr)�ImportErrorZvtfuncr�peeweerrrrrr	r
rrr
rr�	playhouserr*�version_inforrwr�r�r�ryr�rr�PrimaryKeyFieldr �	TextFieldr(r�rP�objectr[rar�rb�	CharFieldrc�
FloatFieldrdrrerrrxZ	_alphabetrHr��upperr�r@r��compiler�r�rr	�extendr �SqliteDatabaser!rUr\�register_opsr�rcr�r�rrrr�<module>!s�



.R�]�CH�