File size: 1,818 Bytes
d5f79b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import asyncio
import os
import sys

# Add project root to python path
sys.path.append(os.getcwd())

from sqlalchemy import text
from app.sql import async_session

async def apply_sql_fix():
    print("Applying SQL fix for fn_get_po_items_for_purchase_return...")
    
    sql_file_path = "app/sql/fn_get_po_items_for_purchase_return.sql"
    
    with open(sql_file_path, "r") as f:
        sql_content = f.read()
        
    async with async_session() as session:
        try:
            # Split the SQL content into statements
            # The file contains a function definition ending with $BODY$; and an ALTER statement
            parts = sql_content.split("$BODY$;")
            
            if len(parts) >= 2:
                # Reconstruct the CREATE FUNCTION statement
                create_func_stmt = parts[0] + "$BODY$;"
                print("Executing CREATE FUNCTION statement...")
                await session.execute(text(create_func_stmt))
                
                # The rest might contain the ALTER statement
                remaining = parts[1].strip()
                if remaining:
                    print(f"Executing remaining statement: {remaining[:50]}...")
                    await session.execute(text(remaining))
            else:
                # Fallback if split fails (unexpected format), try executing as is (might fail)
                print("Could not split by $BODY$;, attempting to execute as single statement...")
                await session.execute(text(sql_content))
                
            await session.commit()
            print("✅ SQL fix applied successfully.")
        except Exception as e:
            print(f"❌ Error applying SQL fix: {e}")
            await session.rollback()

if __name__ == "__main__":
    asyncio.run(apply_sql_fix())