The Data Tier
But there's still a missing piecethe DataTier class library that's the subject of this chapter. Now that you've seen all of the places where its methods are called, you should be able to match up the calls from Listing 3.6 with the methods in Listing 3.7 and see how they fit together.
The data tier is a class used to instantiate an object called oDataTier in MAIN.PRG. Thereafter, any time we need to send data to a data store, we call a method on the oDataTier object.
It's important to note that in this methodology, you either open a DBF or a CURSOR for each table object. If you initiate either an Add or an Edit, you set buffering mode to 3, change something, and then call TableUpdate() and set Buffering back to 1. (If your user cancels, you refresh the screen with whatever was there beforethe original, unchanged record. Tablerevert() does that, as long as you add a little code to go back to the record you were pointing to before the APPEND BLANK step.) If you were using FoxPro, you'd be home now.
However, if you're using SQL Server or an XML Web Service, you're only halfway there. You've done the equivalent in .NET of saving changes to a dataset. Now you need to use the saved data to update the data store, which might be on SQL Server or in Timbuktu. So we still need the TableUpdate() and TableRevert() function calls in the Save and Cancel buttons. We just have to add one more call to the DataTier object to see what else to do. If we're using DBFs, as you'll see, it simply excuses itself and returns. Similarly, in the form's Load event, we call the CreateCursor method of this object, which either creates a cursor, or, in the case of DBF access, opens the appropriate table and sets the index tag.
The proper way to read this code is to find the place in the form template code where each routine is being called, and then see what the DataTier routine does after the template code runs. It's the combination of the template code and the DataTier code that works the magic. Listing 3.7 shows the DataTier code.
Listing 3.7 DataTier.PRG
DEFINE CLASS DataTier AS Custom AccessMethod = [] * Any attempt to assign a value to this property will be trapped * by the "setter" method AccessMethod_Assign. ConnectionString = ; [Driver={SQL Server};Server=(local);Database=Mydatabase;UID=sa;PWD=;] Handle = 0 * Betcha didn't know you could write your own Assign methods... PROCEDURE AccessMethod_Assign PARAMETERS AM DO CASE CASE AM = [DBF] THIS.AccessMethod = [DBF] && FoxPro tables CASE AM = [SQL] THIS.AccessMethod = [SQL] && MS Sql Server THIS.GetHandle CASE AM = [XML] THIS.AccessMethod = [XML] && FoxPro XMLAdapter CASE AM = [WC] THIS.AccessMethod = [WC] && WebConnection server OTHERWISE MESSAGEBOX( [Incorrect access method ] + AM, 16, [Setter error] ) THIS.AccessMethod = [] ENDCASE _VFP.Caption = [Data access method: ] + THIS.AccessMethod ENDPROC * CreateCursor actually opens the DBF if AccessMethod is DBF; * otherwise it uses a structure returned from the data * store to create a cursor that is bound to the screen controls: PROCEDURE CreateCursor LPARAMETERS pTable, pKeyField IF THIS.AccessMethod = [DBF] IF NOT USED ( pTable ) SELECT 0 USE ( pTable ) ALIAS ( pTable ) ENDIF SELECT ( pTable ) IF NOT EMPTY ( pKeyField ) SET ORDER TO TAG ( pKeyField ) ENDIF RETURN ENDIF Cmd = [SELECT * FROM ] + pTable + [ WHERE 1=2] DO CASE CASE THIS.AccessMethod = [SQL] SQLEXEC( THIS.Handle, Cmd ) AFIELDS ( laFlds ) USE CREATE CURSOR ( pTable ) FROM ARRAY laFlds CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE * GetHandle is called in the Assign method of the AccessMethod * property earlier in this listing (two procedures back). PROCEDURE GetHandle IF THIS.AccessMethod = [SQL] IF THIS.Handle > 0 RETURN ENDIF THIS.Handle = SQLSTRINGCONNECT( THIS.ConnectionString ) IF THIS.Handle < 1 MESSAGEBOX( [Unable to connect], 16, [SQL Connection error], 2000 ) ENDIF ELSE Msg = [A SQL connection was requested, but access method is ] ; + THIS.AccessMethod MESSAGEBOX( Msg, 16, [SQL Connection error], 2000 ) THIS.AccessMethod = [] ENDIF RETURN PROCEDURE GetMatchingRecords LPARAMETERS pTable, pFields, pExpr pFields = IIF ( EMPTY ( pFields ), [*], pFields ) pExpr = IIF ( EMPTY ( pExpr ), [], ; [ WHERE ] + STRTRAN ( UPPER ( ALLTRIM ( pExpr ) ), [WHERE ], [] ) ) cExpr = [SELECT ] + pFields + [ FROM ] + pTable + pExpr IF NOT USED ( pTable ) RetVal = THIS.CreateCursor ( pTable ) ENDIF DO CASE CASE THIS.AccessMethod = [DBF] &cExpr CASE THIS.AccessMethod = [SQL] THIS.GetHandle() IF THIS.Handle < 1 RETURN ENDIF lr = SQLExec ( THIS.Handle, cExpr ) IF lr >= 0 THIS.FillCursor() ELSE Msg = [Unable to return records] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF ENDCASE ENDPROC
In my EasySearch template, I open up a new cursor, the name of which is "View" followed by the name of the table that the data is coming from. So it's not a view, just a cursor name:
PROCEDURE CreateView LPARAMETERS pTable IF NOT USED( pTable ) MESSAGEBOX( [Can't find cursor ] + pTable, 16, [Error creating view], 2000 ) RETURN ENDIF SELECT ( pTable ) AFIELDS( laFlds ) SELECT 0 CREATE CURSOR ( [View] + pTable ) FROM ARRAY laFlds ENDFUNC
GetOneRecord is called with all types of data stores. If we're using a DBF, a LOCATE command that refers to the current index tag is Rushmore-optimized and very fast. With SQL, it's also Rushmore-optimized, because SQL 2000 uses Rushmorewith not a single mention of where it came from. But we know...
PROCEDURE GetOneRecord LPARAMETERS pTable, pKeyField, pKeyValue SELECT ( pTable ) Dlm = IIF ( TYPE ( pKeyField ) = [C], ['], [] ) IF THIS.AccessMethod = [DBF] cExpr = [LOCATE FOR ] + pKeyField + [=] + Dlm + TRANSFORM ( pKeyValue ) + Dlm ELSE cExpr = [SELECT * FROM ] + pTable ; + [ WHERE ] + pKeyField + [=] + Dlm + TRANSFORM ( pKeyValue ) + Dlm ENDIF DO CASE CASE THIS.AccessMethod = [DBF] &cExpr CASE THIS.AccessMethod = [SQL] lr = SQLExec ( THIS.Handle, cExpr ) IF lr >= 0 THIS.FillCursor( pTable ) ELSE Msg = [Unable to return record] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE ENDFUNC
FillCursor is analogous to the Fill method of .NET's DataAdapters. FoxPro's ZAP is like the .NET DataAdapter.Clear method. By appending FROM DBF(CursorName) into the named cursor, we don't break the data binding with the form's controls:
PROCEDURE FillCursor LPARAMETERS pTable IF THIS.AccessMethod = [DBF] RETURN ENDIF SELECT ( pTable ) ZAP APPEND FROM DBF ( [SQLResult] ) USE IN SQLResult GO TOP ENDPROC
I'd like to think that all primary keys were going to be integers, but legacy systems sometimes have character keys. That's what the check for delimiters is in the DeleteRecord routine:
PROCEDURE DeleteRecord LPARAMETERS pTable, pKeyField IF THIS.AccessMethod = [DBF] RETURN ENDIF KeyValue = EVALUATE ( pTable + [.] + pKeyField ) Dlm = IIF ( TYPE ( pKeyField ) = [C], ['], [] ) DO CASE CASE THIS.AccessMethod = [SQL] cExpr = [DELETE ] + pTable + [ WHERE ] + pKeyField + [=] ; + Dlm + TRANSFORM ( m.KeyValue ) + Dlm lr = SQLExec ( THIS.Handle, cExpr ) IF lr < 0 Msg = [Unable to delete record] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE ENDFUNC
The SaveRecord routine either does an INSERT or an UPDATE depending on whether the user was adding or not:
PROCEDURE SaveRecord PARAMETERS pTable, pKeyField, pAdding IF THIS.AccessMethod = [DBF] RETURN ENDIF IF pAdding THIS.InsertRecord ( pTable, pKeyField ) ELSE THIS.UpdateRecord ( pTable, pKeyField ) ENDIF ENDPROC
The InsertRecord and UpdateRecord routines call corresponding functions that build SQL INSERT or UPDATE commands, in much the same way that .NET does. I store the resulting string to _ClipText so that I can open up Query Analyzer and execute the command there manually to see what went wrong. It's the fastest way to debug your generated SQL code. Finally, I use SQLExec() to execute the command. SQLExec() returns -1 if there's a problem.
PROCEDURE InsertRecord LPARAMETERS pTable, pKeyField cExpr = THIS.BuildInsertCommand ( pTable, pKeyField ) _ClipText = cExpr DO CASE CASE THIS.AccessMethod = [SQL] lr = SQLExec ( THIS.Handle, cExpr ) IF lr < 0 msg = [Unable to insert record; command follows:] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE ENDFUNC PROCEDURE UpdateRecord LPARAMETERS pTable, pKeyField cExpr = THIS.BuildUpdateCommand ( pTable, pKeyField ) _ClipText = cExpr DO CASE CASE THIS.AccessMethod = [SQL] lr = SQLExec ( THIS.Handle, cExpr ) IF lr < 0 msg = [Unable to update record; command follows:] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE ENDFUNC FUNCTION BuildInsertCommand PARAMETERS pTable, pKeyField Cmd = [INSERT ] + pTable + [ ( ] FOR I = 1 TO FCOUNT() Fld = UPPER(FIELD(I)) IF TYPE ( Fld ) = [G] LOOP ENDIF Cmd = Cmd + Fld + [, ] ENDFOR Cmd = LEFT(Cmd,LEN(Cmd)-2) + [ } VALUES ( ] FOR I = 1 TO FCOUNT() Fld = FIELD(I) IF TYPE ( Fld ) = [G] LOOP ENDIF Dta = ALLTRIM(TRANSFORM ( &Fld )) Dta = CHRTRAN ( Dta, CHR(39), CHR(146) ) * get rid of single quotes in the data Dta = IIF ( Dta = [/ /], [], Dta ) Dta = IIF ( Dta = [.F.], [0], Dta ) Dta = IIF ( Dta = [.T.], [1], Dta ) Dlm = IIF ( TYPE ( Fld ) $ [CM],['],; IIF ( TYPE ( Fld ) $ [DT],['],; IIF ( TYPE ( Fld ) $ [IN],[], []))) Cmd = Cmd + Dlm + Dta + Dlm + [, ] ENDFOR Cmd = LEFT ( Cmd, LEN(Cmd) -2) + [ )] && Remove ", " add " )" RETURN Cmd ENDFUNC FUNCTION BuildUpdateCommand PARAMETERS pTable, pKeyField Cmd = [UPDATE ] + pTable + [ SET ] FOR I = 1 TO FCOUNT() Fld = UPPER(FIELD(I)) IF Fld = UPPER(pKeyField) LOOP ENDIF IF TYPE ( Fld ) = [G] LOOP ENDIF Dta = ALLTRIM(TRANSFORM ( &Fld )) IF Dta = [.NULL.] DO CASE CASE TYPE ( Fld ) $ [CMDT] Dta = [] CASE TYPE ( Fld ) $ [INL] Dta = [0] ENDCASE ENDIF Dta = CHRTRAN ( Dta, CHR(39), CHR(146) ) * get rid of single quotes in the data Dta = IIF ( Dta = [/ /], [], Dta ) Dta = IIF ( Dta = [.F.], [0], Dta ) Dta = IIF ( Dta = [.T.], [1], Dta ) Dlm = IIF ( TYPE ( Fld ) $ [CM],['],; IIF ( TYPE ( Fld ) $ [DT],['],; IIF ( TYPE ( Fld ) $ [IN],[], []))) Cmd = Cmd + Fld + [=] + Dlm + Dta + Dlm + [, ] ENDFOR Dlm = IIF ( TYPE ( pKeyField ) = [C], ['], [] ) Cmd = LEFT ( Cmd, LEN(Cmd) -2 ) ; + [ WHERE ] + pKeyField + [=] ; + + Dlm + TRANSFORM(EVALUATE(pKeyField)) + Dlm RETURN Cmd ENDFUNC
Sometimes I need to return a cursor that I'll use for my own purposes, for example, to load a combo box. I use the default name SQLResult. I only name it here because if I use FoxPro's SELECT, it returns the cursor into a BROWSE by default, and I need to ensure that the cursor name will be SQLResult when I return from this procedure:
PROCEDURE SelectCmdToSQLResult LPARAMETERS pExpr DO CASE CASE THIS.AccessMethod = [DBF] pExpr = pExpr + [ INTO CURSOR SQLResult] &pExpr CASE THIS.AccessMethod = [SQL] THIS.GetHandle() IF THIS.Handle < 1 RETURN ENDIF lr = SQLExec ( THIS.Handle, pExpr ) IF lr < 0 Msg = [Unable to return records] + CHR(13) + cExpr MESSAGEBOX( Msg, 16, [SQL error] ) ENDIF CASE THIS.AccessMethod = [XML] CASE THIS.AccessMethod = [WC] ENDCASE ENDFUNC
When I add a new record, whether I use DBFS or SQL, I'm responsible for inserting a unique value into the table. So I maintain a table of table names and the last key used. If you create this table manually, be sure to update the LastKeyVal field manually before going live, or you'll get thousands of duplicate keys.
FUNCTION GetNextKeyValue LPARAMETERS pTable EXTERNAL ARRAY laVal pTable = UPPER ( pTable ) DO CASE CASE THIS.AccessMethod = [DBF] IF NOT FILE ( [Keys.DBF] ) CREATE TABLE Keys ( TableName Char(20), LastKeyVal Integer ) ENDIF IF NOT USED ( [Keys] ) USE Keys IN 0 ENDIF SELECT Keys LOCATE FOR TableName = pTable IF NOT FOUND() INSERT INTO Keys VALUES ( pTable, 0 ) ENDIF Cmd = [UPDATE Keys SET LastKeyVal=LastKeyVal + 1 ] ; + [ WHERE TableName='] + pTable + ['] &Cmd Cmd = [SELECT LastKeyVal FROM Keys WHERE TableName = '] ; + pTable + [' INTO ARRAY laVal] &Cmd USE IN Keys RETURN TRANSFORM(laVal(1)) CASE THIS.AccessMethod = [SQL] Cmd = [SELECT Name FROM SysObjects WHERE Name='KEYS' AND Type='U'] lr = SQLEXEC( THIS.Handle, Cmd ) IF lr < 0 MESSAGEBOX( "SQL Error:"+ CHR(13) + Cmd, 16 ) ENDIF IF RECCOUNT([SQLResult]) = 0 Cmd = [CREATE TABLE Keys ( TableName Char(20), LastKeyVal Integer )] SQLEXEC( THIS.Handle, Cmd ) ENDIF Cmd = [SELECT LastKeyVal FROM Keys WHERE TableName='] + pTable + ['] lr = SQLEXEC( THIS.Handle, Cmd ) IF lr < 0 MESSAGEBOX( "SQL Error:"+ CHR(13) + Cmd, 16 ) ENDIF IF RECCOUNT([SQLResult]) = 0 Cmd = [INSERT INTO Keys VALUES ('] + pTable + [', 0 )] lr = SQLEXEC( THIS.Handle, Cmd ) IF lr < 0 MESSAGEBOX( "SQL Error:"+ CHR(13) + Cmd, 16 ) ENDIF ENDIF Cmd = [UPDATE Keys SET LastKeyVal=LastKeyVal + 1 WHERE TableName='] ; + pTable + ['] lr = SQLEXEC( THIS.Handle, Cmd ) IF lr < 0 MESSAGEBOX( "SQL Error:"+ CHR(13) + Cmd, 16 ) ENDIF Cmd = [SELECT LastKeyVal FROM Keys WHERE TableName='] + pTable + ['] lr = SQLEXEC( THIS.Handle, Cmd ) IF lr < 0 MESSAGEBOX( "SQL Error:"+ CHR(13) + Cmd, 16 ) ENDIF nLastKeyVal = TRANSFORM(SQLResult.LastKeyVal) USE IN SQLResult RETURN TRANSFORM(nLastKeyVal) CASE THIS.AccessMethod = [WC] CASE THIS.AccessMethod = [XML] ENDCASE ENDDEFINE
Running the Application
Type
BUILD EXE Chapter3 FROM Chapter3
or use the Build button in the Project Manager. When you have an executable, run it and try each of the forms, as well as the search screens. It works pretty nicely, as we're used to seeing with DBF tables.
Now, select Change Data Source from the menu and enter SQL, as shown in Figure 3.4.
Figure 3.4 Changing the data access method.
Now, open the Customer form. There's no data! That's standard for a SQL application because until the user requests a record, they don't have one yet. So click on Find, enter some search criteria (actually, to return all records, just leave them all blank), click on Show Matches, and select one. The search form disappears, and you've got data! Select Edit, and then change something and save it. Reload the page to verify that it worked. Add a record, save it, and see if the search form finds it.
Nothing special happens, except that you just built a FoxPro application that works with either DBFs or SQL without writing a single line of code in any of the forms.