-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkflows.py
More file actions
319 lines (270 loc) · 9.31 KB
/
Copy pathworkflows.py
File metadata and controls
319 lines (270 loc) · 9.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python3
"""
Example: SQL Query Generation and Validation
Demonstrates SQL adapter capabilities:
- Query generation from structured plans
- Safety policy enforcement
- Query validation
- Multiple dialects support
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parents[2]))
from _example_helpers import print_separator
from nlp2cmd import SQLAdapter
from nlp2cmd.adapters import SQLSafetyPolicy
from nlp2cmd.validators import SQLValidator
def print_section(title: str):
"""Print section header."""
print_separator(f" {title}", leading_newline=True, width=60)
print()
def main():
print_section("SQL Query Generation Demo")
# =========================================================================
# Basic Query Generation
# =========================================================================
print_section("1. Basic Query Generation")
adapter = SQLAdapter(dialect="postgresql")
# SELECT query
plan = {
"intent": "select",
"entities": {
"table": "users",
"columns": ["id", "name", "email"],
"filters": [
{"field": "status", "operator": "=", "value": "active"}
]
}
}
query = adapter.generate(plan)
print("Plan:")
print(f" Intent: {plan['intent']}")
print(f" Table: {plan['entities']['table']}")
print(f" Columns: {plan['entities']['columns']}")
print(f"\nGenerated SQL:\n {query}")
# =========================================================================
# Complex Queries
# =========================================================================
print_section("2. Complex Queries")
# JOIN query
join_plan = {
"intent": "select",
"entities": {
"table": "orders",
"columns": ["o.id", "o.total", "u.name", "u.email"],
"joins": [
{
"type": "LEFT",
"table": "users",
"alias": "u",
"on": "o.user_id = u.id"
}
],
"alias": "o",
"filters": [
{"field": "o.status", "operator": "=", "value": "completed"}
],
"order_by": [{"field": "o.created_at", "direction": "DESC"}],
"limit": 10
}
}
query = adapter.generate(join_plan)
print("JOIN Query:")
print(f"\n{query}")
# Aggregation query
agg_plan = {
"intent": "aggregate",
"entities": {
"table": "orders",
"aggregations": [
{"function": "COUNT", "field": "*", "alias": "order_count"},
{"function": "SUM", "field": "total", "alias": "total_revenue"},
{"function": "AVG", "field": "total", "alias": "avg_order_value"}
],
"group_by": ["user_id"],
"having": [
{"function": "COUNT", "field": "*", "operator": ">", "value": 5}
]
}
}
query = adapter.generate(agg_plan)
print("\nAggregation Query:")
print(f"\n{query}")
# =========================================================================
# Safety Policy
# =========================================================================
print_section("3. Safety Policy Enforcement")
# Create adapter with strict safety policy
strict_policy = SQLSafetyPolicy(
allow_delete=False,
allow_drop=False,
allow_truncate=False,
require_where_on_update=True,
require_where_on_delete=True,
max_rows_affected=1000,
)
safe_adapter = SQLAdapter(
dialect="postgresql",
safety_policy=strict_policy
)
print("Safety Policy:")
print(f" Allow DELETE: {strict_policy.allow_delete}")
print(f" Allow DROP: {strict_policy.allow_drop}")
print(f" Require WHERE on UPDATE: {strict_policy.require_where_on_update}")
print(f" Require WHERE on DELETE: {strict_policy.require_where_on_delete}")
print(f" Max rows: {strict_policy.max_rows_affected}")
# Test DELETE without WHERE
delete_plan = {
"intent": "delete",
"entities": {
"table": "logs",
}
}
print("\nAttempting DELETE without WHERE:")
result = safe_adapter.generate(delete_plan)
safety = safe_adapter.check_safety(result)
print(f" Query: {result}")
print(f" Allowed: {safety.get('allowed')}")
reason = safety.get("reason")
if reason:
print(f" Reason: {reason}")
# Test DELETE with WHERE
delete_plan_safe = {
"intent": "delete",
"entities": {
"table": "logs",
"filters": [
{"field": "created_at", "operator": "<", "value": "2024-01-01"}
]
}
}
print("\nAttempting DELETE with WHERE:")
result = safe_adapter.generate(delete_plan_safe)
safety = safe_adapter.check_safety(result)
print(f" Query: {result}")
print(f" Allowed: {safety.get('allowed')}")
reason = safety.get("reason")
if reason:
print(f" Reason: {reason}")
# =========================================================================
# Query Validation
# =========================================================================
print_section("4. Query Validation")
validator = SQLValidator(strict=False)
# Valid query
valid_query = "SELECT * FROM users WHERE id = 1"
print(f"Query: {valid_query}")
result = validator.validate(valid_query)
print(f"Valid: {result.is_valid}")
# Dangerous query
dangerous_query = "DELETE FROM users"
print(f"\nQuery: {dangerous_query}")
result = validator.validate(dangerous_query)
print(f"Valid: {result.is_valid}")
if result.warnings:
print("Warnings:")
for w in result.warnings:
print(f" ⚠️ {w}")
if result.suggestions:
print("Suggestions:")
for s in result.suggestions:
print(f" 💡 {s}")
# Query with syntax issues
bad_syntax = "SELECT * FROM users WHERE (id = 1"
print(f"\nQuery: {bad_syntax}")
result = validator.validate(bad_syntax)
print(f"Valid: {result.is_valid}")
if result.errors:
print("Errors:")
for e in result.errors:
print(f" ❌ {e}")
# =========================================================================
# Multiple Dialects
# =========================================================================
print_section("5. SQL Dialects")
dialects = ["postgresql", "mysql", "sqlite"]
plan = {
"intent": "select",
"entities": {
"table": "users",
"columns": ["id", "name"],
"limit": 10
}
}
for dialect in dialects:
adapter = SQLAdapter(dialect=dialect)
query = adapter.generate(plan)
print(f"{dialect.upper()}:")
print(f" {query}\n")
# =========================================================================
# INSERT and UPDATE
# =========================================================================
print_section("6. Data Modification Queries")
adapter = SQLAdapter(dialect="postgresql")
# INSERT
insert_plan = {
"intent": "insert",
"entities": {
"table": "users",
"values": {
"name": "John Doe",
"email": "john@example.com",
"status": "active"
}
}
}
query = adapter.generate(insert_plan)
print("INSERT:")
print(f" {query}")
# UPDATE
update_plan = {
"intent": "update",
"entities": {
"table": "users",
"values": {
"status": "inactive",
"updated_at": "NOW()"
},
"filters": [
{"field": "last_login", "operator": "<", "value": "2024-01-01"}
]
}
}
query = adapter.generate(update_plan)
print("\nUPDATE:")
print(f" {query}")
# =========================================================================
# Schema Context
# =========================================================================
print_section("7. Schema-Aware Generation")
schema_context = {
"tables": ["users", "orders", "products"],
"columns": {
"users": ["id", "name", "email", "created_at"],
"orders": ["id", "user_id", "product_id", "quantity", "total"],
"products": ["id", "name", "price", "stock"],
},
"relations": {
"orders.user_id": "users.id",
"orders.product_id": "products.id",
}
}
adapter = SQLAdapter(
dialect="postgresql",
schema_context=schema_context
)
print("Schema Context:")
print(f" Tables: {schema_context['tables']}")
print(f" Relations: {list(schema_context['relations'].keys())}")
# Generate query with context
plan = {
"intent": "select",
"entities": {
"table": "orders",
"columns": ["*"],
}
}
query = adapter.generate(plan)
print(f"\nGenerated query uses schema context for validation")
if __name__ == "__main__":
main()