Skip to content

Commit 183717a

Browse files
committed
lint
1 parent ed9ca32 commit 183717a

24 files changed

Lines changed: 3118 additions & 5641 deletions

src/semsql/builder/builder.py

Lines changed: 32 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@
33
import os
44
import shutil
55
import subprocess
6-
from dataclasses import field
76
from pathlib import Path
87
from typing import Optional
98

9+
import requests
1010
from sqlalchemy import create_engine
1111
from sqlalchemy.orm import sessionmaker
12-
import requests
1312

1413
this_path = Path(__file__).parent
1514

@@ -18,7 +17,7 @@ class DockerConfig:
1817
"""
1918
Configuration for running ODK Docker image
2019
"""
21-
odk_version: str = None ## not used yet
20+
odk_version: str = None # not used yet
2221
memory: str = None
2322

2423

@@ -29,23 +28,32 @@ def make(target: str, docker_config: Optional[DockerConfig] = None):
2928
:param target: Make target
3029
:param docker_config: if passed, use ODK docker with the specific config
3130
"""
32-
path_to_makefile = str(this_path / 'build.Makefile')
31+
path_to_makefile = str(this_path / "build.Makefile")
3332
if docker_config is not None:
3433
mem = docker_config.memory
3534
if mem is None:
36-
mem = '4g'
35+
mem = "4g"
3736
pwd = os.getcwd()
38-
pre = ['docker', 'run',
39-
'-m', mem,
40-
'-v', f'{pwd}/:/work',
41-
'-v', f'{this_path}/:/builder',
42-
'-w', '/work',
43-
'--rm', '-ti', 'obolibrary/odkfull']
44-
path_to_makefile = '/builder/build.Makefile'
37+
pre = [
38+
"docker",
39+
"run",
40+
"-m",
41+
mem,
42+
"-v",
43+
f"{pwd}/:/work",
44+
"-v",
45+
f"{this_path}/:/builder",
46+
"-w",
47+
"/work",
48+
"--rm",
49+
"-ti",
50+
"obolibrary/odkfull",
51+
]
52+
path_to_makefile = "/builder/build.Makefile"
4553
else:
4654
pre = []
47-
cmd = pre + ['make', target, '-f', path_to_makefile]
48-
logging.info(f'CMD={cmd}')
55+
cmd = pre + ["make", target, "-f", path_to_makefile]
56+
logging.info(f"CMD={cmd}")
4957
subprocess.run(cmd)
5058

5159

@@ -56,12 +64,12 @@ def db_from_owl(input: str) -> str:
5664
:param input: path to OWL file
5765
:return: path to db file
5866
"""
59-
if input.endswith('.owl'):
60-
db = input.replace('.owl', '.db')
67+
if input.endswith(".owl"):
68+
db = input.replace(".owl", ".db")
6169
make(db)
6270
return db
6371
else:
64-
raise ValueError(f'Path must be an OWL file')
72+
raise ValueError(f"Path must be an OWL file")
6573

6674

6775
def download_obo_sqlite(ontology: str, destination: str):
@@ -72,18 +80,17 @@ def download_obo_sqlite(ontology: str, destination: str):
7280
:param destination:
7381
:return:
7482
"""
75-
db = f'{ontology}.db'
76-
url = f'https://s3.amazonaws.com/bbop-sqlite/{db}.gz'
83+
db = f"{ontology}.db"
84+
url = f"https://s3.amazonaws.com/bbop-sqlite/{db}.gz"
7785
r = requests.get(url, allow_redirects=True)
78-
destination_gzip = f'{destination}.gz'
79-
open(destination_gzip, 'wb').write(r.content)
80-
with gzip.open(destination_gzip, 'rb') as f_in:
81-
with open(destination, 'wb') as f_out:
86+
destination_gzip = f"{destination}.gz"
87+
open(destination_gzip, "wb").write(r.content)
88+
with gzip.open(destination_gzip, "rb") as f_in:
89+
with open(destination, "wb") as f_out:
8290
shutil.copyfileobj(f_in, f_out)
8391
os.remove(destination_gzip)
8492

8593

86-
8794
def connect(owl_file: str):
8895
"""
8996
Generates a SQLite connection to an OWL file
@@ -92,7 +99,7 @@ def connect(owl_file: str):
9299
:return:
93100
"""
94101
db = db_from_owl(owl_file)
95-
engine = create_engine(f'sqlite:///{db}')
102+
engine = create_engine(f"sqlite:///{db}")
96103
Session = sessionmaker(bind=engine)
97104
session = Session()
98105
return session

src/semsql/builder/cli.py

Lines changed: 40 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import logging
22

33
import click
4-
import logging
5-
import semsql.builder.builder as builder
64
from linkml_runtime import SchemaView
75
from linkml_runtime.utils.formatutils import underscore
8-
from semsql.sqlutils.viewgen import get_viewdef
96
from sqlalchemy import text
107

8+
import semsql.builder.builder as builder
9+
from semsql.sqlutils.viewgen import get_viewdef
10+
1111

1212
@click.group()
1313
@click.option("-v", "--verbose", count=True)
@@ -25,12 +25,13 @@ def main(verbose: int, quiet: bool):
2525

2626

2727
@main.command()
28-
@click.argument('path')
29-
@click.option('--docker/--no-docker',
30-
default=False,
31-
show_default=True,
32-
help="Uses ODK docker image"
33-
)
28+
@click.argument("path")
29+
@click.option(
30+
"--docker/--no-docker",
31+
default=False,
32+
show_default=True,
33+
help="Uses ODK docker image",
34+
)
3435
def make(path, docker):
3536
"""
3637
Makes a specified target, such as a db file
@@ -49,8 +50,8 @@ def make(path, docker):
4950

