Debian Codegraph @

gavo/user/dropping.py

raw
1 """
2 Dropping resources. For now, you can only drop entire RDs.
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 api
12 from gavo import base
13 from gavo import utils
14 from gavo.protocols import obscore
15 from gavo.protocols import tap
16 from gavo.rsc import data
17 from gavo.user import common
18
19
20 def _do_dropTable(tableName, conn):
21 """deletes rows generated from tableName from the DC's metadata
22 (and tableName itself).
23 """
24 q = base.UnmanagedQuerier(conn)
25 for metaTableName, columnName in [
26 ("dc.tablemeta", "tableName"),
27 ("dc.simple_col_stats", "tableName"),
28 ("ivoa._obscoresources", "tableName"),
29 ("tap_schema.tables", "table_name"),
30 ("tap_schema.keys", "from_table"),
31 ("tap_schema.keys", "target_table"),
32 ("tap_schema.columns", "table_name")]:
33 if q.getTableType(metaTableName) is not None:
34 q.connection.execute("delete from %s where %s=%%(tableName)s"%(
35 metaTableName, columnName),
36 {"tableName": tableName})
37
38 if q.getTableType(tableName) is not None:
39 q.dropTable(tableName, cascade=True)
40
41
42 def dropTable():
43 """tries to "manually" purge a table from the DC's memories.
44
45 This is a "toplevel" function intended to be called by cli directly.
46 """
47 def parseCmdline():
48 from argparse import ArgumentParser
49 parser = ArgumentParser(
50 description="Removes all traces of the named table within the DC.")
51 parser.add_argument("tablename", help="The name of the table to drop,"
52 " including the schema name.", nargs="+")
53 return parser.parse_args()
54
55 opts = parseCmdline()
56
57 conn = base.getDBConnection("feed")
58 for tableName in opts.tablename:
59 _do_dropTable(tableName, conn)
60 conn.execute("DELETE FROM dc.products WHERE sourcetable=%(t)s",
61 {'t': tableName})
62 obscore.restoreObscore(conn)
63 conn.commit()
64
65
66 def _do_dropRD(opts, rdId, connection, selectedIds=()):
67 """drops the data and services defined in the RD selected by rdId.
68 """
69 try:
70 rd = api.getReferencedElement(rdId, forceType=api.RD)
71 except api.NotFoundError:
72 if opts.force:
73 rd = None
74 else:
75 raise
76
77 if opts.force or rd is None:
78
79 # If the RD doesn't exist any more, just manually purge it
80 # from wherever it could have been mentioned.
81 for tableName in ["dc.tablemeta", "tap_schema.tables",
82 "tap_schema.columns", "tap_schema.keys", "tap_schema.key_columns",
83 "dc.resources", "dc.interfaces", "dc.sets", "dc.subjects",
84 "dc.authors", "dc.res_dependencies", "ivoa._obscoresources",
85 "dc.biblinks", "dc.rdmeta"]:
86 if base.UnmanagedQuerier(connection
87 ).getTableType(tableName) is not None:
88 connection.execute(
89 "delete from %s where sourceRd=%%(sourceRD)s"%tableName,
90 {"sourceRD": rdId})
91
92 else:
93 # use normalised rd id from here on
94 rdId = rd.sourceId
95
96 if opts.dropAll:
97 dds = rd.dds
98 else:
99 dds = common.getPertainingDDs(rd, selectedIds)
100
101 parseOptions = api.getParseOptions(systemImport=opts.systemImport)
102
103 dgraph = data.DDDependencyGraph(dds, spanRDs=False)
104 dropSequence = dgraph.getDestroySequence()
105 toDrop = set(dds)|set(dropSequence)
106 for dd in dropSequence:
107 api.Data.drop(dd, connection=connection,
108 parseOptions=parseOptions)
109 toDrop.remove(dd)
110 for dd in toDrop:
111 api.Data.drop(dd, connection=connection,
112 parseOptions=parseOptions)
113
114 if not selectedIds or opts.dropAll:
115 from gavo.registry import servicelist
116 servicelist.cleanServiceTablesFor(rd, connection)
117 tap.unpublishFromTAP(rd, connection)
118
119 # Against -f, we do *not* drop in dc.resources and friends; we
120 # want to keep some stuff there so we can push out deleted
121 # records.
122 for tableName in ["dc.tablemeta", "tap_schema.tables",
123 "tap_schema.columns", "tap_schema.keys", "tap_schema.key_columns",
124 "dc.res_dependencies", "ivoa._obscoresources",
125 "dc.biblinks", "dc.rdmeta"]:
126 if base.UnmanagedQuerier(connection
127 ).getTableType(tableName) is not None:
128 connection.execute(
129 "delete from %s where sourceRd=%%(sourceRD)s"%tableName,
130 {"sourceRD": rdId})
131
132 try:
133 with connection.savepoint():
134 connection.execute("drop schema %s"%rd.schema)
135 except Exception as msg:
136 api.ui.notifyWarning("Cannot drop RD %s's schema %s because:"
137 " %s."%(rd.sourceId, rd.schema, utils.safe_str(msg)))
138
139 obscore.restoreObscore(connection)
140
141
142 def dropRD():
143 """parses the command line and drops data and services for the
144 selected RD.
145
146 This is a "toplevel" function intended to be called by cli directly.
147 """
148 def parseCmdline():
149 from argparse import ArgumentParser
150 parser = ArgumentParser(
151 description="Drops all tables made in an RD's data element.")
152 parser.add_argument("rdid", help="RD path or id to drop")
153 parser.add_argument("ddids", help="Optional dd id(s) if you"
154 " do not want to drop the entire RD. Note that no service"
155 " publications will be undone if you give DD ids.", nargs="*")
156 parser.add_argument("-s", "--system", help="drop tables even if they"
157 " are system tables",
158 dest="systemImport", action="store_true")
159 parser.add_argument("-f", "--force", help="Even if the RD isn't"
160 " found, try to purge entries referencing it. This only"
161 " makes sense with the full RD id.",
162 dest="force", action="store_true")
163 parser.add_argument("--all", help="drop all DDs in the RD,"
164 " not only the auto ones (overrides manual selection)",
165 dest="dropAll", action="store_true")
166 return parser.parse_args()
167
168 opts = parseCmdline()
169 rdId = opts.rdid
170 ddIds = None
171 if opts.ddids:
172 ddIds = set(opts.ddids)
173
174 conn = base.getDBConnection("feed")
175 _do_dropRD(opts, rdId, conn, ddIds)
176 conn.commit()