sqlctx 0.1.2__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlctx
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: A tool for generating LLM context from database tables
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -14,12 +14,15 @@ Requires-Dist: fastmcp
14
14
  Requires-Dist: uvicorn
15
15
  Requires-Dist: toml>=0.10.2
16
16
  Requires-Dist: click>=8.1.8
17
+ Requires-Dist: ruamel-yaml>=0.18.6
17
18
 
18
19
  # sqlctx
19
20
 
20
- `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data professionals as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
21
+ `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data practioners as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
21
22
 
22
- Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx`) such that you can include them with any LLM-enabled editor by mentioning the file for that database table.
23
+ Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx/{schema_name}/{database_name}/{table_name}.yml`) on a per table basis so that you can include them with any LLM-enabled editor by mentioning the file for that database table. Alternatively, there's a `combined.yml` file that includes output from all the columns from all the tables for long-context LLMs.
24
+
25
+ Inside each yml file is metadata like the table, database, & schema names, as well as sample values for each column. If you have set column or table comments using tools like DBT or SQLMesh, they will also be extracted.
23
26
 
24
27
  SQLContext pairs well with:
25
28
 
@@ -42,7 +45,7 @@ Start by installing either `uv` or `pipx` to run python CLIs without installing
42
45
 
43
46
  SQLContext can be run on demand or configured. To configure for a given directory, run the following to generate a config file. You will need your database connection information handy.
44
47
 
45
- ```uvx sqlctx add```
48
+ `uvx sqlctx add` or if you're using pipx `pipx sqlctx add`
46
49
 
47
50
  A config file will be written to `.sqlctx/config.toml`. You can embed environment variables directly in the toml like `${ENV_VAR}` and they will be replaced if the variable has been set.
48
51
 
@@ -1,8 +1,10 @@
1
1
  # sqlctx
2
2
 
3
- `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data professionals as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
3
+ `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data practioners as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
4
4
 
5
- Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx`) such that you can include them with any LLM-enabled editor by mentioning the file for that database table.
5
+ Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx/{schema_name}/{database_name}/{table_name}.yml`) on a per table basis so that you can include them with any LLM-enabled editor by mentioning the file for that database table. Alternatively, there's a `combined.yml` file that includes output from all the columns from all the tables for long-context LLMs.
6
+
7
+ Inside each yml file is metadata like the table, database, & schema names, as well as sample values for each column. If you have set column or table comments using tools like DBT or SQLMesh, they will also be extracted.
6
8
 
7
9
  SQLContext pairs well with:
8
10
 
@@ -25,7 +27,7 @@ Start by installing either `uv` or `pipx` to run python CLIs without installing
25
27
 
26
28
  SQLContext can be run on demand or configured. To configure for a given directory, run the following to generate a config file. You will need your database connection information handy.
27
29
 
28
- ```uvx sqlctx add```
30
+ `uvx sqlctx add` or if you're using pipx `pipx sqlctx add`
29
31
 
30
32
  A config file will be written to `.sqlctx/config.toml`. You can embed environment variables directly in the toml like `${ENV_VAR}` and they will be replaced if the variable has been set.
31
33
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlctx"
3
- version = "0.1.2"
3
+ version = "0.1.4"
4
4
  description = "A tool for generating LLM context from database tables"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -14,6 +14,7 @@ dependencies = [
14
14
  "uvicorn",
15
15
  "toml>=0.10.2",
16
16
  "click>=8.1.8",
17
+ "ruamel-yaml>=0.18.6",
17
18
  ]
18
19
 
19
20
  [project.scripts]
