From 4039a905aeb57f0f7f0e1dc20093b70abd62ebb9 Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Mon, 19 Sep 2022 14:37:29 +0200 Subject: [PATCH] Drop or set NOT NULL if necessary --- setup.cfg | 2 +- src/procrusql/__init__.py | 15 +++++++++++++-- src/procrusql/parser.py | 4 +++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/setup.cfg b/setup.cfg index 2e9c94d..9ab8553 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = ProcruSQL -version = 0.0.8 +version = 0.0.9 author = Peter J. Holzer author_email = hjp@hjp.at description = Make a database fit its description diff --git a/src/procrusql/__init__.py b/src/procrusql/__init__.py index 690eee0..a0994f7 100644 --- a/src/procrusql/__init__.py +++ b/src/procrusql/__init__.py @@ -212,7 +212,18 @@ class HaveColumn(Node): (self.schema, self.table, self.column, )) r = csr.fetchall() if len(r) == 1: - # Column exists, all ok + # Column exists, check attributes + if (r[0]["is_nullable"] == "YES") != self.definition["nullable"]: + log_action.info("Changing column %s of %s.%s to %s", + self.column, self.schema, self.table, + "null" if self.definition["nullable"] else "not null") + q = sql.SQL("alter table {schema}.{table} alter {column} {action} not null").format( + schema=sql.Identifier(self.schema), + table=sql.Identifier(self.table), + column=sql.Identifier(self.column), + action=sql.SQL("drop" if self.definition["nullable"] else "set") + ) + csr.execute(q) self.set_order() self.ok = True log_state.info("%s is now ok", self.name) @@ -226,7 +237,7 @@ class HaveColumn(Node): schema=sql.Identifier(self.schema), table=sql.Identifier(self.table), column=sql.Identifier(self.column), - definition=sql.SQL(self.definition), + definition=sql.SQL(self.definition["text"]), ) csr.execute(q) self.set_order() diff --git a/src/procrusql/parser.py b/src/procrusql/parser.py index 3cb00d8..27e3345 100755 --- a/src/procrusql/parser.py +++ b/src/procrusql/parser.py @@ -296,7 +296,9 @@ def parse_column_definition(ps): if not m: ps.record_child_failure(ps2, "expected column definition") return - ps2.ast.append(m.group(0)) + text = m.group(0) + nullable = not("not null" in text or "primary key" in text) + ps2.ast.append({ "text": text, "nullable": nullable }) return ps2 def parse_dict(ps):