from Objects import PhysicalModel from Objects import PhysicalEntity from Objects import PhysicalProperty from Objects import PhysicalPropertyLink from Objects import PhysicalRelation from Workers import SaveSqlModel TAB = ' ' # use 4 space instead of real tabs(\t) class SaveMySQLModel(SaveSqlModel): def __init__(self, fname): SaveSqlModel.__init__(self, fname) def GetMySQLColumnType(self, proplink): returnVal = proplink.property.datatype.name if proplink.property.datatype.name == "int": if proplink.property.datatype.size1 == 1: returnVal = 'tinyint' elif proplink.property.datatype.size1 == 2: returnVal = 'smallint' elif proplink.property.datatype.size1 == 3: returnVal = 'mediumint' elif proplink.property.datatype.size1 == 4: returnVal = 'int' elif proplink.property.datatype.size1 == 8: returnVal = 'bigint' elif proplink.property.datatype.name == "float": if proplink.property.datatype.size1 != None: returnVal += "("+str(proplink.property.datatype.size1) if proplink.property.datatype.size2 != None: returnVal += ", "+str(proplink.property.datatype.size2) returnVal += ")" elif proplink.property.datatype.name == "varchar": returnVal += "(" returnVal += str(proplink.property.datatype.size1) returnVal += ")" return returnVal def SavePhysicalPropertyLink(self, proplink): t = TAB + proplink.localname + " " + self.GetMySQLColumnType(proplink) if proplink.primarykey == 1: if int(proplink.sequence) == 1 and proplink.property.datatype.name == "int": t += " AUTO_INCREMENT" t += " NOT NULL" elif proplink.notnull == 1: t += " NOT NULL" if proplink.unique == 1: t += " UNIQUE" else: if proplink.unique == 1: t += " UNIQUE" return t def SavePhysicalEntity(self, model, entity): t = "CREATE TABLE " + entity.name + "( \n" pk = [] fields = [] for i in entity.propertylinks: fields.append(self.SavePhysicalPropertyLink(i)) if i.primarykey == 1: pk.append(str(i.localname)) t += ',\n'.join(fields) if len(pk): t += ',\n' t += TAB + 'PRIMARY KEY (' + ','.join(pk) + ')' fk = [] for i in model.relations: if i.entities[1] == entity: fk.append(TAB + self.SavePhysicalRelation(i)) if len(fk): t += ',\n' t += ',\n'.join(fk) t += "\n)type=innodb;\n" return t def SavePhysicalRelation(self, r): indexsql = 'INDEX ' t = "FOREIGN KEY (" # All FOREIGN KEY names in entity1 props = [] for i in r.properties: props.append(str(r.entities[1].GetPropertyLocalName(i.name))) indexsql += str(r.entities[1].GetPropertyLocalName(i.name)) + '_' s = str(props).replace("\'","") t += s[1:len(s)-1] +") REFERENCES " + r.entities[0].name + " (" indexsql += 'ind ' + '(' + s[1:len(s)-1] + ')' # All FOREIGN KEY names in entity0 props = [] for i in r.properties: props.append(str(r.entities[0].GetPropertyLocalName(i.name))) s = str(props).replace("\'","") t += s[1:len(s)-1] +")" t = t + ',\n\t\t' + indexsql return t