@@ -0,0 +1,30 @@
1
+ import click
2
+ import os
3
+ import shutil
4
+ import toml
5
+ from db_utils import process_database, add_connection
6
+
7
+ __version__ = '1.0.0'
8
+
9
+ @click.group()
10
+ def cli():
11
+ pass
12
+
13
+ @cli.command()
14
+ @click.option('--clean', is_flag=True, help='Clean context directory before processing')
15
+ @click.option('--connection', default=None, help='Database connection string or name of connection from configuration file')
16
+ @click.option('--debug', is_flag=True, help='Enable debug output')
17
+ def generate(clean, connection, debug):
18
+ """Process database and write context files."""
19
+ process_database(connection=connection, clean=clean, debug=debug)
20
+
21
+ @cli.command()
22
+ @click.option('--connection-string', default=None, help='Database connection string')
23
+ def add(connection_string):
24
+ """Add a new database connection."""
25
+ add_connection(connection_string)
26
+
27
+ @cli.command()
28
+ def version():
29
+ """Display the version information."""
30
+ click.echo(f'Version {__version__}')
@@ -0,0 +1,394 @@
1
+ import os
2
+ import duckdb
3
+ from ruamel.yaml import YAML, CommentedMap, CommentedSeq
4
+ import psycopg2
5
+ import mysql.connector
6
+ from urllib.parse import urlparse
7
+ import pandas as pd
8
+ import toml
9
+ import shutil
10
+
11
+ SQLCTX_DIRECTORY = './sqlctx'
12
+ CONFIG_DIRECTORY = './.sqlctx'
13
+
14
+ def load_config():
15
+ config_path = os.path.join(CONFIG_DIRECTORY, 'config.toml')
16
+ if not os.path.exists(config_path):
17
+ # Write default config
18
+ default_config = {
19
+ 'connections': {
20
+ 'default': f'duckdb://{os.path.join(CONFIG_DIRECTORY, "db.db")}'
21
+ }
22
+ }
23
+ os.makedirs(os.path.dirname(config_path), exist_ok=True)
24
+ with open(config_path, 'w') as f:
25
+ toml.dump(default_config, f)
26
+
27
+ # Load the existing config
28
+ with open(config_path, 'r') as f:
29
+ config = toml.load(f)
30
+
31
+ # Replace environment variables in config and throw error if not found
32
+ for conn_name, conn_str in config.get('connections', {}).items():
33
+ expanded_conn_str = os.path.expandvars(conn_str)
34
+ if '$' in expanded_conn_str:
35
+ raise EnvironmentError(f"Environment variable in connection string '{conn_str}' not found for connection '{conn_name}'.")
36
+ config['connections'][conn_name] = expanded_conn_str
37
+
38
+ return config
39
+
40
+ def resolve_connection_string(name_or_string, config):
41
+ connections = config.get('connections', {})
42
+ if name_or_string in connections:
43
+ connection_string = connections[name_or_string]
44
+ else:
45
+ connection_string = name_or_string
46
+
47
+ return connection_string
48
+
49
+ class BaseDatabaseHandler:
50
+ def __init__(self, connection_string, connection_name):
51
+ self.connection_string = connection_string
52
+ self.connection_name = connection_name
53
+ self.con = None
54
+
55
+ def connect(self):
56
+ pass
57
+
58
+ def close(self):
59
+ if self.con:
60
+ self.con.close()
61
+
62
+ def get_database_structure(self):
63
+ pass
64
+
65
+ def sample_table(self, db_name, schema_name, table_name, num_samples=3):
66
+ pass
67
+
68
+ def write_context_files(self, structure, directory=None):
69
+ if directory is None:
70
+ directory = os.path.join(SQLCTX_DIRECTORY, self.connection_name)
71
+ os.makedirs(directory, exist_ok=True)
72
+
73
+ yaml = YAML()
74
+
75
+ # Build overview data
76
+ overview_data = {'databases': []}
77
+ for db_name, schemas_dict in structure.items():
78
+ db_entry = {'name': db_name, 'schemas': []}
79
+ for schema_name, tables_dict in schemas_dict.items():
80
+ schema_entry = {'name': schema_name, 'tables': list(tables_dict.keys())}
81
+ db_entry['schemas'].append(schema_entry)
82
+ overview_data['databases'].append(db_entry)
83
+
84
+ # Write overview.yml if the connection name is not a direct connection string
85
+ if self.connection_name in load_config()['connections']:
86
+ with open(os.path.join(directory, 'overview.yml'), 'w') as f:
87
+ yaml.dump(overview_data, f)
88
+
89
+ combined_data = []
90
+ for db_name, schemas_dict in structure.items():
91
+ for schema_name, tables_dict in schemas_dict.items():
92
+ for table_name, table_info in tables_dict.items():
93
+ columns_info = table_info['columns']
94
+ table_comment = table_info['table_comment']
95
+ # Define the directory path
96
+ path = os.path.join(directory, db_name, schema_name)
97
+ os.makedirs(path, exist_ok=True)
98
+ # Sample the table with 3 records
99
+ sample_df = self.sample_table(db_name, schema_name, table_name, num_samples=3)
100
+ # Prepare sample data
101
+ sample_data_full = sample_df.to_dict(orient='list')
102
+ sample_data = {col: vals[:3] for col, vals in sample_data_full.items()}
103
+
104
+ # Define table data using CommentedMap
105
+ table_data = CommentedMap()
106
+ table_data['database'] = db_name
107
+ table_data['schema'] = schema_name
108
+ table_data['table'] = table_name
109
+
110
+ if table_comment:
111
+ table_data.yaml_add_eol_comment(table_comment, 'table')
112
+
113
+ # Add 'sample data' before 'columns'
114
+ table_data['sample data'] = sample_data
115
+ # Build columns
116
+ columns_seq = CommentedSeq()
117
+ for idx, (col_name, data_type, col_comment) in enumerate(columns_info):
118
+ col_entry = CommentedMap()
119
+ col_entry[col_name] = data_type
120
+ if col_comment:
121
+ col_entry.yaml_add_eol_comment(col_comment, col_name)
122
+ columns_seq.append(col_entry)
123
+
124
+ table_data['columns'] = columns_seq
125
+
126
+ # Write table_data to YAML
127
+ table_context_path = os.path.join(path, f"{table_name}.yml")
128
+ with open(table_context_path, 'w') as f:
129
+ yaml.dump(table_data, f)
130
+
131
+ # Add to combined data
132
+ combined_data.append(table_data)
133
+
134
+ # Write combined content to a file as proper YAML if connection_name is provided
135
+ if self.connection_name in load_config()['connections']:
136
+ combined_path = os.path.join(directory, 'combined.yml')
137
+ with open(combined_path, 'w') as f:
138
+ yaml.dump(combined_data, f)
139
+
140
+ class DuckDBHandler(BaseDatabaseHandler):
141
+ def connect(self):
142
+ parsed = urlparse(self.connection_string)
143
+ db_path = os.path.join(parsed.netloc, parsed.path.lstrip('/')) if parsed.netloc else parsed.path
144
+ db_dir = os.path.dirname(db_path)
145
+ if db_dir and not os.path.exists(db_dir):
146
+ if db_dir.startswith('/'):
147
+ raise ValueError("Cannot create directory at root level")
148
+ os.makedirs(db_dir, exist_ok=True)
149
+ self.con = duckdb.connect(database=db_path, read_only=False)
150
+
151
+ def get_database_structure(self):
152
+ structure = {}
153
+ # Tables query
154
+ tables_query = """
155
+ SELECT
156
+ table_catalog AS database_name,
157
+ table_schema AS schema_name,
158
+ table_name,
159
+ '' AS table_comment -- DuckDB does not support table comments
160
+ FROM information_schema.tables
161
+ WHERE table_type = 'BASE TABLE'
162
+ AND table_schema NOT IN ('information_schema', 'pg_catalog')
163
+ """
164
+ tables = self.con.execute(tables_query).fetchdf().values.tolist()
165
+ # Process tables
166
+ for db_name, schema_name, table_name, table_comment in tables:
167
+ # Initialize nested dictionaries
168
+ structure.setdefault(db_name, {}).setdefault(schema_name, {})
169
+ # Get columns for this table
170
+ columns_query = f"""
171
+ SELECT
172
+ column_name,
173
+ data_type,
174
+ '' AS column_comment -- DuckDB does not support column comments
175
+ FROM information_schema.columns
176
+ WHERE table_catalog = '{db_name}'
177
+ AND table_schema = '{schema_name}'
178
+ AND table_name = '{table_name}'
179
+ """
180
+ columns = self.con.execute(columns_query).fetchdf().values.tolist()
181
+ structure[db_name][schema_name][table_name] = {
182
+ 'columns': columns,
183
+ 'table_comment': table_comment
184
+ }
185
+ return structure
186
+
187
+ def sample_table(self, db_name, schema_name, table_name, num_samples=3):
188
+ qualified_table_name = f'"{db_name}"."{schema_name}"."{table_name}"'
189
+ sample_query = f"SELECT * FROM {qualified_table_name} LIMIT {num_samples}"
190
+ sample_df = self.con.execute(sample_query).df()
191
+ return sample_df
192
+
193
+ class PostgresHandler(BaseDatabaseHandler):
194
+ def connect(self):
195
+ parsed = urlparse(self.connection_string)
196
+ self.con = psycopg2.connect(
197
+ dbname=parsed.path[1:],
198
+ user=parsed.username,
199
+ password=parsed.password,
200
+ host=parsed.hostname,
201
+ port=parsed.port
202
+ )
203
+
204
+ def get_database_structure(self):
205
+ structure = {}
206
+ with self.con.cursor() as cursor:
207
+ # Tables query
208
+ tables_query = """
209
+ SELECT
210
+ n.nspname AS schema_name,
211
+ c.relname AS table_name,
212
+ obj_description(c.oid) AS table_comment
213
+ FROM pg_class c
214
+ JOIN pg_namespace n ON n.oid = c.relnamespace
215
+ WHERE c.relkind = 'r' -- Only tables
216
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
217
+ """
218
+ cursor.execute(tables_query)
219
+ tables = cursor.fetchall()
220
+ for schema_name, table_name, table_comment in tables:
221
+ db_name = self.con.get_dsn_parameters()['dbname']
222
+ # Initialize nested dictionaries
223
+ structure.setdefault(db_name, {}).setdefault(schema_name, {})
224
+ # Get columns for this table
225
+ columns_query = f"""
226
+ SELECT
227
+ a.attname AS column_name,
228
+ pg_catalog.format_type(a.atttypid, a.atttypmod) AS data_type,
229
+ col_description(a.attrelid, a.attnum) AS column_comment
230
+ FROM pg_attribute a
231
+ WHERE a.attrelid = '{schema_name}.{table_name}'::regclass
232
+ AND a.attnum > 0
233
+ AND NOT a.attisdropped
234
+ ORDER BY a.attnum
235
+ """
236
+ cursor.execute(columns_query)
237
+ columns = cursor.fetchall()
238
+ structure[db_name][schema_name][table_name] = {
239
+ 'columns': columns,
240
+ 'table_comment': table_comment
241
+ }
242
+ return structure
243
+
244
+ def sample_table(self, db_name, schema_name, table_name, num_samples=3):
245
+ qualified_table_name = f'"{schema_name}"."{table_name}"'
246
+ sample_query = f'SELECT * FROM {qualified_table_name} LIMIT {num_samples}'
247
+ with self.con.cursor() as cursor:
248
+ cursor.execute(sample_query)
249
+ rows = cursor.fetchall()
250
+ columns = [desc[0] for desc in cursor.description]
251
+ sample_df = pd.DataFrame(rows, columns=columns)
252
+ return sample_df
253
+
254
+ class MySQLHandler(BaseDatabaseHandler):
255
+ def connect(self):
256
+ parsed = urlparse(self.connection_string)
257
+ self.con = mysql.connector.connect(
258
+ user=parsed.username,
259
+ password=parsed.password,
260
+ host=parsed.hostname,
261
+ port=parsed.port,
262
+ database=parsed.path[1:]
263
+ )
264
+
265
+ def get_database_structure(self):
266
+ structure = {}
267
+ cursor = self.con.cursor()
268
+ # Tables query
269
+ tables_query = """
270
+ SELECT
271
+ TABLE_SCHEMA AS schema_name,
272
+ TABLE_NAME AS table_name,
273
+ TABLE_COMMENT AS table_comment
274
+ FROM INFORMATION_SCHEMA.TABLES
275
+ WHERE TABLE_TYPE = 'BASE TABLE'
276
+ AND TABLE_SCHEMA NOT IN ('information_schema', 'performance_schema', 'mysql', 'sys')
277
+ """
278
+ cursor.execute(tables_query)
279
+ tables = cursor.fetchall()
280
+ for schema_name, table_name, table_comment in tables:
281
+ db_name = self.con.database
282
+ # Initialize nested dictionaries
283
+ structure.setdefault(db_name, {}).setdefault(schema_name, {})
284
+ # Get columns for this table
285
+ columns_query = f"""
286
+ SELECT
287
+ COLUMN_NAME AS column_name,
288
+ COLUMN_TYPE AS data_type,
289
+ COLUMN_COMMENT AS column_comment
290
+ FROM INFORMATION_SCHEMA.COLUMNS
291
+ WHERE TABLE_SCHEMA = '{schema_name}'
292
+ AND TABLE_NAME = '{table_name}'
293
+ ORDER BY ORDINAL_POSITION
294
+ """
295
+ cursor.execute(columns_query)
296
+ columns = cursor.fetchall()
297
+ structure[db_name][schema_name][table_name] = {
298
+ 'columns': columns,
299
+ 'table_comment': table_comment
300
+ }
301
+ cursor.close()
302
+ return structure
303
+
304
+ def sample_table(self, db_name, schema_name, table_name, num_samples=3):
305
+ qualified_table_name = f'`{schema_name}`.`{table_name}`'
306
+ sample_query = f"SELECT * FROM {qualified_table_name} LIMIT {num_samples}"
307
+ cursor = self.con.cursor()
308
+ cursor.execute(sample_query)
309
+ rows = cursor.fetchall()
310
+ columns = cursor.column_names
311
+ cursor.close()
312
+ sample_df = pd.DataFrame(rows, columns=columns)
313
+ return sample_df
314
+
315
+ def get_database_handler(name_or_string=None):
316
+ config = load_config()
317
+
318
+ if name_or_string is None:
319
+ name_or_string = 'default'
320
+ connection_string = resolve_connection_string(name_or_string, config)
321
+ parsed = urlparse(connection_string)
322
+ connection_name = name_or_string # Can be a name or connection string
323
+
324
+ if parsed.scheme == 'duckdb':
325
+ handler = DuckDBHandler(connection_string, connection_name)
326
+ elif parsed.scheme in ('postgresql', 'postgres'):
327
+ handler = PostgresHandler(connection_string, connection_name)
328
+ elif parsed.scheme == 'mysql':
329
+ handler = MySQLHandler(connection_string, connection_name)
330
+ else:
331
+ raise ValueError(f"Unsupported database scheme: {parsed.scheme}")
332
+
333
+ handler.connect()
334
+ return handler
335
+
336
+ def process_database(connection=None, clean=False, debug=False):
337
+ handler = get_database_handler(connection)
338
+ directory = os.path.join(SQLCTX_DIRECTORY, handler.connection_name)
339
+
340
+ if debug:
341
+ print(f'Debug: Context directory is set to {directory}')
342
+
343
+ if clean:
344
+ # Clear the target directory
345
+ if os.path.exists(directory):
346
+ if debug:
347
+ print('Debug: Cleaning context directory...')
348
+ shutil.rmtree(directory)
349
+
350
+ if debug:
351
+ print('Debug: Retrieving database structure...')
352
+
353
+ structure = handler.get_database_structure()
354
+
355
+ if debug:
356
+ print('Debug: Writing context files...')
357
+
358
+ handler.write_context_files(structure)
359
+
360
+ if debug:
361
+ print('Debug: Closing database connection...')
362
+
363
+ handler.close()
364
+
365
+ def add_connection(connection_string=None):
366
+ connection_name = input('Please enter a connection name: ')
367
+ if not connection_string:
368
+ connection_string = input(
369
+ 'Please enter a connection string (e.g., "mysql://user:pass@host/db", "postgresql://user:pass@host/db", or "duckdb:///path/to/db"): '
370
+ )
371
+
372
+ try:
373
+ # Test connection
374
+ handler = get_database_handler(connection_string)
375
+ handler.close()
376
+
377
+ # Write to config
378
+ config_path = os.path.join(CONFIG_DIRECTORY, 'config.toml')
379
+ if not os.path.exists(config_path):
380
+ config = {'connections': {}}
381
+ else:
382
+ config = load_config()
383
+ if 'connections' not in config or not isinstance(config['connections'], dict):
384
+ config['connections'] = {}
385
+
386
+ config['connections'][connection_name] = connection_string
387
+
388
+ with open(config_path, 'w') as config_file:
389
+ toml.dump(config, config_file)
390
+
391
+ print('Connection added successfully.')
392
+
393
+ except Exception as e:
394
+ print(f'Failed to connect: {e}')
@@ -5,6 +5,8 @@ import mysql.connector
5
5
  import pandas as pd
