tests/test_createfunction_comprehensive.ps1

# Comprehensive test of CreateFunction (scalar UDFs)
# Tests various parameter types, return types, and use cases

# Load module from parent directory
Import-Module PaperinikDB -Force

$conn = New-DuckDBConnection -Path ':MEMORY:'
$conn.Open()
Write-Host 'Connection opened' -ForegroundColor Green

Write-Host "`n=== Test 1: getenv function (string -> string) ===" -ForegroundColor Cyan
$conn.CreateFunction('getenv', { param($varName) [System.Environment]::GetEnvironmentVariable($varName) }, @([string]), [string])
$result = $conn.sql("SELECT getenv('USERDOMAIN') as domain, getenv('COMPUTERNAME') as computer")
Write-Host "Domain: $($result.domain), Computer: $($result.computer)"

Write-Host "`n=== Test 2: string manipulation (string -> string) ===" -ForegroundColor Cyan
$conn.CreateFunction('reverse_str', { param($s) -join ($s.ToCharArray() | Sort-Object -Descending) }, @([string]), [string])
$result = $conn.sql("SELECT reverse_str('hello') as reversed")
Write-Host "Reversed 'hello': $($result.reversed)"

Write-Host "`n=== Test 3: double function (int -> int) ===" -ForegroundColor Cyan
$conn.CreateFunction('double_it', { param([int]$n) $n * 2 }, @([int]), [int])
$result = $conn.sql("SELECT double_it(21) as doubled")
Write-Host "Double of 21: $($result.doubled)"

Write-Host "`n=== Test 4: add two numbers (int, int -> int) ===" -ForegroundColor Cyan
$conn.CreateFunction('add_nums', { param([int]$a, [int]$b) $a + $b }, @([int], [int]), [int])
$result = $conn.sql("SELECT add_nums(17, 25) as sum")
Write-Host "17 + 25: $($result.sum)"

Write-Host "`n=== Test 5: is_even (int -> bool) ===" -ForegroundColor Cyan
$conn.CreateFunction('is_even', { param([int]$n) ($n % 2) -eq 0 }, @([int]), [bool])
$results = $conn.sql("SELECT i::INTEGER as i, is_even(i::INTEGER) as even FROM range(5) t(i)")
Write-Host "Testing is_even on 0-4:"
$results | ForEach-Object { Write-Host " $($_.i): $($_.even)" }

Write-Host "`n=== Test 6: UDF with table data ===" -ForegroundColor Cyan
$conn.sql("CREATE TABLE test_names (name VARCHAR)")
$conn.sql("INSERT INTO test_names VALUES ('Alice'), ('Bob'), ('Charlie')")
$conn.CreateFunction('greet', { param($name) "Hello, $name!" }, @([string]), [string])
$results = $conn.sql("SELECT name, greet(name) as greeting FROM test_names")
Write-Host "Greetings:"
$results | ForEach-Object { Write-Host " $($_.greeting)" }

Write-Host "`n=== All tests passed! ===" -ForegroundColor Green

$conn.Close()