5051

5152
@main.command()
52-
@click.option('-o', '--output')
53-
@click.argument('ontology')
53+
@click.option("-o", "--output")
54+
@click.argument("ontology")
5455
def download(ontology, output):
5556
"""
5657
Download a read-made SQLite db for an OBO ontology
@@ -63,8 +64,8 @@ def download(ontology, output):
6364

6465

6566
@main.command()
66-
@click.option('-i', '--input')
67-
@click.argument('query')
67+
@click.option("-i", "--input")
68+
@click.argument("query")
6869
def query(input, query):
6970
"""
7071
Performs a SQL query on an OWL file
@@ -81,9 +82,13 @@ def query(input, query):
8182

8283

8384
@main.command()
84-
@click.argument('inputs', nargs=-1)
85-
@click.option('--index/--no-index', default=True, help='Create indexes on each column')
86-
@click.option('--name', '-n', help='Name of class/view to materialize. If blank, will perform for ALL')
85+
@click.argument("inputs", nargs=-1)
86+
@click.option("--index/--no-index", default=True, help="Create indexes on each column")
87+
@click.option(
88+
"--name",
89+
"-n",
90+
help="Name of class/view to materialize. If blank, will perform for ALL",
91+
)
8792
def view2table(inputs, name: str, index: bool):
8893
"""
8994
Generates a command that turns a view into a table
@@ -96,24 +101,23 @@ def view2table(inputs, name: str, index: bool):
96101
```
97102
"""
98103
for input in inputs:
99-
with open(input, 'r') as stream:
100-
sv = SchemaView(input)
101-
schema = sv.schema
102-
for cn, c in sv.all_classes().items():
103-
tn = underscore(cn)
104-
if name is None or str(cn) == name or tn == name:
105-
view = get_viewdef(c)
106-
if view is not None:
107-
print(f'DROP VIEW {tn};')
108-
print(f'CREATE TABLE {tn} AS {view};')
109-
if index:
110-
for sn in sv.class_slots(cn):
111-
colname = underscore(sn)
112-
print(f'CREATE INDEX {tn}_{colname} ON {tn}({colname});')
113-
else:
114-
logging.error(f'No view for {cn}')
115-
116-
117-
118-
if __name__ == '__main__':
104+
sv = SchemaView(input)
105+
for cn, c in sv.all_classes().items():
106+
tn = underscore(cn)
107+
if name is None or str(cn) == name or tn == name:
108+
view = get_viewdef(c)
109+
if view is not None:
110+
print(f"DROP VIEW {tn};")
111+
print(f"CREATE TABLE {tn} AS {view};")
112+
if index:
113+
for sn in sv.class_slots(cn):
114+
colname = underscore(sn)
115+
print(
116+
f"CREATE INDEX {tn}_{colname} ON {tn}({colname});"
117+
)
118+
else:
119+
logging.error(f"No view for {cn}")
120+
121+
122+
if __name__ == "__main__":
119123
main()

src/semsql/loader.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,56 @@
1-
import click
2-
import os
31
import logging
42
import subprocess
53
from typing import List
6-
from sqlalchemy.sql import text
4+
5+
import click
76
from sqlalchemy import create_engine
7+
from sqlalchemy.sql import text
8+
89

