|
| 1 | +import os |
| 2 | +from crewai_tools import tool |
| 3 | +from dotenv import load_dotenv |
| 4 | +from neon_api import NeonAPI |
| 5 | +import psycopg2 |
| 6 | +from psycopg2.extras import RealDictCursor |
| 7 | + |
| 8 | +load_dotenv() |
| 9 | + |
| 10 | +NEON_API_KEY = os.getenv('NEON_API_KEY') |
| 11 | +neon_client = NeonAPI(api_key=NEON_API_KEY) |
| 12 | + |
| 13 | +@tool("Create Neon Project and Database") |
| 14 | +def create_database(project_name: str) -> str: |
| 15 | + """ |
| 16 | + Creates a new Neon project. |
| 17 | + Args: |
| 18 | + project_name: Name of the project to create |
| 19 | + Returns: |
| 20 | + the connection URI for the new project |
| 21 | + """ |
| 22 | + try: |
| 23 | + project = neon_client.project_create(project={"name": project_name}).project |
| 24 | + connection_uri = neon_client.connection_uri(project_id=project.id, database_name="neondb", role_name="neondb_owner").uri |
| 25 | + return f"Project/database created, connection URI: {connection_uri}" |
| 26 | + except Exception as e: |
| 27 | + return f"Failed to create project: {str(e)}" |
| 28 | + |
| 29 | + |
| 30 | +@tool("Execute SQL DDL") |
| 31 | +def execute_sql_ddl(connection_uri: str, command: str) -> str: |
| 32 | + """ |
| 33 | + Inserts data into a specified Neon database. |
| 34 | + Args: |
| 35 | + connection_uri: The connection URI for the Neon database |
| 36 | + command: The DDL command to execute |
| 37 | + Returns: |
| 38 | + the result of the DDL command |
| 39 | + """ |
| 40 | + conn = psycopg2.connect(connection_uri) |
| 41 | + cur = conn.cursor(cursor_factory=RealDictCursor) |
| 42 | + cur.execute(command) |
| 43 | + result = cur.fetchone() |
| 44 | + cur.close() |
| 45 | + conn.close() |
| 46 | + return f"Command result: {result}" |
| 47 | + |
| 48 | + |
| 49 | +@tool("Execute SQL DML") |
| 50 | +def run_sql_query(connection_uri: str, query: str) -> str: |
| 51 | + """ |
| 52 | + Inserts data into a specified Neon database. |
| 53 | + Args: |
| 54 | + connection_uri: The connection URI for the Neon database |
| 55 | + query: The SQL query to execute |
| 56 | + Returns: |
| 57 | + the result of the SQL query |
| 58 | + """ |
| 59 | + conn = psycopg2.connect(connection_uri) |
| 60 | + cur = conn.cursor(cursor_factory=RealDictCursor) |
| 61 | + cur.query(query) |
| 62 | + records = cur.fetchall() |
| 63 | + cur.close() |
| 64 | + conn.close() |
| 65 | + return f"Query result: {records}" |
0 commit comments