TDatabase FWH 17.08 : Datas and Methods

TDatabase FWH 17.08 : Datas and Methods

Postby nageswaragunupudi » Fri Sep 15, 2017 12:50 pm

DATAS

1. aBuffer ( ReadOnly Type: "A" ): Array holding the field values of the current record when ::lBuffer is .T.

2. aFldNames ( ReadOnly Type: "A" ): Array containing field names of DBF

3. aStruct ( ReadOnly Type: "A" ): Structure of the table, similar to DBSTRUCT(). aStruct has additional columns 7 for picture and 8 for index tag.
When programmer assigns an alternate name for a field using ::MapCol(), astruct contains the new name.
When programmer addes virtual columns using ::AddCol(), aStruct contains virtual column information also.
Programmer may modify columns 7 (picture) and 8 (index tag) but not any other column.

4. bBoF ( Type: "B" ): If assigned, executed when BOF() is true

5. bEdit ( Type: "B" ): Optional. Format { |oRec| UserEdit( oRec ) }
If assigned, used to edit current/new record with ::Record() object as parameter. See ::Record() and ::Edit() methods.

6. bEoF ( Type: "B" ): If assigned, executes when EOF() is true

7. bNetError ( Type: "B" ): Optional. If assigned, evaluated when record lock fails

8. BookMark ( Type: "N" ): ACCESS ::BookMark --> RecNo()
ASSIGN ::BookMark := n --> ::DbGoTo( n )

[b]9. bTrigger ( Type: "B" ): [/b]Optional. If asigned, executed when record is modified

10. bValidRow ( Type: "B" Default: {||.t.} ): Optional codeblock to check validity of contents of a row before saving. Save() method evaluates this codeblock with Self as parameter and saves data only if the return value is TRUE.
.

11. cAlias ( ReadOnly Type: "C" Default: "" ): Alias() of DBF

12. Cargo ( Type: "U" ): For programmer's use

13. cDriver ( ReadOnly Type: "C" ): RDD name of DBF

14. cFile ( ReadOnly Type: "C" Default: "" ): File name of DBF with full path

15. hFlds ( ReadOnly Type: "H" ): Hash mapping fields names (original, alternate and virtual) to ordinal position on aStruct array.

16. hRec ( ReadOnly Type: "H" ): Save() method populates the Hash with values prior to modification and provides as 3rd paramter while Evaluating ::bTrigger. Current values of the fields can be compared with old values and necessary action may be taken inside the trigger.

17. lADS ( ReadOnly Type: "L" Default: .F. ): True when RDD is ADS

18. lBuffer ( Type: "L" Default: .T. ): If .T., contents of current record are read into ::aBuffer array whenever row is moved or modified. If .f., ::aBuffer is not used and fields are directly assessed and written.

19. lOemAnsi ( Type: "L" Default: .F. ): If .T., charactger values are converted using OemToAnsi() and AnsiToOem() while reading and saving.

20. lReadOnly ( Type: "L" Default: .F. ): True if the file is opened in readonly mode.

21. lShared ( ReadOnly Type: "L" Default: ! Set(_SET_EXCLUSIVE) ): True if the DBF is used in shared mode

22. nArea ( ReadOnly Type: "N" Default: 0 ): Area number of the DBF used.

23. nBufRec ( Type: "N" ): RecNo() corresponding to the values in ::aBuffer. In case of ::Blank() this value is 0.

24. oCn ( ReadOnly Type: "O" ): ADO Connection object to the folder containing the DBF. Created if and when ::SqlQuery() method is called. Closed by the ::Close() method. Uses VFPOLEDB if installed when DBFCDX is used.

METHODS

METHODS

1. New( [ncArea], [cFile], [cDriver], [lShared], [lReadOnly] ) --> Self
CONSTRUCTOR
Usage 1: Single or no parameters:
oDbf := TDataBase():New( [nArea/cAlias] )
nArea/cAlias defaults to currently selected workarea.
This usage creates the object for a DBF that is already open. Eg:
Code: Select all  Expand view
USE STATES
oDbf := TDataBase():New()

Usage 2: Two or more parameters:
oDbf := TDataBase():New( nil, cFile, [cDriver],[lShared],[lReadOnly] ) --> Self
This usage creates the object but does not open. Requires a call to method ::Use() to open DBF. Datas can be modified before calling ::Use().
3.[cDriver]: Default RDDSETDEFAULT()
4.[lShared]: Default !Set(_SET_EXCLUSIVE)
5.[lReadOnly]: Default .F.
Code: Select all  Expand view
oDbf := TDataBase():New( nil, "states.dbf", "DBFCDX" )
oDbf:lReadOnly := .t.
oDbf:Use()