910
def get_sqlite_path(url: str) -> str:
10-
if url.startswith('sqlite:///'):
11-
return url.replace('sqlite:///', '')
12-
elif ':' in url:
13-
raise Exception('Only sqlite supported')
11+
if url.startswith("sqlite:///"):
12+
return url.replace("sqlite:///", "")
13+
elif ":" in url:
14+
raise Exception("Only sqlite supported")
1415
else:
1516
return url
1617

18+
1719
def load_ddl(con, path: str):
18-
with open(path, 'r') as stream:
20+
with open(path, "r") as stream:
1921
statement = text("\n".join(stream.readlines()))
20-
print(f's={statement}')
22+
print(f"s={statement}")
2123
con.execute(statement)
2224

25+
2326
def create_and_load(inputs: List[str], create: bool, url: str) -> None:
2427
db = get_sqlite_path(url)
2528
if create:
26-
subprocess.run(['cat', 'prefixes/prefix.sql | sqlite3', db])
29+
subprocess.run(["cat", "prefixes/prefix.sql | sqlite3", db])
2730
engine = create_engine(url)
2831
with engine.connect() as con:
29-
load_ddl(con, 'prefixes/prefix.sql')
30-
load_rdftab(con, 'sql/rdftab.sql')
31-
load_rdftab(con, 'sql_schema/semsql.sql')
32+
load_ddl(con, "prefixes/prefix.sql")
33+
#load_rdftab(con, "sql/rdftab.sql")
34+
#load_rdftab(con, "sql_schema/semsql.sql")
3235
for input in inputs:
33-
results = subprocess.run(['./bin/rdftab', db, input])
36+
subprocess.run(["./bin/rdftab", db, input])
37+
3438

3539
@click.command()
36-
@click.option('--url', '-u', help='SQL alchemy URL for db (MUST BE SQLITE)')
37-
@click.option('--db', '-d', help='Path to sqlite db')
38-
@click.option('--create/--no-create', default=True, help='set if db is to be created')
39-
@click.argument('inputs', nargs=-1)
40+
@click.option("--url", "-u", help="SQL alchemy URL for db (MUST BE SQLITE)")
41+
@click.option("--db", "-d", help="Path to sqlite db")
42+
@click.option("--create/--no-create", default=True, help="set if db is to be created")
43+
@click.argument("inputs", nargs=-1)
4044
def cli(inputs: List[str], create: bool, db: str, url: str):
4145
"""
4246
Load from OWL
4347
"""
4448
if db is not None:
45-
url = f'sqlite:///{db}'
49+
url = f"sqlite:///{db}"
4650
if url is None:
47-
logging.error('Must pass --db or --url')
51+
logging.error("Must pass --db or --url")
4852
create_and_load(inputs, create, url)
4953

5054

51-
if __name__ == '__main__':
55+
if __name__ == "__main__":
5256
cli()

src/semsql/ontlib/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from semsql.ontlib.subgraph import extract_subgraph
1+
from semsql.ontlib.subgraph import extract_subgraph

src/semsql/ontlib/common_queries.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import logging
2-
from typing import Optional, List, Dict
2+
from typing import Dict, List, Optional
33

4-
from semsql.sqla.semsql import HasTextDefinitionStatement
5-
from semsql.sqla.semsql import Prefix, RdfsLabelStatement
4+
from semsql.sqla.semsql import (HasTextDefinitionStatement,
5+
Prefix,
6+
RdfsLabelStatement)
67

78
PREFIX_MAP = Dict[str, str]
89
CURIE = str
910

11+
1012
def get_prefixes(session) -> PREFIX_MAP:
1113
"""
1214
Get all defined prefix mappings
@@ -55,7 +57,7 @@ def get_single_value(session, id: CURIE, view=None, strict=False) -> Optional[st
5557
if val is None:
5658
val = s.value
5759
elif val != s.value:
58-
raise Exception(f'Multiple values for {view} where id={id}')
60+
raise Exception(f"Multiple values for {view} where id={id}")
5961
return val
6062

6163

@@ -87,5 +89,5 @@ def term_search(session, terms: List[str], view=None) -> List[CURIE]:
8789
ids.add(str(row.subject))
8890
n += 1
8991
if n == 0:
90-
logging.warning(f'No match for query: {t}')
92+
logging.warning(f"No match for query: {t}")
9193
return list(ids)

0 commit comments

Comments
 (0)