2010-03-07 20:31 UTC+0100 Viktor Szakats (harbour.01 syenar.hu)

* contrib/hbpgsql/tests/tstpgrdd.prg
  * contrib/hbpgsql/tests/async.prg
  * contrib/hbpgsql/tests/test.prg
  * contrib/hbpgsql/tests/cache.prg
  * contrib/hbpgsql/tests/stress.prg
  * contrib/hbpgsql/tests/dbf2pg.prg
    ! Various fixes.
    ! Formatting.
This commit is contained in:
Viktor Szakats
2010-03-07 19:31:54 +00:00
parent bfff433b33
commit 93d5b9b090
7 changed files with 670 additions and 726 deletions

View File

@@ -17,6 +17,16 @@
past entries belonging to author(s): Viktor Szakats.
*/
2010-03-07 20:31 UTC+0100 Viktor Szakats (harbour.01 syenar.hu)
* contrib/hbpgsql/tests/tstpgrdd.prg
* contrib/hbpgsql/tests/async.prg
* contrib/hbpgsql/tests/test.prg
* contrib/hbpgsql/tests/cache.prg
* contrib/hbpgsql/tests/stress.prg
* contrib/hbpgsql/tests/dbf2pg.prg
! Various fixes.
! Formatting.
2010-03-07 19:02 UTC+0100 Viktor Szakats (harbour.01 syenar.hu)
* contrib/hbpgsql/tests/simple.prg
! Fixed typo.

View File

@@ -6,65 +6,68 @@
* This sample show howto use asynchronous/nonblocking queries
*/
Function Main( cServer, cDatabase, cUser, cPass )
Local conn
#include "inkey.ch"
FUNCTION Main( cServer, cDatabase, cUser, cPass )
LOCAL conn
CLEAR SCREEN
? "Connect", conn := PQConnect( cDatabase, cServer, cUser, cPass, 5432)
? "Connect", conn := PQConnect( cDatabase, cServer, cUser, cPass, 5432 )
? "Conection status", PQerrorMessage(conn), PQstatus(conn)
Query( conn, 'SELECT codigo, descri FROM client limit 100', .f. )
Query( conn, 'SELECT codigo, descri FROM fornec limit 100', .f. )
Query( conn, 'SELECT pedido, vlrped FROM pedido', .t. )
Query( conn, "SELECT codigo, descri FROM client limit 100", .F. )
Query( conn, "SELECT codigo, descri FROM fornec limit 100", .F. )
Query( conn, "SELECT pedido, vlrped FROM pedido", .T. )
conn := NIL
return nil
RETURN NIL
Procedure Query( conn, cQuery, lCancel )
Local pCancel, cErrMsg := space(30)
Local res, x, y, xTime
PROCEDURE Query( conn, cQuery, lCancel )
LOCAL pCancel, cErrMsg := Space( 30 )
LOCAL res, x, y, cTime
? "PQSendQuery", PQsendQuery(conn, cQuery)
? "PQSendQuery", PQsendQuery( conn, cQuery )
xTime := time()
cTime := Time()
CLEAR TYPEAHEAD
do while inkey() != 27
DevPos(Row(), 20)
DevOut("Processing: " + Elaptime(xtime, time()))
DO WHILE Inkey() != K_ESC
DevPos( Row(), 20 )
DevOut( "Processing: " + Elaptime( cTime, Time() ) )
inkey(1)
Inkey( 1 )
if lCancel
if .t.
pCancel := PQgetCancel(conn)
IF lCancel
IF .T.
pCancel := PQgetCancel( conn )
? "Canceled: ", PQcancel( pCancel, @cErrMsg ), cErrMsg
pCancel := NIL
else
? PQrequestCancel(conn) // Deprecated
endif
endif
ELSE
? PQrequestCancel( conn ) /* Deprecated */
ENDIF
ENDIF
if PQconsumeInput(conn)
if ! PQisBusy(conn)
exit
endif
endif
enddo
IF PQconsumeInput( conn )
IF ! PQisBusy( conn )
EXIT
ENDIF
ENDIF
ENDDO
if inkey() != 27
? "PQgetResult", hb_valtoexp(res := PQgetResult(conn))
IF Inkey() != K_ESC
? "PQgetResult", hb_valtoexp( res := PQgetResult( conn ) )
for x := 1 to PQlastrec(res)
FOR x := 1 TO PQlastrec( res )
?
for y := 1 to PQfcount(res)
?? PQgetvalue(res, x, y), " "
next
next
else
? "Canceling Query", PQrequestCancel(conn)
endif
Return
FOR y := 1 TO PQfcount( res )
?? PQgetvalue( res, x, y ), " "
NEXT
NEXT
ELSE
? "Canceling Query", PQrequestCancel( conn )
ENDIF
RETURN

View File

