Debian Codegraph @

gavo/registry/servicelist.py

raw
1 """
2 The (DC-internal) service list: querying, adding records, etc.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 from gavo import base
12 from gavo import utils
13 from gavo import rsc
14 from gavo.protocols import vocabularies
15 from gavo.registry import common
16
17
18 def getSetsForResource(restup):
19 """returns the list of set names the resource described by restup
20 belongs to.
21 """
22 with base.getTableConn() as conn:
23 return [str(r[0]) for r in
24 conn.query("SELECT DISTINCT setName FROM dc.sets WHERE"
25 " sourceRD=%(sourceRD)s AND resId=%(resId)s AND NOT deleted",
26 restup)]
27
28
29 def getSets():
30 """returns a sequence of dicts giving setName and and a list of
31 services belonging to that set.
32 """
33 tableDef = common.getServicesRD().getById("sets")
34 setMembers = {}
35
36 for rec in tableDef.doSimpleQuery():
37 setMembers.setdefault(rec["setName"], []).append(
38 (rec["sourceRD"], rec["resId"]))
39
40 return [{"setName": key, "services": value}
41 for key, value in setMembers.items()]
42
43
44 def queryServicesList(whereClause="", pars={}, tableName="resources_join"):
45 """returns a list of services based on selection criteria in
46 whereClause.
47
48 The table queried is the resources_join view, and you'll get back all
49 fields defined there.
50 """
51 td = common.getServicesRD().getById(tableName)
52 return td.doSimpleQuery(fragments=whereClause, params=pars)
53
54
55 def querySubjectsList(setName=None):
56 """returns a list of local services chunked by subjects.
57
58 This is mainly for the root page (see web.root). Query the
59 cache using the __system__/services key to clear the cache on services.
60
61 Note that this will translate known UAT terms to their labels.
62 """
63 try:
64 uat = vocabularies.get_vocabulary("uat")
65 except base.ReportableError as msg:
66 # fetching the vocabulary somehow failed; don't stop operations
67 # just because of that.
68 base.ui.notifyWarning("Tried to get UAT but failed: %s. Trugding on."%
69 msg)
70 uat = {"terms": {}}
71
72 setName = setName or 'local'
73 svcsForSubjs = {}
74 td = common.getServicesRD().getById("subjects_join")
75 for row in td.doSimpleQuery(
76 fragments="setName=%(setName)s AND subject IS NOT NULL",
77 params={"setName": setName}):
78 svcsForSubjs.setdefault(row["subject"], []).append(row)
79
80 for s in list(svcsForSubjs.values()):
81 s.sort(key=lambda a: a["title"])
82
83 res = [{"subject": vocabularies.get_label(uat, subject), "chunk": s}
84 for subject, s in svcsForSubjs.items()]
85 res.sort(key=lambda i: i["subject"])
86 return res
87
88
89 def getChunkedServiceList(setName=None):
90 """returns a list of local services chunked by title char.
91
92 This is mainly for the root page (see web.root). Query the
93 cache using the __system__/services key to clear the cache on services
94 reload.
95 """
96 setName = setName or 'local'
97 return utils.chunk(
98 sorted(queryServicesList("setName=%(setName)s and not deleted",
99 {"setName": setName}),
100 key=lambda s: s.get("title").lower()),
101 lambda srec: srec.get("title", ".")[0].upper())
102
103
104 def getRankedServiceList(setName=None):
105 setName = setName or 'local'
106 rscs = queryServicesList("setName=%(setName)s and not deleted",
107 {"setName": setName})
108 # pre-sort by title; python sort is stable, so we will have alphabetic
109 # ordering within each rank
110 rscs.sort(key=lambda r: r["title"])
111 rscs.sort(key=lambda r: r["rank"] or 10000)
112 return rscs
113
114
115 def cleanServiceTablesFor(rd, connection):
116 """removes/invalidates all entries originating from rd from the service
117 tables.
118 """
119 # this is a bit of a hack: We're running services#tables' newSource
120 # skript without then importing anything new.
121 tables = rsc.Data.create(
122 common.getServicesRD().getById("tables"),
123 connection=connection)
124 tables.runScripts("newSource", sourceToken=rd)
125
126
127 def basename(tableName):
128 if "." in tableName:
129 return tableName.split(".")[-1]
130 else:
131 return tableName
132
133
134 def getTableDef(tableName):
135 """returns a tableDef instance for the schema-qualified tableName.
136
137 If no such table is known to the system, a NotFoundError is raised.
138 """
139 with base.getTableConn() as conn:
140 res = list(conn.query("SELECT tableName, sourceRD FROM dc.tablemeta WHERE"
141 " LOWER(tableName)=LOWER(%(tableName)s)", {"tableName": tableName}))
142 if len(res)!=1:
143 raise base.NotFoundError(tableName, what="table",
144 within="DaCHS' table listing.", hint="The table is missing from"
145 " the dc.tablemeta table. This gets filled at gavoimp time.")
146 tableName, rdId = res[0]
147 return base.caches.getRD(rdId).getById(basename(tableName))