from Objects import PhysicalModel from Objects import PhysicalEntity from Objects import PhysicalProperty from Objects import PhysicalPropertyLink from Objects import PhysicalRelation TAB = ' ' # use 4 space instead of real tabs(\t) class SaveSqlModel (object) : __slots__ = ('filename') def __init__(self, fname): self.filename = fname def save(self, model, view) : #saving model f = file(self.filename, 'w+') txt = self.SavePhysicalModel(model) f.write(txt) f.close() def SavePhysicalModel(self, model): txt = "" entitylist = [] # Make an entitylist sorted by references (= referenced entity always created before the referencing entity) for i in model.entities: entitylist.append(i) # Bubble sorting (if model.HasRelation(i, j) != -1: j could follow i in entitylist) for i in range(len(entitylist)-1, 0, -1): ch = 0 for j in range(0, i): if model.HasRelation(entitylist[j+1], entitylist[j]) != -1: ch += 1 tmp = entitylist[j] entitylist[j] = entitylist[j+1] entitylist[j+1] = tmp if ch == 0: break; for i in entitylist: txt += self.SavePhysicalEntity(model, i) return txt 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);\n" return t def SavePhysicalPropertyLink(self, proplink): t = TAB + proplink.localname + " " + proplink.property.datatype.name if proplink.property.datatype.size1 != None: t += "("+str(proplink.property.datatype.size1) if proplink.property.datatype.size2 != None: t += ", "+str(proplink.property.datatype.size2) t += ")" if proplink.primarykey == 1: 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 SavePhysicalRelation(self, r): t = "FOREIGN KEY (" # All FOREIGN KEY names in entity1 props = [] for i in r.properties: props.append(str(r.entities[1].GetPropertyLocalName(i.name))) s = str(props).replace("\'","") t += s[1:len(s)-1] +") REFERENCES " + r.entities[0].name + " (" # 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] +")" return t