-- Create tables with appropriate primary keysCREATETABLEusers(idSERIALPRIMARYKEY,-- Auto-incrementing primary keyusernameVARCHAR(50)UNIQUENOTNULL,-- Natural key with uniquenessemailVARCHAR(255)UNIQUENOTNULL,-- Natural key with uniquenesscreated_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP);-- Composite primary keys for junction tablesCREATETABLEuser_roles(user_idINTEGERNOTNULL,role_idINTEGERNOTNULL,assigned_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP,assigned_byINTEGER,PRIMARYKEY(user_id,role_id)-- Composite primary key);-- UUID primary keys for distributed systemsCREATEEXTENSIONIFNOTEXISTS"uuid-ossp";CREATETABLEdistributed_entities(idUUIDPRIMARYKEYDEFAULTuuid_generate_v4(),entity_typeVARCHAR(50)NOTNULL,dataJSONBNOTNULL,created_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP);-- Natural primary keys for reference dataCREATETABLEcountries(country_codeCHAR(2)PRIMARYKEY,-- ISO country code as natural keycountry_nameVARCHAR(100)NOTNULL,currency_codeCHAR(3)NOTNULL,created_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP);
-- Create tables with check constraintsCREATETABLEusers(idSERIALPRIMARYKEY,usernameVARCHAR(50)UNIQUENOTNULL,emailVARCHAR(255)UNIQUENOTNULL,ageINTEGER,phoneVARCHAR(20),statusVARCHAR(20)DEFAULT'active',created_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP,-- Check constraints for data validationCONSTRAINTusers_username_lengthCHECK(LENGTH(username)>=3),CONSTRAINTusers_email_formatCHECK(email~*'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),CONSTRAINTusers_age_rangeCHECK(ageISNULLOR(age>=0ANDage<=150)),CONSTRAINTusers_phone_formatCHECK(phoneISNULLORphone~'^\+?[1-9]\d{1,14}$'),CONSTRAINTusers_status_validCHECK(statusIN('active','inactive','suspended','deleted')));CREATETABLEproducts(idSERIALPRIMARYKEY,nameVARCHAR(200)NOTNULL,priceNUMERIC(10,2)NOTNULL,stock_quantityINTEGERNOTNULL,weight_gramsINTEGER,dimensionsJSONB,created_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP,-- Check constraints for business rulesCONSTRAINTproducts_price_positiveCHECK(price>0),CONSTRAINTproducts_stock_non_negativeCHECK(stock_quantity>=0),CONSTRAINTproducts_weight_positiveCHECK(weight_gramsISNULLORweight_grams>0),CONSTRAINTproducts_dimensions_validCHECK(dimensionsISNULLOR(dimensions?'length'ANDdimensions?'width'ANDdimensions?'height')));
-- Create tables with appropriate NOT NULL constraintsCREATETABLEuser_profiles(idSERIALPRIMARYKEY,user_idINTEGERNOTNULL,first_nameVARCHAR(100)NOTNULL,last_nameVARCHAR(100)NOTNULL,emailVARCHAR(255)NOTNULL,phoneVARCHAR(20),date_of_birthDATE,created_atTIMESTAMPTZNOTNULLDEFAULTCURRENT_TIMESTAMP,updated_atTIMESTAMPTZNOTNULLDEFAULTCURRENT_TIMESTAMP);-- Use NOT NULL with default valuesCREATETABLEsystem_settings(idSERIALPRIMARYKEY,setting_nameVARCHAR(100)NOTNULL,setting_valueTEXTNOTNULL,descriptionTEXT,is_activeBOOLEANNOTNULLDEFAULTTRUE,created_atTIMESTAMPTZNOTNULLDEFAULTCURRENT_TIMESTAMP,updated_atTIMESTAMPTZNOTNULLDEFAULTCURRENT_TIMESTAMP);-- Conditional NOT NULL constraintsCREATETABLEuser_addresses(idSERIALPRIMARYKEY,user_idINTEGERNOTNULL,address_typeVARCHAR(20)NOTNULL,street_addressVARCHAR(200)NOTNULL,cityVARCHAR(100)NOTNULL,stateVARCHAR(50),zip_codeVARCHAR(20),countryVARCHAR(50)NOTNULL,is_primaryBOOLEANDEFAULTFALSE,created_atTIMESTAMPTZNOTNULLDEFAULTCURRENT_TIMESTAMP,-- Conditional NOT NULL based on countryCONSTRAINTuser_addresses_state_requiredCHECK((country='US'ANDstateISNOTNULL)OR(country!='US'ANDstateISNULL)));
-- Create custom validation functionsCREATEORREPLACEFUNCTIONvalidate_email(emailTEXT)RETURNSBOOLEANAS$$BEGINIFemailISNULLTHENRETURNFALSE;ENDIF;-- Basic email format validationIFNOT(email~*'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$')THENRETURNFALSE;ENDIF;-- Check for consecutive dotsIFemail~'\.\.'THENRETURNFALSE;ENDIF;-- Check for leading/trailing dotsIFemail~'^\.|\.$'THENRETURNFALSE;ENDIF;RETURNTRUE;END;$$LANGUAGEplpgsql;CREATEORREPLACEFUNCTIONvalidate_phone(phoneTEXT)RETURNSBOOLEANAS$$BEGINIFphoneISNULLTHENRETURNTRUE;-- NULL is allowedENDIF;-- E.164 format validationIFNOT(phone~'^\+[1-9]\d{1,14}$')THENRETURNFALSE;ENDIF;RETURNTRUE;END;$$LANGUAGEplpgsql;CREATEORREPLACEFUNCTIONvalidate_credit_card(card_numberTEXT)RETURNSBOOLEANAS$$DECLAREiINTEGER;sumINTEGER:=0;digitINTEGER;is_evenBOOLEAN:=FALSE;BEGINIFcard_numberISNULLTHENRETURNFALSE;ENDIF;-- Remove non-digitscard_number:=regexp_replace(card_number,'[^0-9]','','g');-- Check lengthIFLENGTH(card_number)<13ORLENGTH(card_number)>19THENRETURNFALSE;ENDIF;-- Luhn algorithmFORiINREVERSELENGTH(card_number)..1LOOPdigit:=(ASCII(SUBSTRING(card_number,i,1))-ASCII('0'));IFis_evenTHENdigit:=digit*2;IFdigit>9THENdigit:=digit-9;ENDIF;ENDIF;sum:=sum+digit;is_even:=NOTis_even;ENDLOOP;RETURN(sum%10)=0;END;$$LANGUAGEplpgsql;-- Use validation functions in constraintsCREATETABLEuser_payments(idSERIALPRIMARYKEY,user_idINTEGERNOTNULL,card_numberVARCHAR(19)NOTNULL,card_holder_nameVARCHAR(100)NOTNULL,expiry_dateDATENOTNULL,cvvVARCHAR(4)NOTNULL,created_atTIMESTAMPTZDEFAULTCURRENT_TIMESTAMP,CONSTRAINTuser_payments_card_validCHECK(validate_credit_card(card_number)),CONSTRAINTuser_payments_expiry_futureCHECK(expiry_date>CURRENT_DATE));
-- Create function to add constraints dynamicallyCREATEORREPLACEFUNCTIONadd_constraint_if_not_exists(table_nameTEXT,constraint_nameTEXT,constraint_definitionTEXT)RETURNSBOOLEANAS$$BEGIN-- Check if constraint already existsIFEXISTS(SELECT1FROMinformation_schema.table_constraintsWHEREtable_name=$1ANDconstraint_name=$2)THENRETURNFALSE;ENDIF;-- Add constraintEXECUTEformat('ALTER TABLE %I ADD CONSTRAINT %I %s',table_name,constraint_name,constraint_definition);RETURNTRUE;END;$$LANGUAGEplpgsql;-- Use function to add constraintsSELECTadd_constraint_if_not_exists('users','users_username_format','CHECK (username ~ ''^[a-zA-Z0-9_]{3,50}$'')');-- Create function to drop constraints safelyCREATEORREPLACEFUNCTIONdrop_constraint_if_exists(table_nameTEXT,constraint_nameTEXT)RETURNSBOOLEANAS$$BEGIN-- Check if constraint existsIFNOTEXISTS(SELECT1FROMinformation_schema.table_constraintsWHEREtable_name=$1ANDconstraint_name=$2)THENRETURNFALSE;ENDIF;-- Drop constraintEXECUTEformat('ALTER TABLE %I DROP CONSTRAINT %I',table_name,constraint_name);RETURNTRUE;END;$$LANGUAGEplpgsql;
# monitoring/constraint_monitor.pyimportpsycopg2importjsonfromdatetimeimportdatetimeimportloggingclassConstraintMonitor:def__init__(self,connection_params):self.conn_params=connection_paramsself.setup_logging()defsetup_logging(self):"""Setup logging."""logging.basicConfig(level=logging.INFO)self.logger=logging.getLogger(__name__)defget_constraint_info(self):"""Get information about all constraints."""conn=psycopg2.connect(**self.conn_params)try:withconn.cursor()ascur:cur.execute(""" SELECT tc.table_name, tc.constraint_name, tc.constraint_type, kcu.column_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name, rc.delete_rule, rc.update_rule FROM information_schema.table_constraints AS tc LEFT JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name LEFT JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name LEFT JOIN information_schema.referential_constraints AS rc ON tc.constraint_name = rc.constraint_name WHERE tc.table_schema = 'public' ORDER BY tc.table_name, tc.constraint_type, tc.constraint_name """)constraints=cur.fetchall()returnconstraintsexceptExceptionase:self.logger.error(f"Error getting constraint info: {e}")return[]finally:conn.close()defcheck_constraint_violations(self,table_name):"""Check for potential constraint violations."""conn=psycopg2.connect(**self.conn_params)try:withconn.cursor()ascur:# Check for duplicate values in unique constraintscur.execute(""" SELECT tc.constraint_name, kcu.column_name, COUNT(*) as duplicate_count FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name WHERE tc.table_name = %s AND tc.constraint_type = 'UNIQUE' GROUP BY tc.constraint_name, kcu.column_name HAVING COUNT(*) > 1 """,(table_name,))violations=cur.fetchall()returnviolationsexceptExceptionase:self.logger.error(f"Error checking constraint violations: {e}")return[]finally:conn.close()defanalyze_constraint_performance(self):"""Analyze constraint performance impact."""conn=psycopg2.connect(**self.conn_params)try:withconn.cursor()ascur:# Get constraint usage statisticscur.execute(""" SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes WHERE indexname LIKE '%_pkey%' OR indexname LIKE '%_unique%' ORDER BY idx_scan DESC """)performance_stats=cur.fetchall()returnperformance_statsexceptExceptionase:self.logger.error(f"Error analyzing constraint performance: {e}")return[]finally:conn.close()defgenerate_constraint_report(self):"""Generate comprehensive constraint report."""constraint_info=self.get_constraint_info()performance_stats=self.analyze_constraint_performance()report={'report_timestamp':datetime.now().isoformat(),'total_constraints':len(constraint_info),'constraint_info':constraint_info,'performance_stats':performance_stats}returnreport# Usageif__name__=="__main__":monitor=ConstraintMonitor({'host':'localhost','database':'production','user':'monitor_user','password':'monitor_password'})report=monitor.generate_constraint_report()print(json.dumps(report,indent=2))
-- Create function for custom constraint error messagesCREATEORREPLACEFUNCTIONhandle_constraint_violation()RETURNSTRIGGERAS$$BEGIN-- Check for specific constraint violationsIFTG_OP='INSERT'THEN-- Check for duplicate emailIFEXISTS(SELECT1FROMusersWHEREemail=NEW.emailANDid!=NEW.id)THENRAISEEXCEPTION'Email address % is already in use',NEW.email;ENDIF;-- Check for duplicate usernameIFEXISTS(SELECT1FROMusersWHEREusername=NEW.usernameANDid!=NEW.id)THENRAISEEXCEPTION'Username % is already taken',NEW.username;ENDIF;ENDIF;RETURNNEW;END;$$LANGUAGEplpgsql;-- Create trigger for custom error handlingCREATETRIGGERusers_constraint_handlerBEFOREINSERTORUPDATEONusersFOREACHROWEXECUTEFUNCTIONhandle_constraint_violation();