rqdb


Namerqdb JSON
Version 1.0.10 PyPI version JSON
download
home_pagehttps://github.com/tjstretchalot/rqdb
SummaryAn unofficial python client for RQLite
upload_time2022-09-27 20:56:20
maintainer
docs_urlNone
authorTimothy Moore
requires_python
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # rqdb

This is an unofficial python client for [rqlite](https://github.com/rqlite/rqlite), a
lightweight distributed relational database based on SQLite.

This client supports SQLite syntax, true parameterized queries, and a
calling syntax reminiscent of DB API 2.0.

Furthermore, this client has convenient asynchronous methods which match
the underlying rqlite API.

## Installation

```py
pip install rqdb
```

## Usage

Synchronous queries:

```py
import rqdb
import secrets

conn = rqdb.connect(['127.0.0.1:4001'])
cursor = conn.cursor()
cursor.execute('CREATE TABLE persons (id INTEGER PRIMARY KEY, uid TEXT UNIQUE NOT NULL, name TEXT NOT NULL)')
cursor.execute('CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT NOT NULL, owner_id INTEGER NOT NULL REFERENCES persons(id) ON DELETE CASCADE)')

# standard execute
cursor.execute('INSERT INTO persons (uid, name) VALUES (?, ?)', (secrets.token_hex(8), 'Jane Doe'))
assert cursor.rows_affected == 1

# The following is stored in a single Raft entry and executed within a transaction.

person_name = 'John Doe'
person_uid = secrets.token_urlsafe(16)
pet_name = 'Fido'
result = cursor.executemany3((
    (
        'INSERT INTO persons (uid, name) VALUES (?, ?)',
        (person_uid, person_name)
    ),
    (
        'INSERT INTO pets (name, owner_id) '
        'SELECT'
        '  ?, persons.id '
        'FROM persons '
        'WHERE uid = ?',
        (pet_name, person_uid)
    )
)).raise_on_error()
assert result[0].rows_affected == 1
assert result[1].rows_affected == 1
```

Asynchronous queries:

```py
import rqdb
import secrets

async def main():
    async with rqdb.connect_async(['127.0.0.1:4001']) as conn:
        cursor = conn.cursor()

        result = await cursor.execute(
            'INSERT INTO persons (uid, name) VALUES (?, ?)',
            (secrets.token_hex(8), 'Jane Doe')
        )
        assert result.rows_affected == 1
```

## Additional Features

### Read Consistency

Selecting read consistency is done at the cursor level, either by passing
`read_consistency` to the cursor constructor (`conn.cursor()`) or by setting
the instance variable `read_consistency` directly. The available consistencies
are `strong`, `weak`, and `none`. You may also indicate the `freshness` value
at the cursor level.

See [CONSISTENCY.md](https://github.com/rqlite/rqlite/blob/master/DOC/CONSISTENCY.md) for
details.

The default consistency is `weak`.

### Foreign Keys

Foreign key support in rqlite is disabled by default, to match sqlite. This is a common source
of confusion. It cannot be configured by the client reliably. Foreign key support
is enabled as described in
[FOREIGN_KEY_CONSTRAINTS.md](https://github.com/rqlite/rqlite/blob/master/DOC/FOREIGN_KEY_CONSTRAINTS.md)

### Nulls

Substituting "NULL" in parametrized queries can be error-prone.  In particular,
sqlite needs null sent in a very particular way, which the rqlite server has
historically not handled properly.

By default, if you attempt to use "None" as a parameter to a query, this package
will perform string substition with the value "NULL" in the correct spot. Be
careful however - you will still need to handle nulls properly in the query,
since "col = NULL" and "col IS NULL" are not the same. In particular, `NULL = NULL`
is `NULL`, which evaluates to false. One way this could be handled is

```py
name: Optional[str] = None

# never matches a row since name is None, even if the rows name is null
cursor.execute('SELECT * FROM persons WHERE name = ?', (name,))

# works as expected
cursor.execute('SELECT * FROM persons WHERE ((? IS NULL AND name IS NULL) OR name = ?)', (name, name))
```

### Backup

Backups can be initiated using `conn.backup(filepath: str, raw: bool = False)`.
The download will be streamed to the given filepath. Both the sql format and a
compressed sqlite format are supported.

### Logging

By default this will log using the standard `logging` module. This can be disabled
using `log=False` in the `connect` call. If logging is desired but just needs to be
configured slightly, it can be done as follows:

```py
import rqdb
import logging

conn = rqdb.connect(
    ['127.0.0.1:4001'],
    log=rqdb.LogConfig(
        # Started a SELECT query
        read_start={
            'enabled': True,
            'level': logging.DEBUG,  # alternatively, 'method': logging.debug
        },

        # Started a UPDATE/INSERT query
        write_start={
            'enabled': True,
            'level': logging.DEBUG,
        },

        # Got the response from the database for a SELECT query
        read_response={
            'enabled': True,
            'level': logging.DEBUG,,
            'max_length': 1024,  # limits how much of the response we log
        },

        # Got the response from the database for a UPDATE/INSERT query
        write_response={
            'enabled': True,
            'level': logging.DEBUG,
        },

        # Failed to connect to one of the nodes.
        connect_timeout={
            'enabled': True,
            'level': logging.WARNING,
        },

        # Failed to connect to any node for a query
        hosts_exhausted={
            'enabled': True,
            'level': logging.CRITICAL,
        },

        # The node returned a status code other than 200-299 or
        # a redirect when a redirect is allowed.
        non_ok_response={
            'enabled': True,
            'level': logging.WARNING
        }
    )
)
```

## Limitations

### Slow Transactions

The primary limitations is that by the connectionless nature of rqlite, while
transactions are possible, the entire transaction must be specified upfront.
That is, you cannot open a transaction, perform a query, and then use the
result of that query to perform another query before closing the transaction.

This can also be seen as a blessing, as these types of transactions are the most
common source of performance issues in traditional applications. They require
long-held locks that can easily lead to N^2 performance. The same behavior can
almost always be achieved with uids, as shown in the example. The repeated UID
lookup causes a consistent overhead, which is highly preferable to the
unpredictable negative feedback loop nature of long transactions.

## Other Notes

It is often helpful to combine this library with a sql builder such
as [pypika](https://pypika.readthedocs.io/en/latest/) when manipulating
complex queries.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/tjstretchalot/rqdb",
    "name": "rqdb",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Timothy Moore",
    "author_email": "mtimothy984@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/b0/fa/648c8a87709bb80997f818da954f313cc1a6c99dbac1c5c8005eaa6f7fd2/rqdb-1.0.10.tar.gz",
    "platform": null,
    "description": "# rqdb\n\nThis is an unofficial python client for [rqlite](https://github.com/rqlite/rqlite), a\nlightweight distributed relational database based on SQLite.\n\nThis client supports SQLite syntax, true parameterized queries, and a\ncalling syntax reminiscent of DB API 2.0.\n\nFurthermore, this client has convenient asynchronous methods which match\nthe underlying rqlite API.\n\n## Installation\n\n```py\npip install rqdb\n```\n\n## Usage\n\nSynchronous queries:\n\n```py\nimport rqdb\nimport secrets\n\nconn = rqdb.connect(['127.0.0.1:4001'])\ncursor = conn.cursor()\ncursor.execute('CREATE TABLE persons (id INTEGER PRIMARY KEY, uid TEXT UNIQUE NOT NULL, name TEXT NOT NULL)')\ncursor.execute('CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT NOT NULL, owner_id INTEGER NOT NULL REFERENCES persons(id) ON DELETE CASCADE)')\n\n# standard execute\ncursor.execute('INSERT INTO persons (uid, name) VALUES (?, ?)', (secrets.token_hex(8), 'Jane Doe'))\nassert cursor.rows_affected == 1\n\n# The following is stored in a single Raft entry and executed within a transaction.\n\nperson_name = 'John Doe'\nperson_uid = secrets.token_urlsafe(16)\npet_name = 'Fido'\nresult = cursor.executemany3((\n    (\n        'INSERT INTO persons (uid, name) VALUES (?, ?)',\n        (person_uid, person_name)\n    ),\n    (\n        'INSERT INTO pets (name, owner_id) '\n        'SELECT'\n        '  ?, persons.id '\n        'FROM persons '\n        'WHERE uid = ?',\n        (pet_name, person_uid)\n    )\n)).raise_on_error()\nassert result[0].rows_affected == 1\nassert result[1].rows_affected == 1\n```\n\nAsynchronous queries:\n\n```py\nimport rqdb\nimport secrets\n\nasync def main():\n    async with rqdb.connect_async(['127.0.0.1:4001']) as conn:\n        cursor = conn.cursor()\n\n        result = await cursor.execute(\n            'INSERT INTO persons (uid, name) VALUES (?, ?)',\n            (secrets.token_hex(8), 'Jane Doe')\n        )\n        assert result.rows_affected == 1\n```\n\n## Additional Features\n\n### Read Consistency\n\nSelecting read consistency is done at the cursor level, either by passing\n`read_consistency` to the cursor constructor (`conn.cursor()`) or by setting\nthe instance variable `read_consistency` directly. The available consistencies\nare `strong`, `weak`, and `none`. You may also indicate the `freshness` value\nat the cursor level.\n\nSee [CONSISTENCY.md](https://github.com/rqlite/rqlite/blob/master/DOC/CONSISTENCY.md) for\ndetails.\n\nThe default consistency is `weak`.\n\n### Foreign Keys\n\nForeign key support in rqlite is disabled by default, to match sqlite. This is a common source\nof confusion. It cannot be configured by the client reliably. Foreign key support\nis enabled as described in\n[FOREIGN_KEY_CONSTRAINTS.md](https://github.com/rqlite/rqlite/blob/master/DOC/FOREIGN_KEY_CONSTRAINTS.md)\n\n### Nulls\n\nSubstituting \"NULL\" in parametrized queries can be error-prone.  In particular,\nsqlite needs null sent in a very particular way, which the rqlite server has\nhistorically not handled properly.\n\nBy default, if you attempt to use \"None\" as a parameter to a query, this package\nwill perform string substition with the value \"NULL\" in the correct spot. Be\ncareful however - you will still need to handle nulls properly in the query,\nsince \"col = NULL\" and \"col IS NULL\" are not the same. In particular, `NULL = NULL`\nis `NULL`, which evaluates to false. One way this could be handled is\n\n```py\nname: Optional[str] = None\n\n# never matches a row since name is None, even if the rows name is null\ncursor.execute('SELECT * FROM persons WHERE name = ?', (name,))\n\n# works as expected\ncursor.execute('SELECT * FROM persons WHERE ((? IS NULL AND name IS NULL) OR name = ?)', (name, name))\n```\n\n### Backup\n\nBackups can be initiated using `conn.backup(filepath: str, raw: bool = False)`.\nThe download will be streamed to the given filepath. Both the sql format and a\ncompressed sqlite format are supported.\n\n### Logging\n\nBy default this will log using the standard `logging` module. This can be disabled\nusing `log=False` in the `connect` call. If logging is desired but just needs to be\nconfigured slightly, it can be done as follows:\n\n```py\nimport rqdb\nimport logging\n\nconn = rqdb.connect(\n    ['127.0.0.1:4001'],\n    log=rqdb.LogConfig(\n        # Started a SELECT query\n        read_start={\n            'enabled': True,\n            'level': logging.DEBUG,  # alternatively, 'method': logging.debug\n        },\n\n        # Started a UPDATE/INSERT query\n        write_start={\n            'enabled': True,\n            'level': logging.DEBUG,\n        },\n\n        # Got the response from the database for a SELECT query\n        read_response={\n            'enabled': True,\n            'level': logging.DEBUG,,\n            'max_length': 1024,  # limits how much of the response we log\n        },\n\n        # Got the response from the database for a UPDATE/INSERT query\n        write_response={\n            'enabled': True,\n            'level': logging.DEBUG,\n        },\n\n        # Failed to connect to one of the nodes.\n        connect_timeout={\n            'enabled': True,\n            'level': logging.WARNING,\n        },\n\n        # Failed to connect to any node for a query\n        hosts_exhausted={\n            'enabled': True,\n            'level': logging.CRITICAL,\n        },\n\n        # The node returned a status code other than 200-299 or\n        # a redirect when a redirect is allowed.\n        non_ok_response={\n            'enabled': True,\n            'level': logging.WARNING\n        }\n    )\n)\n```\n\n## Limitations\n\n### Slow Transactions\n\nThe primary limitations is that by the connectionless nature of rqlite, while\ntransactions are possible, the entire transaction must be specified upfront.\nThat is, you cannot open a transaction, perform a query, and then use the\nresult of that query to perform another query before closing the transaction.\n\nThis can also be seen as a blessing, as these types of transactions are the most\ncommon source of performance issues in traditional applications. They require\nlong-held locks that can easily lead to N^2 performance. The same behavior can\nalmost always be achieved with uids, as shown in the example. The repeated UID\nlookup causes a consistent overhead, which is highly preferable to the\nunpredictable negative feedback loop nature of long transactions.\n\n## Other Notes\n\nIt is often helpful to combine this library with a sql builder such\nas [pypika](https://pypika.readthedocs.io/en/latest/) when manipulating\ncomplex queries.\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "An unofficial python client for RQLite",
    "version": "1.0.10",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "03c018127b8a2f23e6b916b2fef1030c",
                "sha256": "2712dbc806f3aad5695dbe64a1cf667cb8052f96cad779f2e89ab824b592a181"
            },
            "downloads": -1,
            "filename": "rqdb-1.0.10-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "03c018127b8a2f23e6b916b2fef1030c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 24676,
            "upload_time": "2022-09-27T20:56:18",
            "upload_time_iso_8601": "2022-09-27T20:56:18.870708Z",
            "url": "https://files.pythonhosted.org/packages/26/fb/41d635288b60a2beb6b84ebc1c4dcb4722b175ec7237d5dda334a9555a0e/rqdb-1.0.10-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "b4059582e5517a9615c6d34b2b830456",
                "sha256": "a8dec3b50ac3aaf22516f18424cab335390c3921cbda1f24be4a3019faa8b3ec"
            },
            "downloads": -1,
            "filename": "rqdb-1.0.10.tar.gz",
            "has_sig": false,
            "md5_digest": "b4059582e5517a9615c6d34b2b830456",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 20344,
            "upload_time": "2022-09-27T20:56:20",
            "upload_time_iso_8601": "2022-09-27T20:56:20.587967Z",
            "url": "https://files.pythonhosted.org/packages/b0/fa/648c8a87709bb80997f818da954f313cc1a6c99dbac1c5c8005eaa6f7fd2/rqdb-1.0.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-09-27 20:56:20",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "tjstretchalot",
    "github_project": "rqdb",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "rqdb"
}
        
Elapsed time: 0.50793s