6
6
  import yaml
7
7
  import duckdb
8
+ import os
9
+ from db_utils import connect_to_database, load_config
8
10
 
9
11
  # Initialize the FastMCP instance as a global variable
10
12
  mcp = FastMCP("Database Explorer")
@@ -45,9 +47,6 @@ def init_mcp_server(con, combined_yml_path, start=True):
45
47
  if start:
46
48
  mcp.run()
47
49
 
48
- import os
49
- from db_utils import connect_to_database, load_config, get_database_structure, write_context_files
50
-
51
50
  def setup_and_run_mcp_server(connection=None):
52
51
  con, connection_name = connect_to_database(connection)
53
52
  connection_name = connection_name if connection_name in load_config()['connections'] else "default"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlctx
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: A tool for generating LLM context from database tables
5
5
  Requires-Python: >=3.10
6
6
  Description-Content-Type: text/markdown
@@ -14,12 +14,15 @@ Requires-Dist: fastmcp
14
14
  Requires-Dist: uvicorn
15
15
  Requires-Dist: toml>=0.10.2
16
16
  Requires-Dist: click>=8.1.8
17
+ Requires-Dist: ruamel-yaml>=0.18.6
17
18
 
18
19
  # sqlctx
19
20
 
20
- `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data professionals as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
21
+ `sqlctx` or (SQLContext) is a tool for generating LLM context from database tables. It is targeted at data practioners as a force multiplier, codifying the process of providing table schema to LLMs inside of AI-enabled code editors.
21
22
 
22
- Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx`) such that you can include them with any LLM-enabled editor by mentioning the file for that database table.
23
+ Rather than existing as an editor extension, SQLContext outputs context about your database to a directory (`./sqlctx/{schema_name}/{database_name}/{table_name}.yml`) on a per table basis so that you can include them with any LLM-enabled editor by mentioning the file for that database table. Alternatively, there's a `combined.yml` file that includes output from all the columns from all the tables for long-context LLMs.
24
+
25
+ Inside each yml file is metadata like the table, database, & schema names, as well as sample values for each column. If you have set column or table comments using tools like DBT or SQLMesh, they will also be extracted.
23
26
 