@@ -7,142 +7,117 @@
*/
#include "common.ch"
#include "postgres.ch"
#define CONNECTION_OK 0
#define CONNECTION_BAD 1
#define CONNECTION_STARTED 2
#define CONNECTION_MADE 3
#define CONNECTION_AWAITING_RESPONSE 4
#define CONNECTION_AUTH_OK 5
#define CONNECTION_SETENV 6
#define CONNECTION_SSL_STARTUP 7
#define CONNECTION_NEEDED 8
#define DB_ALIAS 1
#define DB_FILE 2
#define DB_QUERY 3
#define DB_ROW 4
#define DB_FETCH 5
#define PGRES_EMPTY_QUERY 0
#define PGRES_COMMAND_OK 1
#define PGRES_TUPLES_OK 2
#define PGRES_COPY_OUT 3
#define PGRES_COPY_IN 4
#define PGRES_BAD_RESPONSE 5
#define PGRES_NONFATAL_ERROR 6
#define PGRES_FATAL_ERROR 7
STATIC s_oServer
STATIC s_aTableTemp := {}
STATIC s_aTempDBF := {}
#define PQTRANS_IDLE 0
#define PQTRANS_ACTIVE 1
#define PQTRANS_INTRANS 2
#define PQTRANS_INERROR 3
#define PQTRANS_UNKNOWN 4
#define DB_ALIAS 1
#define DB_FILE 2
#define DB_QUERY 3
#define DB_ROW 4
#define DB_FETCH 5
STATIC oServer
STATIC aTableTemp := {}
STATIC aTempDBF := {}
Function Main( cServer, cDatabase, cUser, cPass )
Local i
Local cQuery
FUNCTION Main( cServer, cDatabase, cUser, cPass )
LOCAL i
LOCAL cQuery
SetMode( 25, 80 )
if SQLConnect( cServer, cDatabase, cUser, cPass )
QuickQuery('DROP TABLE test')
IF SQLConnect( cServer, cDatabase, cUser, cPass )
QuickQuery( "DROP TABLE test" )
cQuery := 'CREATE TABLE test ( '
cQuery += ' codigo integer primary key, '
cQuery += ' descri char(50), '
cQuery += ' email varchar(50) ) '
SQLQuery(cQuery)
cQuery := "CREATE TABLE test ( "
cQuery += " codigo integer primary key, "
cQuery += " descri char(50), "
cQuery += " email varchar(50) ) "
SQLQuery( cQuery )
SQLOpen( 'nomes', 'SELECT * FROM test')
SQLOpen( "nomes", "SELECT * FROM test" )
for i := 1 to 50
append blank
replace codigo with i
replace descri with 'test ' + str(i)
next
FOR i := 1 TO 50
APPEND BLANK
REPLACE codigo WITH i
REPLACE descri WITH "test " + Str( i )
NEXT
SQLApplyUpdates()
cQuery := 'SELECT * FROM test WHERE codigo >= :1 ORDER BY codigo'
cQuery := "SELECT * FROM test WHERE codigo >= :1 ORDER BY codigo"
cQuery := SQLPrepare( cQuery, 1 )
SQLOpen( 'nomes', cQuery)
SQLOpen( "nomes", cQuery )
Do while ! Eof()
? recno(), nomes->Codigo, nomes->descri, nomes->email
DO WHILE ! Eof()
? RecNo(), nomes->Codigo, nomes->descri, nomes->email
if recno() == 10
delete
endif
IF RecNo() == 10
DELETE
ENDIF
if recno() == 20
REPLACE email WITH 'teste'
endif
IF RecNo() == 20
REPLACE email WITH "teste"
ENDIF
SQLFetch()
enddo
ENDDO
SQLApplyUpdates()
endif
Return SQLGarbageCollector()
ENDIF
RETURN SQLGarbageCollector()
/* Put theses functions in a library */
Function SQLApplyUpdates()
Local cAlias := Upper(Alias())
Local i, x
Local oQuery
Local oRow
Local lUpdate
Local lError := .F.
Local cError
FUNCTION SQLApplyUpdates()
LOCAL cAlias := Upper( Alias() )
LOCAL i, x
LOCAL oQuery
LOCAL oRow
LOCAL lUpdate
LOCAL lError := .F.
LOCAL cError
i := ASCAN(aTableTemp, {|aVal| aVal[DB_ALIAS] == cAlias})
i := AScan( s_aTableTemp, {| aVal | aVal[ DB_ALIAS ] == cAlias } )
IF i != 0
oQuery := aTableTemp[i, 3]
oQuery := s_aTableTemp[ i ][ 3]
FOR i := 1 TO Lastrec()
FOR i := 1 TO LastRec()
DBGoto(i)
dbGoto( i )
IF i > oQuery:Lastrec()
/* Verifica se eh um registro novo */
if ! Deleted()
IF ! Deleted()
oRow := oQuery:GetBlankRow()
FOR x := 1 TO FCount()
if oRow:Fieldpos( Fieldname(x) ) != 0
oRow:FieldPut(Fieldname(x), Fieldget(x))
endif
IF oRow:Fieldpos( FieldName( x ) ) != 0
oRow:FieldPut( FieldName( x ), FieldGet( x ) )
ENDIF
NEXT
oQuery:Append(oRow)
oQuery:Append( oRow )
cError := oQuery:ErrorMsg()
lError := oQuery:NetErr()
endif
ENDIF
ELSE
oRow := oQuery:GetRow(i)
oRow := oQuery:GetRow( i )
lUpdate := .F.
IF Deleted()
oQuery:Delete(oRow)
oQuery:Delete( oRow )
cError := oQuery:ErrorMsg()
lError := oQuery:NetErr()
ELSE
@@ -151,18 +126,18 @@ Function SQLApplyUpdates()
FOR x := 1 TO Fcount()
if oRow:Fieldpos( Fieldname(x) ) != 0
IF oRow:Fieldpos( FieldName( x ) ) != 0
if .not. (Fieldget(x) == oRow:Fieldget(Fieldname(x)))
oRow:Fieldput(Fieldname(x), Fieldget(x))
lUpdate := .t.
endif
endif
IF ! ( Fieldget( x ) == oRow:Fieldget( FieldName( x ) ) )
oRow:Fieldput( FieldName( x ), FieldGet( x ) )
lUpdate := .T.
ENDIF
ENDIF
NEXT
IF lUpdate
oQuery:Update(oRow)
oQuery:Update( oRow )
cError := oQuery:ErrorMsg()
lError := oQuery:NetErr()
@@ -170,175 +145,176 @@ Function SQLApplyUpdates()
ENDIF
ENDIF
if lError
exit
endif
IF lError
EXIT
ENDIF
NEXT
ENDIF
IF lError
Alert(cError)
Alert( cError )
ENDIF
Return ! lError
RETURN ! lError
Procedure SQLCloseTemp( cAlias )
Local x
PROCEDURE SQLCloseTemp( cAlias )
LOCAL x
IF ! Empty(Select(cAlias))
IF ! Empty( Select( cAlias ) )
CLOSE &calias
ENDIF
x := ASCAN(aTableTemp, {|aVal| aVal[DB_ALIAS] == cAlias})
x := AScan( s_aTableTemp, {| aVal | aVal[ DB_ALIAS ] == cAlias } )
IF ! Empty(x)
ADel( aTableTemp, x )
//ASize( aTableTemp, Len(aTableTemp) - 1 )
IF ! Empty( x )
ADel( s_aTableTemp, x )
//ASize( s_aTableTemp, Len( s_aTableTemp ) - 1 )
ENDIF
Return
RETURN
Procedure SQLGarbageCollector()
Local i
Local oQuery
PROCEDURE SQLGarbageCollector()
LOCAL i
LOCAL oQuery
DBCloseAll()
dbCloseAll()
FOR i := 1 TO Len(aTableTemp)
FOR i := 1 TO Len( s_aTableTemp )
/* Apaga arquivos dbfs criados */
FErase(aTableTemp[i, DB_FILE])
oQuery := aTableTemp[i, DB_QUERY]
FErase( s_aTableTemp[ i ][ DB_FILE ] )
oQuery := s_aTableTemp[ i ][ DB_QUERY ]
IF oQuery != NIL
oQuery:Destroy()
ENDIF
NEXT
FOR i := 1 TO Len(aTempDBF)
IF File(aTempDBF[i])
FErase(aTempDBF[i])
FOR i := 1 TO Len( s_aTempDBF )
IF hb_FileExists( s_aTempDBF[ i ] )
FErase( s_aTempDBF[ i ] )
ENDIF
IF File(strtran(aTempDBF[i], '.tmp', '.dbf'))
FErase(strtran(aTempDBF[i], '.tmp', '.dbf'))
IF hb_FileExists( StrTran( s_aTempDBF[ i ], ".tmp", ".dbf" ) )
FErase( StrTran( s_aTempDBF[ i ], ".tmp", ".dbf" ) )
ENDIF
IF File(strtran(aTempDBF[i], '.tmp', '.dbt'))
FErase(strtran(aTempDBF[i], '.tmp', '.dbt'))
IF hb_FileExists( StrTran(s_aTempDBF[ i ], ".tmp", ".dbt" ) )
FErase( StrTran( s_aTempDBF[ i ], ".tmp", ".dbt" ) )
ENDIF
NEXT
aTableTemp := {}
aTempDBF := {}
Return
s_aTableTemp := {}
s_aTempDBF := {}
RETURN
Function SQLFetch( fetchall )
Local oQuery
Local oRow
Local cAlias := Upper(Alias())
Local i, x, y
Local nPos
Local lEof := .F.
FUNCTION SQLFetch( fetchall )
LOCAL oQuery
LOCAL oRow
LOCAL cAlias := Upper( Alias() )
LOCAL i, x, y
LOCAL nPos
LOCAL lEof := .F.
Default Fetchall TO .f.
DEFAULT Fetchall TO .F.
/* Procura pela tabela no array */
i := ASCAN(aTableTemp, {|aVal| aVal[DB_ALIAS] == cAlias})
i := AScan( s_aTableTemp, {| aVal | aVal[ DB_ALIAS ] == cAlias } )
IF i != 0
/* Traz registros da base de dados */
oQuery := aTableTemp[i, DB_QUERY]
nPos := aTableTemp[i, DB_ROW] + 1
oQuery := s_aTableTemp[ i ][ DB_QUERY ]
nPos := s_aTableTemp[ i ][ DB_ROW ] + 1
if Fetchall
aTableTemp[i, DB_FETCH] := .t.
endif
IF Fetchall
s_aTableTemp[ i ][ DB_FETCH ] := .T.
ENDIF
IF oQuery:Lastrec() >= nPos
y := nPos
do while nPos <= IIF( FetchAll, oQuery:Lastrec(), y )
oRow := oQuery:GetRow(nPos)
DBAppend()
DO WHILE nPos <= iif( FetchAll, oQuery:Lastrec(), y )
oRow := oQuery:GetRow( nPos )
dbAppend()
FOR x := 1 TO oRow:FCount()
FieldPut( FieldPos( oRow:FieldName(x) ), oRow:FieldGet(x) )
FieldPut( FieldPos( oRow:FieldName( x ) ), oRow:FieldGet( x ) )
NEXT
aTableTemp[i, DB_ROW] := nPos
s_aTableTemp[ i ][ DB_ROW ] := nPos
nPos++
enddo
ENDDO
ELSE
// Posiciona registro no eof
DBSkip()
dbSkip()
ENDIF
lEof := nPos > oQuery:Lastrec()
ENDIF
return lEof
RETURN lEof
Procedure SQLFetchAll()
SQLFetch(.t.); DBGotop()
Return
PROCEDURE SQLFetchAll()
SQLFetch( .T. )
dbGotop()
RETURN
Function SQLOpen( cAlias, cQuery, xFetch, cOrder )
Local cFile
Local Result := .t.
Local x
Local oServer
Local oQuery
Local aStrudbf
Local lFetch
FUNCTION SQLOpen( cAlias, cQuery, xFetch, cOrder )
LOCAL cFile
LOCAL Result := .t.
LOCAL x
LOCAL s_oServer
LOCAL oQuery
LOCAL aStrudbf
LOCAL lFetch
oServer := SQLCurrentServer()
cAlias := Upper(cAlias)
s_oServer := SQLCurrentServer()
cAlias := Upper( cAlias )
/* Procura por query na area temporaria */
x := ASCAN(aTableTemp, {|aVal| aVal[DB_ALIAS] == cAlias})
x := AScan( s_aTableTemp, {| aVal | aVal[ DB_ALIAS ] == cAlias } )
IF ! Empty(x)
oQuery := aTableTemp[x, 3]
IF ! Empty( x )
oQuery := s_aTableTemp[ x ][ 3 ]
oQuery:Destroy()
ENDIF
IF cQuery == NIL
cQuery := 'SELECT * FROM ' + cAlias
cQuery := "SELECT * FROM " + cAlias
IF ! Empty( cOrder )
cQuery += ' ORDER BY ' + cOrder
cQuery += " ORDER BY " + cOrder
ENDIF
ENDIF
cQuery := cQuery
oQuery := oServer:Query(cQuery)
oQuery := s_oServer:Query( cQuery )
IF oQuery:NetErr()
Alert(oQuery:ErrorMsg())
Alert( oQuery:ErrorMsg() )
RETURN .F.
ENDIF
IF Empty(Select(cAlias))
IF Empty( Select( cAlias ) )
/* Pega estrutura da base de dados */
aStrudbf := oQuery:Struct()
/* Cria tabela */
cFile := TempFile()
DBCreate( cFile, aStrudbf )
dbCreate( cFile, aStrudbf )
/* Abre Tabela */
DBUseArea(.T., NIL, cFile, cAlias, .F.)
dbUseArea( .T., NIL, cFile, cAlias, .F. )
ELSE
SELECT &cAlias
Zap
ZAP
ENDIF
IF xFetch != NIL
@@ -348,245 +324,230 @@ Function SQLOpen( cAlias, cQuery, xFetch, cOrder )
ENDIF
/* Se nao houver query na area temporaria entao adiciona, caso contrario, apenas atualiza */
IF Empty(x)
AADD( aTableTemp, { cAlias,; // Table Name
cFile,; // Temporary File Name
oQuery,; // Object Query
0,; // Current Row
lFetch } ) // Fetch Status
IF Empty( x )
AAdd( s_aTableTemp, { cAlias,; // Table Name
cFile,; // Temporary File Name
oQuery,; // Object Query
0,; // Current Row
lFetch } ) // Fetch Status
ELSE
aTableTemp[ x, DB_QUERY ] := oQuery
aTableTemp[ x, DB_ROW ] := 0
aTableTemp[ x, DB_FETCH ] := lFetch
s_aTableTemp[ x ][ DB_QUERY ] := oQuery
s_aTableTemp[ x ][ DB_ROW ] := 0
s_aTableTemp[ x ][ DB_FETCH ] := lFetch
ENDIF
/* Traz registros da base de dados */
SQLFetch(lFetch)
SQLFetch( lFetch )
IF lFetch
DBGotop()
dbGotop()
ENDIF
Return result
RETURN result
Function SQLConnect( cServer, cDatabase, cUser, cPassword, cSchema )
Local lRetval := .t.
FUNCTION SQLConnect( cServer, cDatabase, cUser, cPassword, cSchema )
LOCAL lRetval := .t.
oServer := TPQServer():New(cServer, cDatabase, cUser, cPassWord, 5432, cSchema)
if oServer:NetErr()
Alert(oServer:ErrorMsg())
lRetval := .f.
endif
oServer:lAllCols := .F.
Return lRetval
Procedure SQLDestroy()
if oServer != NIL
oServer:Destroy()
endif
return
Function SQLCurrentServer
Return oServer
Function SQLQuery( cQuery )
Local oQuery
oQuery := oServer:Query(cQuery)
IF oQuery:NetErr()
Alert(cQuery + ':' + oQuery:ErrorMsg())
s_oServer := TPQServer():New( cServer, cDatabase, cUser, cPassWord, 5432, cSchema )
IF s_oServer:NetErr()
Alert( s_oServer:ErrorMsg() )
lRetval := .F.
ENDIF
Return oQuery
s_oServer:lAllCols := .F.
RETURN lRetval
Function SQLExecQuery( cQuery )
Local oQuery
Local result := .T.
PROCEDURE SQLDestroy()
IF s_oServer != NIL
s_oServer:Destroy()
ENDIF
RETURN
FUNCTION SQLCurrentServer
RETURN s_oServer
FUNCTION SQLQuery( cQuery )
LOCAL oQuery := s_oServer:Query( cQuery )
oQuery := oServer:Query(cQuery)
IF oQuery:NetErr()
Alert('Nao foi possível executar ' + cQuery + ':' + oQuery:ErrorMsg())
Alert( cQuery + ":" + oQuery:ErrorMsg() )
ENDIF
RETURN oQuery
FUNCTION SQLExecQuery( cQuery )
LOCAL oQuery
LOCAL result := .T.
oQuery := s_oServer:Query( cQuery )
IF oQuery:NetErr()
Alert( "Nao foi possível executar " + cQuery + ":" + oQuery:ErrorMsg() )
result := .F.
ELSE
oQuery:Destroy()
ENDIF
Return result
RETURN result
Function SQLPrepare( cQuery, ... )
Local i, x
FUNCTION SQLPrepare( cQuery, ... )
LOCAL i, x
if Pcount() >= 2
IF Pcount() >= 2
/* Limpa espacos desnecessarios */
do while at( Space(2), cQuery ) != 0
cQuery := strtran( cQuery, Space(2), Space(1) )
enddo
DO WHILE At( Space( 2 ), cQuery ) != 0
cQuery := StrTran( cQuery, Space( 2 ), Space( 1 ) )
ENDDO
/* Coloca {} nos parametros */
for i := 1 to Pcount() - 1
if ! empty(x := at( ':' + ltrim(str(i)), cQuery))
cQuery := stuff( cQuery, x, 0, '{' )
cQuery := stuff( cQuery, x + len(ltrim(str(i))) + 2, 0, '}' )
endif
next
FOR i := 1 TO Pcount() - 1
IF ! Empty( x := At( ":" + hb_ntos( i ), cQuery ) )
cQuery := Stuff( cQuery, x, 0, "{" )
cQuery := Stuff( cQuery, x + Len( hb_ntos( i ) ) + 2, 0, "}" )
ENDIF
NEXT
/* Substitui parametros por valores passados */
for i := 2 to PCount()
x := hb_PValue(i)
FOR i := 2 TO PCount()
x := hb_PValue( i )
if x != NIL .and. Empty(x)
x := 'null'
IF x != NIL .AND. Empty( x )
x := "null"
elseif valtype(x) == 'N'
x := ltrim(str(x))
ELSEIF ValType( x ) == "N"
x := hb_ntos( x )
elseif valtype(x) == 'D'
x := DtoQ(x)
ELSEIF ValType( x ) == "D"
x := DToQ( x )
elseif valtype(x) == 'L'
x := IIF( x, "'t'", "'f'" )
ELSEIF ValType( x ) == "L"
x := iif( x, "'t'", "'f'" )
elseif valtype(x) == "C" .or. valtype(x) == 'M'
x := StoQ(Trim(x))
ELSEIF ValType( x ) == "C" .OR. ValType( x ) == "M"
x := SToQ( RTrim( x ) )
else
x := 'null'
endif
ELSE
x := "null"
ENDIF
cQuery := strtran(cQuery, '{:' + ltrim(str(i-1)) + '}', x)
next
endif
cQuery := StrTran( cQuery, "{:" + hb_ntos( i - 1 ) + "}", x )
NEXT
ENDIF
cQuery := strtran(cQuery, '==', '=')
cQuery := strtran(cQuery, '!=', '<>')
cQuery := strtran(cQuery, '.and.', 'and')
cQuery := strtran(cQuery, '.or.', 'or')
cQuery := strtran(cQuery, '.not.', 'not')
Return cQuery
cQuery := StrTran( cQuery, "==", "=" )
cQuery := StrTran( cQuery, "!=", "<>" )
cQuery := StrTran( cQuery, ".and.", "and" )
cQuery := StrTran( cQuery, ".or.", "or" )
cQuery := StrTran( cQuery, ".not.", "not" )
RETURN cQuery
/* Pega resultado de uma sequence */
Function SQLSequence( Sequence_name )
Local nValue
nValue := Val(QuickQuery("SELECT nextval(" + StoQ(sequence_name) + ")" ))
Return nValue
FUNCTION SQLSequence( Sequence_name )
RETURN Val( QuickQuery( "SELECT nextval(" + SToQ( sequence_name ) + ")" ) )
Function SQLStartTrans()
if PQtransactionstatus(oServer:pDB) != PQTRANS_INTRANS
oServer:StartTransaction()
endif
Return nil
PROCEDURE SQLStartTrans()
IF PQtransactionstatus( s_oServer:pDB ) != PQTRANS_INTRANS
s_oServer:StartTransaction()
ENDIF
RETURN
Function SQLInTrans()
Local result
result := (PQtransactionstatus(oServer:pDB) == PQTRANS_INTRANS)
Return result
FUNCTION SQLInTrans()
RETURN PQtransactionstatus( s_oServer:pDB ) == PQTRANS_INTRANS
Function SQLCommitTrans()
oServer:Commit()
Return nil
PROCEDURE SQLCommitTrans()
s_oServer:Commit()
RETURN
Function SQLRollbackTrans()
oServer:rollback()
Return nil
PROCEDURE SQLRollbackTrans()
s_oServer:rollback()
RETURN
/* Faz querie que retorna apenas 1 valor de coluna */
Function QuickQuery( cQuery )
Local pQuery
Local result := ""
Local temp, aTemp
Local x, y
FUNCTION QuickQuery( cQuery )
LOCAL pQuery
LOCAL result := ""
LOCAL temp, aTemp
LOCAL x, y
pQuery := PQexec( oServer:pDB, cQuery )
pQuery := PQexec( s_oServer:pDB, cQuery )
if PQresultstatus(pQuery) == PGRES_TUPLES_OK
if PQLastrec(pQuery) != 0
if PQFcount(pQuery) == 1 .and. PQLastrec(pQuery) == 1
IF PQresultstatus( pQuery ) == PGRES_TUPLES_OK
IF PQLastrec( pQuery ) != 0
IF PQFcount( pQuery ) == 1 .and. PQLastrec( pQuery ) == 1
temp := PQGetValue( pQuery, 1, 1 )
result := iif( temp == NIL, "", temp )
else
ELSE
result := {}
for x := 1 to PQLastrec(pQuery)
FOR x := 1 TO PQLastrec( pQuery )
aTemp := {}
for y := 1 to PQfcount(pQuery)
FOR y := 1 TO PQfcount( pQuery )
temp := PQGetValue( pQuery, x, y )
aadd( aTemp, iif( temp == NIL, "", temp ) )
next
aadd(result, aTemp)
next
endif
endif
endif
Return result
AAdd( aTemp, iif( temp == NIL, "", temp ) )
NEXT
AAdd( result, aTemp )
NEXT
ENDIF
ENDIF
ENDIF
RETURN result
Procedure MakeDBF( cAlias, aStructure, aIndex )
Local cFile, i, cIndex, cKey
PROCEDURE MakeDBF( cAlias, aStructure, aIndex )
LOCAL cFile, i, cIndex, cKey
Default aIndex TO {}
DEFAULT aIndex TO {}
cFile := TempFile()
DBCreate( cFile, aStructure )
dbCreate( cFile, aStructure )
/* Abre Tabela */
DBUseArea(.T., NIL, cFile, cAlias, .F.)
dbUseArea( .T., NIL, cFile, cAlias, .F. )
For i := 1 to Len(aIndex)
cKey := aIndex[i]
FOR i := 1 TO Len( aIndex )
cKey := aIndex[ i ]
cIndex := TempFile()
Index On &cKey To &cIndex
aadd( aTempDBF, cIndex)
Next
INDEX ON &cKey TO &cIndex
AADD( aTempDBF, cFile )
AAdd( s_aTempDBF, cIndex)
NEXT
return
AAdd( s_aTempDBF, cFile )
RETURN
Function DirTmp()
Local xDirectory
xDirectory := IIF(Empty(Getenv("TMP")), Getenv("TEMP"), Getenv("TMP"))
FUNCTION TempFile( cPath, cExt )
LOCAL cString
IF Empty(xDirectory)
xDirectory := ''
ENDIF
DEFAULT cPath TO hb_DirTemp()
DEFAULT cExt TO "tmp"
IF ';' $ xDirectory
xDirectory := LEFT( xDirectory, AT( ';', xDirectory ) - 1 )
ENDIF
cString := cPath + StrZero( Int( hb_random( Val( StrTran( Time(), ":", "" ) ) ) ), 8 ) + "." + cExt
RETURN xDirectory + IIF( Right(xDirectory, 1) != '\' .and. ! Empty(xDirectory), '\', '' )
Function TempFile( cPath, cExt )
Local cString
Default cPath to DirTmp(),;
cExt to 'tmp'
cString := cPath + strzero(int(hb_random(val(strtran(time(), ":", "")))), 8) + '.' + cExt
DO WHILE File( cString )
cString := cPath + strzero(int(hb_random(val(strtran(time(), ":", "")))), 8) + '.' + cExt
DO WHILE hb_FileExists( cString )
cString := cPath + StrZero( Int( hb_random( Val( StrTran( Time(), ":", "" ) ) ) ), 8 ) + "." + cExt
ENDDO
Return cString
RETURN cString
Function DtoQ(cData)
Return "'" + Str(Year(cData),4) + "-" + StrZero(Month(cData), 2) + "-" + StrZero(Day(cData), 2) + "'"
FUNCTION DToQ( cData )
RETURN "'" + Str( Year( cData ), 4 ) + "-" + StrZero( Month( cData ), 2 ) + "-" + StrZero( Day( cData ), 2 ) + "'"
Function StoQ(cData)
Return "'" + cData + "'"
FUNCTION SToQ( cData )
RETURN "'" + cData + "'"

View File

@@ -7,7 +7,8 @@
* dbf2pg.prg - converts a .dbf file into a Postgres table
*
* Copyright 2000 Maurilio Longo <maurilio.longo@libero.it>
* www - http://www.harbour-project.org
* (The Original file was ported from Mysql and changed by Rodrigo Moreno rodrigo_moreno@yahoo.com)
* * www - http://www.harbour-project.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -48,265 +49,260 @@
* whether to permit this exception to apply to your modifications.
* If you do not wish that, delete this exception notice.
*
* The Original file was ported from Mysql and changed by Rodrigo Moreno rodrigo_moreno@yahoo.com
*
*/
#include "inkey.ch"
#include "common.ch"
#define CRLF chr(13) + chr(10)
PROCEDURE Main( ... )
procedure main(...)
local cTok
local cHostName := "localhost"
local cUser := "postgres"
local cPassWord := ""
local cDataBase, cTable, cFile
local aDbfStruct, i
local lCreateTable := .F.
local oServer, oTable, oRecord
Local cField
Local sType
Local dType
Local cValue
Local nCommit := 100
Local nHandle
Local nCount := 0
Local nRecno := 0
Local lTruncate := .F.
Local lUseTrans := .F.
Local cPath := 'public'
LOCAL cTok
LOCAL cHostName := "localhost"
LOCAL cUser := "postgres"
LOCAL cPassWord := ""
LOCAL cDataBase, cTable, cFile
LOCAL aDbfStruct, i
LOCAL lCreateTable := .F.
LOCAL oServer, oTable, oRecord
LOCAL cField
LOCAL sType
LOCAL dType
LOCAL cValue
LOCAL nCommit := 100
LOCAL nHandle
LOCAL nCount := 0
LOCAL nRecno := 0
LOCAL lTruncate := .F.
LOCAL lUseTrans := .F.
LOCAL cPath := "public"
SET CENTURY ON
SET DATE ANSI
SET EPOCH TO 1960
SET DELETE ON
SET DATE FORMAT "dd/mm/yyyy"
rddSetDefault( "DBFDBT" )
if PCount() < 6
IF PCount() < 6
help()
quit
endif
QUIT
ENDIF
i := 1
// Scan parameters and setup workings
while (i <= PCount())
/* Scan parameters and setup workings */
DO WHILE i <= PCount()
cTok := hb_PValue(i++)
cTok := hb_PValue( i++ )
do case
case cTok == "-h"
cHostName := hb_PValue(i++)
DO CASE
CASE cTok == "-h"
cHostName := hb_PValue( i++ )
case cTok == "-d"
cDataBase := hb_PValue(i++)
CASE cTok == "-d"
cDataBase := hb_PValue( i++ )
case cTok == "-t"
cTable := hb_PValue(i++)
CASE cTok == "-t"
cTable := hb_PValue( i++ )
case cTok == "-f"
cFile := hb_PValue(i++)
CASE cTok == "-f"
cFile := hb_PValue( i++ )
case cTok == "-u"
cUser := hb_PValue(i++)
CASE cTok == "-u"
cUser := hb_PValue( i++ )
case cTok == "-p"
cPassWord := hb_PValue(i++)
CASE cTok == "-p"
cPassWord := hb_PValue( i++ )
case cTok == "-c"
CASE cTok == "-c"
lCreateTable := .T.
case cTok == "-x"
CASE cTok == "-x"
lTruncate := .T.
case cTok == "-s"
CASE cTok == "-s"
lUseTrans := .T.
case cTok == "-m"
nCommit := val(hb_PValue(i++))
CASE cTok == "-m"
nCommit := Val( hb_PValue( i++ ) )
case cTok == "-r"
nRecno := val(hb_PValue(i++))
CASE cTok == "-r"
nRecno := Val( hb_PValue( i++ ) )
case cTok == "-e"
cPath := hb_PValue(i++)
CASE cTok == "-e"
cPath := hb_PValue( i++ )
otherwise
OTHERWISE
help()
quit
endcase
enddo
QUIT
ENDCASE
ENDDO
// create log file
if (nHandle := FCreate(Trim(cTable) + '.log')) == -1
? 'Cannot create log file'
quit
endif
IF ( nHandle := FCreate( RTrim( cTable ) + ".log" ) ) == -1
? "Cannot create log file"
QUIT
ENDIF
USE (cFile) SHARED
USE ( cFile ) SHARED
aDbfStruct := DBStruct()
oServer := TPQServer():New(cHostName, cDatabase, cUser, cPassWord, nil, cPath)
if oServer:NetErr()
oServer := TPQServer():New( cHostName, cDatabase, cUser, cPassWord, NIL, cPath )
IF oServer:NetErr()
? oServer:ErrorMsg()
quit
endif
QUIT
ENDIF
oServer:lallCols := .F.
if lCreateTable
if oServer:TableExists(cTable)
oServer:DeleteTable(cTable)
if oServer:NetErr()
IF lCreateTable
IF oServer:TableExists( cTable )
oServer:DeleteTable( cTable )
IF oServer:NetErr()
? oServer:ErrorMsg()
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + CRLF )
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + hb_osNewLine() )
FClose( nHandle )
quit
endif
endif
oServer:CreateTable(cTable, aDbfStruct)
QUIT
ENDIF
ENDIF
oServer:CreateTable( cTable, aDbfStruct )
if oServer:NetErr()
IF oServer:NetErr()
? oServer:ErrorMsg()
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + CRLF )
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + hb_osNewLine() )
FClose( nHandle )
quit
endif
endif
QUIT
ENDIF
ENDIF
if lTruncate
oServer:Execute('truncate table ' + cTable)
if oServer:NetErr()
? oServer:ErrorMsg()
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + CRLF )
FClose( nHandle )
quit
endif
endif
IF lTruncate
oServer:Execute( "truncate table " + cTable )
IF oServer:NetErr()
? oServer:ErrorMsg()
FWrite( nHandle, "Error: " + oServer:ErrorMsg() + hb_osNewLine() )
FClose( nHandle )
QUIT
ENDIF
ENDIF
oTable := oServer:Query("SELECT * FROM " + cTable + " LIMIT 1")
if oTable:NetErr()
Alert(oTable:ErrorMsg())
FWrite( nHandle, "Error: " + oTable:ErrorMsg() + CRLF )
oTable := oServer:Query( "SELECT * FROM " + cTable + " LIMIT 1" )
IF oTable:NetErr()
Alert( oTable:ErrorMsg() )
FWrite( nHandle, "Error: " + oTable:ErrorMsg() + hb_osNewLine() )
FClose( nHandle )
quit
endif
QUIT
ENDIF
if lUseTrans
IF lUseTrans
oServer:StartTransaction()
endif
ENDIF
FWrite( nHandle, "Start: " + time() + CRLF )
FWrite( nHandle, "Start: " + Time() + hb_osNewLine() )
? "Start: ", time()
? "Start: ", Time()
?
if ! Empty(nRecno)
dbgoto(nRecno)
endif
IF ! Empty( nRecno )
dbGoto( nRecno )
ENDIF
do while ! eof() .and. Inkey() != K_ESC .and. (empty(nRecno) .or. nRecno == recno())
DO WHILE ! Eof() .AND. Inkey() != K_ESC .AND. ( Empty( nRecno ) .OR. nRecno == RecNo() )
oRecord := oTable:GetBlankRow()
for i := 1 to oTable:FCount()
cField := lower(oTable:FieldName(i))
sType := fieldtype(fieldpos(cField))
dType := oRecord:Fieldtype(i)
cValue := fieldget(fieldpos(cField))
FOR i := 1 TO oTable:FCount()
cField := Lower( oTable:FieldName( i ) )
sType := FieldType( FieldPos( cField ) )
dType := oRecord:Fieldtype( i )
cValue := FieldGet( FieldPos( cField ) )
if cValue != NIL
if dType != sType
if dType == 'C' .and. sType == 'N'
cValue := Str(cValue)
IF cValue != NIL
IF dType != sType
IF dType == "C" .AND. sType == "N"
cValue := Str( cValue )
elseif dType == 'C' .and. sType == 'D'
cValue := DtoC(cValue)
ELSEIF dType == "C" .AND. sType == "D"
cValue := DToC( cValue )
elseif dType == 'C' .and. sType == 'L'
cValue := IIF( cValue, "S", "N" )
ELSEIF dType == "C" .AND. sType == "L"
cValue := iif( cValue, "S", "N" )
elseif dType == 'N' .and. sType == 'C'
cValue := val(cValue)
ELSEIF dType == "N" .AND. sType == "C"
cValue := Val( cValue )
elseif dType == 'N' .and. sType == 'D'
cValue := Val(DtoS(cValue))
ELSEIF dType == "N" .AND. sType == "D"
cValue := Val( DToS( cValue ) )
elseif dType == 'N' .and. sType == 'L'
cValue := IIF( cValue, 1, 0 )
ELSEIF dType == "N" .AND. sType == "L"
cValue := iif( cValue, 1, 0 )
elseif dType == 'D' .and. sType == 'C'
cValue := CtoD(cValue)
ELSEIF dType == "D" .AND. sType == "C"
cValue := CToD( cValue )
elseif dType == 'D' .and. sType == 'N'
cValue := StoD(Str(cValue))
ELSEIF dType == "D" .AND. sType == "N"
cValue := SToD( Str( cValue ) )
elseif dType == 'L' .and. sType == 'N'
cValue := ! Empty(cValue)
ELSEIF dType == "L" .AND. sType == "N"
cValue := ! Empty( cValue )
elseif dType == 'L' .and. sType == 'C'
cValue := IIF( alltrim(cValue) $ "YySs1", .T., .F. )
ELSEIF dType == "L" .AND. sType == "C"
cValue := iif( AllTrim( cValue ) $ "YySs1", .T., .F. )
endif
endif
ENDIF
ENDIF
if cValue != NIL
if oRecord:Fieldtype(i) == 'C' .or. oRecord:Fieldtype(i) == 'M'
oRecord:FieldPut(i, hb_oemtoansi(cValue))
else
oRecord:FieldPut(i, cValue)
endif
endif
endif
next
IF cValue != NIL
IF oRecord:Fieldtype( i ) == "C" .OR. oRecord:Fieldtype( i ) == "M"
oRecord:FieldPut( i, hb_oemtoansi( cValue ) )
ELSE
oRecord:FieldPut( i, cValue )
ENDIF
ENDIF
ENDIF
NEXT
oTable:Append(oRecord)
if oTable:NetErr()
IF oTable:NetErr()
?
? "Error Record: ", recno(), left(oTable:ErrorMsg(),70)
? "Error Record: ", RecNo(), Left( oTable:ErrorMsg(), 70 )
?
FWrite( nHandle, "Error at record: " + Str(recno()) + " Description: " + oTable:ErrorMsg() + CRLF )
else
FWrite( nHandle, "Error at record: " + Str( RecNo() ) + " Description: " + oTable:ErrorMsg() + hb_osNewLine() )
ELSE
nCount++
endif
ENDIF
dbSkip()
if (nCount % nCommit) == 0
DevPos(Row(), 1)
DevOut("imported recs: " + Str(nCount))
IF ( nCount % nCommit ) == 0
DevPos( Row(), 1 )
DevOut( "imported recs: " + Str( nCount ) )
if lUseTrans
IF lUseTrans
oServer:commit()
oServer:StartTransaction()
endif
endif
enddo
ENDIF
ENDIF
ENDDO
if (nCount % nCommit) != 0
if lUseTrans
oServer:commit()
endif
endif
IF ( nCount % nCommit ) != 0
IF lUseTrans
oServer:commit()
ENDIF
ENDIF
FWrite( nHandle, "End: " + time() + ", records in dbf: " + ltrim(str(recno())) + ", imported recs: " + ltrim(str(nCount)) + CRLF )
FWrite( nHandle, "End: " + Time() + ", records in dbf: " + hb_ntos( RecNo() ) + ", imported recs: " + hb_ntos( nCount ) + hb_osNewLine() )
? "End: ", time()
? "End: ", Time()
?
FClose( nHandle )
close all
CLOSE ALL
oTable:Destroy()
oServer:Destroy()
return
RETURN
procedure Help()
PROCEDURE Help()
? "dbf2pg - dbf file to PostgreSQL table conversion utility"
? "-h hostname (default: localhost)"
@@ -324,4 +320,4 @@ procedure Help()
? ""
return
RETURN

