💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add metadata support for client-server databases, closes #532
davidmezzettia1b92e0a33b2
diff --git a/setup.py b/setup.pyindex 7763805f..654a9cc9 100644--- a/setup.py+++ b/setup.py@@ -37,7 +37,7 @@ extras["cloud"] = ["apache-libcloud>=3.3.1"]extras["console"] = ["rich>=12.0.1"]-extras["database"] = ["duckdb>=0.7.1", "pillow>=7.1.2"]+extras["database"] = ["duckdb>=0.7.1", "pillow>=7.1.2", "sqlalchemy>=2.0.20"]extras["graph"] = ["networkx>=2.6.3", "python-louvain>=0.16"]diff --git a/src/python/txtai/database/__init__.py b/src/python/txtai/database/__init__.pyindex 4655c4f4..c564b2dd 100644--- a/src/python/txtai/database/__init__.py+++ b/src/python/txtai/database/__init__.py@@ -3,9 +3,12 @@ Database imports"""from .base import Database+from .client import Clientfrom .duckdb import DuckDB+from .embedded import Embeddedfrom .encoder import *from .factory import DatabaseFactory-from .filedb import FileDB+from .rdbms import RDBMS+from .schema import *from .sqlite import SQLitefrom .sql import *diff --git a/src/python/txtai/database/client.py b/src/python/txtai/database/client.pynew file mode 100644index 00000000..771f8aa4--- /dev/null+++ b/src/python/txtai/database/client.py@@ -0,0 +1,176 @@+"""+Client module+"""++import time++# Conditional import+try:+ from sqlalchemy import StaticPool, Text, cast, create_engine, insert, text as textsql+ from sqlalchemy.orm import Session, aliased++ from .schema import Base, Batch, Document, Object, Section, SectionBase, Score++ ORM = True+except ImportError:+ ORM = False++from .rdbms import RDBMS+++class Client(RDBMS):+ """+ Database client instance. This class connects to an external database using SQLAlchemy. It supports any database+ that is supported by SQLAlchemy (PostgreSQL, MariaDB, etc) and has JSON support.+ """++ def __init__(self, config):+ """+ Creates a new Database.++ Args:+ config: database configuration parameters+ """++ super().__init__(config)++ if not ORM:+ raise ImportError('SQLAlchemy is not available - install "database" extra to enable')++ def reindexstart(self):+ # Working table name+ name = f"rebuild{round(time.time() * 1000)}"++ # Create working table metadata+ type("Rebuild", (SectionBase,), {"__tablename__": name})+ Base.metadata.tables[name].create(self.connection.bind)++ return name++ def reindexend(self, name):+ # Remove table object from metadata+ Base.metadata.remove(Base.metadata.tables[name])++ def jsonprefix(self):+ # JSON column prefix+ return "cast("++ def jsoncolumn(self, name):+ # Alias documents table+ d = aliased(Document, name="d")++ # Build JSON column expression for column+ return str(cast(d.data[name], Text).compile(dialect=self.connection.bind.dialect, compile_kwargs={"literal_binds": True}))++ def createtables(self):+ # Create tables+ Base.metadata.create_all(self.connection.bind)++ # Clear existing data - table schema is created upon connecting to database+ for table in ["sections", "documents", "objects"]:+ self.cursor.execute(f"DELETE FROM {table}")++ def finalize(self):+ # Flush cached objects+ self.connection.flush()++ def insertdocument(self, uid, data, tags, entry):+ self.connection.add(Document(id=uid, data=data, tags=tags, entry=entry))++ def insertobject(self, uid, data, tags, entry):+ self.connection.add(Object(id=uid, object=data, tags=tags, entry=entry))++ def insertsection(self, index, uid, text, tags, entry):+ # Save text section+ self.connection.add(Section(indexid=index, id=uid, text=text, tags=tags, entry=entry))++ def createbatch(self):+ # Create temporary batch table, if necessary+ Base.metadata.tables["batch"].create(self.connection.bind, checkfirst=True)++ def insertbatch(self, indexids, ids, batch):+ if indexids:+ self.connection.execute(insert(Batch), [{"indexid": i, "batch": batch} for i in indexids])+ if ids:+ self.connection.execute(insert(Batch), [{"id": str(uid), "batch": batch} for uid in ids])++ def createscores(self):+ # Create temporary scores table, if necessary+ Base.metadata.tables["scores"].create(self.connection.bind, checkfirst=True)++ def insertscores(self, scores):+ # Average scores by id+ self.connection.execute(insert(Score), [{"indexid": i, "score": sum(s) / len(s)} for i, s in scores.items()])++ def connect(self, path=None):+ # Create engine using database URL+ engine = create_engine(self.config["content"], poolclass=StaticPool, echo=False)++ # Create database session+ return Session(engine)++ def getcursor(self):+ return Cursor(self.connection)++ def rows(self):+ return self.cursor++ def addfunctions(self):+ return+++class Cursor:+ """+ Implements basic compatability with the Python DB-API.+ """++ def __init__(self, connection):+ self.connection = connection+ self.result = None++ def __iter__(self):+ return self.result++ def execute(self, statement):+ """+ Executes statement.++ Args:+ statement: statement to execute+ """++ if isinstance(statement, str):+ statement = textsql(statement)++ self.result = self.connection.execute(statement)++ def fetchall(self):+ """+ Fetches all rows from the current result.++ Returns:+ all rows from current result+ """++ return self.result.all() if self.result else None++ def fetchone(self):+ """+ Fetches first row from current result.++ Returns:+ first row from current result+ """++ return self.result.first() if self.result else None++ @property+ def description(self):+ """+ Returns columns for current result.++ Returns:+ list of columns+ """++ return [(key,) for key in self.result.keys()] if self.result else Nonediff --git a/src/python/txtai/database/duckdb.py b/src/python/txtai/database/duckdb.pyindex 1f66ff1c..22f00c91 100644--- a/src/python/txtai/database/duckdb.py+++ b/src/python/txtai/database/duckdb.py@@ -14,10 +14,11 @@ try:except ImportError:DUCKDB = False-from .filedb import FileDB+from .embedded import Embedded+from .schema import Statement-class DuckDB(FileDB):+class DuckDB(Embedded):"""Database instance backed by DuckDB."""@@ -32,21 +33,19 @@ class DuckDB(FileDB):if not DUCKDB:raise ImportError('DuckDB is not available - install "database" extra to enable')- def insertdocument(self, uid, document, tags, entry):- if document:- # Delete existing document- self.cursor.execute(DuckDB.DELETE_DOCUMENT, [uid])+ def insertdocument(self, uid, data, tags, entry):+ # Delete existing document+ self.cursor.execute(DuckDB.DELETE_DOCUMENT, [uid])# Call parent logic- return super().insertdocument(uid, document, tags, entry)+ super().insertdocument(uid, data, tags, entry)- def insertobject(self, uid, obj, tags, entry):- if self.encoder:- # Delete existing object- self.cursor.execute(DuckDB.DELETE_OBJECT, [uid])+ def insertobject(self, uid, data, tags, entry):+ # Delete existing object+ self.cursor.execute(DuckDB.DELETE_OBJECT, [uid])# Call parent logic- super().insertobject(uid, obj, tags, entry)+ super().insertobject(uid, data, tags, entry)def connect(self, path=":memory:"):# Create connection and start a transaction@@ -89,7 +88,7 @@ class DuckDB(FileDB):self.connection.execute(f"COPY {table} TO '{directory}/{table}.parquet' (FORMAT parquet)")# Create initial schema- for schema in [FileDB.CREATE_DOCUMENTS, FileDB.CREATE_OBJECTS, FileDB.CREATE_SECTIONS % "sections"]:+ for schema in [Statement.CREATE_DOCUMENTS, Statement.CREATE_OBJECTS, Statement.CREATE_SECTIONS % "sections"]:connection.execute(schema)# Import tables into new schema@@ -97,7 +96,7 @@ class DuckDB(FileDB):connection.execute(f"COPY {table} FROM '{directory}/{table}.parquet' (FORMAT parquet)")# Create indexes and sync data to database file- connection.execute(FileDB.CREATE_SECTIONS_INDEX)+ connection.execute(Statement.CREATE_SECTIONS_INDEX)connection.execute("CHECKPOINT")# Start transactiondiff --git a/src/python/txtai/database/embedded.py b/src/python/txtai/database/embedded.pynew file mode 100644index 00000000..467b1334--- /dev/null+++ b/src/python/txtai/database/embedded.py@@ -0,0 +1,80 @@+"""+Embedded module+"""++from .rdbms import RDBMS+++class Embedded(RDBMS):+ """+ Base class for embedded relational databases. An embedded relational database stores all content in a local file.+ """++ def __init__(self, config):+ """+ Creates a new Database.++ Args:+ config: database configuration parameters+ """++ super().__init__(config)++ # Path to database file+ self.path = None++ def load(self, path):+ # Call parent logic+ super().load(path)++ # Store path reference+ self.path = path++ def save(self, path):+ # Temporary database+ if not self.path:+ # Save temporary database+ self.connection.commit()++ # Copy data from current to new+ connection = self.copy(path)++ # Close temporary database+ self.connection.close()++ # Point connection to new connection+ self.connection = connection+ self.cursor = self.getcursor()+ self.path = path++ # Register custom functions+ self.addfunctions()++ # Paths are equal, commit changes+ elif self.path == path:+ self.connection.commit()++ # New path is different from current path, copy data and continue using current connection+ else:+ self.copy(path).close()++ def jsonprefix(self):+ # Return json column prefix+ return "json_extract(data"++ def jsoncolumn(self, name):+ # Generate json column using json_extract function+ return f"json_extract(data, '$.{name}')"++ def copy(self, path):+ """+ Copies the current database into path.++ Args:+ path: path to write database++ Returns:+ new connection with data copied over+ """++ raise NotImplementedErrordiff --git a/src/python/txtai/database/factory.py b/src/python/txtai/database/factory.pyindex ae680829..0b9732f0 100644--- a/src/python/txtai/database/factory.py+++ b/src/python/txtai/database/factory.py@@ -2,8 +2,11 @@Factory module"""+from urllib.parse import urlparse+from ..util import Resolver+from .client import Clientfrom .duckdb import DuckDBfrom .sqlite import SQLite@@ -41,7 +44,14 @@ class DatabaseFactory:elif content == "sqlite":database = SQLite(config)elif content:- database = DatabaseFactory.resolve(content, config)+ # Check if content is a URL+ url = urlparse(content)+ if url.scheme:+ # Connect to database server URL+ database = Client(config)+ else:+ # Resolve custom database if content is not a URL+ database = DatabaseFactory.resolve(content, config)# Store config backconfig["content"] = contentdiff --git a/src/python/txtai/database/filedb.py b/src/python/txtai/database/rdbms.pysimilarity index 59%rename from src/python/txtai/database/filedb.pyrename to src/python/txtai/database/rdbms.pyindex 7f4fa636..7f310415 100644--- a/src/python/txtai/database/filedb.py+++ b/src/python/txtai/database/rdbms.py@@ -1,104 +1,21 @@"""-FileDB module+RDBMS module"""import datetimeimport jsonfrom .base import Database+from .schema import Statement# pylint: disable=R0904-class FileDB(Database):+class RDBMS(Database):"""- Base file database class.+ Base relational database class. A relational database uses SQL to insert, update, delete and select from a+ database instance."""- # Temporary table for working with id batches- CREATE_BATCH = """- CREATE TEMP TABLE IF NOT EXISTS batch (- indexid INTEGER,- id TEXT,- batch INTEGER- )- """-- DELETE_BATCH = "DELETE FROM batch"- INSERT_BATCH_INDEXID = "INSERT INTO batch (indexid, batch) VALUES (?, ?)"- INSERT_BATCH_ID = "INSERT INTO batch (id, batch) VALUES (?, ?)"-- # Temporary table for joining similarity scores- CREATE_SCORES = """- CREATE TEMP TABLE IF NOT EXISTS scores (- indexid INTEGER PRIMARY KEY,- score REAL- )- """-- DELETE_SCORES = "DELETE FROM scores"- INSERT_SCORE = "INSERT INTO scores VALUES (?, ?)"-- # Documents - stores full content- CREATE_DOCUMENTS = """- CREATE TABLE IF NOT EXISTS documents (- id TEXT PRIMARY KEY,- data JSON,- tags TEXT,- entry DATETIME- )- """-- INSERT_DOCUMENT = "INSERT OR REPLACE INTO documents VALUES (?, ?, ?, ?)"- DELETE_DOCUMENTS = "DELETE FROM documents WHERE id IN (SELECT id FROM batch)"-- # Objects - stores binary content- CREATE_OBJECTS = """- CREATE TABLE IF NOT EXISTS objects (- id TEXT PRIMARY KEY,- object BLOB,- tags TEXT,- entry DATETIME- )- """-- INSERT_OBJECT = "INSERT OR REPLACE INTO objects VALUES (?, ?, ?, ?)"- DELETE_OBJECTS = "DELETE FROM objects WHERE id IN (SELECT id FROM batch)"-- # Sections - stores section text- CREATE_SECTIONS = """- CREATE TABLE IF NOT EXISTS %s (- indexid INTEGER PRIMARY KEY,- id TEXT,- text TEXT,- tags TEXT,- entry DATETIME- )- """-- CREATE_SECTIONS_INDEX = "CREATE INDEX section_id ON sections(id)"- INSERT_SECTION = "INSERT INTO sections VALUES (?, ?, ?, ?, ?)"- DELETE_SECTIONS = "DELETE FROM sections WHERE id IN (SELECT id FROM batch)"- COPY_SECTIONS = (- "INSERT INTO %s SELECT (select count(*) - 1 from sections s1 where s.indexid >= s1.indexid) indexid, "- + "s.id, %s AS text, s.tags, s.entry FROM sections s LEFT JOIN documents d ON s.id = d.id ORDER BY indexid"- )- STREAM_SECTIONS = "SELECT s.id, s.text, object, s.tags FROM %s s LEFT JOIN objects o ON s.id = o.id ORDER BY indexid"- DROP_SECTIONS = "DROP TABLE sections"- RENAME_SECTIONS = "ALTER TABLE %s RENAME TO sections"-- # Queries- SELECT_IDS = "SELECT indexid, id FROM sections WHERE id in (SELECT id FROM batch)"- COUNT_IDS = "SELECT count(indexid) FROM sections"-- # Partial sql clauses- TABLE_CLAUSE = (- "SELECT %s FROM sections s "- + "LEFT JOIN documents d ON s.id = d.id "- + "LEFT JOIN objects o ON s.id = o.id "- + "LEFT JOIN scores sc ON s.indexid = sc.indexid"- )- IDS_CLAUSE = "s.indexid in (SELECT indexid from batch WHERE batch=%s)"-def __init__(self, config):"""Creates a new Database.@@ -109,16 +26,14 @@ class FileDB(Database):super().__init__(config)- # Database connection handle+ # Database connectionself.connection = Noneself.cursor = None- self.path = Nonedef load(self, path):# Load an existing database. Thread locking must be handled externally.self.connection = self.connect(path)self.cursor = self.getcursor()- self.path = path# Register custom functionsself.addfunctions()@@ -134,7 +49,7 @@ class FileDB(Database):for uid, document, tags in documents:if isinstance(document, dict):# Insert document and use return value for sections table- document = self.insertdocument(uid, document, tags, entry)+ document = self.loaddocument(uid, document, tags, entry)if document is not None:if isinstance(document, list):@@ -142,43 +57,43 @@ class FileDB(Database):document = " ".join(document)elif not isinstance(document, str):# If object support is enabled, save object- self.insertobject(uid, document, tags, entry)+ self.loadobject(uid, document, tags, entry)# Clear section text for objects, even when objects aren't inserteddocument = None# Save text section- self.insertsection(index, uid, document, tags, entry)+ self.loadsection(index, uid, document, tags, entry)index += 1+ # Post processing logic+ self.finalize()+def delete(self, ids):if self.connection:# Batch idsself.batch(ids=ids)# Delete all documents, objects and sections by id- self.cursor.execute(FileDB.DELETE_DOCUMENTS)- self.cursor.execute(FileDB.DELETE_OBJECTS)- self.cursor.execute(FileDB.DELETE_SECTIONS)+ self.cursor.execute(Statement.DELETE_DOCUMENTS)+ self.cursor.execute(Statement.DELETE_OBJECTS)+ self.cursor.execute(Statement.DELETE_SECTIONS)def reindex(self, columns=None):if self.connection:- # Working table name- name = "rebuild"-# Resolve and build column strings if providedselect = "text"if columns:select = "|| ' ' ||".join([self.resolve(c) for c in columns])- # Create new table to hold reordered sections- self.cursor.execute(FileDB.CREATE_SECTIONS % name)+ # Initialize reindex operation+ name = self.reindexstart()# Copy data over- self.cursor.execute(FileDB.COPY_SECTIONS % (name, select))+ self.cursor.execute(Statement.COPY_SECTIONS % (name, select))# Stream new results- self.cursor.execute(FileDB.STREAM_SECTIONS % name)+ self.cursor.execute(Statement.STREAM_SECTIONS % name)for uid, text, obj, tags in self.rows():if not text and self.encoder and obj:yield (uid, self.encoder.decode(obj), tags)@@ -186,38 +101,16 @@ class FileDB(Database):yield (uid, text, tags)# Swap as new table- self.cursor.execute(FileDB.DROP_SECTIONS)- self.cursor.execute(FileDB.RENAME_SECTIONS % name)- self.cursor.execute(FileDB.CREATE_SECTIONS_INDEX)-- def save(self, path):- # Temporary database- if not self.path:- # Save temporary database- self.connection.commit()+ self.cursor.execute(Statement.DROP_SECTIONS)+ self.cursor.execute(Statement.RENAME_SECTIONS % name)- # Copy data from current to new- connection = self.copy(path)+ # Finish reindex operation+ self.reindexend(name)- # Close temporary database- self.connection.close()-- # Point connection to new connection- self.connection = connection- self.cursor = self.getcursor()- self.path = path-- # Register custom functions- self.addfunctions()-- # Paths are equal, commit changes- elif self.path == path:+ def save(self, path):+ if self.connection:self.connection.commit()- # New path is different from current path, copy data and continue using current connection- else:- self.copy(path).close()-def close(self):# Close connectionif self.connection:@@ -226,13 +119,13 @@ class FileDB(Database):def ids(self, ids):# Batch ids and run queryself.batch(ids=ids)- self.cursor.execute(FileDB.SELECT_IDS)+ self.cursor.execute(Statement.SELECT_IDS)# Format and return resultsreturn self.cursor.fetchall()def count(self):- self.cursor.execute(FileDB.COUNT_IDS)+ self.cursor.execute(Statement.COUNT_IDS)return self.cursor.fetchone()[0]def resolve(self, name, alias=None):@@ -254,7 +147,7 @@ class FileDB(Database):return self.expressions[name]# Name is already resolved, skip- if name.startswith("json_extract(data") or any(f"s.{s}" == name for s in sections):+ if name.startswith(self.jsonprefix()) or any(f"s.{s}" == name for s in sections):return name# Standard columns - need prefixes@@ -266,7 +159,7 @@ class FileDB(Database):return name# Other columns come from documents.data JSON- return f"json_extract(data, '$.{name}')"+ return self.jsoncolumn(name)def embed(self, similarity, batch):# Load similarity results id batch@@ -277,7 +170,7 @@ class FileDB(Database):self.scores(similarity)# Return ids clause placeholder- return FileDB.IDS_CLAUSE % batch+ return Statement.IDS_CLAUSE % batch# pylint: disable=R0912def query(self, query, limit):@@ -289,7 +182,7 @@ class FileDB(Database):similarity = query.get("similar")# Build query text- query = FileDB.TABLE_CLAUSE % select+ query = Statement.TABLE_CLAUSE % selectif where is not None:query += f" WHERE {where}"if groupby is not None:@@ -330,7 +223,7 @@ class FileDB(Database):for x, column in enumerate(columns):if column not in result or result[column] is None:# Decode object- if self.encoder and column == "object":+ if self.encoder and column == self.object:result[column] = self.encoder.decode(row[x])else:result[column] = row[x]@@ -352,19 +245,31 @@ class FileDB(Database):# Register custom functionsself.addfunctions()- # Create initial schema and indices- self.cursor.execute(FileDB.CREATE_DOCUMENTS)- self.cursor.execute(FileDB.CREATE_OBJECTS)- self.cursor.execute(FileDB.CREATE_SECTIONS % "sections")- self.cursor.execute(FileDB.CREATE_SECTIONS_INDEX)+ # Create initial table schema+ self.createtables()- def insertdocument(self, uid, document, tags, entry):+ def createtables(self):"""- Inserts a document.+ Creates the initial table schema.+ """++ self.cursor.execute(Statement.CREATE_DOCUMENTS)+ self.cursor.execute(Statement.CREATE_OBJECTS)+ self.cursor.execute(Statement.CREATE_SECTIONS % "sections")+ self.cursor.execute(Statement.CREATE_SECTIONS_INDEX)++ def finalize(self):+ """+ Post processing logic run after inserting a batch of documents. Default method does nothing.+ """++ def loaddocument(self, uid, document, tags, entry):+ """+ Applies pre-processing logic and inserts a document.Args:uid: unique id- document: input document+ document: input document dictionarytags: document tagsentry: generated entry date@@ -380,18 +285,31 @@ class FileDB(Database):# Insert document as JSONif document:- self.cursor.execute(FileDB.INSERT_DOCUMENT, [uid, json.dumps(document, allow_nan=False), tags, entry])+ self.insertdocument(uid, json.dumps(document, allow_nan=False), tags, entry)- # If text and object are both available, insert object as it won't otherwise be used+ # If text and object are both available, load object as it won't otherwise be usedif self.text in document and obj:- self.insertobject(uid, obj, tags, entry)+ self.loadobject(uid, obj, tags, entry)# Return value to use for section - use text if available otherwise use objectreturn document[self.text] if self.text in document else obj- def insertobject(self, uid, obj, tags, entry):+ def insertdocument(self, uid, data, tags, entry):"""- Inserts an object.+ Inserts a document.++ Args:+ uid: unique id+ data: document data+ tags: document tags+ entry: generated entry date+ """++ self.cursor.execute(Statement.INSERT_DOCUMENT, [uid, data, tags, entry])++ def loadobject(self, uid, obj, tags, entry):+ """+ Applies pre-preprocessing logic and inserts an object.Args:uid: unique id@@ -402,7 +320,34 @@ class FileDB(Database):# If object support is enabled, save objectif self.encoder:- self.cursor.execute(FileDB.INSERT_OBJECT, [uid, self.encoder.encode(obj), tags, entry])+ self.insertobject(uid, self.encoder.encode(obj), tags, entry)++ def insertobject(self, uid, data, tags, entry):+ """+ Inserts an object.++ Args:+ uid: unique id+ data: encoded data+ tags: object tags+ entry: generated entry date+ """++ self.cursor.execute(Statement.INSERT_OBJECT, [uid, data, tags, entry])++ def loadsection(self, index, uid, text, tags, entry):+ """+ Applies pre-processing logic and inserts a section.++ Args:+ index: index id+ uid: unique id+ text: section text+ tags: section tags+ entry: generated entry date+ """++ self.insertsection(index, uid, text, tags, entry)def insertsection(self, index, uid, text, tags, entry):"""@@ -417,17 +362,34 @@ class FileDB(Database):"""# Save text section- self.cursor.execute(FileDB.INSERT_SECTION, [index, uid, text, tags, entry])+ self.cursor.execute(Statement.INSERT_SECTION, [index, uid, text, tags, entry])- def defaults(self):+ def reindexstart(self):"""- Returns a list of default columns when there is no select clause.+ Starts a reindex operation.Returns:- list of default columns+ temporary working table name"""- return "s.id, text, score"+ # Working table name+ name = "rebuild"++ # Create new table to hold reordered sections+ self.cursor.execute(Statement.CREATE_SECTIONS % name)++ return name++ # pylint: disable=W0613+ def reindexend(self, name):+ """+ Ends a reindex operation.++ Args:+ name: working table name+ """++ self.cursor.execute(Statement.CREATE_SECTIONS_INDEX)def batch(self, indexids=None, ids=None, batch=None):"""@@ -439,17 +401,33 @@ class FileDB(Database):batch: batch index, used when statement has multiple subselects"""- # Create or Replace temporary batch table- self.cursor.execute(FileDB.CREATE_BATCH)+ # Create or replace batch table+ self.createbatch()# Delete batch when batch id is empty or for batch 0if not batch:- self.cursor.execute(FileDB.DELETE_BATCH)+ self.cursor.execute(Statement.DELETE_BATCH)++ # Add batch+ self.insertbatch(indexids, ids, batch)++ def createbatch(self):+ """+ Creates temporary batch table.+ """++ # Create or Replace temporary batch table+ self.cursor.execute(Statement.CREATE_BATCH)++ def insertbatch(self, indexids, ids, batch):+ """+ Inserts batch of ids.+ """if indexids:- self.cursor.executemany(FileDB.INSERT_BATCH_INDEXID, [(i, batch) for i in indexids])+ self.cursor.executemany(Statement.INSERT_BATCH_INDEXID, [(i, batch) for i in indexids])if ids:- self.cursor.executemany(FileDB.INSERT_BATCH_ID, [(str(uid), batch) for uid in ids])+ self.cursor.executemany(Statement.INSERT_BATCH_ID, [(str(uid), batch) for uid in ids])def scores(self, similarity):"""@@ -459,11 +437,11 @@ class FileDB(Database):similarity: similarity results as [(indexid, score)]"""- # Create or Replace temporary scores table- self.cursor.execute(FileDB.CREATE_SCORES)+ # Create or replace scores table+ self.createscores()# Delete scores- self.cursor.execute(FileDB.DELETE_SCORES)+ self.cursor.execute(Statement.DELETE_SCORES)if similarity:# Average scores per id, needed for multiple similar() clauses@@ -474,8 +452,37 @@ class FileDB(Database):scores[i] = []scores[i].append(score)- # Average scores by id- self.cursor.executemany(FileDB.INSERT_SCORE, [(i, sum(s) / len(s)) for i, s in scores.items()])+ # Add scores+ self.insertscores(scores)++ def createscores(self):+ """+ Creates temporary scores table.+ """++ # Create or Replace temporary scores table+ self.cursor.execute(Statement.CREATE_SCORES)++ def insertscores(self, scores):+ """+ Inserts a batch of scores.++ Args:+ scores: scores to add+ """++ # Average scores by id+ self.cursor.executemany(Statement.INSERT_SCORE, [(i, sum(s) / len(s)) for i, s in scores.items()])++ def defaults(self):+ """+ Returns a list of default columns when there is no select clause.++ Returns:+ list of default columns+ """++ return "s.id, text, score"def connect(self, path=None):"""@@ -500,35 +507,45 @@ class FileDB(Database):raise NotImplementedError- def rows(self):+ def jsonprefix(self):"""- Returns current cursor row iterator for last executed query.-- Args:- cursor: cursor+ Returns json column prefix to test for.Returns:- iterable collection of rows+ dynamic column prefix"""raise NotImplementedError- def addfunctions(self):+ def jsoncolumn(self, name):"""- Adds custom functions in current connection.+ Builds a json extract column expression for name.++ Args:+ name: column name++ Returns:+ dynamic column expression"""raise NotImplementedError- def copy(self, path):+ def rows(self):"""- Copies the current database into path.+ Returns current cursor row iterator for last executed query.Args:- path: path to write database+ cursor: cursorReturns:- new connection with data copied over+ iterable collection of rows+ """++ raise NotImplementedError++ def addfunctions(self):+ """+ Adds custom functions in current connection."""raise NotImplementedErrordiff --git a/src/python/txtai/database/schema/__init__.py b/src/python/txtai/database/schema/__init__.pynew file mode 100644index 00000000..c91db785--- /dev/null+++ b/src/python/txtai/database/schema/__init__.py@@ -0,0 +1,6 @@+"""+Schema imports+"""++from .orm import *+from .statement import Statementdiff --git a/src/python/txtai/database/schema/orm.py b/src/python/txtai/database/schema/orm.pynew file mode 100644index 00000000..03edb6b4--- /dev/null+++ b/src/python/txtai/database/schema/orm.py@@ -0,0 +1,99 @@+"""+ORM Module+"""++# Conditional import+try:+ from sqlalchemy import Column, DateTime, Float, JSON, Integer, LargeBinary, String, Text+ from sqlalchemy.orm import DeclarativeBase++ ORM = True+except ImportError:+ ORM = False+++# Standard database schema using object relational mapping (ORM).+if ORM:++ def idcolumn():+ """+ Creates an id column. This method creates an unbounded text field for platforms that support it.++ Returns:+ id column definition+ """++ return String(512).with_variant(Text(), "sqlite", "postgresql")++ class Base(DeclarativeBase):+ """+ Base mapping.+ """++ class Batch(Base):+ """+ Batch temporary table mapping.+ """++ __tablename__ = "batch"+ __table_args__ = {"prefixes": ["TEMPORARY"]}++ autoid = Column(Integer, primary_key=True, autoincrement=True)+ indexid = Column(Integer)+ id = Column(idcolumn())+ batch = Column(Integer)++ class Score(Base):+ """+ Scores temporary table mapping.+ """++ __tablename__ = "scores"+ __table_args__ = {"prefixes": ["TEMPORARY"]}++ indexid = Column(Integer, primary_key=True, autoincrement=False)+ score = Column(Float)++ class Document(Base):+ """+ Documents table mapping.+ """++ __tablename__ = "documents"++ id = Column(idcolumn(), primary_key=True)+ data = Column(JSON)+ tags = Column(Text)+ entry = Column(DateTime)++ class Object(Base):+ """+ Objects table mapping.+ """++ __tablename__ = "objects"++ id = Column(idcolumn(), primary_key=True)+ object = Column(LargeBinary)+ tags = Column(Text)+ entry = Column(DateTime)++ class SectionBase(Base):+ """+ Generic sections table mapping. Allows multiple section table names for reindexing.+ """++ __abstract__ = True++ indexid = Column(Integer, primary_key=True, autoincrement=False)+ id = Column(idcolumn(), index=True)+ text = Column(Text)+ tags = Column(Text)+ entry = Column(DateTime)++ class Section(SectionBase):+ """+ Section table mapping.+ """++ __tablename__ = "sections"diff --git a/src/python/txtai/database/schema/statement.py b/src/python/txtai/database/schema/statement.pynew file mode 100644index 00000000..b949c6ff--- /dev/null+++ b/src/python/txtai/database/schema/statement.py@@ -0,0 +1,94 @@+"""+Statement module+"""+++class Statement:+ """+ Standard database schema SQL statements.+ """++ # Temporary table for working with id batches+ CREATE_BATCH = """+ CREATE TEMP TABLE IF NOT EXISTS batch (+ indexid INTEGER,+ id TEXT,+ batch INTEGER+ )+ """++ DELETE_BATCH = "DELETE FROM batch"+ INSERT_BATCH_INDEXID = "INSERT INTO batch (indexid, batch) VALUES (?, ?)"+ INSERT_BATCH_ID = "INSERT INTO batch (id, batch) VALUES (?, ?)"++ # Temporary table for joining similarity scores+ CREATE_SCORES = """+ CREATE TEMP TABLE IF NOT EXISTS scores (+ indexid INTEGER PRIMARY KEY,+ score REAL+ )+ """++ DELETE_SCORES = "DELETE FROM scores"+ INSERT_SCORE = "INSERT INTO scores VALUES (?, ?)"++ # Documents - stores full content+ CREATE_DOCUMENTS = """+ CREATE TABLE IF NOT EXISTS documents (+ id TEXT PRIMARY KEY,+ data JSON,+ tags TEXT,+ entry DATETIME+ )+ """++ INSERT_DOCUMENT = "INSERT OR REPLACE INTO documents VALUES (?, ?, ?, ?)"+ DELETE_DOCUMENTS = "DELETE FROM documents WHERE id IN (SELECT id FROM batch)"++ # Objects - stores binary content+ CREATE_OBJECTS = """+ CREATE TABLE IF NOT EXISTS objects (+ id TEXT PRIMARY KEY,+ object BLOB,+ tags TEXT,+ entry DATETIME+ )+ """++ INSERT_OBJECT = "INSERT OR REPLACE INTO objects VALUES (?, ?, ?, ?)"+ DELETE_OBJECTS = "DELETE FROM objects WHERE id IN (SELECT id FROM batch)"++ # Sections - stores section text+ CREATE_SECTIONS = """+ CREATE TABLE IF NOT EXISTS %s (+ indexid INTEGER PRIMARY KEY,+ id TEXT,+ text TEXT,+ tags TEXT,+ entry DATETIME+ )+ """++ CREATE_SECTIONS_INDEX = "CREATE INDEX section_id ON sections(id)"+ INSERT_SECTION = "INSERT INTO sections VALUES (?, ?, ?, ?, ?)"+ DELETE_SECTIONS = "DELETE FROM sections WHERE id IN (SELECT id FROM batch)"+ COPY_SECTIONS = (+ "INSERT INTO %s SELECT (select count(*) - 1 from sections s1 where s.indexid >= s1.indexid) indexid, "+ + "s.id, %s AS text, s.tags, s.entry FROM sections s LEFT JOIN documents d ON s.id = d.id ORDER BY indexid"+ )+ STREAM_SECTIONS = "SELECT s.id, s.text, object, s.tags FROM %s s LEFT JOIN objects o ON s.id = o.id ORDER BY indexid"+ DROP_SECTIONS = "DROP TABLE sections"+ RENAME_SECTIONS = "ALTER TABLE %s RENAME TO sections"++ # Queries+ SELECT_IDS = "SELECT indexid, id FROM sections WHERE id in (SELECT id FROM batch)"+ COUNT_IDS = "SELECT count(indexid) FROM sections"++ # Partial sql clauses+ TABLE_CLAUSE = (+ "SELECT %s FROM sections s "+ + "LEFT JOIN documents d ON s.id = d.id "+ + "LEFT JOIN objects o ON s.id = o.id "+ + "LEFT JOIN scores sc ON s.indexid = sc.indexid"+ )+ IDS_CLAUSE = "s.indexid in (SELECT indexid from batch WHERE batch=%s)"diff --git a/src/python/txtai/database/sqlite.py b/src/python/txtai/database/sqlite.pyindex 5fe300ae..5325f880 100644--- a/src/python/txtai/database/sqlite.py+++ b/src/python/txtai/database/sqlite.py@@ -5,10 +5,10 @@ SQLite moduleimport osimport sqlite3-from .filedb import FileDB+from .embedded import Embedded-class SQLite(FileDB):+class SQLite(Embedded):"""Database instance backed by SQLite."""diff --git a/test/python/testdatabase/testclient.py b/test/python/testdatabase/testclient.pynew file mode 100644index 00000000..2ffae3ab--- /dev/null+++ b/test/python/testdatabase/testclient.py@@ -0,0 +1,59 @@+"""+Client module tests+"""++import os+import time+import tempfile++from txtai.embeddings import Embeddings++from .testrdbms import Common+++# pylint: disable=R0904+class TestClient(Common.TestRDBMS):+ """+ Embeddings with content stored in a client RDBMS.+ """++ @classmethod+ def setUpClass(cls):+ """+ Initialize test data.+ """++ cls.data = [+ "US tops 5 million confirmed virus cases",+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",+ "The National Park Service warns against sacrificing slower friends in a bear attack",+ "Maine man wins $1M from $25 lottery ticket",+ "Make huge profits without work, earn up to $100,000 a day",+ ]++ # Content backend+ cls.backend = None++ # Create embeddings model, backed by sentence-transformers & transformers+ cls.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})++ @classmethod+ def tearDownClass(cls):+ """+ Cleanup data.+ """++ if cls.embeddings:+ cls.embeddings.close()++ def setUp(self):+ """+ Set unique database path for each test.+ """++ # Generate unique database path and set on embeddings+ path = os.path.join(tempfile.gettempdir(), f"{int(time.time() * 1000)}.sqlite")+ self.backend = f"sqlite:///{path}"++ self.embeddings.config["content"] = self.backenddiff --git a/test/python/testdatabase/testduckdb.py b/test/python/testdatabase/testduckdb.pyindex a12e5af5..7aa17a70 100644--- a/test/python/testdatabase/testduckdb.py+++ b/test/python/testdatabase/testduckdb.py@@ -7,11 +7,11 @@ import unittestfrom txtai.embeddings import Embeddings-from .testfiledb import Common+from .testrdbms import Common# pylint: disable=R0904-class TestDuckDB(Common.TestFileDB):+class TestDuckDB(Common.TestRDBMS):"""Embeddings with content stored in DuckDB."""diff --git a/test/python/testdatabase/testfiledb.py b/test/python/testdatabase/testrdbms.pysimilarity index 93%rename from test/python/testdatabase/testfiledb.pyrename to test/python/testdatabase/testrdbms.pyindex b3c7ff98..d7a1b882 100644--- a/test/python/testdatabase/testfiledb.py+++ b/test/python/testdatabase/testrdbms.py@@ -9,7 +9,7 @@ import tempfileimport unittestfrom txtai.embeddings import Embeddings, IndexNotFoundError-from txtai.database import FileDB, SQLError+from txtai.database import Embedded, RDBMS, SQLErrorclass Common:@@ -18,7 +18,7 @@ class Common:"""# pylint: disable=R0904- class TestFileDB(unittest.TestCase):+ class TestRDBMS(unittest.TestCase):"""Embeddings with content stored in a file database tests."""@@ -39,7 +39,7 @@ class Common:]# Content backend- cls.backend = "sqlite"+ cls.backend = None# Create embeddings model, backed by sentence-transformers & transformerscls.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": cls.backend})@@ -63,7 +63,7 @@ class Common:self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.{extension}")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.{extension}")self.embeddings.save(index)self.embeddings.load(index)@@ -83,14 +83,14 @@ class Common:"""# Default sequence id- embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2", content=True)+ embeddings = Embeddings(path="sentence-transformers/nli-mpnet-base-v2", content=self.backend)embeddings.index(self.data)result = embeddings.search("feel good story", 1)[0]self.assertEqual(result["text"], self.data[4])# UUID- embeddings = Embeddings(autoid="uuid4", path="sentence-transformers/nli-mpnet-base-v2", content=True)+ embeddings.config["autoid"] = "uuid4"embeddings.index(self.data)result = embeddings.search(self.data[4], 1)[0]@@ -126,7 +126,7 @@ class Common:embeddings.index([(0, "Close test", None)])# Save index- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.close")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.close")embeddings.save(index)# Close index@@ -172,6 +172,8 @@ class Common:Test empty index"""+ print(self.__class__.__name__)+# Test search against empty indexembeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": self.backend})self.assertEqual(embeddings.search("test"), [])@@ -227,27 +229,6 @@ class Common:self.assertEqual(self.embeddings.explain("select * from txtai limit 1")[0]["id"], "0")- def testFunction(self):- """- Test custom functions- """-- embeddings = Embeddings(- {- "path": "sentence-transformers/nli-mpnet-base-v2",- "content": self.backend,- "functions": [{"name": "length", "function": "testdatabase.testsqlite.length"}],- }- )-- # Create an index for the list of text- embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])-- # Search for best match- result = embeddings.search("select length(text) length from txtai where id = 0", 1)[0]-- self.assertEqual(result["length"], 39)-def testGenerator(self):"""Test index with a generator@@ -274,7 +255,7 @@ class Common:data = [(uid, text, None) for uid, text in enumerate(self.data)]# Index data with sparse + dense vectors.- embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "hybrid": True, "content": True})+ embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "hybrid": True, "content": self.backend})embeddings.index(data)# Run search@@ -282,7 +263,7 @@ class Common:self.assertEqual(result["text"], data[4][1])# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.hybrid")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.hybrid")# Test load/saveembeddings.save(index)@@ -392,7 +373,7 @@ class Common:embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.json")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.json")embeddings.save(index)@@ -412,7 +393,7 @@ class Common:data = [(uid, text, None) for uid, text in enumerate(self.data)]# Index data with sparse + dense vectors- embeddings = Embeddings({"keyword": True, "content": True})+ embeddings = Embeddings({"keyword": True, "content": self.backend})embeddings.index(data)# Run search@@ -423,7 +404,7 @@ class Common:self.assertEqual(embeddings.count(), len(data))# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.keyword")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.keyword")# Test load/saveembeddings.save(index)@@ -470,14 +451,14 @@ class Common:self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])# Save original index- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.insert")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.insert")self.embeddings.save(index)# Modify indexself.embeddings.upsert([(0, "Looking out into the dreadful abyss", None)])# Save to a different location- indexupdate = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.update")+ indexupdate = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.update")self.embeddings.save(indexupdate)# Save to same location@@ -503,7 +484,7 @@ class Common:# Disable top-level indexingembeddings = Embeddings({- "content": True,+ "content": self.backend,"defaults": False,})@@ -517,14 +498,33 @@ class Common:Test exceptions for non-implemented methods"""- db = FileDB({})+ db = RDBMS({})self.assertRaises(NotImplementedError, db.connect, None)self.assertRaises(NotImplementedError, db.getcursor)+ self.assertRaises(NotImplementedError, db.jsonprefix)+ self.assertRaises(NotImplementedError, db.jsoncolumn, None)self.assertRaises(NotImplementedError, db.rows)self.assertRaises(NotImplementedError, db.addfunctions)++ db = Embedded({})self.assertRaises(NotImplementedError, db.copy, None)+ def testObject(self):+ """+ Test object field+ """++ # Encode object+ embeddings = Embeddings({"defaults": False, "content": self.backend, "objects": True})+ embeddings.index([{"object": "binary data".encode("utf-8")}])++ # embeddings.save("/tmp/a")++ # Decode and test extracted object+ obj = embeddings.search("select object from txtai where id = 0")[0]["object"]+ self.assertEqual(str(obj.getvalue(), "utf-8"), "binary data")+def testQueryModel(self):"""Test index@@ -570,7 +570,7 @@ class Common:self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}")self.embeddings.save(index)self.embeddings.load(index)@@ -647,7 +647,9 @@ class Common:data = [(uid, text, None) for uid, text in enumerate(self.data)]# Disable top-level indexing and create subindex- embeddings = Embeddings({"content": True, "defaults": False, "indexes": {"index1": {"path": "sentence-transformers/nli-mpnet-base-v2"}}})+ embeddings = Embeddings(+ {"content": self.backend, "defaults": False, "indexes": {"index1": {"path": "sentence-transformers/nli-mpnet-base-v2"}}}+ )embeddings.index(data)# Run search@@ -663,7 +665,7 @@ class Common:embeddings.search("select id, text, score from txtai where similar('feel good story', 'notindex')")# Generate temp file path- index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.backend}.subindex")+ index = os.path.join(tempfile.gettempdir(), f"embeddings.{self.category()}.subindex")# Test load/saveembeddings.save(index)@@ -750,3 +752,13 @@ class Common:self.assertEqual(result["text"], data[0][1])finally:del self.embeddings.config["batch"]++ def category(self):+ """+ Content backend category.++ Returns:+ category+ """++ return self.__class__.__name__.lower().replace("test", "")diff --git a/test/python/testdatabase/testsqlite.py b/test/python/testdatabase/testsqlite.pyindex edd3a6f4..1d00cf19 100644--- a/test/python/testdatabase/testsqlite.py+++ b/test/python/testdatabase/testsqlite.py@@ -4,11 +4,11 @@ SQLite module testsfrom txtai.embeddings import Embeddings-from .testfiledb import Common+from .testrdbms import Common# pylint: disable=R0904-class TestSQLite(Common.TestFileDB):+class TestSQLite(Common.TestRDBMS):"""Embeddings with content stored in SQLite tests."""@@ -43,6 +43,27 @@ class TestSQLite(Common.TestFileDB):if cls.embeddings:cls.embeddings.close()+ def testFunction(self):+ """+ Test custom functions+ """++ embeddings = Embeddings(+ {+ "path": "sentence-transformers/nli-mpnet-base-v2",+ "content": self.backend,+ "functions": [{"name": "length", "function": "testdatabase.testsqlite.length"}],+ }+ )++ # Create an index for the list of text+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ # Search for best match+ result = embeddings.search("select length(text) length from txtai where id = 0", 1)[0]++ self.assertEqual(result["length"], 39)+def length(text):"""diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 6d91d888..50e53b24 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -40,6 +40,7 @@ class TestOptional(unittest.TestCase):"sklearn.decomposition","sentence_transformers","soundfile",+ "sqlalchemy","tika","ttstokenizer","xmltodict",@@ -107,8 +108,10 @@ class TestOptional(unittest.TestCase):Test missing database dependencies"""- from txtai.database import DuckDB- from txtai.database import ImageEncoder+ from txtai.database import Client, DuckDB, ImageEncoder++ with self.assertRaises(ImportError):+ Client({})with self.assertRaises(ImportError):DuckDB({})