24
27
  SQLContext pairs well with:
25
28
 
@@ -42,7 +45,7 @@ Start by installing either `uv` or `pipx` to run python CLIs without installing
42
45
 
43
46
  SQLContext can be run on demand or configured. To configure for a given directory, run the following to generate a config file. You will need your database connection information handy.
44
47
 
45
- ```uvx sqlctx add```
48
+ `uvx sqlctx add` or if you're using pipx `pipx sqlctx add`
46
49
 
47
50
  A config file will be written to `.sqlctx/config.toml`. You can embed environment variables directly in the toml like `${ENV_VAR}` and they will be replaced if the variable has been set.
48
51
 
@@ -7,3 +7,4 @@ fastmcp
7
7
  uvicorn
8
8
  toml>=0.10.2
9
9
  click>=8.1.8
10
+ ruamel-yaml>=0.18.6
@@ -1,91 +0,0 @@
1
- import click
2
- import os
3
- import shutil
4
- import toml
5
- from db_utils import connect_to_database, load_config, get_database_structure, write_context_files
6
-
7
- @click.group()
8
- def cli():
9
- pass
10
-
11
- @cli.command()
12
- @click.option('--clean', is_flag=True, help='Clean context directory before processing')
13
- @click.option('--connection', default=None, help='Database connection string or name of connection from configuration file')
14
- @click.option('--debug', is_flag=True, help='Enable debug output')
15
- def generate(clean, connection, debug):
16
- """Process database and write context files."""
17
- directory = './sqlctx/'
18
- config_path = './.sqlctx/config.toml'
19
-
20
- if debug:
21
- click.echo(f'Debug: Context directory is set to {directory}')
22
-
23
- if not os.path.exists(config_path):
24
- click.echo('No configuration file found. You need to initialize configuration first. Run `add` command to add a connection.')
25
- return
26
-
27
- if clean:
28
- # Clear the target directory
29
- if os.path.exists(directory):
30
- if debug:
31
- click.echo('Debug: Cleaning context directory...')
32
- shutil.rmtree(directory)
33
-
34
- if debug:
35
- click.echo('Debug: Establishing database connection...')
36
-
37
- con, connection_name = connect_to_database(connection)
38
- connection_name = connection_name if connection_name in load_config()['connections'] else "default"
39
-
40
- if debug:
41
- click.echo(f'Debug: Using connection "{connection_name}"')
42
-
43
- if debug:
44
- click.echo('Debug: Retrieving database structure...')
45
-
46
- structure = get_database_structure(con)
47
-
48
- if debug:
49
- click.echo('Debug: Writing context files...')
50
-
51
- write_context_files(con, structure, connection_name)
52
-
53
- if debug:
54
- click.echo('Debug: Closing database connection...')
55
-
56
- con.close()
57
-
58
- @cli.command()
59
- @click.option('--connection-string', default=None, help='Database connection string')
60
- def add(connection_string):
61
- """Add a new database connection."""
62
- connection_name = click.prompt('Please enter a connection name', type=str)
63
- if not connection_string:
64
- connection_string = click.prompt(
65
- 'Please enter a connection string (e.g., "mysql://user:pass@host/db", "postgresql://user:pass@host/db", or "duckdb:///path/to/db")',
66
- type=str
67
- )
68
-
69
- try:
70
- # Test connection
71
- con, _ = connect_to_database(connection_string)
72
- con.close()
73
-
74
- # Write to config
75
- config_path = './.sqlctx/config.toml'
76
- if not os.path.exists(config_path):
77
- config = {'connections': {}}
78
- else:
79
- config = load_config()
80
- if 'connections' not in config or not isinstance(config['connections'], dict):
81
- config['connections'] = {}
82
-
83
- config['connections'][connection_name] = connection_string
84
-
85
- with open(config_path, 'w') as config_file:
86
- toml.dump(config, config_file)
87
-
88
- click.echo('Connection added successfully.')
89
-
90
- except Exception as e:
91
- click.echo(f'Failed to connect: {e}')
@@ -1,215 +0,0 @@
1
- import os
2
- import duckdb
3
- import yaml
4
- import psycopg2
5
- import mysql.connector
6
- from urllib.parse import urlparse
7
- import pandas as pd
8
- import toml
9
-
10
- SQLCTX_DIRECTORY = './sqlctx'
11
- CONFIG_DIRECTORY = './.sqlctx'
12
-
13
- def load_config():
14
- config_path = os.path.join(CONFIG_DIRECTORY, 'config.toml')
15
- if not os.path.exists(config_path):
16
- # Write default config
17
- default_config = {
18
- 'connections': {
19
- 'default': f'duckdb://{os.path.join(CONFIG_DIRECTORY, "db.db")}'
20
- }
21
- }
22
- os.makedirs(os.path.dirname(config_path), exist_ok=True)
23
- with open(config_path, 'w') as f:
24
- toml.dump(default_config, f)
25
-
26
- # Load the existing config
27
- with open(config_path, 'r') as f:
28
- config = toml.load(f)
29
-
30
- # Replace environment variables in config and throw error if not found
31
- for conn_name, conn_str in config.get('connections', {}).items():
32
- expanded_conn_str = os.path.expandvars(conn_str)
33
- if '$' in expanded_conn_str:
34
- raise EnvironmentError(f"Environment variable in connection string '{conn_str}' not found for connection '{conn_name}'.")
35
- config['connections'][conn_name] = expanded_conn_str
36
-
37
- return config
38
-
39
- def resolve_connection_string(name_or_string, config):
40
- connections = config.get('connections', {})
41
- if name_or_string in connections:
42
- connection_string = connections[name_or_string]
43
- else:
44
- connection_string = name_or_string
45
-
46
- return connection_string
47
-
48
- def connect_to_database(name_or_string=None):
49
- config = load_config()
50
-
51
- if name_or_string is None:
52
- name_or_string = 'default'
53
- connection_string = resolve_connection_string(name_or_string, config)
54
- parsed = urlparse(connection_string)
55
- if parsed.scheme == 'duckdb':
56
- db_path = os.path.join(parsed.netloc, parsed.path.lstrip('/')) if parsed.netloc else parsed.path
57
- db_dir = os.path.dirname(db_path)
58
- if db_dir and not os.path.exists(db_dir):
59
- if db_dir.startswith('/'):
60
- raise ValueError("Cannot create directory at root level")
61
- os.makedirs(db_dir, exist_ok=True)
62
- con = duckdb.connect(database=db_path, read_only=False)
63
- return con, name_or_string
64
- elif parsed.scheme in ('postgresql', 'postgres'):
65
- con = psycopg2.connect(
66
- dbname=parsed.path[1:],
67
- user=parsed.username,
68
- password=parsed.password,
69
- host=parsed.hostname,
70
- port=parsed.port
71
- )
72
- return con, name_or_string
73
- elif parsed.scheme == 'mysql':
74
- con = mysql.connector.connect(
75
- user=parsed.username,
76
- password=parsed.password,
77
- host=parsed.hostname,
78
- port=parsed.port,
79
- database=parsed.path[1:]
80
- )
81
- return con, name_or_string
82
- else:
83
- raise ValueError(f"Unsupported database scheme: {parsed.scheme}")
84
-
85
- def get_database_structure(con):
86
- tables_query = """
87
- SELECT
88
- table_catalog AS database_name,
89
- table_schema AS schema_name,
90
- table_name
91
- FROM information_schema.tables
92
- WHERE table_type = 'BASE TABLE'
93
- AND table_schema NOT IN ('information_schema', 'pg_catalog')
94
- """
95
- if isinstance(con, duckdb.DuckDBPyConnection):
96
- tables = con.execute(tables_query).fetchdf().values.tolist()
97
- elif isinstance(con, psycopg2.extensions.connection):
98
- with con.cursor() as cursor:
99
- cursor.execute(tables_query)
100
- tables = cursor.fetchall()
101
- elif isinstance(con, mysql.connector.connection_cext.CMySQLConnection):
102
- cursor = con.cursor()
103
- cursor.execute(tables_query)
104
- tables = cursor.fetchall()
105
- cursor.close()
106
- else:
107
- raise TypeError("Unsupported connection type")
108
-
109
- structure = {}
110
- for db_name, schema_name, table_name in tables:
111
- # Initialize nested dictionaries
112
- structure.setdefault(db_name, {}).setdefault(schema_name, {})
113
- # Get columns for this table
114
- columns_query = f"""
115
- SELECT column_name, data_type
116
- FROM information_schema.columns
117
- WHERE table_catalog = '{db_name}'
118
- AND table_schema = '{schema_name}'
119
- AND table_name = '{table_name}'
120
- """
121
- if isinstance(con, duckdb.DuckDBPyConnection):
122
- columns = con.execute(columns_query).fetchdf().values.tolist()
123
- elif isinstance(con, psycopg2.extensions.connection):
124
- with con.cursor() as cursor:
125
- cursor.execute(columns_query)
126
- columns = cursor.fetchall()
127
- elif isinstance(con, mysql.connector.connection_cext.CMySQLConnection):
128
- cursor = con.cursor()
129
- cursor.execute(columns_query)
130
- columns = cursor.fetchall()
131
- cursor.close()
132
- else:
133
- raise TypeError("Unsupported connection type")
134
- structure[db_name][schema_name][table_name] = columns
135
- return structure
136
-
137
- def sample_table(con, db_name, schema_name, table_name, num_samples=3):
138
- if isinstance(con, duckdb.DuckDBPyConnection):
139
- qualified_table_name = f'"{db_name}"."{schema_name}"."{table_name}"'
140
- sample_query = f"SELECT * FROM {qualified_table_name} LIMIT {num_samples}"
141
- sample_df = con.execute(sample_query).df()
142
- return sample_df
143
- elif isinstance(con, psycopg2.extensions.connection):
144
- qualified_table_name = f'"{schema_name}"."{table_name}"'
145
- sample_query = f'SELECT * FROM {qualified_table_name} LIMIT {num_samples}'
146
- with con.cursor() as cursor:
147
- cursor.execute(sample_query)
148
- rows = cursor.fetchall()
149
- columns = [desc[0] for desc in cursor.description]
150
- sample_df = pd.DataFrame(rows, columns=columns)
151
- return sample_df
152
- elif isinstance(con, mysql.connector.connection_cext.CMySQLConnection):
153
- qualified_table_name = f'`{schema_name}`.`{table_name}`'
154
- sample_query = f"SELECT * FROM {qualified_table_name} LIMIT {num_samples}"
155
- cursor = con.cursor()
156
- cursor.execute(sample_query)
157
- rows = cursor.fetchall()
158
- columns = cursor.column_names
159
- cursor.close()
160
- sample_df = pd.DataFrame(rows, columns=columns)
161
- return sample_df
162
- else:
163
- raise TypeError("Unsupported connection type")
164
-
165
- def write_context_files(con, structure, connection_name, directory=None):
166
- if directory is None:
167
- directory = os.path.join(SQLCTX_DIRECTORY, connection_name)
168
- os.makedirs(directory, exist_ok=True)
169
-
170
- # Build overview data
171
- overview_data = {'databases': []}
172
- for db_name, schemas_dict in structure.items():
173
- db_entry = {'name': db_name, 'schemas': []}
174
- for schema_name, tables_dict in schemas_dict.items():
175
- schema_entry = {'name': schema_name, 'tables': list(tables_dict.keys())}
176
- db_entry['schemas'].append(schema_entry)
177
- overview_data['databases'].append(db_entry)
178
-
179
- # Write overview.yml if the connection name is not a direct connection string
180
- if connection_name in load_config()['connections']:
181
- with open(os.path.join(directory, 'overview.yml'), 'w') as f:
182
- yaml.safe_dump(overview_data, f, default_flow_style=False, sort_keys=False)
183
-
184
- combined_data = []
185
- for db_name, schemas_dict in structure.items():
186
- for schema_name, tables_dict in schemas_dict.items():
187
- for table_name, columns in tables_dict.items():
188
- # Define the directory path
189
- path = os.path.join(directory, db_name, schema_name)
190
- os.makedirs(path, exist_ok=True)
191
- # Sample the table with 3 records
192
- sample_df = sample_table(con, db_name, schema_name, table_name, num_samples=3)
193
- # Prepare sample data
194
- sample_data_full = sample_df.to_dict(orient='list')
195
- sample_data = {col: vals[:3] for col, vals in sample_data_full.items()}
196
- # Define table data
197
- table_data = {
198
- 'database': db_name,
199
- 'schema': schema_name,
200
- 'table': table_name,
201
- 'columns': [{cname: ctype} for cname, ctype in columns],
202
- 'sample data': sample_data,
203
- }
204
- # Write table_data to YAML
205
- table_context_path = os.path.join(path, f"{table_name}.yml")
206
- with open(table_context_path, 'w') as f:
207
- yaml.dump(table_data, f, default_flow_style=False)
208
- # Add to combined data
209
- combined_data.append(table_data)
210
-
211
- # Write combined content to a file as proper YAML if connection_name is provided
212
- if connection_name in load_config()['connections']:
213
- combined_path = os.path.join(directory, 'combined.yml')
214
- with open(combined_path, 'w') as f:
215
- yaml.safe_dump(combined_data, f, default_flow_style=False, sort_keys=False)
File without changes
File without changes
File without changes