"""
Handling table metadata in the dc.(table|column)meta tables.

This has been a mediocre plan, and it's almost unused these days except
to locate RDs for tables.  Hence, we should tear this entire thing down
and have the table->RD mapping stowed somewhere else.

Or at least give up on the extra connection and have the clients use
base.getTableDefForTable(connection, tableName) directly.
"""

#c Copyright 2008-2024, the GAVO project <gavo@ari.uni-heidelberg.de>
#c
#c This program is free software, covered by the GNU GPL.  See the
#c COPYING file in the source distribution.


from gavo import base


class MetaTableHandler(object):
	"""an interface to DaCHS meta tables.

	This used to be a fairly complex interface to all sorts for DC-related
	metadata.  These day, the only thing it does is figure out where
	table definitions reside and which are available for ADQL.  This thing
	has been a bad idea all around.

	Though you can construct MetaTableHandlers of your own, you should
	use base.caches.getMTH(None) when reading.
	"""
	def __init__(self):
		self.rd = base.caches.getRD("__system__/dc_tables")

	def getTableDefForTable(self, tableName):
		"""returns a TableDef for tableName.

		As it is not a priori clear which RD a given table lives in,
		this goes through dc.tablemeta to figure this out.  The
		object comes from the actual RD, though, so this might very well
		trigger database action and RD loading.
		"""
		with base.getTableConn() as conn:
			return base.getTableDefForTable(conn, tableName)

	def getTAPTables(self):
		"""returns a list of all names of tables accessible through TAP in
		this data center.
		"""
		with base.getTableConn() as conn:
			return [r["tablename"] for r in
				conn.queryToDicts(
					"select tablename from dc.tablemeta where adql")]


def _getMetaTable(ignored):
	return MetaTableHandler()

base.caches.makeCache("getMTH", _getMetaTable)
