databases.service.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {
  2. CreateDatabaseRequest,
  3. ListDatabasesRequest,
  4. DropDatabasesRequest,
  5. } from '@zilliz/milvus2-sdk-node';
  6. import { throwErrorFromSDK } from '../utils/Error';
  7. import { clientCache } from '../app';
  8. import { DatabaseObject } from '../types';
  9. import { SimpleQueue } from '../utils';
  10. export class DatabasesService {
  11. async createDatabase(clientId: string, data: CreateDatabaseRequest) {
  12. const { milvusClient } = clientCache.get(clientId);
  13. const res = await milvusClient.createDatabase(data);
  14. throwErrorFromSDK(res);
  15. return res;
  16. }
  17. async listDatabase(
  18. clientId: string,
  19. data?: ListDatabasesRequest
  20. ): Promise<DatabaseObject[]> {
  21. const { milvusClient, database } = clientCache.get(clientId);
  22. const res = await milvusClient.listDatabases(data);
  23. // test if the user has permission to access the database, loop through all databases
  24. // and check if the user has permission to access the database
  25. const availableDatabases: DatabaseObject[] = [];
  26. for (let i = 0; i < res.db_names.length; i++) {
  27. try {
  28. await milvusClient.use({ db_name: res.db_names[i] });
  29. await milvusClient.listDatabases(data);
  30. const collections = await milvusClient.showCollections();
  31. availableDatabases.push({
  32. name: res.db_names[i],
  33. collections: collections.data.map(c => c.name),
  34. createdTime: (res as any).created_timestamp[i] || -1,
  35. });
  36. } catch (e) {
  37. // ignore
  38. }
  39. }
  40. // recover current database
  41. await milvusClient.use({ db_name: database });
  42. throwErrorFromSDK(res.status);
  43. return availableDatabases;
  44. }
  45. async dropDatabase(clientId: string, data: DropDatabasesRequest) {
  46. const { milvusClient } = clientCache.get(clientId);
  47. const res = await milvusClient.dropDatabase(data);
  48. throwErrorFromSDK(res);
  49. return res;
  50. }
  51. async use(clientId: string, db_name: string) {
  52. const currentClient = clientCache.get(clientId);
  53. // clear collectionsQueue when switching database
  54. currentClient.collectionsQueue.stop();
  55. currentClient.collectionsQueue = new SimpleQueue<string>();
  56. return await await currentClient.milvusClient.use({ db_name });
  57. }
  58. async hasDatabase(clientId: string, data: string) {
  59. const dbs = await this.listDatabase(clientId);
  60. return dbs.map(d => d.name).indexOf(data) !== -1;
  61. }
  62. }