View File

@@ -9,119 +9,99 @@
#include "common.ch"
#include "postgres.ch"
Function Main( cServer, cDatabase, cUser, cPass )
Local conn, res, i, x
PROCEDURE Main( cServer, cDatabase, cUser, cPass )
LOCAL conn, res, i, x
Local cQuery
LOCAL cQuery
CLEAR SCREEN
? 'Connecting....'
conn := PQconnect(cDatabase, cServer, cUser, cPass, 5432)
? "Connecting...."
conn := PQconnect( cDatabase, cServer, cUser, cPass, 5432 )
? PQstatus(conn), PQerrormessage(conn)
? PQstatus( conn ), PQerrormessage( conn )
if PQstatus(conn) != CONNECTION_OK
quit
endif
IF PQstatus( conn ) != CONNECTION_OK
QUIT
ENDIF
? 'Dropping table...'
? "Dropping table..."
res := PQexec(conn, 'DROP TABLE test')
res := NIL
PQexec( conn, "DROP TABLE test" )
? 'Creating test table...'
cQuery := 'CREATE TABLE test('
cQuery += ' Code integer not null primary key, '
cQuery += ' dept Integer, '
cQuery += ' Name Varchar(40), '
cQuery += ' Sales boolean, '
cQuery += ' Tax Float4, '
cQuery += ' Salary Double Precision, '
cQuery += ' Budget Numeric(12,2), '
cQuery += ' Discount Numeric (5,2), '
cQuery += ' Creation Date, '
cQuery += ' Description text ) '
? "Creating test table..."
cQuery := "CREATE TABLE test("
cQuery += " Code integer not null primary key, "
cQuery += " dept Integer, "
cQuery += " Name Varchar(40), "
cQuery += " Sales boolean, "
cQuery += " Tax Float4, "
cQuery += " Salary Double Precision, "
cQuery += " Budget Numeric(12,2), "
cQuery += " Discount Numeric(5,2), "
cQuery += " Creation Date, "
cQuery += " Description text ) "
res := PQexec(conn, cQuery)
res := NIL
PQexec( conn, cQuery )
PQexec( conn, "SELECT code, dept, name, sales, salary, creation FROM test" )
PQexec( conn, "BEGIN" )
res := PQexec(conn, 'SELECT code, dept, name, sales, salary, creation FROM test')
res := NIL
FOR i := 1 TO 10000
@ 15, 0 SAY "Inserting values...." + Str( i )
res := PQexec(conn, 'BEGIN')
res := NIL
cQuery := "INSERT INTO test(code, dept, name, sales, salary, creation) " +;
"VALUES( " + Str( i ) + "," + Str( i + 1 ) + ", 'DEPARTMENT NAME " + StrZero( i ) + "', 'y', " + Str( 300.49 + i ) + ", '2003-12-28' )"
For i := 1 to 10000
@ 15,0 say 'Inserting values....' + str(i)
PQexec( conn, cQuery )
cQuery := 'INSERT INTO test(code, dept, name, sales, salary, creation) '
cQuery += 'VALUES( ' + str(i) + ',' + str(i+1) + ", 'DEPARTMENT NAME " + strzero(i) + "', 'y', " + str(300.49+i) + ", '2003-12-28' )"
IF Mod( i, 100 ) == 0
? PQexec(conn, "COMMIT")
? PQexec(conn, "BEGIN")
ENDIF
NEXT
res := PQexec(conn, cQuery)
res := NIL
FOR i := 5000 TO 7000
@ 16, 0 SAY "Deleting values...." + Str( i )
if mod(i,100) == 0
? res := PQexec(conn, 'COMMIT')
? res := NIL
cQuery := "DELETE FROM test WHERE code = " + Str( i )
PQexec( conn, cQuery )
? res := PQexec(conn, 'BEGIN')
? res := NIL
endif
Next
IF Mod( i, 100 ) == 0
PQexec( conn, "COMMIT" )
PQexec( conn, "BEGIN" )
ENDIF
NEXT
For i := 5000 to 7000
@ 16,0 say 'Deleting values....' + str(i)
FOR i := 2000 TO 3000
@ 17, 0 SAY "Updating values...." + Str( i )
cQuery := 'DELETE FROM test WHERE code = ' + str(i)
res := PQexec(conn, cQuery)
res := NIL
cQuery := "UPDATE FROM test SET salary = 400 WHERE code = " + str( i )
PQexec( conn, cQuery )
if mod(i,100) == 0
res := PQexec(conn, 'COMMIT')
res := NIL
IF Mod( i, 100 ) == 0
PQexec( conn, "COMMIT" )
PQexec( conn, "BEGIN" )
ENDIF
NEXT
res := PQexec(conn, 'BEGIN')
res := NIL
endif
Next
res := PQexec( conn, "SELECT sum(salary) as sum_salary FROM test WHERE code between 1 and 4000" )
For i := 2000 to 3000
@ 17,0 say 'Updating values....' + str(i)
cQuery := 'UPDATE FROM test SET salary = 400 WHERE code = ' + str(i)
res := PQexec(conn, cQuery)
res := NIL
if mod(i,100) == 0
res := PQexec(conn, 'COMMIT')
res := NIL
res := PQexec(conn, 'BEGIN')
res := NIL
endif
Next
res := PQexec(conn, 'SELECT sum(salary) as sum_salary FROM test WHERE code between 1 and 4000')
if PQresultStatus(res) == PGRES_TUPLES_OK
@ 18,0 say 'Sum values....' + PQgetvalue(res, 1, 1)
endif
res := NIL
IF PQresultStatus( res ) == PGRES_TUPLES_OK
@ 18, 0 SAY "Sum values...." + PQgetvalue( res, 1, 1 )
ENDIF
x := 0
For i := 1 to 4000
res := PQexec(conn, 'SELECT salary FROM test WHERE code = ' + str(i))
FOR i := 1 TO 4000
res := PQexec( conn, "SELECT salary FROM test WHERE code = " + Str( i ) )
if PQresultStatus(res) == PGRES_TUPLES_OK
x += val(PQgetvalue(res, 1, 1))
IF PQresultStatus( res ) == PGRES_TUPLES_OK
x += Val( PQgetvalue( res, 1, 1 ) )
@ 19,0 say 'Sum values....' + str(x)
endif
Next
@ 19, 0 SAY "Sum values...." + Str( x )
ENDIF
NEXT
? "Closing..."
conn := NIL
return nil
RETURN