This method creates the object but does not open the dbf. We need to call ::Use() method to open the dbf.

Recommended to use ::Open() constructor which opens the dbf in a single call.

2. Open( [cAlias], cFile, [cDriver], [lShared], [lReadOnly] ) --> Self
CONSTRUCTOR
Highly recommended to leave [cAlias] parameter as nil, allowing the class to use a new alias name.
Parameter cFile is compulsory.
Other parameters are similar to method New()
Opens cFile and returns Self.

Code: Select all  Expand view
oDbf := TDataBase():Open( nil, "states.dbf" )


3. Create( cFile, aStruct, [cDriver], [cIndexFields] )
CONSTRUCTOR
If called as constructor, cFile is created, indexes created and opened.
If called by an already created object, creates dbf file.

4. Activate() Same as ::Use()

5. AddCol( cCol, uExpr, cType, nLen, nDec, cPic, cTag ) --> nNewCol
Creates a new virtual (calculated) column. uExpr can be character expression or a codeblock. Column name (cCol) can have more than 10 characters.
Code: Select all  Expand view

oDbf:AddCol( "DUE", "::Sales - ::Paid", "N", 12, 2, NUMPICT( 12, 2 ), "SALES" )
? oDbf:Due


6. AddIndex( cFile, cTag ) Adds new index file. Use with NTX files

7. AnsiToOem()
Internal Internally used when ::lOemToAnsi is .T.

8. Append( [aFlds], [aVals] ) --> lSuccess
Usage 1: Append() without parameters:
Appends a blank record and returns success
This usage is consistent with all previous versions.

Usage 2:
Append( aFldsAndValues )
aFldsAndValues is a multi-dim array in the form of { { fld1, val1 }, ... { fldN, valN } }.
fldN can be field name of field number.

Append( flds, aVals )
flds can be nil ( all fields) or list of fields or array of field names/numbers
aVals can be an array of corresponding values. aVals can be a single row or multiple rows.

9. AppendFrom( cFile, aFields, bFor, bWhile, nNext, nRec, lRest ) Executes APPEND FROM command

10. Blank()
Fills ::aBuffer with blank values. (From ver 17.08 fills default values where necessary.) The blank values can be edited/modified normally and can be appended to dbf by calling ::Append() followed by ::Save().
Code: Select all  Expand view
oDbf:Blank()
// edit/modify
oDbf:Append() // Optional from 17.08
oDbf:Save()

Notes: (1) Record pointer should not be moved during the entire operation because that will overwrite the ::aBuffer
(2) oDbf:Append() should be called before calling Save(). Otherwise, the new data may overwrite an existing record. There is no such problem with 17.08.
From FWH17.08
Code: Select all  Expand view
oDbf:Blank()
// edit/modify
oDbf:Save()


11. Bof() returns BOF()

12. BookMark( [nGoTo] ) --> RecNo()
::BookMark() --> RecNo()
::BookMark( n ) --> ::GoTo( n ) and return new RecNo

13. ClearFilter() Same as DBCLEARFILTER()

14. ClearRelation() Executes DbClearRelation()

15. Close()
Closes the Alias and ::oCn if already open.
Till 17.07, calling ::Close() again after the dbf is closed could have some side effects in some cases. 17.08 makes it safe.

16. CloseIndex() Closes index

17. Commit() Performs COMMIT for the Alias

18. CopyTo( cFile, aFields, bFor, bWhile, nNext, nRec, cRdd, cCp ) Executes COPY TO command

19. CreateIndex( cFile, cTag, cKey, bKey, lUnique) ( ::nArea )->( OrdCreate( cFile, cTag, cKey, bKey, lUnique ) )

20. DbCreate( aStruct ) DbCreate( ::cFile, aStruct, ::cDriver )

21. Deactivate() Closes Alias

22. Delete() Deletes current record and skips to next undeleted record.

23. Deleted() Returns .T. if current record is deleted

24. DeleteIndex( cTag, cFile ) Removes the index tag from the order bag

25. Edit( [cFiedList], [lNew] ) Creates a record object and invokes Edit(). This is a safe way to edit existing or new records. By default Edit() calls native dialog of record object, but user can specify his own dialog with ::bEdit

