Info API::CreateTable(SqlCommandCreateTable* command){ IndexManager index_manager; CatalogManager catalog_manager; TableInfo table; std::string table_name = command->table_name(); std::string primary_key = command->primary_key(); std::vector<std::string> unique_keys = command->unique(); int attribute_count = 0; //判断表是否存在 if(catalog_manager.HasTable(table_name)){ std::string error_info; error_info = "Table \"" + table_name + "\" already exists."; return Info(error_info); } else{ table.set_table_name(table_name); //Check primary key. if (primary_key.empty()){ return Info("Must assign a primary key."); } std::map<std::string, std::pair<std::string,int>> attributes = command->attribute(); for (auto it = attributes.begin(); it != attributes.end(); ++it){ AttributeInfo single_attribute_info; single_attribute_info.set_name(it->first); attribute_count++; //判断类型是否有效 if (it->second.first != "char" && it->second.first != "int" && it->second.first != "float"){ std::string error_info; error_info = "The type \"" + it->second.first + "\" of attribute \"" + it->first + "\" is invalid."; return Info(error_info); } else{ single_attribute_info.set_type(it->second.first); //判断char(n) n是否在1~255的范围内 if (0<it->second.second && it->second.second<256){ single_attribute_info.set_length(it->second.second); } else{ std::string error_info; error_info = "The length of char of attribute \"" + it->first + "\" must in range of [1,256]."; return Info(error_info); } } //判断是否是 primary_key if(it->first == primary_key){ single_attribute_info.set_is_primary_key(true); single_attribute_info.add_index("#pri_" + table_name +"_"+it->first); index_manager.CreateIndex(it->second.first,it->second.second,IndexInfo("#pri_" + table_name +"_"+it->first,table_name,it->first)); catalog_manager.RegisterIndex(IndexInfo("#pri_" + table_name +"_"+it->first,table_name,it->first)); } else{ single_attribute_info.set_is_primary_key(false); } //判断是否 unique if (std::find(unique_keys.begin(), unique_keys.end(), it->first) != unique_keys.end()){ single_attribute_info.set_is_unique(true); } else{ single_attribute_info.set_is_unique(false); } table.add_attribute(single_attribute_info); } if(!table.HasAttribute(primary_key)){ std::string error_info; error_info = "assigned primary key \"" + primary_key + "\" is not an attribute of the table."; return Info(error_info); } table.set_attribute_number(attribute_count); table.set_attribute_names_ordered(command->attribute_names_ordered()); if(catalog_manager.RegisterTable(table)){ return Info(); } else{ return Info("Register table failed."); } } }