3 from lsst.pex.config
import ConfigurableField
8 import psycopg2
as pgsql
15 """Context manager to provide a pgsql registry
17 def __init__(self, registryName, createTableFunc, forceCreateTables):
18 """Construct a context manager
20 @param registryName: Name of registry file
21 @param createTableFunc: Function to create tables
22 @param forceCreateTables: Force the (re-)creation of tables?
25 data = PgsqlRegistry.readYaml(registryName)
26 self.
conn = pgsql.connect(host=data[
"host"], port=data[
"port"], user=data[
"user"],
27 password=data[
"password"], database=data[
"database"])
28 cur = self.
conn.cursor()
31 cur.execute(
"SELECT relname FROM pg_class WHERE relkind='r' AND relname='raw'")
34 if forceCreateTables
or len(rows) == 0:
37 cur.execute(
"SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
38 tables = cur.fetchall()
40 cur.execute(
"DROP TABLE %s CASCADE" % tt)
41 createTableFunc(self.
conn)
43 def __exit__(self, excType, excValue, traceback):
53 """Open the registry and return the connection handle.
55 @param directory Directory in which the registry file will be placed
56 @param create Clobber any existing registry and create a new one?
57 @param dryrun Don't do anything permanent?
58 @return Database connection
62 registryName = os.path.join(directory,
"registry.pgsql")
66 """Create the registry tables
68 One table (typically 'raw') contains information on all files, and the
69 other (typically 'raw_visit') contains information on all visits.
71 This method is required because there's a slightly different syntax
72 compared to SQLite (FLOAT instead of DOUBLE, SERIAL instead of
75 @param conn Database connection
76 @param table Name of table to create in database
81 typeMap = {
'int':
'INT',
86 cmd =
"CREATE TABLE %s (id SERIAL NOT NULL PRIMARY KEY, " % table
87 cmd +=
",".join([
"%s %s" % (col, typeMap.get(colType.lower(),
'text'))
for
88 col, colType
in self.
config.columns.items()])
89 if len(self.
config.unique) > 0:
90 cmd +=
", UNIQUE(" +
",".join(self.
config.unique) +
")"
94 cmd =
"CREATE TABLE %s_visit (" % self.
config.table
95 cmd +=
",".join([
"%s %s" % (col, typeMap.get(self.
config.columns[col].lower(),
'TEXT'))
for
97 cmd +=
", UNIQUE(" +
",".join(
set(self.
config.visit).intersection(
set(self.
config.unique))) +
")"
105 register = ConfigurableField(target=PgsqlRegisterTask, doc=
"Registry entry")
109 ConfigClass = PgsqlIngestConfig