sqlalchemy icon indicating copy to clipboard operation
sqlalchemy copied to clipboard

add official API to have naming conventions work for alternate constraint types

Open CaselIT opened this issue 3 years ago • 13 comments

Using them is poorly tested and the use case seems quite limited.

CaselIT avatar Sep 12 '23 14:09 CaselIT

as stated, how do we supply naming conventions for ExcludeConstraint as well as any other third party constraint? that was likely why I had it supporting this style

zzzeek avatar Sep 12 '23 14:09 zzzeek

are they supported at the moment?

This https://github.com/sqlalchemy/sqlalchemy/issues/3011 seems also related

CaselIT avatar Sep 12 '23 14:09 CaselIT

i dont know, not sure if we have tests. we'd want to see if there are excludeconstraint naming convention tests in PG (I dont think there are)

zzzeek avatar Sep 12 '23 15:09 zzzeek

I guess the objective of the issue is then:

  • verify if other contraints work when passed aw type
  • if they do properly test the feature/improve typing as needed
  • if not then we could probably consider deprecating this

CaselIT avatar Sep 12 '23 16:09 CaselIT

if we deprecate then we need a new way to support naming conventions for other constraint types

zzzeek avatar Sep 12 '23 17:09 zzzeek

well the thinking was if it does not work at the moment then chances are no-one wants-uses it

CaselIT avatar Sep 12 '23 18:09 CaselIT

constraint types that are not in the immediate schema.py hierarchy are pretty major. some way to register a new two letter code, something like that. just cant be a brick wall

zzzeek avatar Sep 12 '23 19:09 zzzeek

I guess the idea here was the naming convention dict allows arbitrary keys and can't use TypedDict? I definitely think custom letter codes should be allowed in that dict, in any case. A full expansion of naming convention stuff to other constraints would be nice also but not priority.

unless we want to move this to "make an official extensibility API for naming conventions" I would say we close this

zzzeek avatar Aug 14 '25 15:08 zzzeek

I actually use the naming conventions a lot and, not realizing it is not supported, I have custom ones added. To add a custom constraint naming convention:

# Define the custom naming convention
CONSTRAINTS_NAMING_CONVENTION: _NamingSchemaParameter = {
    'ix': 'IX_%(column_0_label)s',
    'uq': 'UQ_%(table_name)s_%(column_0_N_name)s',
    'ck': 'CK_%(table_name)s_%(constraint_name)s',
    'fk': 'FK_%(table_name)s_to_%(referred_table_name)s',
    'pk': 'PK_%(table_name)s',
    'ctcn_cols': ctcn_columns,
    'ctcn': 'UQ_%(table_name)s[%(ctcn_cols)s]_per_%(referred_table_name)s',
}

# Define the custom constraint
class CustomConstraint(UniqueConstraint): ...

# Add the prefix and the type:
_prefix_dict[CustomConstraint] = 'ctcn'

# Define the callback function
def ctcn_columns(constraint: Constraint, table: Table) -> str:
    if not isinstance(constraint, CustomConstraint):
        return ''

    str_tokens = # add your logic here
    return '_'.join(str_tokens)

I think this was working fine in alembic as well, but I don't have any code handy to double check.

I don't know what would need to be added to make this supported, but I don't think that it should be that much since it is working just fine using the private variable _prefix_dict.

Other than that, I think that the _NamingSchemaParameter should be public since you would need it to properly document the dictionary that defines the custom rules.

puc9 avatar Nov 02 '25 03:11 puc9

I actually use the naming conventions a lot and, not realizing it is not supported, I have custom ones added. To add a custom constraint naming convention:

that's great! yeah the task here should just be to make this official. i had even forgotten about the callable path in naming conventions, so yeah, you're using it!

zzzeek avatar Nov 02 '25 14:11 zzzeek

I would favor an API that doesn't actually modify _prefix_dict but places some directive on the target class that is picked up instead, like this:

class CustomConstraint(UniqueConstraint):
    __sa_naming_convention_prefix__ = 'cc'

in fact looking at _prefix_dict this seems kind of pointless as written:

_prefix_dict = {
    Index: "ix",
    PrimaryKeyConstraint: "pk",
    CheckConstraint: "ck",
    UniqueConstraint: "uq",
    ForeignKeyConstraint: "fk",
}


def _get_convention(dict_, key):
    for super_ in key.__mro__:
        if super_ in _prefix_dict and _prefix_dict[super_] in dict_:
            return dict_[_prefix_dict[super_]]
        elif super_ in dict_:
            return dict_[super_]
    else:
        return None

_get_convention() is just doing the work of resolving an attribute on the class! Class.attr is exactly "walk ___mro__ until you find this attribute"

zzzeek avatar Nov 02 '25 14:11 zzzeek

it's also checking for the class itself in the dict. now when did I add that? that does not seem to be documented?

    def test_constraint_classes_for_keys(self):
        u1 = self._fixture(
            naming_convention={
                UniqueConstraint: "uq_%(table_name)s_%(column_0_name)s"
            }
        )
        uq = UniqueConstraint(u1.c.data)
        eq_(uq.name, "uq_user_data")

added in fbafc24d2. no docs. " As part of this change, lesser used forms of the naming convention dictionary are also typed, including that it currently allows for Constraint type objects as keys as well."

OK I guess when I first wrote naming conventions, I had it look for the class in the dict and i never wrote any tests or docs. OK.

Anyway @puc9 you can do this, and it would work too:

from sqlalchemy import Column
from sqlalchemy import Constraint
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import UniqueConstraint
from sqlalchemy.schema import CreateTable

# Define the callback function
def ctcn_columns(constraint: Constraint, table: Table) -> str:
    if not isinstance(constraint, CustomConstraint):
        return ''

    str_tokens = [c.key for c in constraint.columns]
    return '_'.join(str_tokens)

# Define the custom constraint
class CustomConstraint(UniqueConstraint):
    pass

# Define the custom naming convention
CONSTRAINTS_NAMING_CONVENTION = {
    'ix': 'IX_%(column_0_label)s',
    'uq': 'UQ_%(table_name)s_%(column_0_N_name)s',
    'ck': 'CK_%(table_name)s_%(constraint_name)s',
    'fk': 'FK_%(table_name)s_to_%(referred_table_name)s',
    'pk': 'PK_%(table_name)s',
    'ctcn_cols': ctcn_columns,
    CustomConstraint: 'UQ_%(table_name)s[%(ctcn_cols)s]',
}




m = MetaData(naming_convention=CONSTRAINTS_NAMING_CONVENTION)

t = Table("t", m, Column("q", Integer), CustomConstraint("q"))

print(CreateTable(t))

@CaselIT I think this is super easy:

  1. document you can put classes in your naming convention dict
  2. support ___sa_naming_convention_prefix___ and use that instead of _prefix_dict
  3. optionally keep looking in _prefix_dict for easier backwards compat

zzzeek avatar Nov 02 '25 14:11 zzzeek

so we are doing it. I guess just document stuff and add missing tests

CaselIT avatar Nov 02 '25 20:11 CaselIT