exnihilo-95 2.1.0__py3-none-any.whl

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.
@@ -0,0 +1,12 @@
1
+ """
2
+ ExNihilo 95 — Python SDK
3
+ Zero-Config Relational Synthesis & Database Engine
4
+
5
+ Concept & Architecture by Mrityunjai (@Mrityunjai-hue)
6
+ Licensed under the MIT License
7
+ """
8
+
9
+ from .client import execute_sql, QueryResult
10
+
11
+ __version__ = "2.1.0"
12
+ __all__ = ["execute_sql", "QueryResult"]
exnihilo_95/client.py ADDED
@@ -0,0 +1,207 @@
1
+ """
2
+ client.py — Python Client for ExNihilo 95 Relational Synthesis Engine
3
+ Provides seamless ex nihilo query execution with pandas DataFrame conversion.
4
+ """
5
+
6
+ import json
7
+ import subprocess
8
+ import os
9
+ import sys
10
+ import urllib.request
11
+ import urllib.error
12
+ from typing import List, Dict, Any, Optional
13
+
14
+ DEFAULT_CLOUD_ENDPOINT = "https://exnihilo-95.vercel.app/api/execute"
15
+ DEFAULT_LOCAL_ENDPOINT = "http://localhost:3000/api/execute"
16
+
17
+
18
+ class QueryResult:
19
+ """
20
+ Structured execution result from ExNihilo 95 engine.
21
+ """
22
+ def __init__(self, data: dict):
23
+ self.raw = data
24
+ self.success: bool = data.get("ok", data.get("success", False))
25
+ self.error: Optional[str] = data.get("error")
26
+ self.results = data.get("allResults", data.get("results", []))
27
+
28
+ # Primary table results
29
+ self.columns: List[str] = data.get("columns", [])
30
+ self.rows: List[List[Any]] = data.get("rows", [])
31
+ self.row_count: int = data.get("rowCount", len(self.rows))
32
+ self.execution_time_ms: float = float(data.get("executionTimeMs", 0.0))
33
+
34
+ # Fallback to first result in allResults if top-level fields are missing
35
+ if not self.columns and self.results:
36
+ first_res = self.results[0]
37
+ self.columns = first_res.get("columns", [])
38
+ self.rows = first_res.get("rows", [])
39
+ self.row_count = len(self.rows)
40
+
41
+ def to_dict(self) -> List[Dict[str, Any]]:
42
+ """
43
+ Convert table rows into a list of dictionaries mapping column_name -> value.
44
+ """
45
+ return [dict(zip(self.columns, row)) for row in self.rows]
46
+
47
+ def to_dataframe(self):
48
+ """
49
+ Convert results into a pandas DataFrame.
50
+ Requires pandas to be installed (pip install pandas).
51
+ """
52
+ try:
53
+ import pandas as pd
54
+ return pd.DataFrame(self.rows, columns=self.columns)
55
+ except ImportError:
56
+ raise ImportError(
57
+ "pandas is required to convert results to a DataFrame. "
58
+ "Install it via: pip install pandas"
59
+ )
60
+
61
+ def __iter__(self):
62
+ return iter(self.to_dict())
63
+
64
+ def __len__(self):
65
+ return self.row_count
66
+
67
+ def __repr__(self) -> str:
68
+ if not self.success:
69
+ return f"<ExNihilo 95 Query Error: {self.error}>"
70
+ if not self.columns:
71
+ return f"<ExNihilo 95 Result (0 columns, 0 rows) [{self.execution_time_ms:.1f}ms]>"
72
+
73
+ # Render vintage tabular ASCII grid
74
+ col_widths = []
75
+ for i, c in enumerate(self.columns):
76
+ max_val_len = max((len(str(r[i])) for r in self.rows), default=0)
77
+ col_widths.append(max(len(str(c)), max_val_len))
78
+
79
+ header = " | ".join(f"{c:<{w}}" for c, w in zip(self.columns, col_widths))
80
+ separator = "-+-".join("-" * w for w in col_widths)
81
+
82
+ row_lines = []
83
+ preview_rows = self.rows[:10]
84
+ for r in preview_rows:
85
+ row_lines.append(" | ".join(f"{str(val):<{w}}" for val, w in zip(r, col_widths)))
86
+
87
+ if len(self.rows) > 10:
88
+ row_lines.append(f"... ({len(self.rows) - 10} additional rows)")
89
+
90
+ table_str = "\n".join([header, separator] + row_lines)
91
+ return f"\n{table_str}\n\n[Kernel: {self.row_count} rows synthesized in {self.execution_time_ms:.1f}ms]"
92
+
93
+
94
+ def _try_local_node_execution(sql: str) -> Optional[QueryResult]:
95
+ """
96
+ Attempts to execute query directly via local Node.js engine runner if available.
97
+ """
98
+ possible_runner_paths = [
99
+ os.path.join(os.path.dirname(__file__), "..", "..", "scripts", "run_query.mjs"),
100
+ os.path.join(os.getcwd(), "scripts", "run_query.mjs"),
101
+ ]
102
+
103
+ for runner_path in possible_runner_paths:
104
+ abs_path = os.path.abspath(runner_path)
105
+ if os.path.exists(abs_path):
106
+ try:
107
+ npx_bin = "npx.cmd" if os.name == "nt" else "npx"
108
+ cmd = [npx_bin, "tsx", abs_path, sql]
109
+ proc = subprocess.run(
110
+ cmd,
111
+ capture_output=True,
112
+ text=True,
113
+ timeout=15
114
+ )
115
+ if proc.returncode == 0 and proc.stdout.strip():
116
+ data = json.loads(proc.stdout.strip())
117
+ return QueryResult(data)
118
+ except Exception:
119
+ pass
120
+ return None
121
+
122
+
123
+ def execute_sql(
124
+ sql: str,
125
+ dialect: str = "MySQL",
126
+ rows_per_table: int = 20,
127
+ endpoint: Optional[str] = None
128
+ ) -> QueryResult:
129
+ """
130
+ Executes any SQL query ex nihilo using the ExNihilo 95 relational synthesis engine.
131
+ Automatically deduces schemas, resolves foreign key DAGs, and synthesizes realistic datasets.
132
+
133
+ Args:
134
+ sql: The SQL query statement to run (any dialect: MySQL, PostgreSQL, SQLite, SSMS, Oracle)
135
+ dialect: SQL dialect name (default: 'MySQL')
136
+ rows_per_table: Number of rows to synthesize per inferred table (default: 20)
137
+ endpoint: Target API endpoint URL (auto-selects local or cloud by default)
138
+
139
+ Returns:
140
+ QueryResult object with .columns, .rows, .to_dict(), and .to_dataframe()
141
+
142
+ Example:
143
+ from exnihilo_95 import execute_sql
144
+
145
+ result = execute_sql("SELECT name, distance_light_years FROM celestial_objects")
146
+ print(result)
147
+ df = result.to_dataframe()
148
+ """
149
+ if not sql or not isinstance(sql, str):
150
+ raise ValueError("sql must be a non-empty string.")
151
+
152
+ # 1. First priority: Try local Node.js engine runner if inside/near repository
153
+ if not endpoint:
154
+ local_result = _try_local_node_execution(sql)
155
+ if local_result is not None:
156
+ return local_result
157
+
158
+ # 2. Second priority: Try HTTP execution
159
+ payload = json.dumps({
160
+ "sql": sql,
161
+ "dialect": dialect,
162
+ "rowsPerTable": rows_per_table
163
+ }).encode("utf-8")
164
+
165
+ headers = {
166
+ "Content-Type": "application/json",
167
+ "User-Agent": "ExNihilo95-Python/2.1.0"
168
+ }
169
+
170
+ target_endpoint = endpoint
171
+
172
+ # Auto-resolve target endpoint if not specified
173
+ if not target_endpoint:
174
+ # Check if local Next.js server is active
175
+ try:
176
+ req = urllib.request.Request(
177
+ DEFAULT_LOCAL_ENDPOINT,
178
+ data=payload,
179
+ headers=headers,
180
+ method="POST"
181
+ )
182
+ with urllib.request.urlopen(req, timeout=1.0) as resp:
183
+ data = json.loads(resp.read().decode("utf-8"))
184
+ return QueryResult(data)
185
+ except Exception:
186
+ # Fallback to high-availability cloud endpoint
187
+ target_endpoint = DEFAULT_CLOUD_ENDPOINT
188
+
189
+ try:
190
+ req = urllib.request.Request(
191
+ target_endpoint,
192
+ data=payload,
193
+ headers=headers,
194
+ method="POST"
195
+ )
196
+ with urllib.request.urlopen(req, timeout=15.0) as resp:
197
+ data = json.loads(resp.read().decode("utf-8"))
198
+ return QueryResult(data)
199
+ except urllib.error.HTTPError as e:
200
+ err_body = e.read().decode("utf-8", errors="ignore")
201
+ try:
202
+ err_json = json.loads(err_body)
203
+ return QueryResult(err_json)
204
+ except Exception:
205
+ return QueryResult({"success": False, "error": f"HTTP {e.code}: {e.reason}"})
206
+ except Exception as e:
207
+ return QueryResult({"success": False, "error": str(e)})
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: exnihilo-95
3
+ Version: 2.1.0
4
+ Summary: Zero-Config Relational SQL Synthesis Engine & Database Client
5
+ Author-email: Mrityunjai <mrityunjai@users.noreply.github.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://exnihilo-95.vercel.app
8
+ Project-URL: Repository, https://github.com/Mrityunjai-hue/exnihilo-95
9
+ Project-URL: Bug Tracker, https://github.com/Mrityunjai-hue/exnihilo-95/issues
10
+ Keywords: sql,sqlite,relational-synthesis,mock-data,faker,windows-95,database
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Database
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ Provides-Extra: pandas
18
+ Requires-Dist: pandas>=1.3.0; extra == "pandas"
19
+
20
+ # ExNihilo 95 — Python SDK
21
+
22
+ **The Zero-Config In-Browser SQL IDE & Relational Synthesis Engine**
23
+ *Query tables that don't even exist with automatic schema deduction, foreign key DAG resolution, and calibrated mock data synthesis.*
24
+
25
+ ---
26
+
27
+ ## 🚀 Quickstart
28
+
29
+ ### Installation
30
+ ```bash
31
+ # Direct install from GitHub repository:
32
+ pip install "git+https://github.com/Mrityunjai-hue/exnihilo-95.git#subdirectory=python"
33
+
34
+ # Or from local source:
35
+ pip install .
36
+ ```
37
+
38
+ ### Basic Query Synthesis
39
+ ```python
40
+ from exnihilo_95 import execute_sql
41
+
42
+ # Execute any query ex nihilo without setting up databases or tables:
43
+ result = execute_sql("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
44
+
45
+ # Print the formatted ASCII result table
46
+ print(result)
47
+
48
+ # Access columns and rows programmatically
49
+ print("Columns:", result.columns)
50
+ print("Rows:", result.rows)
51
+
52
+ # Convert to a list of dictionaries
53
+ records = result.to_dict()
54
+ print(records[0])
55
+ ```
56
+
57
+ ---
58
+
59
+ ## 📊 Pandas DataFrame Integration
60
+
61
+ ExNihilo 95 integrates seamlessly with Pandas for instant data science experimentation and ETL testing:
62
+
63
+ ```python
64
+ from exnihilo_95 import execute_sql
65
+
66
+ result = execute_sql("""
67
+ SELECT
68
+ e.department,
69
+ AVG(e.salary) AS avg_salary,
70
+ COUNT(e.id) AS headcount
71
+ FROM employees e
72
+ GROUP BY e.department
73
+ ORDER BY avg_salary DESC;
74
+ """)
75
+
76
+ # Convert directly to a pandas DataFrame
77
+ df = result.to_dataframe()
78
+ print(df.head())
79
+ ```
80
+
81
+ ---
82
+
83
+ ## 🌐 Dialects Supported
84
+
85
+ ExNihilo 95 automatically transpiles multi-dialect syntax:
86
+ - **MySQL:** `GROUP_CONCAT`, `DATE_FORMAT`
87
+ - **PostgreSQL:** `ILIKE`, `->>`, `::numeric`
88
+ - **T-SQL / SSMS:** `SELECT TOP (n)`, `[bracketed_columns]`
89
+ - **Oracle:** `ROWNUM <= n`, `NVL2`, `DECODE`
90
+ - **SQLite:** Native WebAssembly execution
91
+
92
+ ```python
93
+ # T-SQL query with bracketed identifiers:
94
+ res = execute_sql("SELECT TOP 5 [name], [distance_light_years] FROM [celestial_objects]")
95
+ print(res)
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 📜 License
101
+ Licensed under the **MIT License** with Attribution.
102
+ Original Concept & Architecture by **Mrityunjai** ([@Mrityunjai-hue](https://github.com/Mrityunjai-hue)).
@@ -0,0 +1,6 @@
1
+ exnihilo_95/__init__.py,sha256=G5S0RLCGGX3u0ZyDAyk_G40Fli5_CZoRT_Ka-AifnH8,283
2
+ exnihilo_95/client.py,sha256=PGD_NCVE_qP4cXCirSlTH7qmqAMFtqFRyWvsvCsHkPs,7388
3
+ exnihilo_95-2.1.0.dist-info/METADATA,sha256=uXz_P_zKPsV5ZNDwAyHSQ0RjkjMCHEWjSzFygED1iKg,3014
4
+ exnihilo_95-2.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ exnihilo_95-2.1.0.dist-info/top_level.txt,sha256=4tUIIUWDGxbOCtVzr_OliTpJJywYhDyR81MTJkI5SCI,12
6
+ exnihilo_95-2.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ exnihilo_95