Skip to content

Commit

Permalink
Beta version
Browse files Browse the repository at this point in the history
Added utils subpackages: Manager class, api function decorator
and global_session function.
  • Loading branch information
MatteoGuadrini committed Nov 6, 2021
2 parents 453afee + 47e65c0 commit fb8dff3
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 16 deletions.
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

_nosqlapi_ is a library for building standard NOSQL python libraries.

> ATTENTION: This is **WIP** in _alpha_ version
> ATTENTION: This is **WIP** in _beta_ version
## Introduction

Expand Down Expand Up @@ -146,11 +146,11 @@ This read-only attribute contains a boolean value.

#### Connection methods

`.close()`
`.close(parameters...)`

Closing the connection now.

`.connect()`
`.connect(parameters...)`

Connecting to database with the arguments when object has been instantiated.

Expand All @@ -166,7 +166,7 @@ Checking if exists a single database with position and keyword arguments.

Deleting of a single database with position and keyword arguments.

`.databases()`
`.databases(parameters...)`

List all databases.

Expand Down Expand Up @@ -229,7 +229,7 @@ Updating one or more existing data on specific database with position and keywor

Deleting one existing data on specific database with position and keyword arguments.

`.close()`
`.close(parameters...)`

Closing the session and connection now.

Expand Down Expand Up @@ -301,7 +301,7 @@ This read/write attribute represents _limit_ number of objects returned from fin

#### Selector methods

`.build()`
`.build(parameters...)`

Building a _selector_ string in the dialect of a NOSQL language based on various property of the `Selector` object.

Expand Down Expand Up @@ -329,6 +329,10 @@ This read-only attribute represents a string information (header) of an operatio

This read-only attribute represents a string error of an operation.

`.dict`

This read-only attribute represents a dictionary transformation of Response object.

### Batch Objects

`Batch` objects should respond to the following methods.
Expand Down
2 changes: 1 addition & 1 deletion __info__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

"""Information variable used by modules on this package."""

__version__ = '0.0.8'
__version__ = '0.0.9'
__author__ = 'Matteo Guadrini'
__email__ = 'matteo.guadrini@hotmail.it'
__homepage__ = 'https://github.com/MatteoGuadrini/nosqlapi'
22 changes: 16 additions & 6 deletions nosqlapi/common/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,8 @@
# endregion

# region global variable
__all__ = ['Connection', 'Selector', 'Session', 'Response', 'Batch']


# endregion

# region global variables
API_NAME = 'nosqlapi'
__all__ = ['Connection', 'Selector', 'Session', 'Response', 'Batch']


# endregion
Expand Down Expand Up @@ -431,6 +426,15 @@ def error(self):
"""Error of an operation"""
return self._error

@property
def dict(self):
d = dict()
d['data'] = self.data
d['code'] = self.code
d['header'] = self.header
d['error'] = self.error
return d

def __bool__(self):
if self.error:
return False
Expand All @@ -443,9 +447,15 @@ def __str__(self):
def __repr__(self):
return f"<{API_NAME} {self.__class__.__name__} object>"

def __len__(self):
return self.data.__len__()

def __contains__(self, item):
return True if item in self.data else False

def __getitem__(self, item):
return self.data[item]


class Batch(ABC):
"""Batch abstract class"""
Expand Down
5 changes: 5 additions & 0 deletions nosqlapi/common/core.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ class Response:
code: int
header: Union[str, tuple]
error: Union[str, Exception]
dict: dict

def __init__(self, data: Any, code: int = None, header: Union[str, tuple] = None,
error: Union[str, Exception] = None) -> None:
Expand All @@ -168,4 +169,8 @@ class Response:

def __repr__(self) -> str: ...

def __len__(self) -> int: ...

def __contains__(self, item) -> bool: ...

def __getitem__(self, item) -> Any: ...
56 changes: 56 additions & 0 deletions nosqlapi/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
'show_database', 'get', 'insert', 'insert_many', 'update', 'update_many', 'delete', 'find',
'grant', 'revoke', 'new_user', 'set_user', 'delete_user', 'add_index', 'add_index',
'call', 'build', 'execute', 'link', 'detach')
__all__ = ['api', 'global_session', 'Manager']


# endregion
Expand Down Expand Up @@ -63,11 +64,24 @@ def wrapped(cls):
return wrapped


