Skip to content

Commit

Permalink
Updated code formatting and lint (latest ruff, mypy) (surrealdb#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-beedie authored Mar 25, 2024
1 parent 7de2c20 commit c8a4c84
Show file tree
Hide file tree
Showing 40 changed files with 806 additions and 520 deletions.
9 changes: 3 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@ repos:
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.245'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.3
hooks:
- id: ruff
- repo: https://github.com/psf/black
rev: 22.8.0
hooks:
- id: black
- id: ruff-format
4 changes: 0 additions & 4 deletions flake8_config

This file was deleted.

9 changes: 3 additions & 6 deletions python_package/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@ repos:
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.245'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.3
hooks:
- id: ruff
- repo: https://github.com/psf/black
rev: 22.8.0
hooks:
- id: black
- id: ruff-format
64 changes: 37 additions & 27 deletions python_package/examples/basic_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,40 +16,50 @@ async def main():
},
)
print(await db.select("person"))
print(await db.update("person", {
"user":"you",
"pass":"very_safe",
"marketing": False,
"tags": ["Awesome"]
}))
print(
await db.update(
"person",
{
"user": "you",
"pass": "very_safe",
"marketing": False,
"tags": ["Awesome"],
},
)
)
print(await db.delete("person"))

# You can also use the query method
# You can also use the query method
# doing all of the above and more in SurrealQl
# In SurrealQL you can do a direct insert

# In SurrealQL you can do a direct insert
# and the table will be created if it doesn't exist
await db.query("""
insert into person {
user: 'me',
pass: 'very_safe',
tags: ['python', 'documentation']
};
""")
await db.query(
"""
insert into person {
user: 'me',
pass: 'very_safe',
tags: ['python', 'documentation']
};
"""
)
print(await db.query("select * from person"))

print(await db.query("""
update person content {
user: 'you',
pass: 'more_safe',
tags: ['awesome']
};
"""))

print(
await db.query(
"""
update person content {
user: 'you',
pass: 'more_safe',
tags: ['awesome']
};
"""
)
)
print(await db.query("delete person"))


if __name__ == "__main__":
import asyncio

asyncio.run(main())
asyncio.run(main())
81 changes: 40 additions & 41 deletions python_package/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,58 +28,52 @@ pydantic = "^1.10.6"
websockets = "^10.4"

[tool.poetry.dev-dependencies]
pre-commit = ">=2.20.0"
black = ">=22.8.0"
ruff = ">=0.0.245"
mypy = ">=1.2.0"
pre-commit = "3.6.2"
ruff = "0.3.3"
mypy = "1.9.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.black]
line-length = 88
color = true

exclude = '''
/(
\.bzr
| \.direnv
| \.eggs
| \.git
| \.hg
| \.mypy_cache
| \.nox
| \.pants\.d
| \.ruff_cache
| \.__pypackages__
| \.svn
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
| env
| venv
)/
'''

[tool.ruff]
select = ["I", "D", "N", "UP"]
target-version = "py38"
line-length = 88

ignore = [
lint.select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"D", # flake8-docstrings
"E", # pycodestyle
"EM", # flake8-errmsg
"F", # pyflakes
"FA", # flake8-future-annotations
"FBT001", # flake8-boolean-trap
"I", # isort
"N", # pep8-naming
"PIE", # flake8-pie
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"TCH", # flake8-type-checking
"TD", # flake8-todos
"TID", # flake8-tidy-imports
"TRY", # tryceratops
"UP", # pyupgrade
"W", # pycodestyle
]
lint.ignore = [
"D100", # Missing docstring in public module
"D104", # Missing docstring in public package
"D107", # Missing docstring in __init__
"D205", # 1 blank line required between summary line and description
"D212", # Multi-line docstring summary should start at the first line
"E501", # Line too long (eg: docstring)
"N805", # First argument of a method should be named self
"N818", # Exception name ... should be named with an Error suffix
"UP035" # Typing deprecations
"TD002", # Missing author in TODO
"TD003", # Missing issue link on the line following this TODO
]

exclude = [
".bzr",
".direnv",
Expand All @@ -93,23 +87,28 @@ exclude = [
".svn",
".tox",
".venv",
"__pycache__",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"venv",
".git",
"__pycache__",
]

[tool.ruff.pydocstyle]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]

[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.ruff.pyupgrade]
[tool.ruff.lint.pyupgrade]
keep-runtime-typing = true

[tool.ruff.format]
docstring-code-format = true

[tool.mypy]
python_version = 3.8
pretty = true
Expand Down
1 change: 1 addition & 0 deletions python_package/surrealdb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
"""

from .http import SurrealHTTP
from .ws import Surreal

Expand Down
47 changes: 31 additions & 16 deletions python_package/surrealdb/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@
See the License for the specific language governing permissions and
limitations under the License.
"""

