|
| 1 | +import json |
| 2 | +import uuid |
| 3 | +from typing import List |
| 4 | +import mariadb |
| 5 | +import pandas as pd |
| 6 | +from sentence_transformers import SentenceTransformer |
| 7 | +from mindsql.vectorstores import IVectorstore |
| 8 | + |
| 9 | + |
| 10 | +class MariaDBVectorStore(IVectorstore): |
| 11 | + def __init__(self, config=None): |
| 12 | + if config is None: |
| 13 | + raise ValueError("MariaDB configuration is required") |
| 14 | + |
| 15 | + self.collection_name = config.get('collection_name', 'mindsql_vectors') |
| 16 | + self.connection_params = { |
| 17 | + 'host': config.get('host', 'localhost'), |
| 18 | + 'port': config.get('port', 3306), |
| 19 | + 'user': config.get('user'), |
| 20 | + 'password': config.get('password'), |
| 21 | + } |
| 22 | + |
| 23 | + if 'database' in config and config['database']: |
| 24 | + self.connection_params['database'] = config['database'] |
| 25 | + |
| 26 | + self.embedding_model = SentenceTransformer("all-MiniLM-L6-v2") |
| 27 | + self.dimension = 384 |
| 28 | + self._init_database() |
| 29 | + |
| 30 | + def _init_database(self): |
| 31 | + try: |
| 32 | + conn = mariadb.connect(**self.connection_params) |
| 33 | + cursor = conn.cursor() |
| 34 | + |
| 35 | + cursor.execute(f"DROP TABLE IF EXISTS {self.collection_name}") |
| 36 | + cursor.execute(f"DROP TABLE IF EXISTS {self.collection_name}_sql_pairs") |
| 37 | + |
| 38 | + cursor.execute(f""" |
| 39 | + CREATE TABLE {self.collection_name} ( |
| 40 | + id VARCHAR(36) PRIMARY KEY, |
| 41 | + document TEXT NOT NULL, |
| 42 | + embedding VECTOR({self.dimension}) NOT NULL, |
| 43 | + metadata JSON, |
| 44 | + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, |
| 45 | + INDEX idx_created_at (created_at), |
| 46 | + FULLTEXT(document) |
| 47 | + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
| 48 | + """) |
| 49 | + |
| 50 | + cursor.execute(f""" |
| 51 | + CREATE TABLE {self.collection_name}_sql_pairs ( |
| 52 | + id VARCHAR(36) PRIMARY KEY, |
| 53 | + question TEXT NOT NULL, |
| 54 | + sql_query TEXT NOT NULL, |
| 55 | + embedding VECTOR({self.dimension}) NOT NULL, |
| 56 | + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, |
| 57 | + FULLTEXT(question, sql_query) |
| 58 | + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci |
| 59 | + """) |
| 60 | + |
| 61 | + conn.commit() |
| 62 | + cursor.close() |
| 63 | + conn.close() |
| 64 | + except Exception as e: |
| 65 | + raise RuntimeError(f"Failed to initialize MariaDB vector store: {e}") |
| 66 | + |
| 67 | + def _format_vector_for_insertion(self, embedding_array): |
| 68 | + if len(embedding_array) != self.dimension: |
| 69 | + raise ValueError(f"Expected {self.dimension} dimensions, got {len(embedding_array)}") |
| 70 | + return '[' + ','.join(f'{float(x)}' for x in embedding_array) + ']' |
| 71 | + |
| 72 | + def add_ddl(self, ddl: str): |
| 73 | + embedding = self.embedding_model.encode(ddl).tolist() |
| 74 | + vector_json = self._format_vector_for_insertion(embedding) |
| 75 | + |
| 76 | + conn = mariadb.connect(**self.connection_params) |
| 77 | + cursor = conn.cursor() |
| 78 | + doc_id = str(uuid.uuid4()) |
| 79 | + cursor.execute(f""" |
| 80 | + INSERT INTO {self.collection_name} |
| 81 | + (id, document, embedding, metadata) |
| 82 | + VALUES (?, ?, VEC_FromText(?), ?) |
| 83 | + """, (doc_id, ddl, vector_json, json.dumps({"type": "ddl"}))) |
| 84 | + conn.commit() |
| 85 | + cursor.close() |
| 86 | + conn.close() |
| 87 | + |
| 88 | + def add_question_sql(self, question: str, sql: str): |
| 89 | + embedding = self.embedding_model.encode(question).tolist() |
| 90 | + vector_json = self._format_vector_for_insertion(embedding) |
| 91 | + |
| 92 | + conn = mariadb.connect(**self.connection_params) |
| 93 | + cursor = conn.cursor() |
| 94 | + doc_id = str(uuid.uuid4()) |
| 95 | + cursor.execute(f""" |
| 96 | + INSERT INTO {self.collection_name}_sql_pairs |
| 97 | + (id, question, sql_query, embedding) |
| 98 | + VALUES (?, ?, ?, VEC_FromText(?)) |
| 99 | + """, (doc_id, question, sql, vector_json)) |
| 100 | + conn.commit() |
| 101 | + cursor.close() |
| 102 | + conn.close() |
| 103 | + |
| 104 | + def get_similar_question_sql(self, question: str, n_results: int = 5): |
| 105 | + conn = mariadb.connect(**self.connection_params) |
| 106 | + cursor = conn.cursor() |
| 107 | + cursor.execute(f""" |
| 108 | + SELECT question, sql_query, |
| 109 | + MATCH(question, sql_query) AGAINST (? IN NATURAL LANGUAGE MODE) as text_score |
| 110 | + FROM {self.collection_name}_sql_pairs |
| 111 | + WHERE MATCH(question, sql_query) AGAINST (? IN NATURAL LANGUAGE MODE) |
| 112 | + ORDER BY text_score DESC LIMIT ? |
| 113 | + """, (question, question, n_results)) |
| 114 | + results = cursor.fetchall() |
| 115 | + cursor.close() |
| 116 | + conn.close() |
| 117 | + |
| 118 | + return [{'question': r[0], 'sql': r[1], 'similarity': r[2], 'text_score': r[2]} for r in results] |
| 119 | + |
| 120 | + def retrieve_relevant_ddl(self, question: str, **kwargs) -> list: |
| 121 | + conn = mariadb.connect(**self.connection_params) |
| 122 | + cursor = conn.cursor() |
| 123 | + cursor.execute(f""" |
| 124 | + SELECT document FROM {self.collection_name} |
| 125 | + WHERE JSON_EXTRACT(metadata, '$.type') = 'ddl' |
| 126 | + ORDER BY created_at DESC LIMIT ? |
| 127 | + """, (kwargs.get('n_results', 5),)) |
| 128 | + results = cursor.fetchall() |
| 129 | + cursor.close() |
| 130 | + conn.close() |
| 131 | + return [row[0] for row in results] |
| 132 | + |
| 133 | + def retrieve_relevant_documentation(self, question: str, **kwargs) -> list: |
| 134 | + conn = mariadb.connect(**self.connection_params) |
| 135 | + cursor = conn.cursor() |
| 136 | + cursor.execute(f""" |
| 137 | + SELECT document FROM {self.collection_name} |
| 138 | + WHERE JSON_EXTRACT(metadata, '$.type') = 'documentation' |
| 139 | + ORDER BY created_at DESC LIMIT ? |
| 140 | + """, (kwargs.get('n_results', 5),)) |
| 141 | + results = cursor.fetchall() |
| 142 | + cursor.close() |
| 143 | + conn.close() |
| 144 | + return [row[0] for row in results] |
| 145 | + |
| 146 | + def retrieve_relevant_question_sql(self, question: str, **kwargs) -> list: |
| 147 | + return self.get_similar_question_sql(question, kwargs.get('n_results', 3)) |
| 148 | + |
| 149 | + def index_question_sql(self, question: str, sql: str, **kwargs) -> str: |
| 150 | + try: |
| 151 | + self.add_question_sql(question, sql) |
| 152 | + return "Successfully added question-SQL pair" |
| 153 | + except Exception as e: |
| 154 | + return f"Failed: {e}" |
| 155 | + |
| 156 | + def index_ddl(self, ddl: str, **kwargs) -> str: |
| 157 | + try: |
| 158 | + self.add_ddl(ddl) |
| 159 | + return "Successfully added DDL" |
| 160 | + except Exception as e: |
| 161 | + return f"Failed: {e}" |
| 162 | + |
| 163 | + def index_documentation(self, documentation: str, **kwargs) -> str: |
| 164 | + try: |
| 165 | + embedding = self.embedding_model.encode(documentation).tolist() |
| 166 | + vector_json = self._format_vector_for_insertion(embedding) |
| 167 | + |
| 168 | + conn = mariadb.connect(**self.connection_params) |
| 169 | + cursor = conn.cursor() |
| 170 | + doc_id = str(uuid.uuid4()) |
| 171 | + cursor.execute(f""" |
| 172 | + INSERT INTO {self.collection_name} |
| 173 | + (id, document, embedding, metadata) |
| 174 | + VALUES (?, ?, VEC_FromText(?), ?) |
| 175 | + """, (doc_id, documentation, vector_json, json.dumps({"type": "documentation"}))) |
| 176 | + conn.commit() |
| 177 | + cursor.close() |
| 178 | + conn.close() |
| 179 | + return "Successfully added documentation" |
| 180 | + except Exception as e: |
| 181 | + return f"Failed: {e}" |
| 182 | + |
| 183 | + def fetch_all_vectorstore_data(self, **kwargs) -> pd.DataFrame: |
| 184 | + conn = mariadb.connect(**self.connection_params) |
| 185 | + main_df = pd.read_sql(f"SELECT id, document, created_at FROM {self.collection_name}", conn) |
| 186 | + sql_pairs_df = pd.read_sql(f"SELECT id, question, sql_query, created_at FROM {self.collection_name}_sql_pairs", conn) |
| 187 | + conn.close() |
| 188 | + |
| 189 | + data = [] |
| 190 | + for _, row in main_df.iterrows(): |
| 191 | + data.append({'id': row['id'], 'content': row['document'], 'type': 'document', 'created_at': row['created_at']}) |
| 192 | + for _, row in sql_pairs_df.iterrows(): |
| 193 | + data.append({'id': row['id'], 'content': f"Q: {row['question']} | SQL: {row['sql_query']}", |
| 194 | + 'type': 'question_sql', 'created_at': row['created_at']}) |
| 195 | + return pd.DataFrame(data) |
| 196 | + |
| 197 | + def delete_vectorstore_data(self, item_id: str, **kwargs) -> bool: |
| 198 | + conn = mariadb.connect(**self.connection_params) |
| 199 | + cursor = conn.cursor() |
| 200 | + cursor.execute(f"DELETE FROM {self.collection_name} WHERE id = ?", (item_id,)) |
| 201 | + main_deleted = cursor.rowcount |
| 202 | + cursor.execute(f"DELETE FROM {self.collection_name}_sql_pairs WHERE id = ?", (item_id,)) |
| 203 | + pairs_deleted = cursor.rowcount |
| 204 | + conn.commit() |
| 205 | + cursor.close() |
| 206 | + conn.close() |
| 207 | + return (main_deleted + pairs_deleted) > 0 |
| 208 | + |
| 209 | + def add_documents(self, documents: List[str]): |
| 210 | + for doc in documents: |
| 211 | + self.add_ddl(doc) |
0 commit comments