﻿B4J=true
Group=Default Group
ModulesStructureVersion=1
Type=StaticCode
Version=10.45
@EndOfDesignText@

Sub Process_Globals
	Type DBResult (Columns As Map, Rows As List)
	Private DateTimeMethods As Map
End Sub

'Similar to SQL.ExecQuery2 - Returns a DBResult with each record (row) as an array of objects and a columns map that describes the array order.
Public Sub ExecQuery(SQL As SQL, Query As String, Args As List) As DBResult
	Return ExecQuery2(SQL, Query, Args, 0x7ffffff)
End Sub

'See ExecQuery. With a limit on the number of returned rows.
Public Sub ExecQuery2(SQL As SQL, Query As String, Args As List, Limit As Int) As DBResult
	If NotInitialized(DateTimeMethods) Then DateTimeMethods = CreateMap(91: "getDate", 92: "getTime", 93: "getTimestamp")
	Dim rs As ResultSet = SQL.ExecQuery2(Query, Args)
	Dim jrs As JavaObject = rs
	Dim rsmd As JavaObject = jrs.RunMethod("getMetaData", Null)
	Dim cols As Int = rs.ColumnCount
	Dim res As DBResult
	res.Initialize
	res.columns.Initialize
	For i = 0 To cols - 1
		res.columns.Put(rs.GetColumnName(i), i)
	Next
	res.Rows.Initialize
	Do While rs.NextRow And Limit > 0
		Dim row(cols) As Object
		For i = 0 To cols - 1
			Dim ct As Int = rsmd.RunMethod("getColumnType", Array(i + 1))
			'check whether it is a blob field
			If ct = -2 Or ct = 2004 Or ct = -3 Or ct = -4 Then
				row(i) = rs.GetBlob2(i)
			Else if ct = 2 Or ct = 3 Then
				row(i) = rs.GetDouble2(i)
			Else If DateTimeMethods.ContainsKey(ct) Then
				Dim SQLTime As JavaObject = jrs.RunMethodJO(DateTimeMethods.Get(ct), Array(i + 1))
				If SQLTime.IsInitialized Then
					row(i) = SQLTime.RunMethod("getTime", Null)
				Else
					row(i) = Null
				End If
			Else
				row(i) = jrs.RunMethod("getObject", Array(i + 1))
			End If
			
		Next
		res.Rows.Add(row)
	Loop
	rs.Close
	Return res
End Sub

'Prints the table to the logs.
Public Sub PrintTable(Table As DBResult)
	Log("Columns: " & Table.Columns.Size & ", Rows: " & Table.Rows.Size)
	Dim sb As StringBuilder
	sb.Initialize
	For Each col In Table.Columns.Keys
		sb.Append(col).Append(TAB)
	Next
	Log(sb.ToString)
	For Each row() As Object In Table.Rows
		Dim sb As StringBuilder
		sb.Initialize
		For Each record As Object In row
			sb.Append(record).Append(TAB)
		Next
		Log(sb.ToString)
	Next
End Sub