collection_registry.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "collection_registry.hpp"
  2. #include <ctime>
  3. namespace svapi {
  4. CollectionMeta CollectionMeta::fromJson(const nlohmann::json& j) {
  5. CollectionMeta m;
  6. m.name = j.value("name", "");
  7. m.kind = j.value("kind", "json");
  8. m.vectorDimension = j.value("vector_dimension", 0u);
  9. m.embeddingModel = j.value("embedding_model", "");
  10. m.createdAt = j.value("created_at", 0ull);
  11. return m;
  12. }
  13. nlohmann::json CollectionMeta::toJson() const {
  14. return {{"name", name}, {"kind", kind}, {"vector_dimension", vectorDimension},
  15. {"embedding_model", embeddingModel}, {"created_at", createdAt}};
  16. }
  17. CollectionRegistry::CollectionRegistry(DbGateway& db) : db_(db) {}
  18. void CollectionRegistry::ensure(const std::string& project) {
  19. const std::string c = coll(project);
  20. if (!db_.client().getCollectionInfo(c).has_value())
  21. db_.client().createCollection(c, 0, false, 0, 0);
  22. }
  23. void CollectionRegistry::bootstrap(const std::vector<std::string>& projects) {
  24. for (const auto& p : projects) ensure(p);
  25. }
  26. bool CollectionRegistry::add(const std::string& project, const CollectionMeta& meta) {
  27. CollectionMeta m = meta;
  28. if (m.createdAt == 0) m.createdAt = static_cast<uint64_t>(std::time(nullptr));
  29. auto [id, isNew] = db_.client().upsert(coll(project), m.toJson(), m.name);
  30. return !id.empty();
  31. }
  32. std::optional<CollectionMeta> CollectionRegistry::get(const std::string& project,
  33. const std::string& name) {
  34. if (auto doc = db_.client().get(coll(project), name))
  35. return CollectionMeta::fromJson(*doc);
  36. return std::nullopt;
  37. }
  38. std::vector<CollectionMeta> CollectionRegistry::list(const std::string& project) {
  39. std::vector<CollectionMeta> out;
  40. smartbotic::database::Client::QueryOptions opts;
  41. opts.limit = 100000;
  42. for (const auto& doc : db_.client().find(coll(project), opts))
  43. out.push_back(CollectionMeta::fromJson(doc));
  44. return out;
  45. }
  46. bool CollectionRegistry::remove(const std::string& project, const std::string& name) {
  47. return db_.client().remove(coll(project), name);
  48. }
  49. } // namespace svapi