26. End() Closes DBF and ::oCn object

27. Eof() True if EOF()

28. Eval( bBlock, bFor, bWhile, nNext, nRecord, lRest ) Executes DBEVAL() with same parameters

29. Exec( bAction ) Evaluates bAction in the WorkArea of the object.

30. ExecTigger()
Internal
EValiuates ::bTrigger with Self as parameter and returns the result. This method is internally used by Save() method and when ::lBuffer is .t. and FieldPut() method when ::lBuffer is .f.
Application programs may use this method only when DBF is directly modified at RDD level.

31. FCount() Total number of fields, including virtual fields created by programmer using ::AddCol() method

32. FieldBlock( nCol ) returns FIELDWBLOCK() for this column

33. FieldDefault( nFld/cFldName, [uDefault], [lRO] ) --> uDefault

Sets/Queries default value to be used for the field while appending new data. Default values are first saved to DBF before saving data in aBuffer( FWH 17.08)

34. FieldGet( nPos/FieldName ) --> uValue
1. Parameter can be field number, field name, alternative name or virtual field name. Returns value of the field.
2. Parameter can also be an expression. Returns value of the expression.

35. FieldName( nField ) FieldName (alternative name is used)

36. FieldPos( cField ) cField can also be alternate name assigned by ::MapCol() or virtual field name created by ::AddCol()

37. FieldPut( nPos/FieldName, uValue )
First parameter can be field number or fieldname (original, alternative or virtual). Assigns uvalue to the field.
If ::lBuffer is .T. (default), the value is stored in the buffer and saved to DBF only when ::Save() is called.
If ::lBuffer is .F., data is immediately saved to DBF.

38. FieldReadOnly( nFld/cFldName, [lRO] ) --> lReadOnly

Sets or queries the readonly flag of the field. AutoInc and timestamp fields ( +,=,@ ) are automatically flagged as readonly and can not be changed by the application. In addition application can toggle readonly flag of other fields. FieldPut does not modify readonly fields.
(FWH 17.08)

39. FieldType( n, [c] ) Returns field type of nth field.

40. Found() Returns success of immediately preceeding Seek or Locate()

41. GoBottom() Go to last record

42. GoTo( nRecNo ) Go to nRecNo

43. GoTop() Goes to first record

44. IndexBagName( [nInd] ) Order bag name of index tag at position nInd, if specified or else current index tag

45. IndexKey( [ncTag], [cFile] ) Index expression of currently active index or the specified index tag and orderbag

46. IndexName( [nTag], [cFile] ) Active index tag name or at the position specified

47. IndexOrder( cTag, cFile ) Serial number of index tag

48. IsFileLocked() If dbf is locked with FLOCK()

49. IsRecLocked( [nRecNo := recno()] ) --> lLocked Returns .t. if the record or file is locked already.

50. KeyCount()
Returns OrdKeyCount().
Note: The count includes deleted records also unless filter is set to include "!DELETED()"

51. KeyGoTo( nkeyNo ) Goes to record at the position in the order of the active index. For accurate results include "!DELETED()" in the filter expression.

52. KeyNo() Serial number of the record in the index order. For accurate results include "!DELETED()" in the filter expression.

53. LastRec() Total records in the DBF, including deleted records.

54. Load() Reads field values from current record into ::aBuffer in memory, if ::lBuffer is true. Normally there is no need for the programmer to call this method in the application, as this method is automatically executed after every record movement and modification.

55. Lock() Executes FLOCK()

56. Locked() Same as ::IsRecLocked()

57. LookUp( uSeek, [cOrder/cField], bcRetExpr ) --> uResult
Looks up value in the table and return the result of expression in the 3rd parameter. The record position and sort order are restored before returning the result.
Parameters:
1. uValue: Value/Expression to be looked up.
if 2nd param is an order name, DBSEEK( uValue ) is executed after switching the sort order.
If 2nd param is field name LOCATE is executed for cField = uValue
If 2nd param is omitted and uValue is character value, LOCATE is executed for uValue as expression.
2. Order name or field name
3. Any expression of codeblock which is evaluated and result is returned.
Code: Select all  Expand view
val := oDbf:LookUp( 108, "ID", "SALARY" )
val := oDbf:LookUp( "ID=99", nil, "SALARY += 100" )
//Salary field is incremented by 100 and returns the incremented value
 


58. lValidRow( cOperation, [hRec] ) --> lValid
Internal Evaluates ::bValidRow with parameters Self, cOpertion and optional hRec and returns the result. The method is internally used by Save() method.