View File

@@ -4,96 +4,88 @@
#include "postgres.ch"
Function main()
Local conn, res, aTemp, x, y, pFile
Local cDb := 'test'
Local cUser := 'user'
Local cPass := 'pass'
PROCEDURE main()
LOCAL conn, res, aTemp, x, y, pFile
LOCAL cDb := "test"
LOCAL cUser := "user"
LOCAL cPass := "pass"
CLEAR SCREEN
conn := PQsetdbLogin( 'localhost', "5432", NIL, NIL, cDb, cUser, cPass)
? PQdb(conn), PQuser(conn), PQpass(conn), PQhost(conn), PQport(conn), PQtty(conn), PQoptions(conn)
? conn := NIL
conn := PQsetdbLogin( "localhost", "5432", NIL, NIL, cDb, cUser, cPass )
? PQdb( conn ), PQuser( conn ), PQpass( conn ), PQhost( conn ), PQport( conn ), PQtty( conn ), PQoptions( conn )
conn := PQConnect(cDb, 'localhost', cuser, cpass, 5432)
conn := PQConnect( cDb, "localhost", cuser, cpass, 5432 )
? PQstatus(conn), PQerrormessage(conn)
? PQstatus( conn ), PQerrormessage( conn )
if PQstatus(conn) != CONNECTION_OK
quit
endif
IF PQstatus( conn ) != CONNECTION_OK
QUIT
ENDIF
? "Blocking: ", PQisnonblocking(conn), PQsetnonblocking(conn, .t.), PQisnonblocking(conn)
? "Blocking: ", PQisnonblocking( conn ), PQsetnonblocking( conn, .T. ), PQisnonblocking( conn )
pFile := PQcreatetrace( 'trace.log' )
pFile := PQcreatetrace( "trace.log" )
PQtrace( conn, pFile )
? "Verbose: ", PQsetErrorVerbosity(conn, 2)
? "Protocol: ", PQprotocolVersion(conn), ;
" Server Version: ", PQserverVersion(conn), ;
" Client Encoding: ", PQsetClientEncoding(conn, "ASCII"), ;
"New encode: ", PQclientEncoding(conn)
? "Protocol: ", PQprotocolVersion( conn ),;
" Server Version: ", PQserverVersion( conn ),;
" Client Encoding: ", PQsetClientEncoding( conn, "ASCII" ),;
"New encode: ", PQclientEncoding( conn )
? PQdb(conn), PQuser(conn), PQpass(conn), PQhost(conn), PQport(conn), PQtty(conn), PQoptions(conn)
? PQdb( conn ), PQuser( conn ), PQpass( conn ), PQhost( conn ), PQport( conn ), PQtty( conn ), PQoptions( conn )
res := PQexec('drop table products')
? PQresultStatus(res), PQresultErrorMessage(res)
res := PQexec( "drop table products" )
? PQresultStatus( res ), PQresultErrorMessage( res )
res := NIL
res := PQexec('create table products ( product_no numeric(10), name varchar(20), price numeric(10,2) )')
? PQresultStatus(res), PQresultErrorMessage(res)
res := NIL
res := PQexec( "create table products ( product_no numeric(10), name varchar(20), price numeric(10,2) )" )
? PQresultStatus( res ), PQresultErrorMessage( res )
res := PQexecParams(conn, 'insert into products(product_no, name, price) values ($1, $2, $3)', {'2', 'bread', '10.95'})
? "Oid Row: ", PQoidValue(res), PQoidStatus(res)
res := PQexecParams( conn, "insert into products(product_no, name, price) values ($1, $2, $3)", { "2", "bread", "10.95" } )
? "Oid Row: ", PQoidValue( res ), PQoidStatus( res )
if PQresultStatus(res) != PGRES_COMMAND_OK
? PQresultStatus(res), PQresultErrorMessage(res)
endif
res := NIL
IF PQresultStatus( res ) != PGRES_COMMAND_OK
? PQresultStatus( res ), PQresultErrorMessage( res )
ENDIF
res := PQexec(conn, 'select price, name, product_no as "produto" from products')
res := PQexec( conn, 'select price, name, product_no as "produto" from products' )
if PQresultStatus(res) != PGRES_TUPLES_OK
? PQresultStatus(res), PQresultErrorMessage(res)
endif
IF PQresultStatus( res ) != PGRES_TUPLES_OK
? PQresultStatus( res ), PQresultErrorMessage( res )
ENDIF
? "Binary: ", PQbinaryTuples(res)
? "Rows: ", PQntuples(res), "Cols: ", PQnfields(res)
? PQfname(res, 1), PQftable(res, 1), PQftype(res, 1), PQfnumber(res, "name"), PQfmod(res, 1), PQfsize(res, 1), PQgetisnull(res,1,1)
? "Binary: ", PQbinaryTuples( res )
? "Rows: ", PQntuples( res ), "Cols: ", PQnfields( res )
? PQfname( res, 1 ), PQftable( res, 1 ), PQftype( res, 1 ), PQfnumber( res, "name" ), PQfmod( res, 1 ), PQfsize( res, 1 ), PQgetisnull( res, 1, 1 )
aTemp := PQmetadata(res)
aTemp := PQmetadata( res )
for x := 1 to len(aTemp)
FOR x := 1 TO Len( aTemp )
? "Linha 1: "
for y := 1 to 6
?? aTemp[x,y], ", "
next
next
FOR y := 1 TO 6
?? aTemp[ x ][ y ], ", "
NEXT
NEXT
? PQFcount(res)
? PQFcount( res )
? PQlastrec(res)
? PQlastrec( res )
? PQGetvalue(res,1, 2)
? res := NIL
? PQGetvalue( res, 1, 2 )
? "Large Objects, always should be in a transaction..."
res := PQexec(conn, 'begin')
res := NIL
PQexec( conn, "begin" )
? (x := lo_Import( conn, 'test.prg' ))
? lo_Export( conn, x, 'test.new' )
? ( x := lo_Import( conn, "test.prg" ) )
? lo_Export( conn, x, "test.new" )
? lo_Unlink( conn, x )
res := PQexec(conn, 'commit')
res := NIL
PQexec( conn, "commit" )
PQuntrace( conn )
pFile := NIL
conn := NIL
return NIL
RETURN

