Skip to content

Commit 9d67fbf

Browse files
committed
chore: typechecking
1 parent 6ac587b commit 9d67fbf

File tree

10 files changed

+88
-55
lines changed

10 files changed

+88
-55
lines changed

ckanext/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
try:
33
import pkg_resources
44

5-
pkg_resources.declare_namespace(__name__)
5+
pkg_resources.declare_namespace(__name__) # pyright: ignore[reportAttributeAccessIssue]
66
except ImportError:
77
import pkgutil
88

ckanext/relationship/helpers.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ def relationship_get_entity_list(
2323
entity: str, entity_type: str, include_private: bool = True
2424
) -> list[dict[str, str]]:
2525
"""Return ids list of specified entity (entity, entity_type)."""
26-
context = {}
26+
2727
if entity == "package":
2828
entity_list = tk.get_action("package_search")(
29-
context,
29+
{},
3030
{
3131
"fq": f"type:{entity_type}",
3232
"rows": 1000,
@@ -36,7 +36,7 @@ def relationship_get_entity_list(
3636
entity_list = entity_list["results"]
3737
else:
3838
entity_list = tk.get_action("relationship_get_entity_list")(
39-
context,
39+
{},
4040
{"entity": entity, "entity_type": entity_type},
4141
)
4242
entity_list = [
@@ -57,8 +57,8 @@ def relationship_get_current_relations_list(
5757
related_entity_type = data["related_entity_type"]
5858
relation_type = data["relation_type"]
5959

60-
current_relation_by_id = []
61-
current_relation_by_name = []
60+
current_relation_by_id: list[str] = []
61+
current_relation_by_name: list[str] = []
6262

6363
if subject_id:
6464
current_relation_by_id = tk.get_action("relationship_relations_ids_list")(
@@ -120,13 +120,13 @@ def relationship_get_selected_json(selected_ids: list[str] | None = None) -> str
120120
def relationship_get_choices_for_related_entity_field(
121121
field: dict[str, Any],
122122
current_entity_id: str | None,
123-
) -> list[str | None]:
123+
) -> list[tuple[str, str | None]]:
124124
entities = relationship_get_entity_list(
125125
field["related_entity"],
126126
field["related_entity_type"],
127127
)
128128

129-
choices = []
129+
choices: list[tuple[str, str | None]] = []
130130

131131
for entity in entities:
132132
if entity["id"] == current_entity_id:
@@ -148,11 +148,11 @@ def relationship_get_choices_for_related_entity_field(
148148

149149
choices.append((entity["id"], entity.get("title") or entity.get("name")))
150150

151-
choices.sort(key=lambda x: x[1])
151+
choices.sort(key=lambda x: x[1]) # pyright: ignore[reportArgumentType, reportCallIssue]
152152
return choices
153153

154154

155-
def relationship_format_autocomplete(packages: dict[str, Any]) -> dict[str, Any]:
155+
def relationship_format_autocomplete(packages: list[dict[str, Any]]) -> dict[str, Any]:
156156
return {
157157
"ResultSet": {
158158
"Result": [

ckanext/relationship/logic/action.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from flask import jsonify
66
from flask.wrappers import Response
7-
from sqlalchemy import or_
7+
import sqlalchemy as sa
88

99
import ckan.plugins.toolkit as tk
1010
from ckan import authz, logic
@@ -35,15 +35,15 @@ def get_actions():
3535
@validate(schema.relation_create)
3636
def relationship_relation_create(
3737
context: Context, data_dict: dict[str, Any]
38-
) -> list[dict[str, str]]:
38+
) -> list[dict[str, Any]]:
3939
"""Create relation with specified type (relation_type) between two entities
4040
specified by ids (subject_id, object_id). Also create reverse relation.
4141
"""
4242
tk.check_access("relationship_relation_create", context, data_dict)
4343

4444
subject_id = data_dict["subject_id"]
4545
object_id = data_dict["object_id"]
46-
relation_type = data_dict.get("relation_type")
46+
relation_type = data_dict["relation_type"]
4747
extras = data_dict.get("extras", {})
4848

4949
if Relationship.by_object_id(subject_id, object_id, relation_type):
@@ -89,11 +89,11 @@ def relationship_relation_delete(
8989
context["session"]
9090
.query(Relationship)
9191
.filter(
92-
or_(
92+
sa.or_(
9393
Relationship.subject_id == subject_id,
9494
Relationship.subject_id == subject_name,
9595
),
96-
or_(
96+
sa.or_(
9797
Relationship.object_id == object_id,
9898
Relationship.object_id == object_name,
9999
),
@@ -109,11 +109,11 @@ def relationship_relation_delete(
109109
context["session"]
110110
.query(Relationship)
111111
.filter(
112-
or_(
112+
sa.or_(
113113
Relationship.subject_id == object_id,
114114
Relationship.subject_id == object_name,
115115
),
116-
or_(
116+
sa.or_(
117117
Relationship.object_id == subject_id,
118118
Relationship.object_id == subject_name,
119119
),
@@ -202,7 +202,7 @@ def relationship_get_entity_list(
202202

203203
@validate(schema.autocomplete)
204204
def relationship_autocomplete(context: Context, data_dict: dict[str, Any]) -> Response:
205-
fq = f'type:{data_dict["entity_type"]} -id:{data_dict["current_entity_id"]}'
205+
fq = f"type:{data_dict['entity_type']} -id:{data_dict['current_entity_id']}"
206206

207207
if data_dict.get("owned_only") and not (
208208
authz.is_sysadmin(tk.current_user.id) and not data_dict.get("check_sysadmin")
@@ -228,9 +228,9 @@ def relationship_autocomplete(context: Context, data_dict: dict[str, Any]) -> Re
228228
if tk.h.check_access("package_update", {"id": pkg["id"]})
229229
]
230230

231-
format_autocomplete_helper = getattr(
231+
format_autocomplete_helper: Any = getattr(
232232
tk.h,
233-
data_dict.get("format_autocomplete_helper"),
233+
data_dict.get("format_autocomplete_helper", "relationship_format_autocomplete"),
234234
tk.h.relationship_format_autocomplete,
235235
)
236236

ckanext/relationship/logic/schema.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1+
from __future__ import annotations
2+
13
from ckan.logic.schema import validator_args
24
from ckan.types import Schema, Validator, ValidatorFactory
35

46

57
@validator_args
68
def relation_create(
79
not_empty: Validator,
8-
one_of: Validator,
10+
one_of: ValidatorFactory,
911
default: ValidatorFactory,
1012
convert_to_json_if_string: Validator,
1113
dict_only: Validator,
@@ -26,7 +28,7 @@ def relation_create(
2628

2729
@validator_args
2830
def relation_delete(
29-
not_empty: Validator, one_of: Validator, ignore_missing: Validator
31+
not_empty: Validator, one_of: ValidatorFactory, ignore_missing: Validator
3032
) -> Schema:
3133
return {
3234
"subject_id": [
@@ -44,7 +46,7 @@ def relation_delete(
4446

4547
@validator_args
4648
def relations_list(
47-
not_empty: Validator, one_of: Validator, ignore_missing: Validator
49+
not_empty: Validator, one_of: ValidatorFactory, ignore_missing: Validator
4850
) -> Schema:
4951
return {
5052
"subject_id": [
@@ -66,7 +68,7 @@ def relations_list(
6668

6769
@validator_args
6870
def relations_ids_list(
69-
not_empty: Validator, one_of: Validator, ignore_missing: Validator
71+
not_empty: Validator, one_of: ValidatorFactory, ignore_missing: Validator
7072
) -> Schema:
7173
return {
7274
"subject_id": [
@@ -87,7 +89,7 @@ def relations_ids_list(
8789

8890

8991
@validator_args
90-
def get_entity_list(not_empty: Validator, one_of: Validator) -> Schema:
92+
def get_entity_list(not_empty: Validator, one_of: ValidatorFactory) -> Schema:
9193
return {
9294
"entity": [
9395
not_empty,

ckanext/relationship/logic/validators.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
from __future__ import annotations
22

33
import json
4-
from typing import Any
5-
6-
from six import string_types
4+
from typing import Any, cast
75

86
import ckan.plugins.toolkit as tk
97
from ckan.types import Context, FlattenDataDict, FlattenErrorDict, FlattenKey
108

119
from ckanext.scheming.validation import (
12-
scheming_multiple_choice_output,
13-
scheming_validator,
10+
scheming_multiple_choice_output, # pyright: ignore[reportUnknownVariableType]
11+
scheming_validator, # pyright: ignore[reportUnknownVariableType]
1412
)
1513

1614

@@ -61,9 +59,9 @@ def validator(
6159

6260
def get_current_relations(
6361
entity_id: str | None,
64-
related_entity: str,
65-
related_entity_type: str,
66-
relation_type: str,
62+
related_entity: str | None,
63+
related_entity_type: str | None,
64+
relation_type: str | None,
6765
):
6866
if entity_id:
6967
current_relations = tk.get_action("relationship_relations_list")(
@@ -81,19 +79,24 @@ def get_current_relations(
8179
return set(current_relations)
8280

8381

84-
def get_selected_relations(selected_relations: list | str | None) -> set[str]:
85-
if isinstance(selected_relations, string_types) and "," in selected_relations:
82+
def get_selected_relations(selected_relations: list[Any] | str | None) -> set[str]:
83+
if selected_relations is None:
84+
selected_relations = []
85+
86+
if isinstance(selected_relations, str) and "," in selected_relations:
8687
selected_relations = selected_relations.split(",")
8788

8889
if (
8990
len(selected_relations) == 1
90-
and isinstance(selected_relations[0], string_types)
91+
and isinstance(selected_relations[0], str)
9192
and "," in selected_relations[0]
9293
):
9394
selected_relations = selected_relations[0].split(",")
9495

9596
if selected_relations is not tk.missing:
96-
selected_relations = scheming_multiple_choice_output(selected_relations)
97+
selected_relations = cast(
98+
"list[str]", scheming_multiple_choice_output(selected_relations)
99+
)
97100
selected_relations = [] if selected_relations == [""] else selected_relations
98101
else:
99102
selected_relations = []

ckanext/relationship/model/base.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
from __future__ import annotations
2+
3+
from typing import Any
14
from sqlalchemy.ext.declarative import declarative_base
5+
import ckan.plugins.toolkit as tk
6+
7+
Base: Any
28

3-
Base = declarative_base()
9+
if hasattr(tk, "BaseModel"):
10+
Base = tk.BaseModel
11+
else:
12+
Base = declarative_base()

ckanext/relationship/model/relationship.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
from __future__ import annotations
22

3+
from typing import Any
4+
from typing_extensions import override
35
from datetime import datetime
46

5-
from sqlalchemy import Column, DateTime, Text, or_
7+
import sqlalchemy as sa
68
from sqlalchemy.dialects.postgresql import JSONB
9+
from sqlalchemy.orm import Mapped
710

811
from ckan import logic, model
912
from ckan.model.types import make_uuid
@@ -12,20 +15,31 @@
1215

1316

1417
class Relationship(Base):
15-
__tablename__ = "relationship_relationship"
16-
id: str = Column(Text, primary_key=True, default=make_uuid)
17-
subject_id: str = Column(Text, nullable=False)
18-
object_id: str = Column(Text, nullable=False)
19-
relation_type: str = Column(Text, nullable=False)
20-
created_at: datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
21-
extras: dict = Column(JSONB, nullable=False, default=dict)
22-
23-
reverse_relation_type = {
18+
__table__: sa.Table = sa.Table(
19+
"relationship_relationship",
20+
Base.metadata,
21+
sa.Column("id", sa.Text, primary_key=True, default=make_uuid),
22+
sa.Column("subject_id", sa.Text, nullable=False),
23+
sa.Column("object_id", sa.Text, nullable=False),
24+
sa.Column("relation_type", sa.Text, nullable=False),
25+
sa.Column("created_at", sa.DateTime, nullable=False, default=datetime.utcnow), # pyright: ignore[reportDeprecated]
26+
sa.Column("extras", JSONB, nullable=False, default=dict),
27+
)
28+
29+
id: Mapped[str]
30+
subject_id: Mapped[str]
31+
object_id: Mapped[str]
32+
relation_type: Mapped[str]
33+
created_at: Mapped[datetime]
34+
extras: Mapped[dict[str, Any]]
35+
36+
reverse_relation_type: dict[str, Any] = {
2437
"related_to": "related_to",
2538
"child_of": "parent_of",
2639
"parent_of": "child_of",
2740
}
2841

42+
@override
2943
def __repr__(self):
3044
return (
3145
"Relationship("
@@ -90,7 +104,7 @@ def by_subject_id(
90104
object_class = logic.model_name_to_class(model, object_entity)
91105
q = q.join(
92106
object_class,
93-
or_(
107+
sa.or_(
94108
cls.object_id == object_class.id,
95109
cls.object_id == object_class.name,
96110
),

ckanext/relationship/plugin.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import contextlib
4-
from typing import Any
4+
from typing import Any, cast
55

66
import ckan.plugins.toolkit as tk
77
from ckan import plugins as p
@@ -86,7 +86,9 @@ def after_dataset_delete(self, context: Context, pkg_dict: dict[str, Any]):
8686
def before_dataset_index(self, pkg_dict: dict[str, Any]):
8787
pkg_id = pkg_dict["id"]
8888
pkg_type = pkg_dict["type"]
89-
schema = sch.scheming_get_schema("dataset", pkg_type)
89+
schema = cast(
90+
"dict[str, Any] | None", sch.scheming_get_schema("dataset", pkg_type)
91+
)
9092
if not schema:
9193
return pkg_dict
9294
relations_info = utils.get_relations_info(pkg_type)
@@ -113,7 +115,7 @@ def before_dataset_index(self, pkg_dict: dict[str, Any]):
113115
related_entity_type,
114116
relation_type,
115117
)
116-
pkg_dict[f'vocab_{field["field_name"]}'] = relations_ids
118+
pkg_dict[f"vocab_{field['field_name']}"] = relations_ids
117119

118120
pkg_dict.pop(field["field_name"], None)
119121

0 commit comments

Comments
 (0)