59. MapCol( cFld, cNewName ) --> lSuccess
Programmer can set a user friendly name to a field, which can be more than 10 chars. The field can be accessed using either the original name or new name. Eg:
Code: Select all  Expand view
oDbf:MapCol( "STATE", "StateName" )
? oDbf:StateName


60. Modified() Returns true if any values in the ::aBuffer are changed and not yet saved.

61. Move( n ) Same as ::Skip( n ). This method is created for compatibility with ADO syntax

62. MoveFirst() Same as GoTop().

63. MoveLast() Same as GoBottom()

64. MoveNext() Same as Skip( 1 )

65. MovePrevious() Same as Skip( -1 )

66. OemToAnsi()
Internal Internally used when ::lOemToAnsi is set to .T.

67. OrdDescend( cnTag, cFile, lDesc ) Toggles index order to descending/ascending

68. OrdScope( nScopeType, uValue ) Calls OrdScope() to set scope.

69. Pack() Packs the DBF, removing all deleted records. Fails if the DBF is opened as shared or readonly.

70. Recall()
Recalls the current record, if deleted.
Executes ::bTrigger and if it succeeds Recall is executed

71. RecCount() Total number of records in the DBF

72. RecLock( [nRecNo], @lLocked ) --> lLocked
nRecNo defaults to current RecNo().
Locks the record using DBRLOCK( nRecNo ), if the dbf is shared and record/file is not already locked. lLocked is set to .t. if the record is locked in this method.
Returns .t. if the file is exclusive or record/file is locked earlier or by this method, indicating that data can be written to the record.

73. RecNo() Current Record Number

74. Record( [cFieldList], [lNew] ) --> oRec
1.[cFieldList]: Default all fields (including virtual fields)
2.[lNew]: Default current record.
Creates and returns Record Object (TDataRow) for the current record or optionally new blank record for edit. After edit, executing oRec:Save() saves changes to the record or appends new record if lNew is .t.

75. RecUnLock( [nRecNo] ) nRecNo defaults to current record. Unlocks specified record only

76. ReIndex()
ReIndexes the database.
FWH 17.08

77. RollBack() Cancels any changes made to current record of DBF, pending commit to disk. See also ::Updated()

78. RowGet( cFieldList, lBlank )
Internal Used internally by TDataRow()

79. RowPut( aData, nPutRec, lCommit, oRec, lSaved )
Internal Used internally by TDataRow

80. Save() Saves changes made to ::aBuffer if the file is not readonly and ::Modified() is true and Eval( ::bValidRow ) is true, to the record corresponding to the buffer. If the buffer is created by ::Blank() method, then the data is appended,

81. SaveBuff()
Internal Used by ::Save()

82. Seek( uExpr, [lSoft], [lWildSeek] ) --> lFound Seeks uExpr and returns lFound.

83. SetArea( nWorkArea )
Internal

84. SetBuffer( [lOnOff] ) --> ::lBuffer Optionally sets ::lBuffer and returns value of ::lBuffer

85. SetFilter( [cFilter] ) --> cFilter
Sets filter to cFilter.
Clears filter if cFilter is ""

86. SetOrder( cnTag, [cFile] ) Sets order to index no/tag name in the optional orderbag.

87. SetRelation( uChild, cRelation, [lScoped] ) Sets relation to another workarea/database object. uChild can be workarea number of other TDatabase object

88. SetXBrowse( oBrw, aCols, lAutoSort, lAutoCols )
Internal Used by XBrowse SetoDbf() method

89. Skip( nRecords ) Skips nRecords, executes bBof or bEof when necessary and loads field values into ::aBuffer if ::lBufer is true.

90. Skipper
Internal Used by XBrowse, This method is not useful directly in application.

91. SqlQuery( cSql, lExecute, lCompact )

92. UnLock()
Removes all pending locks.
Note: RecUnlock( nRecNo ) unlocks the record only and retains other existing locks.

93. Update( aFlds, aVals ) --> lSaved
Syntax similar to ADO Update()

1. oDbf:Update( aValues )
2. oDbf:Update( aFldNames/Nos, aValues )
3. oDbf:Update( cFieldList, aValues )
4. oDbf:Update( aFieldValueArray )

Data is saved only if ::bEditRow is evaluated to true.

