def getBody(self) : if self.static : if util.inherits(self.subfield.data_type, dbtypes.ClassType) : return "{ " + "return {0}(staticData().{1}.{2});".format(util.getPublicTypeName(self.subfield.data_type, out_of_ns = False), self.field_name, self.subfield_name) + " }" return "{ return staticData()." + self.field_name + "." + self.subfield_name + "; }" if util.inherits(self.subfield.data_type, dbtypes.ClassType) : return "{ return " + "{0}(getInstance().{1}.{2});".format(util.getPublicTypeName(self.subfield.data_type, out_of_ns = False), self.field_name, self.subfield_name) + " }" return "{ return " + "getInstance()." + self.field_name + "." + self.subfield_name + "; }"
def getClasses() : result = "" for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : result += "\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n" result += gen_defs.getDBClass(the_class) return result
def getUnionSetters(self, name) : result = [] for subfield_name in self.data_type.__dict__.keys() : subfield = self.data_type.__dict__[subfield_name] if util.inherits(subfield, Field) : result.append(UnionSetter(self, name, subfield, subfield_name, public = (self.privacy == PUBLIC_FIELD or self.privacy == READONLY_FIELD))) return result
def getMethods(self, name, memory_type) : result = [] if not self.array : result.append(SimpleFieldGetter(self, name, public = (self.privacy == PUBLIC_FIELD or self.privacy == READONLY_FIELD))) result.append(SimpleFieldSetter(self, name, public = (self.privacy == PUBLIC_FIELD))) if util.inherits(self.data_type, dbtypes.UnionType) : result += self.getUnionGetters(name) result += self.getUnionSetters(name) else : if self.array_size != 0 : result.append(FArrayLenMethod(self, name, public = (self.privacy == PUBLIC_FIELD or self.privacy == READONLY_FIELD))) result.append(FArrayPtrMethod(self, name)) else : result.append(VArrayIsExistsMethod(self, name)) result.append(VArrayReallocDataMethod(self, name, memory_type)) result.append(VArrayPtrMethod(self, name, memory_type)) result.append(VArrayAvailableMethod(self, name)) result.append(VArrayResizeMethod(self, name, memory_type)) result.append(VArrayClearMethod(self, name)) result.append(ArrayGetiMethod(self, name, public = (self.privacy == PUBLIC_FIELD or self.privacy == READONLY_FIELD))) result.append(ArraySetiMethod(self, name, public = (self.privacy == PUBLIC_FIELD))) result.append(ArrayReadMethod(self, name, public = (self.privacy == PUBLIC_FIELD or self.privacy == READONLY_FIELD))) result.append(ArrayWriteMethod(self, name, public = (self.privacy == PUBLIC_FIELD))) return result
def getPredefs() : result = "" for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : result += "class " + the_class.__name__ + ";\n" result += "\n" return result
def getParentDestroyCode(self) : result = "" ## Дополнительный код удаления родителя имеет смысл возвращать только для каскадных отношений ## и если дочерние объекты не являются базовым типом if self.cascade and not util.inherits(self.child, dbtypes.BaseType) : return " cascadeRemove{0}{1}();\n".format(self.name, self.child_name) return result
def getChildDestroyCode(self) : if self.child_only or not util.inherits(self.child, dbtypes.ClassType) : return "" if self.static : return " {0}::remove{1}{2}(*this);\n".format(self.parent_name, self.name, self.child_name) else : return " if ( get{1}{0}().isValid() )\n get{1}{0}().remove{1}{2}(*this);\n".format(self.parent_name, self.name, self.child_name)
def prepareClassUserMethods(the_class) : method_names = sorted([key for key in the_class.__dict__.keys() if util.inherits(the_class.__dict__[key], methods.Method)]) for method_name in method_names : method = the_class.__dict__[method_name] method.name = method_name method.user = True method.inline = False the_class.methods.append(method)
def getBody(self) : result = "{\n" result += " for(StdUInt i = 0; i < count; i++)\n" if util.inherits(self.field.data_type, dbtypes.ClassType) : result += " dest[i] = {0}(geti{1}(i));\n".format(util.getPublicTypeName(self.field.data_type), self.field_name) else : result += " dest[i] = geti{1}(i);\n".format(self.field.data_type.__name__, self.field_name) result += "}\n" return result
def getResetRoutine(self, name) : if self.static or self.array or util.inherits(self.data_type, dbtypes.UnionType) : return "" result = "" if self.initial_value == None : result += " set" + name + "({0});\n".format(util.getDefaultValue(self.data_type)) else : result += " set" + name + "({0});\n".format(self.initial_value) return result
def registerType(_type): if not util.inherits(_type, dbtypes.DataType): print "unable to register unknown type" return False for tp in dbtypes.HSDB.types: if tp.__name__ == _type.__name__: print "Type '{0}' already registered".format(_type.__name__) return False dbtypes.HSDB.types.append(_type) return True
def getBody(self) : result = "{\n" result += self.getLogArrayRecordRoutine("index", "1") if util.inherits(self.field.data_type, dbtypes.ClassType) : result += " get{0}Ptr()[index] = value.id();\n".format(self.field_name) else : result += " get{0}Ptr()[index] = value;\n".format(self.field_name) result += self.getLogArrayRecordRoutine("index", "1") result += "}\n" return result
def getBody(self) : result = "{\n" result += self.getLogArrayRecordRoutine("0", "count") result += " for (StdUInt i = 0; i < count; i++)\n" if util.inherits(self.field.data_type, dbtypes.ClassType) : result += " get{0}Ptr()[i] = source[i].id();\n".format(self.field_name) else : result += " get{0}Ptr()[i] = source[i];\n".format(self.field_name) result += self.getLogArrayRecordRoutine("0", "count") result += "}\n" return result
def generateUserFile(header_name, filename) : f = open(filename, "w") if f == None : print "Unable to open file " + filename sys.exit(1) code = header_block code += "#include <{0}.h>\n\n".format(header_name) for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : code += "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n" code += gen_defs.getUserMethodsBodies(the_class) code += "Void {0}::onDatabaseStart()".format(dbtypes.HSDB.prefix) + " { /** @todo Put Your code here */ }\n" f.write(code) f.close()
def getBody(self) : result = "{\n" result += self.getLogRecordRoutine() if self.static : result += " staticData().{0}.{1} = ".format(self.field_name, self.subfield_name) else : result += " getInstance().{0}.{1} = ".format(self.field_name, self.subfield_name) if util.inherits(self.subfield.data_type, dbtypes.ClassType) : result += "value.id();\n" else : result += "value;\n" result += self.getLogRecordRoutine() result += "}\n" return result
def getSaveDatabaseFunction() : result = "\ninline Bool saveDatabase(yamm::HSDBFile * file)\n{\n" ## Сохранение системных данных if dbtypes.HSDB.logger_enabled : result += " if (!metadata::saveDatabase(file)) return false;\n" elif dbtypes.HSDB.use_disk : result += " if(!yamm::saveDatabase(file)) return false;\n" ## Сохранение классов for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) and the_class.save_data : result += " if (!{0}::save(file)) return false;\n".format(the_class.__name__) result += " if(!symManager.serialize(file)) return false;\n" result += " return true;\n" result += "}\n" return result
def getArgs(self) : if isinstance(self.args, str) : return self.args result = "" arg_names = sorted(self.args.keys()) for arg_name in arg_names : arg_type = self.args[arg_name] if isinstance(arg_type, str) : result += "{0} {1}, ".format(arg_type, arg_name) elif util.inherits(arg_type, dbtypes.ClassType) : if arg_name[0] == '*' : result += "{0} {1}, ".format(util.getPublicTypeName(arg_type, out_of_ns = False), arg_name) else : result += "const {0} & {1}, ".format(util.getPublicTypeName(arg_type, out_of_ns = False), arg_name) else : result += "{0} {1}, ".format(util.getPublicTypeName(arg_type, out_of_ns = False), arg_name) if len(result) != 0 and result[-2] == ',' : result = result[:-2] return result
def generateCommonSourceFile(header_name, filename) : f = open(filename, "w") if f == None : print "Unable to open file " + filename sys.exit(1) code = header_block code += "#include <{0}.h>\n\n".format(header_name) if dbtypes.HSDB.use_disk : code += "yamm::SymManager<yamm::DSKVector> {0}::symManager;\n".format(dbtypes.HSDB.prefix) else : code += "yamm::SymManager<yamm::RAMVector> {0}::symManager;\n".format(dbtypes.HSDB.prefix) if dbtypes.HSDB.logger_enabled : code += "metadata::Module {0}::Module;\n".format(dbtypes.HSDB.prefix) for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : code += "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n" code += generateClassSourceFileCode(the_class) f.write(code) f.close()
def getLoadDatabaseFunction() : result = "\ninline Bool loadDatabase(yamm::HSDBFile * file)\n{\n" ## Загрузка системных данных if dbtypes.HSDB.logger_enabled : result += " if (!metadata::loadDatabase(file)) return false;\n" #result += " file_pos += file->read(reinterpret_cast<Char*>(&Module), sizeof(metadata::Module));\n" elif dbtypes.HSDB.use_disk : result += " if (!yamm::loadDatabase(file)) return false;\n" ## Загрузка классов for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : if the_class.save_data : result += " if (!{0}::load(file)) return false;\n".format(the_class.__name__) else : result += " {0}::init();\n".format(the_class.__name__) if dbtypes.HSDB.logger_enabled : result += " {0}::registerClass();\n".format(the_class.__name__) result += " if(!symManager.deserialize(file)) return false;\n" result += " return true;\n" result += "}\n" return result
def generateCommonHeaderFile(filename) : f = open(filename, "w") if f == None : print "Unable to open file " + filename sys.exit(1) code = header_block code += "#ifndef {0}_h\n".format(dbtypes.HSDB.prefix) code += "#define {0}_h\n".format(dbtypes.HSDB.prefix) code += "#include <yamutils.h>\n" if dbtypes.HSDB.use_disk : code += "#include <yampointer.h>\n" if dbtypes.HSDB.logger_enabled : code += "#include <metasystem.h>\n" code += "\nnamespace " + dbtypes.HSDB.prefix code += "{\n\n" code += "const StdUInt DEFAULT_HASH_TABLE_SIZE = 15541;\n" if dbtypes.HSDB.logger_enabled : code += "extern metadata::Module Module;\n" code += getTypedefs() code += getPredefs() code += getEnums() code += getUnions() code += getStructures() code += getClasses() code += getSymManager() code += getStartDatabaseFunction() code += getSaveDatabaseFunction() code += getLoadDatabaseFunction() #code += getStopDatabaseFunction() code += "\n}\n\n" for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : code += gen_defs.getHeaderFileMethodsBodies(the_class) code += "#endif // {0}_h\n".format(dbtypes.HSDB.prefix) f.write(code) f.close()
def getStartDatabaseFunction() : result = "Void onDatabaseStart();\n\n" if dbtypes.HSDB.use_disk : result += "inline Void startDatabase(StdUInt max_memory, char * const filename)\n{\n" else : result += "inline Void startDatabase()\n{\n" if dbtypes.HSDB.logger_enabled : result += " metadata::initMetasystem(max_memory, filename);\n" result += " {0}::Module = metadata::registerModule(\"{0}\");\n".format(dbtypes.HSDB.prefix) elif dbtypes.HSDB.use_disk : result += " yamm::startDatabase(max_memory, filename);\n" ## Инициализация и регистрация классов for the_class in dbtypes.HSDB.types : if util.inherits(the_class, dbtypes.ClassType) : result += " {0}::init();\n".format(the_class.__name__) if dbtypes.HSDB.logger_enabled : result += " {0}::registerClass();\n".format(the_class.__name__) ## Инициализация символьного менеджера result += " symManager.Init();\n" if dbtypes.HSDB.logger_enabled : result += " metadata::enableLog();\n" result += " onDatabaseStart();\n" result += "}\n\n" return result
def getTypedefs() : result = "" for typedef in dbtypes.HSDB.types : if util.inherits(typedef, dbtypes.TypedefType) : result += gen_defs.getTypedefDefinition(typedef) return result
def getUnions() : result = "" for union in dbtypes.HSDB.types : if util.inherits(union, dbtypes.UnionType) : result += gen_defs.getUnionDefinition(union) return result
def getStructures() : result = "" for struct in dbtypes.HSDB.types : if util.inherits(struct, dbtypes.StructType) : result += gen_defs.getStructDefinition(struct) return result
def prepareClass(the_class) : ## Создание пустого списка для методов класса the_class.methods = [] prepareClassUserMethods(the_class) if dbtypes.HSDB.logger_enabled : the_class.methods.append(RegisterMethod()) the_class.methods.append(InitMethod(the_class)) #the_class.methods.append(toStringMethod(the_class)) if the_class.save_data : the_class.methods.append(SaveMethod(the_class)) the_class.methods.append(LoadMethod(the_class)) the_class.methods.append(OnSaveHandler(the_class)) the_class.methods.append(OnLoadHandler(the_class)) ## Создание системных полей для несинглтон класса (создается счетчик выделенных объектов Used и флаг существования объекта Exists) if not the_class.singleton : the_class.methods.append(ResetMethod(the_class)) rel_stack.createStack(the_class, the_class, "Free", False, True, False, True) the_class.__dict__["Used"] = fields.Field(field_type = dbtypes.StdUInt, static = True, privacy = fields.PRIVATE_FIELD, initial_value = 0, comment = "The number of instances that was already been created at least one") the_class.__dict__["Exists"] = fields.Field(field_type = dbtypes.Bool, privacy = fields.PRIVATE_FIELD, initial_value = "true", comment = "Flag indicating object is exists now (was created but not destroyed yet)") the_class.__field_names__ = [name for name in sorted(the_class.__dict__.keys()) if util.inherits(the_class.__dict__[name], fields.Field)] ## Cоздание дополнительных полей для динамических массивов for name in the_class.__field_names__ : field = the_class.__dict__[name] privacy_val = fields.READONLY_FIELD if field.privacy == fields.PRIVATE_FIELD : privacy_val = fields.PRIVATE_FIELD if field.array and field.array_size == 0 : the_class.__dict__[name + "Len"] = fields.Field(field_type = dbtypes.StdUInt, privacy = privacy_val, initial_value = 0, comment = "The length of '{0}' array field of a given class instance".format(name)) if not the_class.singleton : the_class.__dict__[name + "Used"] = fields.Field(field_type = dbtypes.StdUInt, static = True, privacy = fields.PRIVATE_FIELD, initial_value = 0, comment = "The number of buffer elements that is already in use by class objects") the_class.__dict__[name + "Index"] = fields.Field(field_type = dbtypes.StdUInt, privacy = fields.PRIVATE_FIELD, initial_value = "Null", comment = "Index of the first array field element in array buffer of given class instance") rel_list.createList(the_class, the_class, "__" + name + "Block" + "__", static = True, public = False) the_class.__field_names__ = [name for name in sorted(the_class.__dict__.keys()) if util.inherits(the_class.__dict__[name], fields.Field)] ## Создание методов для несинглтон классов if not the_class.singleton : the_class.methods.append(CreateClassMethod(the_class)) the_class.methods.append(ExtendedCreateClassMethod(the_class)) the_class.methods.append(DestroyMethod(the_class)) the_class.methods.append(OnCreateHandler(the_class)) the_class.methods.append(OnDestroyHandler(the_class)) if the_class.singleton : for name in the_class.__field_names__ : the_class.__dict__[name].static = True ## Экстракция пользовательских методов, объявленных в описании БД for name in the_class.__field_names__ : the_class.methods = the_class.methods + the_class.__dict__[name].getMethods(name, the_class.memory_type) ## Экстракция методов из отношений класса for rel in dbtypes.HSDB.relationships : if rel.parent == the_class : the_class.methods = the_class.methods + rel.getParentMethods() if rel.child == the_class : the_class.methods = the_class.methods + rel.getChildMethods() for method in the_class.methods : method.parent = the_class if the_class.singleton : method.static = True
def getEnums() : result = "" for enum in dbtypes.HSDB.types : if util.inherits(enum, dbtypes.EnumType) : result += gen_defs.getEnumDefinition(enum) return result
def getBody(self) : if util.inherits(self.field.data_type, dbtypes.ClassType) : return "{ return " + "{0}(get{1}Ptr()[index]);".format(util.getPublicTypeName(self.field.data_type), self.field_name) + " }" return "{ return " + "get{0}Ptr()[index];".format(self.field_name) + " }"
def createVector(parent, child, name = "", cascade = False, child_only = False, public = True, static = False) : if not util.inherits(child, dbtypes.ClassType) : print "Unable to create rel_base whith child that is not a Class" return dbtypes.HSDB.relationships.append(VectorRelationship(parent, child, name, cascade, child_only, public, static))