View File

@@ -2,92 +2,94 @@
* $Id$
*/
/* The aim of this test is to check the same RDD functions and statements against a dbf file
/* The aim of this test is to check the same RDD functions and statements against a dbf file
and the same dbf imported into a PostgreSQL database.
Replace <...> with your data and configuration.
*/
procedure main()
#if 0
local nConn
PROCEDURE Main()
set deleted on
LOCAL NCONN
request DBFCDX
request PGRDD
SET DELETED ON
use <table> index <index> exclusive via "dbfcdx"
REQUEST DBFCDX
REQUEST PGRDD
set order to 1
USE <table> INDEX <index> EXCLUSIVE VIA "dbfcdx"
SET ORDER TO 1
test_code( "DBF" )
use
USE
nConn := dbpgconnection( "<host>;<database>;<user>;<password>;<port>;<scheme>" )
/* if you want to update and insert data you need at least a primary key */
use "select <fields,...> from <table> order by <same order as dbf>" alias <table> via "pgrdd" connection nConn
USE "select <fields,...> FROM <table> ORDER BY <same order as dbf>" ALIAS <table> VIA "pgrdd" CONNECTION NCONN
test_code( "SQL" )
use
USE
dbpgclearconnection( nConn )
return
RETURN
function test_code( cMode )
PROCEDURE test_code( cMode )
local xTemp
LOCAL xTemp
<table>->( dbgotop() )
<table>->( dbGoTop() )
? <table>-><field1>, <table>-><field2>, <table>-><field3>
<table>->( dbgobottom() )
<table>->( dbGoBottom() )
? <table>-><field1>, <table>-><field2>, <table>-><field3>
/* goto 100 has different meaning */
<table>->( dbgoto( 100 ) )
<table>->( dbGoto( 100 ) )
? <table>-><field1>, <table>-><field2>, <table>-><field3>
xTemp := <table>-><field3>
replace <table>-><field3> with "*** replaced ***"
REPLACE <table>-><field3> WITH "*** replaced ***"
? <table>-><field1>, <table>-><field2>, <table>-><field3>
replace <table>-><field3> with xTemp
dbcommit() // the real write is made via dbcommit() so it is needed
REPLACE <table>-><field3> WITH xTemp
dbCommit() // the real write is made via dbCommit() so it is needed
? <table>-><field1>, <table>-><field2>, <table>-><field3>
? eof()
dbgobottom()
dbskip()
? eof()
? bof()
dbgotop()
dbskip(-1)
? bof()
? Eof()
dbGoBottom()
dbSkip()
? Eof()
? Bof()
dbGoTop()
dbSkip( -1 )
? Bof()
dbappend()
replace <table>-><field1> with <"9">
replace <table>-><field2> with <"999999">
replace <table>-><field3> with <"APPENDED">
dbcommit()
dbAppend()
REPLACE <table>-><field1> WITH <"9">
REPLACE <table>-><field2> WITH <"999999">
REPLACE <table>-><field3> WITH <"APPENDED">
dbCommit()
// recno() has different meaning, in SQL it is the number of the row and change for every select */
? <table>->( recno() ), <table>-><field1>, <table>-><field2>, <table>-><field3>
// RecNo() has different meaning, in SQL it is the number of the row and change for every select */
? <table>->( RecNo() ), <table>-><field1>, <table>-><field2>, <table>-><field3>
wait
WAIT
cls
CLS
BROWSE()
Browse()
dbgobottom()
replace <table>-><field3> with "REPLACED"
dbcommit()
dbgobottom()
dbGoBottom()
REPLACE <table>-><field3> WITH "REPLACED"
dbCommit()
dbGoBottom()
BROWSE()
Browse()
delete for <table>-><field1> = "9"
return nil
DELETE FOR <table>-><field1> = "9"
RETURN
#endif