94. Updated()
True if some fields of the current record are written to dbf but not yet written to disk. RDD writes changes to disk only when record pointer is moved or DBCOMMIT() is executed. At this stage, it is still possible to cancel the changes by calling oDbf:RollBack().
Note: This is not the same as ::Modified(). See ::Modified()

95. Use()
Opens the DBF set with ::New() method.
Instead of using ::New() and then calling ::Use(), it is recommended to use ::Open() method.

Side-effects of calling Use when the dbf is alerady open are removed in FWH 17.08.

After the dbf is closed with Close()/End() methods Use() can be called to reopen the dbf.(from 17.08)

96. Used() True if dbf is already opened and in use.

97. xads_KeyGoTo( n )
Internal ::KeyGoTo() uses this method internally for ADS RDD.

98. xBrowse( oWnd, cTitle, aCols, lAutoSort, bSetUp )
Quick way to create and show XBrowse of the table in oWnd. If oWnd is MDI, xbrowse is shown in a new MDICHILD of the window or shown in the window.
If oWnd is nil, XBrowser is used.

99. Zap() Zaps() all records. Fails if dbf is opened as shared or readonly.

100. td_Destroy()
DESTRUCTOR
This method calls ::Close() method.
This method should not be called directly in the application and it is called by (x)Harbour when all references to the object go out of scope in memory.
Regards

G. N. Rao.
Hyderabad, India
User avatar
nageswaragunupudi
 
Posts: 10245
Joined: Sun Nov 19, 2006 5:22 am
Location: India

Re: TDatabase FWH 17.08 : Datas and Methods

Postby nageswaragunupudi » Fri Sep 15, 2017 3:39 pm

This sample demonstrates usage of the following features of TDatabase
    1. Using constructor Create()
    2. Appending multiple rows of data with single call to :Append()
    3. Setting default value for some fields
    4. Setting Readonly flag for some fields
    5. Using :bValidRow to ensure writing correct data despite mistakes in UI
    6. Using Triggers to autocalculate some fields.

Code: Select all  Expand view
#include "fivewin.ch"

REQUEST DBFCDX

//----------------------------------------------------------------------------//

function Main()

   local oDbf
   local aStruct := { ;
      { "ID",        "+",  4, 0  }, ;
      { "ITEM",      "N",  3, 0  }, ;
      { "QTY",       "N",  9, 3  }, ;
      { "RATE",      "N",  5, 2  }, ;
      { "AMOUNT",    "N", 12, 2  }, ;
      { "TAX",       "N",  2, 0  }, ;
      { "TOTAL",     "N", 12, 2  }, ;
      { "UPDATEDT",  "=",  8, 0  }, ;
      { "CREATEDT",  "@",  8, 0  }  }
   local aData := { ;
      { 101, 123, 23.25 }, ;
      { 102, 209, 40.00 }, ;
      { 103, 342, 50,00 }  }

   RDDSETDEFAULT( "DBFCDX" )
   SET DELETED OFF
   SET DATE ITALIAN
   SET CENTURY ON
   SET TIME FORMAT TO "HH:MM:SS"

   oDbf  := TDataBase():Create( "TESTSALE", aStruct, "DBFCDX", "*" )

   WITH OBJECT oDbf
      :FieldDefault(    "TAX",   12,   .T. )
      :FieldReadOnly(   "AMOUNT",   .T. )
      :FieldReadOnly(   "TOTAL",    .T. )

      :bValidRow  := < |Self, cMsg|
            if ::Item < 101 .or. ::Item > 104
               cMsg     := "Item should be between 101 and 104"
               return .f.
            endif
            if ::Qty <= 0
               cMsg     := "Qty should be > 0"
               return .f.
            endif
            if ::Rate <= 0
               cMsg     := "Rate Should be > 0"
            endif
            return .t.
            >

      :bTrigger   := < |Self|
         FIELD->AMOUNT  := FIELD->QTY * FIELD->RATE
         FIELD->TOTAL   := FIELD->AMOUNT * ( 1 + FIELD->TAX * 0.01 )
         return .t.
         >

   END

   oDbf:Append( "ITEM,QTY,RATE", aData ) // Append 3 rows.

   XBROWSER oDbf FASTEDIT

return nil

//----------------------------------------------------------------------------//
 
Regards

G. N. Rao.
Hyderabad, India
User avatar
nageswaragunupudi
 
Posts: 10245
Joined: Sun Nov 19, 2006 5:22 am
Location: India


Return to FiveWin for Harbour/xHarbour

Who is online

Users browsing this forum: No registered users and 19 guests