|
- <%
- '=======================================================================================================================
- ' DATABASE CLASS (native G3DB)
- '=======================================================================================================================
- ' Thin wrapper over AxonASP's G3DB library. Keeps the original Database_Class API (Query, PagedQuery, Execute,
- ' Begin/Commit/RollbackTransaction, Connection) so callers such as DAL() and the Migrator are unchanged.
- '
- ' Connection string: "<driver>:<dsn>", e.g.
- ' sqlite:/opt/axonasp/site/db/app.sqlite
- ' mysql:user:pass@tcp(127.0.0.1:3306)/app?parseTime=true
- ' postgres:host=127.0.0.1 port=5432 user=u password=p dbname=app sslmode=disable
- ' mssql:server=127.0.0.1;port=1433;user id=u;password=p;database=app
- '
- ' Behavior notes (G3DB):
- ' - Query returns a forward-only result set (EOF, MoveNext, rs("col"), rs(0), Fields.Count, Close).
- ' - Parameters are positional "?" values. G3DB does not expand an array, so this class does (max MAX_PARAMS).
- ' - G3DB signals failure with Empty plus LastError; this class turns that into a raised VBScript error that
- ' includes the SQL, so errors are never silently ignored.
- ' - Transactions are handle based; while one is open, Query/Execute are routed through it.
- Class Database_Class
- Private m_db
- Private m_tx
- Private m_txFailed ' first error raised inside the open transaction ("" while none)
- Private m_driver
- Private m_dsn
- Private m_connection_string
- Private m_trace_enabled
-
- Public Sub set_trace(bool)
- m_trace_enabled = bool
- End Sub
-
- Public Property Get is_trace_enabled
- is_trace_enabled = m_trace_enabled
- End Property
-
- '---------------------------------------------------------------------------------------------------------------------
- Public Sub Initialize(connection_string)
- Dim p
- m_connection_string = "" & connection_string
- p = InStr(m_connection_string, ":")
- If p < 2 Then
- Err.Raise vbObjectError + 100, "Database_Class", "ConnectionString must look like '<driver>:<dsn>' (for example sqlite:/path/app.sqlite). Got: [" & m_connection_string & "]"
- End If
- m_driver = LCase(Left(m_connection_string, p - 1))
- m_dsn = Mid(m_connection_string, p + 1)
- If m_driver = "sqlite" Or m_driver = "sqlite3" Then
- If InStr(m_dsn, "?") = 0 Then m_dsn = m_dsn & "?_busy_timeout=5000"
- End If
- End Sub
-
- '---------------------------------------------------------------------------------------------------------------------
- ' The underlying G3DB object (opened on first use)
- Public Function Connection()
- If Not IsObject(m_db) Then
- Set m_db = Server.CreateObject("G3DB")
- If Not m_db.Open(m_driver, m_dsn) Then
- Dim msg
- msg = m_db.LastError
- Set m_db = Empty
- Err.Raise vbObjectError + 101, "Database_Class", "Could not open " & m_driver & " database: " & msg
- End If
- End If
- Set Connection = m_db
- End Function
-
- '---------------------------------------------------------------------------------------------------------------------
- ' Runs a SELECT. params: Empty/Null (none), a scalar (one value) or an array of values.
- Public Function Query(sql, params)
- Dim target, rs
- Set target = Handle()
- Set rs = RunQuery(target, sql, ParamList(params))
- If IsEmpty(rs) Then RaiseDbError "Query failed", sql
- Set Query = rs
- End Function
-
- '---------------------------------------------------------------------------------------------------------------------
- ' Runs INSERT/UPDATE/DELETE/DDL. Returns the G3DBResult (RowsAffected, LastInsertId).
- Public Function Exec(sql, params)
- Dim target, result
- Set target = Handle()
- Set result = RunExec(target, sql, ParamList(params))
- If IsEmpty(result) Then RaiseDbError "Statement failed", sql
- Set Exec = result
- End Function
-
- ' Same as Exec but discards the result (kept for the original Execute(sql, params) call style).
- Public Sub [Execute](sql, params)
- Dim result
- Set result = Exec(sql, params)
- Set result = Nothing
- End Sub
-
- '---------------------------------------------------------------------------------------------------------------------
- ' Returns one page of rows (1-based page_num) using LIMIT/OFFSET (SQLite, MySQL, PostgreSQL).
- ' sql must not already contain LIMIT/OFFSET.
- Public Function PagedQuery(sql, params, per_page, page_num)
- Dim size, page
- size = CLng(per_page)
- page = CLng(page_num)
- If size < 1 Then size = 1
- If page < 1 Then page = 1
- Set PagedQuery = Query(sql & " LIMIT " & size & " OFFSET " & ((page - 1) * size), params)
- End Function
-
- '---------------------------------------------------------------------------------------------------------------------
- Public Sub BeginTransaction()
- If IsObject(m_tx) Then
- Err.Raise vbObjectError + 102, "Database_Class", "A transaction is already open"
- End If
- Dim tx
- Set tx = Connection().Begin()
- If IsEmpty(tx) Then RaiseDbError "Could not begin transaction", ""
- Set m_tx = tx
- m_txFailed = ""
- End Sub
-
- ' Refuses to commit when any statement failed inside the transaction: callers run several statements under
- ' On Error Resume Next and check Err once, but the next DAL call resets Err, so an early failure would otherwise
- ' be lost and a partial write committed. The transaction is rolled back and the first error is raised.
- Public Sub CommitTransaction()
- Dim tx, failed
- If Not IsObject(m_tx) Then Exit Sub
- Set tx = m_tx
- Set m_tx = Empty
- failed = "" & m_txFailed
- m_txFailed = ""
- If Len(failed) > 0 Then
- tx.Rollback
- Err.Raise vbObjectError + 105, "Database_Class", "Transaction rolled back because a statement in it failed: " & failed
- End If
- tx.Commit
- End Sub
-
- Public Sub RollbackTransaction()
- Dim tx
- m_txFailed = ""
- If Not IsObject(m_tx) Then Exit Sub
- Set tx = m_tx
- Set m_tx = Empty
- tx.Rollback
- End Sub
-
- '---------------------------------------------------------------------------------------------------------------------
- ' Private helpers
- '---------------------------------------------------------------------------------------------------------------------
- ' The object to run statements on: the open transaction if there is one, otherwise the connection
- Private Function Handle()
- If IsObject(m_tx) Then
- Set Handle = m_tx
- Else
- Set Handle = Connection()
- End If
- End Function
-
- ' Normalizes params to a zero-based array (possibly empty)
- Private Function ParamList(params)
- If IsArray(params) Then
- ParamList = params
- ElseIf IsEmpty(params) Or IsNull(params) Then
- ParamList = Array()
- Else
- ParamList = Array(params)
- End If
- End Function
-
- Private Function TxNote()
- If IsObject(m_tx) Then
- TxNote = " (statement ran inside a transaction; G3DB does not expose the driver error there)"
- Else
- TxNote = ""
- End If
- End Function
-
- Private Sub RaiseDbError(prefix, sql)
- Dim detail
- detail = ""
- If IsObject(m_db) Then detail = m_db.LastError
- If Len(detail) = 0 Then
- ' G3DB reports no LastError for statements run inside a transaction handle
- detail = "no driver message available" & TxNote()
- End If
- If IsObject(m_tx) Then
- If Len("" & m_txFailed) = 0 Then
- m_txFailed = prefix & " -- SQL: " & sql
- End If
- End If
- Err.Raise vbObjectError + 103, "Database_Class", prefix & ": " & detail & " -- SQL: " & sql
- End Sub
-
- ' G3DB takes positional arguments, not an array, so expand explicitly
- Private Function RunQuery(target, sql, p)
- Select Case UBound(p)
- Case -1 : Set RunQuery = target.Query(sql)
- Case 0 : Set RunQuery = target.Query(sql, p(0))
- Case 1 : Set RunQuery = target.Query(sql, p(0), p(1))
- Case 2 : Set RunQuery = target.Query(sql, p(0), p(1), p(2))
- Case 3 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3))
- Case 4 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4))
- Case 5 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5))
- Case 6 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6))
- Case 7 : Set RunQuery = target.Query(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6), p(7))
- Case Else
- Err.Raise vbObjectError + 104, "Database_Class", "Too many parameters (" & (UBound(p) + 1) & "); the maximum is 8"
- End Select
- End Function
-
- Private Function RunExec(target, sql, p)
- Select Case UBound(p)
- Case -1 : Set RunExec = target.Exec(sql)
- Case 0 : Set RunExec = target.Exec(sql, p(0))
- Case 1 : Set RunExec = target.Exec(sql, p(0), p(1))
- Case 2 : Set RunExec = target.Exec(sql, p(0), p(1), p(2))
- Case 3 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3))
- Case 4 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4))
- Case 5 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5))
- Case 6 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6))
- Case 7 : Set RunExec = target.Exec(sql, p(0), p(1), p(2), p(3), p(4), p(5), p(6), p(7))
- Case Else
- Err.Raise vbObjectError + 104, "Database_Class", "Too many parameters (" & (UBound(p) + 1) & "); the maximum is 8"
- End Select
- End Function
-
- Private Sub Class_Terminate()
- On Error Resume Next
- If IsObject(m_tx) Then m_tx.Rollback
- If IsObject(m_db) Then m_db.Close
- On Error GoTo 0
- End Sub
- End Class
- %>
|