Skip to content

42Wor/mDB_python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

maazDB_python: Python Client Library for maazDB

License: MIT Python Versions Package Version

Introduction

for interacting with maazDB, a lightweight and efficient database server accessible via WebSocket. This library provides a simple and asynchronous interface to connect to your maazDB server and execute SQL queries, making it easy to build Python applications that leverage the power of maazDB.

Installation

Navigate to your project directory in your terminal and create a virtual environment:

virtualenv venv

Activate the virtual environment:

On Linux/macOS:

source venv/bin/activate

On Windows:

venv\Scripts\activate

Install maazDB_python:

pip install maazDB_python

This command will download and install maazDB_python and its dependency, websockets. pip will automatically handle dependency resolution and ensure that all necessary packages are installed correctly.

Verify Installation

After successful installation, you can verify it by opening a Python interpreter and trying to import the MaazDBClient class:

import maazdb_python
from maazdb_python import MaazDBClient

print(maazdb_python.__version__)  # If you add __version__ to __init__.py
print(MaazDBClient)

If no errors occur during the import, and you see the class printed, the installation was successful.

Prerequisites

  • Python: maazDB_python requires Python 3.7 or higher. It is recommended to use the latest stable version of Python for the best experience and security.
  • maazDB Server: You need to have a running maazDB server instance that you can connect to. Make sure you have the server address and port number readily available. Refer to the maazDB server documentation for instructions on how to set up and run a maazDB server.
  • Network Connectivity: Ensure that your Python application has network connectivity to the machine where the maazDB server is running, and that the port used by the server is accessible. Firewall rules might need to be adjusted if you are connecting across networks.

Getting Started

Let's walk through a basic example to get you started with maazDB_python. This example demonstrates how to:

  1. Import the MaazDBClient class.
  2. Create a MaazDBClient instance.
  3. Connect to the maazDB server.
  4. Select a database to use.
  5. Execute a simple SELECT query.
  6. Print the results.
  7. Close the connection.
import asyncio
from maazdb_python import MaazDBClient

async def main():
    """
    Example usage of the MaazDBClient.
    """
    client = MaazDBClient("localhost", 8080)  # Replace with your server address and port

    try:
        await client.connect()
        await client.use_database("mydatabase.db")  # Replace with an existing database name on your server

        # Example SELECT query
        select_query = "SELECT * FROM users"
        select_results = await client.execute_select(select_query)
        if select_results:
            print("SELECT Results:")
            for row in select_results:
                print(row)
        else:
            print("SELECT query returned no results or error.")

        await client.close()

    except Exception as e:
        print(f"Client error: {e}")
    finally:
        if client.websocket and client.websocket.open:  # Ensure close even if errors occurred
            await client.close()

if __name__ == "__main__":
    asyncio.run(main())

Explanation of the Example

  • import asyncio and from maazdb_python import MaazDBClient: Imports the necessary modules. asyncio is required for asynchronous operations, and MaazDBClient is the class we will use to interact with the database.
  • client = MaazDBClient("localhost", 8080): Creates an instance of MaazDBClient. Replace "localhost" with the address of your maazDB server and 8080 with the port number.
  • await client.connect(): Establishes a connection to the maazDB server. This is an asynchronous operation, so we use await.
  • await client.use_database("mydatabase.db"): Selects the database named "mydatabase.db". Replace this with the name of a database that exists on your maazDB server.
  • select_query = "SELECT * FROM users": Defines a simple SQL SELECT query to retrieve all rows from the users table.
  • select_results = await client.execute_select(select_query): Executes the SELECT query. The results are returned as a list of dictionaries, where each dictionary represents a row from the database.
  • if select_results: and the for loop: Checks if results were returned (i.e., the query was successful and returned data) and then iterates through the results, printing each row.
  • await client.close(): Closes the connection to the maazDB server. It's important to close the connection when you are finished with it to release resources.
  • try...except...finally block: Encloses the code in a try...except block to catch potential exceptions during client operations. The finally block ensures that the connection is closed even if errors occur.
  • if __name__ == "__main__": asyncio.run(main()): This standard Python idiom runs the main() asynchronous function when the script is executed directly. asyncio.run() is used to start the asyncio event loop and run the main() coroutine.

Running the Example

  1. Save the code: Save the code above as a Python file (e.g., example.py).
  2. Ensure maazDB Server is Running: Make sure your maazDB server is running and accessible at the specified address and port (localhost:8080 in this example). Also, ensure that the database "mydatabase.db" exists and contains a table named "users" (or adjust the query and database name accordingly).
  3. Run the Script: Execute the Python script from your terminal:
python example.py
python test.py

If everything is set up correctly, you should see output similar to:

Connected to maazDB server at ws://localhost:8080
Using database: mydatabase.db
SELECT Results:
{'id': 1, 'name': 'Alice'}
{'id': 2, 'name': 'Bob'}
... (and so on, depending on your data) ...
Connection to maazDB server closed.

If you encounter errors, carefully check the error messages and ensure that the maazDB server is running, the database exists, and the connection details are correct.for interacting with maazDB, a lightweight and efficient database server accessible via WebSocket. This library provides a simple and asynchronous interface to connect to your maazDB server and execute SQL queries, making it easy to build Python applications that leverage the power of maazDB.

This client library is designed with ease of use and developer experience in mind. It handles the complexities of WebSocket communication and data serialization, allowing you to focus on writing your database queries and building your application logic. Whether you are building a small personal project or a large-scale application, maazDB_python aims to be a reliable and performant tool for your database interactions.

Key Features:

  • Asynchronous Communication: Built using asyncio and websockets, ensuring non-blocking operations and efficient handling of concurrent requests.
  • Simple and Intuitive API: Easy-to-use functions for connecting, selecting databases, and executing SQL queries (SELECT and INSERT supported in this version).
  • Error Handling: Comprehensive error handling to gracefully manage connection issues, database errors, and invalid queries.
  • Parameterized Queries: Supports parameterized queries for secure and efficient data insertion, preventing SQL injection vulnerabilities.
  • Clear Response Handling: Processes server responses and provides results in a Python-friendly format (lists of dictionaries for SELECT, status dictionaries for INSERT).
  • Connection Management: Provides methods for establishing and closing connections to the maazDB server.
  • Database Selection: Allows you to specify which database to use for your operations.
  • Lightweight and Minimal Dependencies: Relies on the robust websockets library for WebSocket communication, keeping dependencies minimal and the library lightweight.

Target Audience:

This library is intended for Python developers who want to:

  • Interact with a maazDB database server from their Python applications.
  • Build applications that require real-time data access and updates.
  • Utilize a lightweight and efficient database solution.
  • Work with asynchronous programming paradigms for improved performance.
  • Develop applications ranging from simple scripts to complex web services.

Project Status:

This library is currently in Alpha stage. It is functional and provides core features for interacting with maazDB. However, it is still under active development, and the API might evolve based on user feedback and further testing. We encourage users to try it out, provide feedback, and report any issues they encounter. Future versions may include support for more SQL operations (UPDATE, DELETE, CREATE TABLE, etc.), enhanced error handling, and additional features to improve usability and performance.

License:

maazDB_python is released under the MIT License. This permissive license allows you to use, modify, and distribute the library freely, even for commercial purposes. See the LICENSE file for the full license text.

About

for interacting with maazDB, a lightweight and efficient database server accessible via WebSocket. This library provides a simple and asynchronous interface to connect to your maazDB server and execute SQL queries, making it easy to build Python applications that leverage the power of maazDB.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors