Opening, traversing and closing DBF/TopConn tables
Organizes owned-workarea lifecycles for DBF and TopConn queries.
Overview
Prepare a test environment and establish alias ownership. For DBF, supply an authorized server file and compatible RDD, open a new read-only area, position with DbGoTop, traverse while !Eof and close only the created alias. For SQL through TopConn, DBUseArea receives TCGenQry as its source argument and requires an available connection. Traverse forward without assuming DbGoTop or negative DbSkip support. The example counts active customers in the scope returned by xFilial without exposing individual records; explicit SQL does not automatically inherit every framework access rule. Verify scope and permissions before execution. (Refs. 1–3) xFilial honors SX2 sharing: a shared-table scope may cover multiple branches. RetSqlName resolves the physical name; ChangeQuery adapts SQL and TCSetField sets the numeric QTDE type. Assumes a valid original workarea for GetArea/RestArea. (Refs. 4–5)
Commented example
#Include "Protheus.ch"
#Include "TopConn.ch"
User Function EdConsulta()
Local aArea := GetArea()
Local cAlias := GetNextAlias()
Local cBranch := StrTran(xFilial("SA1"), "'", "''")
Local cSql := "SELECT COUNT(*) AS QTDE FROM " + RetSqlName("SA1") + ;
" WHERE D_E_L_E_T_ = ' ' AND A1_FILIAL = '" + cBranch + "'"
// Connected Protheus environment; SELECT restricted to a count.
cSql := ChangeQuery(cSql)
DBUseArea(.T., "TOPCONN", TCGenQry(Nil, Nil, cSql), cAlias, .T., .T.)
TCSetField(cAlias, "QTDE", "N", 18, 0)
While !(cAlias)->(Eof())
ConOut(cValToChar((cAlias)->QTDE))
(cAlias)->(DbSkip())
EndDo
(cAlias)->(DbCloseArea())
RestArea(aArea)
Return NilProposal: one count, owned-cursor closing and restoration of the original area on the normal path. For DBF, apply the described sequence to a test copy. Connection failures and exceptional cleanup require project-level handling. Under review: editorial example neither compiled nor run in Protheus. Check includes, release, RDD and context before testing.
- Verification: test empty tables, denied permission, alias collisions and query failure; inspect cleanup and restoration on every path. Do not use DbCloseAll or write transactions for a read demonstration.
- Under review: editorial example neither compiled nor run in Protheus. Check includes, release, RDD and context before testing.

Comments
There are no approved comments yet.
Sign in with Google or Microsoft to comment.