Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 79 additions & 22 deletions tinymongo/tinymongo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
from uuid import uuid1

from tinydb import Query, TinyDB, where
from .results import InsertOneResult, InsertManyResult, UpdateResult, DeleteResult
from .errors import DuplicateKeyError

# from .results import InsertOneResult, InsertManyResult, UpdateResult, DeleteResult
# from .errors import DuplicateKeyError
from tinymongodb.results import InsertOneResult, InsertManyResult, UpdateResult, DeleteResult
from tinymongodb.errors import DuplicateKeyError
try:
basestring
except NameError:
Expand Down Expand Up @@ -66,10 +67,14 @@ def _storage(self):
return serialization

"""
# return storages.JSONStorage
return TinyDB.default_storage_class

def __getitem__(self, key):
"""Gets a new or existing database based in key"""
return self._get_db(key)

def _get_db(self, key):
return TinyMongoDatabase(key, self._foldername, self._storage)

def close(self):
Expand All @@ -78,7 +83,8 @@ def close(self):

def __getattr__(self, name):
"""Gets a new or existing database based in attribute"""
return TinyMongoDatabase(name, self._foldername, self._storage)
# return TinyMongoDatabase(name, self._foldername, self._storage)
return self._get_db(name)


class TinyMongoDatabase(object):
Expand Down Expand Up @@ -152,6 +158,13 @@ def count(self):
"""
return self.find().count()

def count_documents(self, filter=None):
"""
Counts the documents in the collection.
:return: Integer representing the number of documents in the collection.
"""
return self.find(filter).count()

def drop(self, **kwargs):
"""
Removes a collection from the database.
Expand Down Expand Up @@ -426,7 +439,7 @@ def update(self, query, doc, *args, **kwargs):
else:
return self.update_one(query, doc, *args, **kwargs)

def update_one(self, query, doc):
def update_one(self, query, doc, *args, **kwargs):
"""
Updates one element of the collection

Expand All @@ -451,20 +464,21 @@ def update_one(self, query, doc):

return UpdateResult(raw_result=result)

def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs):
def find(self, _filter=None, sort=None, skip=None, limit=None, *args, **kwargs):
"""
Finds all matching results

:param query: dictionary representing the mongo query
:param _filter: dictionary representing the mongo query
:type _filter: Optional[dict]
:return: cursor containing the search results
"""
if self.table is None:
self.build_table()

if filter is None:
if _filter is None:
result = self.table.all()
else:
allcond = self.parse_query(filter)
allcond = self.parse_query(_filter)

try:
result = self.table.search(allcond)
Expand All @@ -475,7 +489,7 @@ def find(self, filter=None, sort=None, skip=None, limit=None, *args, **kwargs):

return result

def find_one(self, filter=None):
def find_one(self, _filter=None):
"""
Finds one matching query element

Expand All @@ -486,7 +500,7 @@ def find_one(self, filter=None):
if self.table is None:
self.build_table()

allcond = self.parse_query(filter)
allcond = self.parse_query(_filter)

return self.table.get(allcond)

Expand Down Expand Up @@ -594,7 +608,8 @@ def _list_parser(list_doc):

# (TODO) include more data type
if value is None or not isinstance(
value, (dict, list, basestring, bool, float, int)
# value, (dict, list, basestring, bool, float, int)
value, (dict, list, str, bool, float, int)
):
# not support/sortable value type
value = (0, None)
Expand All @@ -605,7 +620,9 @@ def _list_parser(list_doc):
elif isinstance(value, (int, float)):
value = (1, value)

elif isinstance(value, basestring):
# elif isinstance(value, basestring):
elif isinstance(value, str):

value = (2, value)

elif isinstance(value, dict):
Expand Down Expand Up @@ -634,9 +651,11 @@ def sort(self, key_or_list, direction=None):
Sorts a cursor object based on the input

:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
# i.e. ('user_number': -1), or a basestring
i.e. ('user_number': -1), or a str
:param direction: sorting direction, 1 or -1, needed if key_or_list
is a basestring
# is a basestring
is a str
:return:
"""

Expand All @@ -654,14 +673,16 @@ def sort(self, key_or_list, direction=None):
raise TypeError("key pair should be a list or tuple.")
if not len(pair) == 2:
raise ValueError("Need to be (key, direction) pair")
if not isinstance(pair[0], basestring):
# if not isinstance(pair[0], basestring):
if not isinstance(pair[0], str):
raise TypeError("first item in each key pair must " "be a string")
if not isinstance(pair[1], int) or not abs(pair[1]) == 1:
raise TypeError("bad sort specification.")

sort_specifier = key_or_list

elif isinstance(key_or_list, basestring):
# elif isinstance(key_or_list, basestring):
elif isinstance(key_or_list, str):
if direction is not None:
if not isinstance(direction, int) or not abs(direction) == 1:
raise TypeError("bad sort specification.")
Expand Down Expand Up @@ -765,6 +786,19 @@ def sort(self, key_or_list, direction=None):

return self

def limit(self, n):
self.cursordat = self.cursordat[:n]
return self

def has_next(self):
"""
Returns True if the cursor has a next position, False if not
:return:
"""
cursor_pos = self.cursorpos + 1

return cursor_pos + 1 < len(self.cursordat)

def hasNext(self):
"""
Returns True if the cursor has a next position, False if not
Expand Down Expand Up @@ -795,23 +829,46 @@ def count(self, with_limit_and_skip=False):
"""
return len(self.cursordat)

def __iter__(self):
self.cursorpos = -1
return self

def __next__(self):
"""
Returns the next record
:return:
"""
if not self.hasNext():
raise StopIteration
self.cursorpos += 1
return self.cursordat[self.cursorpos]


class TinyGridFS(object):
"""GridFS for tinyDB"""

def __init__(self, *args, **kwargs):
self.database = None

def GridFS(self, tinydatabase):
def grid_fs(self, tinydatabase):
"""TODO: Must implement yet"""
self.database = tinydatabase
return self

def GridFS(self, tinydatabase):
"""TODO: Must implement yet"""
self.database = tinydatabase
return self

def generate_id():
"""Generate new UUID"""
# TODO: Use six.string_type to Py3 compat
try:
return unicode(uuid1()).replace(u"-", u"")
except NameError:
return str(uuid1()).replace(u"-", u"")
return str(uuid1()).replace(u"-", u"")

# def generate_id():
# """Generate new UUID"""
# # TODO: Use six.string_type to Py3 compat
# try:
# return unicode(uuid1()).replace(u"-", u"")
# except NameError:
# return str(uuid1()).replace(u"-", u"")