from __future__ import annotations

import json
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, List, Optional, Type
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type

import httpx

if TYPE_CHECKING:
from types import TracebackType

__all__ = ("SurrealHTTP",)


Expand All @@ -31,7 +34,8 @@ class SurrealException(Exception):

@dataclass(frozen=True)
class SurrealResponse:
"""Represents a http response from a SurrealDB server.
"""
Represents a http response from a SurrealDB server.
Attributes:
time: The time the request was processed.
Expand All @@ -49,7 +53,8 @@ class SurrealResponse:


class SurrealHTTP:
"""Represents a http connection to a SurrealDB server.
"""
Represents a http connection to a SurrealDB server.
Args:
url: The URL of the SurrealDB server.
Expand Down Expand Up @@ -125,18 +130,19 @@ async def _request(
surreal_data = await surreal_response.aread()
return json.loads(surreal_data)

# TODO add missing methods - currently undocumented
# TODO: add missing methods - currently undocumented
# Missing method - wait
# Missing method - use
# Missing method - invalidate
# Missing method - authenticate
# Missing method - let
# Missing method - merge
# TODO fix signup and signin methods
# TODO: fix signup and signin methods
# TODO: Review type: ignore comments.

async def signup(self, vars: Dict[str, Any]) -> str:
"""Sign this connection up to a specific authentication scope.
"""
Sign this connection up to a specific authentication scope.
Args:
vars: Variables used in a signup query.
Expand All @@ -150,7 +156,8 @@ async def signup(self, vars: Dict[str, Any]) -> str:
return response # type: ignore

async def signin(self, vars: Dict[str, Any]) -> str:
"""Sign this connection in to a specific authentication scope.
"""
Sign this connection in to a specific authentication scope.
Args:
vars: Variables used in a signin query.
Expand All @@ -166,7 +173,8 @@ async def signin(self, vars: Dict[str, Any]) -> str:
async def query(
self, sql: str, vars: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
"""Run a set of SurrealQL statements against the database.
"""
Run a set of SurrealQL statements against the database.
Args:
sql: Specifies the SurrealQL statements.
Expand All @@ -189,7 +197,8 @@ async def query(
return response # type: ignore

async def select(self, thing: str) -> List[Dict[str, Any]]:
"""Select all records in a table (or other entity),
"""
Select all records in a table (or other entity),
or a specific record, in the database.
This function will run the following query in the database:
Expand All @@ -214,11 +223,13 @@ async def select(self, thing: str) -> List[Dict[str, Any]]:
uri=f"/key/{table}/{record_id}" if record_id else f"/key/{table}",
)
if not response and record_id is not None:
raise SurrealException(f"Key {record_id} not found in table {table}")
msg = f"Key {record_id} not found in table {table}"
raise SurrealException(msg)
return response[0]["result"] # type: ignore

async def create(self, thing: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Create a record in the database.
"""
Create a record in the database.
This function will run the following query in the database:
create $thing content $data
Expand Down Expand Up @@ -247,11 +258,13 @@ async def create(self, thing: str, data: Optional[Dict[str, Any]] = None) -> str
data=json.dumps(data, ensure_ascii=False),
)
if not response and record_id is not None:
raise SurrealException(f"Key {record_id} not found in table {table}")
msg = f"Key {record_id} not found in table {table}"
raise SurrealException(msg)
return response[0]["result"] # type: ignore

async def update(self, thing: str, data: Any) -> Dict[str, Any]:
"""Update all records in a table, or a specific record, in the database.
"""
Update all records in a table, or a specific record, in the database.
This function replaces the current document / record data with the
specified data.
Expand Down Expand Up @@ -285,7 +298,8 @@ async def update(self, thing: str, data: Any) -> Dict[str, Any]:
return response[0]["result"] # type: ignore

async def patch(self, thing: str, data: Any) -> Dict[str, Any]:
"""Apply JSON Patch changes to all records, or a specific record, in the database.
"""
Apply JSON Patch changes to all records, or a specific record, in the database.
This function patches the current document / record data with
the specified JSON Patch data.
Expand Down Expand Up @@ -318,7 +332,8 @@ async def patch(self, thing: str, data: Any) -> Dict[str, Any]:
return response[0]["result"] # type: ignore

async def delete(self, thing: str) -> List[Dict[str, Any]]:
"""Delete all records in a table, or a specific record, from the database.
"""
Delete all records in a table, or a specific record, from the database.
This function will run the following query in the database:
delete * from $thing
Expand Down
Loading

0 comments on commit c8a4c84

Please sign in to comment.