Debian Codegraph @

gavo/user/limits.py

raw
1 """
2 Updating table and column metadata.
3
4 While column statistics can be explicitly defined in values elements
5 (and there may be cases when manually defining them makes sense), the
6 typical case is to gather statistics from the database and keep them in
7 a few tables in the dc schema.
8
9 Starting with DaCHS 2.3.1 (schema version 27), there's
10 dc.simple_col_stats for floats and "2 sigma" statistics.
11
12 Starting with DaCHS 2.5.2 (schema version 30), there's in addition
13 dc.string_col_dist for statistics of enumerated string columns.
14
15 The actual acquisition of the statistics is currently done in user.info
16 (and should probably move to rscdef).
17 """
18
19 #c Copyright 2008-2025, the GAVO project <[email protected]>
20 #c
21 #c This program is free software, covered by the GNU GPL. See the
22 #c COPYING file in the source distribution.
23
24 from gavo import base
25 from gavo import rsc
26 from gavo import utils
27 from gavo.user import info
28
29
30 def iterCoverageItems(updater):
31 """yields coverage items for inclusion in RDs.
32
33 NOTE: so far, we can only have one coverage item. So, it's enough
34 to just say "fill this into axis x of coverage". If and when we
35 have more than one coverage items, we'll have to re-think that.
36 That's why there's the "reserved" value in the tuples. We'll have to
37 put something in there (presumably the index of the coverage element,
38 but perhaps we'll have a better identity at some point).
39 """
40 if updater is base.NotGiven:
41 return
42
43 if updater.parent.spatial is not None:
44 sourceTable = updater.spaceTable or updater.sourceTable
45
46 if sourceTable:
47 cov = info.getMOCForStdTable(sourceTable, updater.mocOrder)
48 if cov:
49 yield "spatial", cov.asASCII()
50
51 if updater.parent.temporal is not None:
52 sourceTable = updater.timeTable or updater.sourceTable
53 if sourceTable:
54 res = []
55 for pair in info.iterScalarLimits(
56 sourceTable,
57 info.getTimeLimitsExprs):
58 res.extend(pair)
59 yield "temporal", res
60
61 if updater.parent.spectral is not None:
62 sourceTable = updater.spectralTable or updater.sourceTable
63 if sourceTable:
64 res = []
65 for pair in info.iterScalarLimits(
66 sourceTable,
67 info.getSpectralLimitsExprs):
68 res.extend(list(sorted(pair)))
69 yield "spectral", res
70
71
72 def updateRDLevelMetadata(rd, conn):
73 """Determines RD-level metadata (coverage, mainly) and inserts it into
74 dc.rds.
75 """
76 conn.execute(
77 "UPDATE dc.rdmeta"
78 " SET spatial=NULL, temporal=NULL, spectral=NULL"
79 " WHERE sourceRD=%(rdId)s",
80 {"rdId": rd.sourceId})
81
82 if rd.coverage:
83 base.ui.notifyProcessStarts(f"Obtaining coverage from {rd.sourceId}")
84 try:
85 for colName, value in iterCoverageItems(rd.coverage.updater):
86 conn.execute(
87 "UPDATE dc.rdmeta"
88 f" SET {colName}=%(value)s"
89 " WHERE sourceRD=%(rdId)s",
90 {"value": value, "rdId": rd.sourceId})
91 finally:
92 base.ui.notifyProcessEnded()
93
94
95 def updateTableLevelStats(
96 td,
97 conn,
98 samplePercent=None,
99 acquireColumnMeta=True):
100 """determines column metadata for the table td and inserts it into
101 dc.*stats.
102
103 samplePercent, if given, says how much of the table to look at; giving
104 this on views will fail.
105
106 If acquireColumnMeta is False, only the size of the table is estimated.
107 """
108 tableType = base.UnmanagedQuerier(conn).getTableType(td.getQName())
109 if tableType is None:
110 base.ui.notifyWarning("Skipping non-existing table %s"%td.getQName())
111 return
112
113 elif tableType=="VIEW":
114 samplePercent = 0
115
116 info.annotateDBTable(td, samplePercent, acquireColumnMeta)
117
118 for toImport in [
119 "//dc_tables#import_simple_col_stats",
120 "//dc_tables#import_discrete_string_values"]:
121 rsc.makeData(
122 base.resolveCrossId(toImport),
123 forceSource=td,
124 connection=conn)
125
126 conn.execute("UPDATE dc.tablemeta SET nrows=%(nrows)s"
127 " WHERE tableName=%(tableName)s",
128 {"nrows": td.nrows, "tableName": td.getQName()})
129
130
131 def updateForRD(rd, conn, samplePercent=None, acquireColumnMeta=True):
132 """obtains RD- and table-level metadata for rd and writes it to
133 the meta data tables through conn.
134 """
135 base.ui.notifyInfo(f"Obtaining metadata for rd {rd.sourceId}...")
136 updateRDLevelMetadata(rd, conn)
137 for td in rd.tables:
138 if td.onDisk:
139 if td.viewStatement and not td.getProperty("forceStats", False):
140 continue
141
142 updateTableLevelStats(
143 td, conn, samplePercent, acquireColumnMeta)
144
145
146 def _getUpdatableRdIds():
147 """returns a list of RD ids that presumably had dachs limits
148 run on them before (because they have coverage or table stats).
149 """
150 with base.getTableConn() as conn:
151 return [r[0] for r in conn.query(
152 "SELECT sourceRD FROM"
153 " dc.rdmeta"
154 " WHERE spatial IS NOT NULL"
155 " OR temporal IS NOT NULL OR spectral IS NOT NULL"
156 " UNION"
157 " SELECT sourceRD FROM"
158 " dc.tablemeta"
159 " WHERE nrows IS NOT NULL")]
160
161
162 def dumpTableLevelStats(td, conn):
163 """writes limits metadata for the table td.
164 """
165 if not td.onDisk:
166 return
167 qName = td.getQName()
168
169 heading = f"Statistics for {qName}"
170 print("\n"+heading+"\n"+"-"*len(heading))
171
172 try:
173 print("|rows| = {}\n".format(next(conn.query(
174 "SELECT nrows FROM dc.tablemeta WHERE tablename=%(qName)s",
175 locals()))[0] or "<Unknown>"))
176 except StopIteration:
177 print("No metadata (table not imported)?")
178 return
179
180 statsTD = base.resolveCrossId("//dc_tables#simple_col_stats")
181 colNames = ("column_name min_value max_value percentile03"
182 " median percentile97 fill_factor").split()
183
184 stats = [["{:.5g}".format(v) if isinstance(v, float)
185 else utils.makeEllipsis(str(v), 12, "…") for v in r]
186 for r in conn.query(statsTD.getSimpleQuery(
187 colNames,
188 "tablename=%(tablename)s"),
189 {"tablename": td.getQName()})]
190 stats.sort()
191 print(utils.formatSimpleTable(stats, False, colNames))
192
193
194 def dumpStatsForRD(rd, conn):
195 """writes metadata for rd and its tables
196 """
197 print("="*72)
198 rdId = rd.sourceId
199 print(f"Statistics for RD {rdId}")
200
201 try:
202 print("spatial converage {}".format(next(conn.query(
203 "SELECT spatial FROM dc.rdmeta WHERE sourcerd=%(rdId)s",
204 locals()))[0] or "<Unknown>"))
205 except StopIteration:
206 print("No RD stats.")
207
208 else:
209 print("temporal converage {}".format(next(conn.query(
210 "SELECT temporal FROM dc.rdmeta WHERE sourcerd=%(rdId)s",
211 locals()))[0] or "<Unknown>"))
212
213 print("spectral converage {}".format(next(conn.query(
214 "SELECT spectral FROM dc.rdmeta WHERE sourcerd=%(rdId)s",
215 locals()))[0] or "<Unknown>"))
216
217 for td in rd.tables:
218 dumpTableLevelStats(td, conn)
219
220
221 def parseCmdLine():
222 from argparse import ArgumentParser
223
224 parser = ArgumentParser(
225 description="Updates existing values min/max items in a referenced"
226 " table or RD.")
227 parser.add_argument("-t", "--tables-only",
228 dest="tablesOnly",
229 action="store_true",
230 help="Only acquire table/resource-level metadata (rather than column"
231 " metadata, which usually takes a lot longer).")
232 parser.add_argument("-s", "--sample-percent",
233 type=float,
234 default=None,
235 dest="samplePercent",
236 metavar="P",
237 help="Only look at P percent of the table to determine min/max/mean.")
238 parser.add_argument("-d", "--dump",
239 action="store_true",
240 default=False,
241 dest="dumpOnly",
242 help="Do not obtain statistics but rather dump the results of the"
243 " last run")
244 parser.add_argument("itemId",
245 nargs="+",
246 help="Cross-RD reference of a table or"
247 " RD to update, as in ds/q or ds/q#mytable; only RDs in inputsDir"
248 " can be updated. A single ALL will expand to all RDs that already"
249 " have limits-obtained metadata.")
250 return parser.parse_args()
251
252
253 def main():
254 from gavo import api
255 args = parseCmdLine()
256
257 if len(args.itemId)==1 and args.itemId[0]=="ALL":
258 args.itemId = _getUpdatableRdIds()
259
260 with api.getWritableAdminConn() as conn:
261 for itemRef in args.itemId:
262 item = api.getReferencedElement(itemRef)
263
264 if isinstance(item, api.TableDef):
265 if args.dumpOnly:
266 dumpTableLevelStats(item, conn)
267 else:
268 updateTableLevelStats(item, conn,
269 args.samplePercent, not args.tablesOnly)
270
271 elif isinstance(item, api.RD):
272 if args.dumpOnly:
273 dumpStatsForRD(item, conn)
274 else:
275 updateForRD(item, conn, args.samplePercent, not args.tablesOnly)
276
277 else:
278 raise base.ReportableError(
279 "%s references neither an RD nor a table definition"%args.itemId)
280
281 conn.commit()