Skip to content

Commit

Permalink
Implement mypy (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ce11an authored May 16, 2023
1 parent 37c6405 commit f0293e6
Show file tree
Hide file tree
Showing 7 changed files with 207 additions and 92 deletions.
46 changes: 46 additions & 0 deletions .github/actions/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Build Poetry

description: 'Build Poetry'

runs:
using: 'composite'

steps:
- uses: actions/checkout@v3
- name: Set up Python 3.8
uses: actions/setup-python@v4
with:
python-version: 3.8

- name: Get full Python version
id: full-python-version
run: echo "version=$(python -c "import sys; print('-'.join(str(v) for v in sys.version_info))")" >> $GITHUB_OUTPUT
shell: bash

- name: Bootstrap poetry
run: curl -sL https://install.python-poetry.org | python - -y
shell: bash

- name: Update PATH
run: echo "$HOME/.local/bin" >> $GITHUB_PATH
shell: bash

- name: Configure poetry
run: poetry config virtualenvs.in-project true
shell: bash

- name: Set up cache
uses: actions/cache@v3
id: cache
with:
path: .venv
key: venv-${{ runner.os }}-${{ steps.full-python-version.outputs.version }}-${{ inputs.working-directory }}-${{ hashFiles('**/poetry.lock') }}

- name: Ensure cache is healthy
if: steps.cache.outputs.cache-hit == 'true'
run: timeout 10s poetry run pip --version || rm -rf .venv
shell: bash

- name: Install Dependencies
run: poetry install
shell: bash
16 changes: 0 additions & 16 deletions .github/workflows/ruff.yml

This file was deleted.

38 changes: 38 additions & 0 deletions .github/workflows/stability.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Code Stability

on:
push:
branches:
- main
pull_request:
branches:
- main

concurrency:
group: stability-${{ github.head_ref || github.ref }}
cancel-in-progress: true

jobs:
stability:
name: Code Stability
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Build Python
uses: ./.github/actions

- name: Install tools
run: poetry install --only dev

- id: ruff
if: always()
run: poetry run ruff --format=github surrealdb/

- id: Black
if: always()
run: poetry run black surrealdb/ --check --verbose --diff --color

- id: mypy
if: always()
run: poetry run mypy surrealdb/
52 changes: 50 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 19 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ websockets = "^10.4"
pre-commit = ">=2.20.0"
black = ">=22.8.0"
ruff = ">=0.0.245"
mypy = ">=1.2.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down Expand Up @@ -73,7 +74,7 @@ ignore = [
"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
"D212", # Multi-line docstring summary should start at the first line
"N805", # First argument of a method should be named self
"N818", # Exception name ... should be named with an Error suffix
"UP035" # Typing deprecations
Expand Down Expand Up @@ -108,3 +109,20 @@ convention = "google"

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

[tool.mypy]
python_version = 3.8
pretty = true
show_traceback = true
color_output = true
check_untyped_defs = true
disallow_incomplete_defs = true
ignore_missing_imports = true
implicit_reexport = true
strict_equality = true
strict_optional = false
warn_no_return = true
warn_redundant_casts = true
warn_unreachable = true
warn_unused_configs = true
warn_unused_ignores = true
52 changes: 28 additions & 24 deletions surrealdb/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ async def __aexit__(
traceback: Optional[TracebackType] = None,
) -> None:
"""Disconnect from the http client when exiting the context manager."""
await self.disconnect()
await self.close()

async def connect(self) -> None:
"""Connects to a local or remote database endpoint."""
"""Connect to a local or remote database endpoint."""
await self._http.__aenter__()

async def close(self) -> None:
"""Closes the persistent connection to the database."""
"""Close the persistent connection to the database."""
await self._http.aclose()

async def _request(
Expand All @@ -132,36 +132,41 @@ async def _request(
# 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:
"""Signs 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.
Examples:
await db.signup({"user": "bob", "pass": "123456"})
"""
response = await self._request(method="POST", uri="/signup", data=json.dumps(vars))
return response
response = await self._request(
method="POST", uri="/signup", data=json.dumps(vars)
)
return response # type: ignore

async def signin(self, vars: Dict[str, Any]) -> str:
"""Signs 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.
Examples:
await db.signin({"user": "root", "pass": "root"})
"""
response = await self._request(method="POST", uri="/signin", data=json.dumps(vars))
return response
response = await self._request(
method="POST", uri="/signin", data=json.dumps(vars)
)
return response # type: ignore

async def query(
self, sql: str, vars: Optional[Dict[str, Any]] = None
) -> List[Dict[str, Any]]:
"""Runs 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 @@ -181,10 +186,10 @@ async def query(
result[1]['result']
"""
response = await self._request(method="POST", uri="/sql", data=sql, params=vars)
return response
return response # type: ignore

async def select(self, thing: str) -> List[Dict[str, Any]]:
"""Selects 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 @@ -210,7 +215,7 @@ async def select(self, thing: str) -> List[Dict[str, Any]]:
)
if not response and record_id is not None:
raise SurrealException(f"Key {record_id} not found in table {table}")
return response[0]['result']
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.
Expand Down Expand Up @@ -243,11 +248,10 @@ async def create(self, thing: str, data: Optional[Dict[str, Any]] = None) -> str
)
if not response and record_id is not None:
raise SurrealException(f"Key {record_id} not found in table {table}")
return response[0]['result']

return response[0]["result"] # type: ignore

async def update(self, thing: str, data: Any) -> Dict[str, Any]:
"""Updates 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 @@ -278,10 +282,10 @@ async def update(self, thing: str, data: Any) -> Dict[str, Any]:
uri=f"/key/{table}/{record_id}" if record_id else f"/key/{table}",
data=json.dumps(data, ensure_ascii=False),
)
return response[0]['result']
return response[0]["result"] # type: ignore

async def patch(self, thing: str, data: Any) -> Dict[str, Any]:
"""Applies 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 @@ -311,10 +315,10 @@ async def patch(self, thing: str, data: Any) -> Dict[str, Any]:
uri=f"/key/{table}/{record_id}" if record_id else f"/key/{table}",
data=json.dumps(data, ensure_ascii=False),
)
return response[0]['result']
return response[0]["result"] # type: ignore

async def delete(self, thing: str) -> None:
"""Deletes all records in a table, or a specific record, from the database.
async def delete(self, thing: str) -> List[Dict[str, Any]]:
"""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 All @@ -333,4 +337,4 @@ async def delete(self, thing: str) -> None:
method="DELETE",
uri=f"/key/{table}/{record_id}" if record_id else f"/key/{table}",
)
return response
return response # type: ignore
Loading

0 comments on commit f0293e6

Please sign in to comment.