/ src / python / txtai / database / factory.py
factory.py
 1  """
 2  Factory module
 3  """
 4  
 5  from urllib.parse import urlparse
 6  
 7  from ..util import Resolver
 8  
 9  from .client import Client
10  from .duckdb import DuckDB
11  from .sqlite import SQLite
12  
13  
14  class DatabaseFactory:
15      """
16      Methods to create document databases.
17      """
18  
19      @staticmethod
20      def create(config):
21          """
22          Create a Database.
23  
24          Args:
25              config: database configuration parameters
26  
27          Returns:
28              Database
29          """
30  
31          # Database instance
32          database = None
33  
34          # Enables document database
35          content = config.get("content")
36  
37          # Standardize content name
38          if content is True:
39              content = "sqlite"
40  
41          # Create document database instance
42          if content == "duckdb":
43              database = DuckDB(config)
44          elif content == "sqlite":
45              database = SQLite(config)
46          elif content:
47              # Check if content is a URL
48              url = urlparse(content)
49              if content == "client" or url.scheme:
50                  # Connect to database server URL
51                  database = Client(config)
52              else:
53                  # Resolve custom database if content is not a URL
54                  database = DatabaseFactory.resolve(content, config)
55  
56          # Store config back
57          config["content"] = content
58  
59          return database
60  
61      @staticmethod
62      def resolve(backend, config):
63          """
64          Attempt to resolve a custom backend.
65  
66          Args:
67              backend: backend class
68              config: index configuration parameters
69  
70          Returns:
71              Database
72          """
73  
74          try:
75              return Resolver()(backend)(config)
76          except Exception as e:
77              raise ImportError(f"Unable to resolve database backend: '{backend}'") from e