2015-01-16 14 views
14

पर SQLlchemy के साथ आंशिक अद्वितीय अनुक्रमणिका बनाना SQLAlchemy partial indexes in postgresql बनाने का समर्थन करता है।Postgres

क्या एसक्यूएलकेमी के माध्यम से partial unique index बनाना संभव है?

एक मेज/मॉडल की कल्पना के रूप में इतना:

class ScheduledPayment(Base): 
    invoice_id = Column(Integer) 
    is_canceled = Column(Boolean, default=False) 

मैं एक अद्वितीय सूचकांक जहां केवल एक "सक्रिय" किसी दिए गए चालान के लिए ScheduledPayment हो सकता है चाहते हैं।

मैं postgres में मैन्युअल रूप से यह बना सकते हैं:

CREATE UNIQUE INDEX only_one_active_invoice on scheduled_payment 
    (invoice_id, is_canceled) where not is_canceled; 

मैं सोच रहा हूँ कि कैसे मैं SQLAlchemy 0.9 का उपयोग करके मेरी SQLAlchemy मॉडल है कि जोड़ सकते हैं।

उत्तर

22
class ScheduledPayment(Base): 
    id = Column(Integer, primary_key=True) 
    invoice_id = Column(Integer) 
    is_canceled = Column(Boolean, default=False) 

    __table_args__ = (
     Index('only_one_active_invoice', invoice_id, is_canceled, 
       unique=True, 
       postgresql_where=(~is_canceled)), 
    ) 
+0

बिल्कुल सही .... धन्यवाद! – brianz

1

मामले में किसी को एक स्तंभ के साथ एक आंशिक अद्वितीय बाधा है कि वैकल्पिक रूप से NULL हो सकता है स्थापित करने के लिए देख कर बंद हो जाता है, तो यहां देखें: कि

__table_args__ = (
    db.Index(
     'uk_providers_name_category', 
     'name', 'category', 
     unique=True, 
     postgresql_where=(user_id.is_(None))), 
    db.Index(
     'uk_providers_name_category_user_id', 
     'name', 'category', 'user_id', 
     unique=True, 
     postgresql_where=(user_id.isnot(None))), 
) 

जहां user_id एक स्तंभ है NULL और मैं हो सकता है के साथ सभी तीन कॉलम (name, category, user_id) में लागू एक अद्वितीय बाधा चाहते हैं, बस user_id के लिए अनुमत मानों में से एक है।