Skip to content

Commit

Permalink
Slight cleanup of foreign-key constraint name stuff.
Browse files Browse the repository at this point in the history
  • Loading branch information
coleifer committed Dec 14, 2024
1 parent 76f9512 commit 3d7e0a2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 17 deletions.
30 changes: 15 additions & 15 deletions peewee.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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,)),
Expand Down Expand Up @@ -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))
Expand Down
7 changes: 5 additions & 2 deletions playhouse/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ')
Expand Down

0 comments on commit 3d7e0a2

Please sign in to comment.