"""
RD injections: This code fetches metadata on RDs (identified by their
normalised source ID) from the database and injects it into parse contexts.
"""

from gavo import base
from gavo.base import sqlsupport


def _getRecordsFor(rdId, fromTable, conn):
	"""returns (dict) records from fromTable coming from rdId.
	"""
	try:
		return list(
			conn.queryToDicts(
				"select * from %s where sourceRD=%%(rdId)s"%fromTable, 
				locals()))
	except sqlsupport.ProgrammingError as ex:
		if ex.pgcode=="42P01": # table not found; we're bootstrapping, probably
			return []
		raise


def injectIntoContext(ctx, rdId):
	"""fills context's injected metadata from material from the various
	database tables for the RD rdId.
	"""
	with base.getTableConn() as conn:
		for row in _getRecordsFor(rdId, "dc.rdmeta", conn):
			if row["data_updated"]:
				ctx.inject("_dataUpdated", row["data_updated"])

		for row in _getRecordsFor(rdId, "dc.resources", conn):
			key = "resprop:%s#%s"%(row["sourcerd"], row["resid"])
			ctx.inject(key, row)

		for row in _getRecordsFor(rdId, "dc.tablemeta", conn):
			key = "table:%s"%(row["tablename"].split(".")[-1])
			ctx.inject(key, row)
