From 3d7e0a2bf7ab0af79ff87992a728e23bec042cd8 Mon Sep 17 00:00:00 2001 From: Charles Leifer Date: Sat, 14 Dec 2024 11:14:44 -0600 Subject: [PATCH] Slight cleanup of foreign-key constraint name stuff. --- peewee.py | 30 +++++++++++++++--------------- playhouse/migrate.py | 7 +++++-- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/peewee.py b/peewee.py index 3c2711117..2d421b9fa 100644 --- a/peewee.py +++ b/peewee.py @@ -5564,6 +5564,12 @@ def get_modifiers(self): return self.rel_field.get_modifiers() return super(ForeignKeyField, self).get_modifiers() + def get_constraint_name(self): + return self.constraint_name or 'fk_%s_%s_refs_%s' % ( + self.model._meta.table_name, + self.column_name, + self.rel_model._meta.table_name) + def adapt(self, value): return self.rel_field.adapt(value) @@ -5613,10 +5619,14 @@ def bind(self, model, name, set_attribute=True): setattr(self.rel_model, self.backref, self.backref_accessor_class(self)) - def foreign_key_constraint(self): + def foreign_key_constraint(self, explicit_name=False): parts = [] - if self.constraint_name: - parts.extend((SQL('CONSTRAINT'), Entity(self.constraint_name))) + if self.constraint_name or explicit_name: + name = self.get_constraint_name() + parts.extend([ + SQL('CONSTRAINT'), + Entity(_truncate_constraint_name(name))]) + parts.extend([ SQL('FOREIGN KEY'), EnclosedNodeList((self,)), @@ -6145,22 +6155,12 @@ def drop_sequence(self, field): self.database.execute(seq_ctx) def _create_foreign_key(self, field): - if not field.constraint_name: - name = 'fk_%s_%s_refs_%s' % (field.model._meta.table_name, - field.column_name, - field.rel_model._meta.table_name) - nodes = NodeList((SQL(' CONSTRAINT'), - Entity(_truncate_constraint_name(name)))) - else: - nodes = NodeList(()) return (self ._create_context() .literal('ALTER TABLE ') .sql(field.model) - .literal(' ADD') - .sql(nodes) - .literal(' ') - .sql(field.foreign_key_constraint())) + .literal(' ADD ') + .sql(field.foreign_key_constraint(True))) def create_foreign_key(self, field): self.database.execute(self._create_foreign_key(field)) diff --git a/playhouse/migrate.py b/playhouse/migrate.py index cb0927603..56f49d68c 100644 --- a/playhouse/migrate.py +++ b/playhouse/migrate.py @@ -286,8 +286,11 @@ def add_inline_fk_sql(self, ctx, field): @operation def add_foreign_key_constraint(self, table, column_name, rel, rel_column, - on_delete=None, on_update=None): - constraint = 'fk_%s_%s_refs_%s' % (table, column_name, rel) + on_delete=None, on_update=None, + constraint_name=None): + constraint = constraint_name or 'fk_%s_%s_refs_%s' % (table, + column_name, + rel) ctx = (self .make_context() .literal('ALTER TABLE ')