def global_session(connection, *args, **kwargs):
"""Global session
:param connection: Connection object
:param args: positional arguments of connect method on Connection object
:param kwargs: keywords arguments of connect method on Connection object
:return: None
"""
if not hasattr(connection, 'connect'):
raise ConnectError(f'{connection} is not valid api connection')
globals()['SESSION'] = connection.connect(*args, **kwargs)

# endregion


# region classes
class Manager:
"""Manager class for api compliant nosql database connection"""

def __init__(self, connection, *args, **kwargs):
# Check if connection is a compliant API connection object
Expand Down Expand Up @@ -106,6 +120,45 @@ def description(self):
def indexes(self):
return self._indexes

# Connection methods

def create_database(self, *args, **kwargs):
"""Create new database
:return: Union[bool, Response]
"""
return self.connection.create_database(*args, **kwargs)

def has_database(self, *args, **kwargs):
"""Check if database exists
:return: Union[bool, Response]
"""
return self.connection.has_database(*args, **kwargs)

def delete_database(self, *args, **kwargs):
"""Delete database on server
:return: Union[bool, Response]
"""
return self.connection.delete_database(*args, **kwargs)

def databases(self, *args, **kwargs):
"""Get all databases
:return: Union[tuple, list, Response]
"""
return self.connection.databases(*args, **kwargs)

def show_database(self, *args, **kwargs):
"""Show a database information
:return : Union[Any, Response]
"""
return self.connection.show_database(*args, **kwargs)

# Session methods

def get(self, *args, **kwargs):
"""Get one or more value
Expand Down Expand Up @@ -247,4 +300,7 @@ def __enter__(self):
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()

def __del__(self):
self.close()

# endregion
19 changes: 17 additions & 2 deletions nosqlapi/common/utils.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from nosqlapi import Response, Batch, Connection
from typing import Union
from typing import Union, Any


def api(**methods: str) -> type: ...

def global_session(connection: Any, *args, **kwargs) -> None: ...

class Manager:

item_count: int
Expand All @@ -43,6 +46,16 @@ class Manager:
self._description = self.session.description
self._indexes = self.session.indexes

def create_database(self, *args, **kwargs) -> Union[bool, Response]: ...

def has_database(self, *args, **kwargs) -> Union[bool, Response]: ...

def delete_database(self, *args, **kwargs) -> Union[bool, Response]: ...

def databases(self, *args, **kwargs) -> Union[tuple, list, Response]: ...

def show_database(self, *args, **kwargs) -> Union[Any, Response]: ...

def get(self, *args, **kwargs) -> Union[tuple, dict, Response]: ...

def insert(self, *args, **kwargs) -> Union[bool, Response]: ...
Expand Down Expand Up @@ -83,6 +96,8 @@ class Manager:

def __bool__(self) -> bool: ...

def __enter__(self) -> None: ...
def __enter__(self) -> object: ...

def __exit__(self, exc_type: type, exc_val: str, exc_tb: str) -> None: ...

def __del__(self) -> None: ...
22 changes: 21 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest
import nosqlapi
from test_kvdb import MyDBConnection as KVConn
from test_kvdb import MyDBConnection as KVConn, MyDBResponse
from test_docdb import MyDBConnection as DocConn


Expand Down Expand Up @@ -53,6 +53,26 @@ def test_manager_crud_operation(self):
man.update('key', 'new_value')
self.assertEqual(man.item_count, 1)

def test_connection_operation(self):
man = nosqlapi.Manager(KVConn(host='mykvdb.local', username='test', password='pass', database='test_db'))
# Create database
man.create_database('test_db')
self.assertEqual(man.connection.return_data, 'DB_CREATED')
# Exists database
man.has_database('test_db')
self.assertEqual(man.connection.return_data, 'DB_EXISTS')
# Delete database
man.delete_database('test_db')
self.assertEqual(man.connection.return_data, 'DB_DELETED')
# All databases
dbs = man.databases()
self.assertIsInstance(dbs, MyDBResponse)
self.assertEqual(dbs.data, ['test_db', 'db1', 'db2'])
# Show database
db = man.show_database('test_db')
self.assertIsInstance(db, MyDBResponse)
self.assertEqual(db.data, 'name=test_db, size=0.4GB')

def test_change_connection(self):
man = nosqlapi.Manager(KVConn(host='mykvdb.local', username='test', password='pass', database='test_db'))
self.assertIsInstance(man.connection, KVConn)
Expand Down

0 comments on commit fb8dff3

Please sign in to comment.