228
BaanERP Tools Programming features

BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

  • Upload
    others

  • View
    19

  • Download
    0

Embed Size (px)

Citation preview

Page 1: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

BaanERP Tools

Programming features

Page 2: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

A publication of:

Baan Development B.V.P.O.Box 1433770 AC BarneveldThe Netherlands

Printed in the Netherlands

© Baan Development B.V. 1998.All rights reserved.

The information in this documentis subject to change withoutnotice. No part of this documentmay be reproduced, stored ortransmitted in any form or by anymeans, electronic or mechanical,for any purpose, without theexpress written permission ofBaan Development B.V.

Baan Development B.V.assumes no liability for anydamages incurred, directly orindirectly, from any errors,omissions or discrepanciesbetween the software and theinformation contained in thisdocument.

Document Information

Code: U7168A USGroup: User DocumentationEdition: ADate: December, 1998

Page 3: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

i

Programming features

1 Introduction 1-13GL scripts 1-14GL UI and DAL scripts 1-1Report scripts 1-2Baan SQL 1-2Dynamic-link libraries 1-2BaanERP debugger 1-2Multitasking 1-33GL/4GL functions 1-3

2 3GL programming language features 2-1Overview 2-1Vocabulary 2-1Character set 2-1Continuation symbol 2-1Comment 2-1Separators 2-2Reserved words 2-2Constants 2-3Numeric constants 2-3String constants 2-4Symbolic constants 2-4Enumerate and set constants 2-4Variables 2-5Data types 2-6Declarations 2-6Tables 2-7Domains 2-8Arrays 2-9Fixed and based variables 2-12Multibyte strings 2-13Bidirectional strings 2-14Common variables 2-14NULL characters in strings 2-15Expressions and operators 2-16Arithmetic operators 2-17Relational operators 2-18

Table of contents

Page 4: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

ii

Logical operators 2-18Operator precedence 2-19Assignment Operator 2-20Transfer of control 2-21The GOTO statement 2-21The IF ... THEN ... ELSE statement 2-22The ON CASE statement 2-23Iterations 2-25WHILE statement 2-25FOR statement 2-26REPEAT ... UNTIL statement 2-26Using BREAK and CONTINUE (iterations) 2-26Functions 2-27Function type and return value 2-27Local variables 2-28Static variables 2-28Global variables 2-30External variables 2-31Function arguments 2-32Function prototypes 2-35Function calls 2-36Preprocessor 2-36Include files 2-36Macro definition 2-37Token pasting 2-39Object identifications 2-39Pragma codes 2-40Conditional compiling 2-41Compiler 2-45

3 4GL programming features 3-1Overview 3-14GL script types 3-1Event-driven programming 3-2Event sections 3-2Program sections 3-3Main sections 3-3Form sections 3-5Main sections 3-5Subsections 3-6Group sections 3-7Main section 3-7Subsections 3-7

Page 5: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

iii

Choice sections 3-8Main section 3-8Subsections 3-8Standard commands 3-9Field sections 3-13Main sections 3-13Subsections 3-13Example 3-16Zoom.from sections 3-17Main sections 3-17Subsections 3-17Example 3-18Main table sections 3-18Main section 3-18Subsections 3-18Example 3-20Flow of standard program 3-21Main routine 3-21Choice sections 3-22Form sections 3-22Field sections 3-23End of program 3-25Zoom sections 3-25Update database 3-25Main table i/o section 3-27Automatic import of variables 3-27Case 1 3-27Case 2 3-27Case 3 3-28Case 4 3-28Case 5 3-29Case 6 3-29

4 Report scripts 4-1Overview 4-1Event sections 4-1Program sections 4-1Report sections 4-2Main sections 4-3Subsections 4-4Text field sections 4-4Main section 4-5Subsection 4-5

Page 6: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

iv

Predefined variables 4-5Report script functions 4-7Expanding text variables 4-8Syntax 4-8Example 4-8

5 Database handling 5-1Overview 5-1Database tables 5-2Primary keys 5-2Relationships/references 5-2Combined fields 5-3Indexes 5-3Structured Query Language (SQL) 5-3Naming conventions 5-4Using tables in program scripts 5-4Data types 5-4Transaction handling 5-5Locking 5-5Record/page locking 5-6Table locks 5-7Application locks 5-7Retry points 5-8Coding retry points 5-8Testing retry points 5-9Baan SQL 5-9SQL syntax 5-10SELECT <select list> 5-10FROM <from list> 5-11WHERE <where condition> 5-11GROUP BY <group condition> 5-13HAVING <having condition> 5-14ORDER BY<order by condition> 5-14Set specification 5-15Using program variables 5-15SELECT clause 5-16FROM clause 5-16Note 5-16References 5-17Retrieving references to a record 5-17Retrieving references using REFERS TO 5-17REFERS TO syntax 5-18Using aliases with REFERS TO 5-19

Page 7: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

v

Using program variables or constants with REFERS TO 5-19Example 5-21Company numbers 5-21The <table._compnr field 5-21Using <table>._compnr in the WHERE clause 5-22SQL and combined fields 5-23Specifying a combined field 5-23Comparison operators for combined fields 5-24Indexes as combined fields 5-24Meanings of upper and lower limits 5-25SQL subqueries 5-26Example 1 5-26Example 2 5-26SQL programming 5-27Embedded SQL 5-27Dynamic SQL 5-29SQL and delayed locks 5-31SQL trace options 5-32Client tracing 5-32Server tracing 5-32Query identification 5-33Trace options 5-33Error handling 5-39Fatal and non-fatal errors 5-39The eflag 5-40Example 5-41Hints for using SQL 5-41Hints for using db.retry.point 5-43Situation 1: Only update actions, commit per fetch 5-44Situation 2: Only update actions, commits over fetches 5-44Situation 3: only print / collect actions (no commit) 5-45Situation 4: Update actions plus print/collect with commit per fetch 5-45Situation 5: Update actions plus print/collect with commit over fetches 5-45

6 Data Access Layer (DAL) 6-1Overview 6-1Database integrity checks 6-2Business methods 6-2DAL terminology 6-3UI, DAL, and STP interaction 6-3Overview 6-3Example 6-4

Page 8: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

vi

UI function calls 6-4Function flow 6-4One-way interaction 6-5DAL hooks 6-5Property hooks 6-6fieldname.check() 6-6Object hooks 6-7Available object hooks 6-7Return values and errors 6-8before.open.object.set() 6-9before.get.object() 6-9after.get.object() 6-10before.destroy.object() 6-12after.destroy.object() 6-12before.save.object() 6-13after.save.object() 6-14after.commit.transaction() 6-15method.is.allowed() 6-15Data Access Methods (DAM) 6-16Property methods 6-17Setting properties 6-17Retrieving properties 6-17Query extensions 6-17Communication with STP and CDAS 6-18Transition issues (BAAN IV to BaanERP) 6-184GL event sections 6-184GL functions 6-19Session codes 6-20Predefined variables 6-20Questions 6-20Messages 6-21Non-table fields 6-21Include files 6-21

7 Multitasking and the GUI 7-1Overview 7-1Bshell scheduler 7-2Running queue 7-2Blocking queue 7-2Sleeping queue 7-3Terminating queue 7-3Context switches 7-3Forcing a context switch 7-3

Page 9: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

vii

Allocating bonus ticks 7-3Events 7-5Event types 7-5Event flow 7-5Event masks 7-6Event functions 7-6Event arrays 7-6Sample code 7-7Requests, inquiries, and replies 7-7Processes, process groups, and main windows 7-8Processes 7-8Process groups 7-9Main windows 7-9Process groups and main windows 7-9Synchronizing processes with the wait() function 7-13

8 Dynamic-link libraries 8-1Overview 8-1Function declarations 8-2Scope of variables across DLLs 8-2Global variables 8-2External variables 8-2Database fields 8-2Sharing DLL object code 8-3Dynamic linking 8-3Dynamic linking at compile time 8-3Dynamic linking at runtime 8-4Function overloading 8-4Specifying which DLLs belong to an object 8-5Function search algorithm 8-5Function overloading – example 8-6Object information tool 8-7Syntax 8-7Options 8-7Object and function descriptions 8-8DLL compilation and runtime errors 8-9Compilation errors 8-9Runtime errors 8-9

9 The BAAN debugger 9-1Overview 9-1Commands 9-1Debugger mouse actions 9-7

Page 10: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

viii

10 Errors 10-1UNIX errors 10-1Database errors 10-6

11 Known limits 11-1Reports 11-1Bshell 11-1Bic 11-1SQL 11-1Tables 11-1Indexes 11-2

12 ASCII table (ISO 8859-1) 12-1

13 Index 13-1

Page 11: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

ix

This document describes the main features of the Baan 3GL/4GL programminglanguage. Programming functions are described in a separate document:BaanERP Tools: Functions Reference (document number: U7167A US).

SummaryChapter 1 provides a brief introduction to Baan 3GL/4GL programming features.

Chapter 2 describes in detail the features of the Baan 3GL programminglanguage.

Chapter 3 describes the 4GL language features for BaanERP Tools. In particularit describes the 4GL event sections used in Baan 4GL program scripts. It alsodescribes the flow of the standard program, and it discusses the automatic importof variables

Chapter 4 describes the functionality available for creating report scripts.

Chapter 5 provides information about database handling and describes Baan SQLin detail.

Chapter 6 describes in detail the Data Access Layer (DAL) and the functionalityavailable for creating DAL scripts.

Chapter 7 describes how the bshell provides a multitasking executionenvironment for BAAN applications. It provides information about the Bshellscheduler, context switches, events, requests, inquiries and replies, process andprocess groups, and process synchronization.

Chapter 8 discussion the use of Dynamic Link Libraries (DLLs) in Baanapplications.

Chapter 9 provides information on the Baan Debugger.

Chapter 10 lists and describes operating system and database errors.

Chapter 11 lists the known limits that apply to Baan applications.

Chapter 12 presents an ASCII table (ISO 8859-1).

About this document

Page 12: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Table of contents

Programming features

x

Typographical conventionsThe following conventions are used in this manual:

bold Bold type is used for the names of functions, 4GL eventsections, and predefined variables, when these are included indescriptive text.

italics Italics are used for the names of function arguments, whenthese are included in descriptive text. Italics are also used forother non-literals, for emphasis in the text, and for the titles ofpublications.

monospace Monospace type is used for the syntax of functions,declarations, expressions, SQL statements, and so on, forprogram startup commands, and for code examples.

AcronymsCDAS Common Data Access Server

DAL Data Access Layer

DAM Data Access Methods

DLL Dynamic-link library

RDBMS Relational Database Management System

SQL Structured Query Language

STP Standard Program

UI User Interface

Related documentsBaanERP Tools: Functions Reference (document number: U7167A US)

This document describes in detail the functions available for developingBaanERP applications with the Baan 3GL/4GL programming language.

BaanERP Tools: Programming Features onlineThis document is available online as a Microsoft Windows help file. The helpfile includes the document BaanERP Tools: Functions Reference. Both the helpfile and the printed manuals are similarly organized. However, the help fileincludes numerous hypertext links to facilitate navigation, and a comprehensiveindex and full text search facility.

You can access the help file by choosing the Manual Pages option on theSpecific menu of the session Program Scripts (ttadv2530m000). The name of thehelp file is tt_mp2.hlp.

Page 13: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

1-1

The development tools supplied by the BaanERP Tools package enabledevelopers to program additional functionality for existing BaanERP applicationsor to build entirely new applications.

The features provided by the development tools include:

n The BaanERP 3GL programming language.

n 4GL language features that enable you to add to or modify the defaultbehaviour of sessions, reports, and the Data Access Layer.

n Baan SQL, which enables you to retrieve database data.

n Support for Dynamic Link Libraries (DLLs).

n A debugger that enables you to control and test the execution of yourprograms.

3GL scripts3GL scripts are program scripts that are either linked to sessions without formsor not linked to sessions at all. They do not have any relationship with the 4GLEngine (previously known as the Standard Program or STP). When creating suchscripts, you must specify the entire program flow, including the main function.You cannot use 4GL event sections or functions. Chapter 2, 3GL programminglanguage features, describes the 3GL programming language in detail.

4GL UI and DAL scriptsIn BaanERP applications, the 4GL engine provides much of the defaultfunctionality for a session. You can add to or modify the default functionality ofa session by creating a 4GL script that is linked to the session. 4GL scripts areevent-oriented. They consist of one or more event sections in which you programactions to be performed at particular states of execution of the 4GL engine.

In previous versions of the software, changes or additions to the defaultfunctionality of a session were programmed in a single script that was associatedwith the session. In BaanERP, user interface actions and database actions havebeen separated.

1 Introduction

Page 14: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Introduction

Programming features

1-2

The Data Access Layer (DAL) now handles database interaction. Programmerscreate a user interface (UI) script to change the default behavior of a session.They create a DAL script to program all the logical integrity rules for a particulartable.

Chapter 3, 4GL programming features, describes the 4GL event sections that youcan use in UI scripts. Chapter 6, Data Access Layer, describes the event sectionsand DAL functions that you can use in DAL scripts.

The statements programmed in event sections can be a combination of 3GL/4GLfunctions and 3GL language statements.

Report scriptsReport scripts are 4GL scripts that are linked to a report in order to add to ormodify its output. In a report script, you can program actions that you want to beperformed at particular stages of the report execution. Chapter 4, Report scripts,describes the event sections and report functions that you can use in reportscripts.

Baan SQLYou can use Baan SQL (Structured Query Language) in 4GL scripts to retrievedata from database tables. There are two ways to use Baan SQL in a 4GLprogram. You can embed it in the language (embedded SQL), or you can useBaanERP 4GL functions (dynamic SQL). Chapter 5, Database handling,describes both options in detail.

Dynamic-link librariesBaanERP Tools supports the use of dynamic-link libraries (DLLs). A DLLconsists of a library of functions that is compiled and stored separately from theprocesses that use the library. Each program that uses a DLL links to it atruntime. Chapter 8, Dynamic-link libraries, describes the use of DLLs inBaanERP applications.

BaanERP debuggerWhen you compile your programs, you can use the BaanERP debugger to controland test their execution. Chapter 9 provides an overview of the debugger anddescribes the numerous options it supports.

Page 15: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Introduction

Programming features

1-3

MultitaskingThe bshell (also referred to as the Baan Virtual Machine) provides a multitaskingexecution environment for BaanERP applications. Each bshell can execute andschedule multiple parallel processes. Chapter 7, Multitasking and the GUI,provides an overview of how processes and user interface interaction aremanaged by the bshell.

3GL/4GL functionsBaanERP 3GL and 4GL functions are described in a separate document:BaanERP Tools: Functions Reference (document number U7167A US).

Page 16: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Introduction

Programming features

1-4

Page 17: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

2-1

OverviewThis section describes the features of the Baan 3GL programming language. Youcan use the 3GL language in both 3GL scripts and 4GL scripts.

Vocabulary

Character set

You can include the following characters in a 3GL language statement:

n The full alphabet – a-z and A-Z

n The digits 0-9

n The characters # $ ^ & * ( ) - _ + = { } [ ] | \ ; : " , . / < >

This document uses uppercase characters to indicate keywords. However, this isnot necessary in your programs.

Continuation symbol

If a statement does not fit on one line, you can split it across two or more lines.There is no limit to the number of lines that you can use for one statement.Wherever you can include a space, you can also make a new line.

There are two exceptions: a string constant and a macro definition. If these donot fit on one line, you must place a caret symbol [^] at the beginning of thesecond and subsequent lines. You can use the caret symbol in other statementsalso, but this is not necessary.

Comment

The pipe symbol [|] indicates that the text from the symbol to the end of the linemust be handled as a comment. The compiler ignores this text. Good commentshelp the reader of a program source to understand the program better.

2 3GL programming language features

Page 18: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-2

Separators

You can use tabs, newlines, and spaces as separators in your program.

Reserved words

The Baan 3GL programming language includes a number of words with definedmeanings. These are reserved words that you cannot use other than in the contextfor which they were designed. Not all these words are described in thisdocument; some are for internal use or for compatibility with older releases.

The following is a list of these reserved words:

AND END IN SELECTBIND

AT ENDCASE INPUT SELECTDO

BASE ENDFOR LE SELECTEMPTY

BASED ENDIF LONG SELECTEOS

BREAK ENDWHILE LT SELECTERROR

BSET ENDSELECT MB STATIC

CALL ENDDLLUSAGE MULTIBYTE STEP

CASE EQ NE STOP

COMMON EXTERN NOT STRING

CONST FALSE ON TABLE

CONTINUE FIXED OR THEN

DEFAULT FOR PRINT TO

DIM FUNCTION PROMPT TRUE

DLLUSAGE GE REF UNTIL

DOMAIN GLOBAL REFERENCE VOID

DOUBLE GOTO REPEAT WHEREBIND

ELSE GT RETURN WHEREUSED

EMPTY IF SELECT WHILE

Page 19: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-3

ConstantsA constant is a value of a special type that you can assign to a variable. The Baan3GL programming language supports the following types of constants:

n Numeric constantsn String constantsn Symbolic constantsn Enumerate / set constants

Numeric constants

The Baan 3GL programming language supports long and floating pointconstants. Both types can be preceded by a ’+’ or a ’-’ sign.

Long constants

A long constant consists of the digits 0-9 only. For example:

12345-5300xFFF (hexadecimal)

Floating point constants

Floating point constants consist of the digits 0-9 and a decimal point. You cannotend a constant with a decimal point. An exponential part can be added to aconstant by including the letter ’e’ followed by a long constant (maximum 307).You can have up to six digits after the decimal point in a constant. For example:

123.560.8743.8743123.5e-5-2.34e10

Page 20: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-4

String constants

A string constant is a number of displayable single-byte or multibyte charactersenclosed by double quotation marks. A string constant with length zero (that is,an empty string) is indicated by two adjacent quotation marks. To include adouble quotation mark within a string constant, you must include two adjacentdouble quotes.

For example:

"This is a string constant""""A quote "" within a string constant""This is a very long string constant whic^h does not fit on one line"

Symbolic constants

A symbolic constant is used in your program as a symbolic name, but at runtimeit has a fixed value. The defined constants are:

FALSE | The actual value is 0TRUE | The actual value is 1PI | The actual value is 3.141592653589793

Note that if FALSE and TRUE are used as boolean values (for example, as aresult of expressions), they mean zero and not zero respectively.

Enumerate and set constants

In the data dictionary you can define database table fields and domains of typeenumerate or set.

An enumerate or set domain consists of a number of constants. In the programscript (and other places in the data dictionary), a symbolic name is used. Thesymbolic name is the domain name, followed by a period [.] followed by thename of the constant. Variables of type set can also consist of a combination ofset values.

Examples of enumerate constants

DOMAIN colorbox_color | color is an enumerate domain| with two constants, green| and red

box_color = color.greenbox_color = color.red

Page 21: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-5

Examples of set constants

DOMAIN feature cf | feature is a domain of type set| with the constants bold,| reverse, underlined

cf = feature.boldcf = cf + feature.reverse| add constant, cf contains

| bold and reversecf = cf - feature.bold | subtract constantetol( cf ) | returns the combined number of the

| current value, here reverse.

For working with sets, see also the bit functions in U7167A US BaanERP Tools:Functions reference.

A special constant of type enumerate or set is EMPTY. This indicates an emptyset or an enumerate which is not defined. Internally, it has the value 0.

VariablesThe name of a variable is used to indicate the memory location where data(characters, numbers, and so on) is stored. The name of the variable refers to theassociated data.

The value of a variable can change during execution of the program. A variablebelongs to a data type and must be declared before its use. This is usually done atthe start of the program. In some cases initialization of the declared variables isnecessary. The default initial value is always zero for longs and doubles, and anempty string for strings.

The name of a variable can consist of any number of letters, digits, underscores[_], and periods [.]. It must begin with an alphabetic character.

You should keep the following in mind when naming a variable:

n The name of a variable must not be the same as a reserved word or apreviously declared variable.

n The name of the variable must give an indication of its contents. It is goodpractice to indicate the purpose of a variable beside its declaration, in theform of comments.

n A variable must not be used for a purpose other than the one for which it wasoriginally intended.

Page 22: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-6

Data types

There are five types of variables: long, double, string, table, and domainvariables.

n Long variables can contain any whole number from -2147483648 to2147483647. For numbers beyond this range, use double variables instead.Physically, four bytes are reserved for each long variable.

n Double variables are used for any number containing a decimal point, with amaximum of 15 significant digits (8 bytes).

n A string variable contains a string constant. The maximum length of a stringis 1024 characters.

n A table variable is used for database tables in your program. The table mustbe defined in the data dictionary.

n A domain variable is a variable of a certain type that is defined in the datadictionary. Each of the following types are possible: long, byte, integer, date,enumerate, set, float, double, string, text. Each domain defined in the datadictionary can be used in a declaration of your program. See also “Domains”later in this chapter.

Declarations

You can declare variables either within a function block or at the start of theprogram. Variables declared in a function block can be used within that functionblock only. Variables declared at the start of the program can be used in eachfunction described below the declaration.

General syntax

You declare variables with the following syntax (parts between [ ] are optional):

[ special ] <type> <variable> [ option ] [, <variable>[ option ], ...]

Page 23: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-7

The following are the possible values for the various parts of a variabledeclaration:

special EXTERN | Not in function blocksSTATIC | Only in function block; see

| "Functions" later in this chapter.

type LONGDOUBLESTRINGTABLEDOMAIN <domain name> | domain name is a domain

| defined in the data| dictionary

variable The syntax for <variable> is:

<name>[(<expression>,...)]

option BASED | (only for arrays)FIXEDMB | (multibyte)

You can declare several variables of the same type in the same statement. To doso, simply include commas between the variable names.

If a variable is to be accessed by its symbolic name from outside the program, itmust be declared with the keyword EXTERN, so that the variable name is storedin the symbol table of the object.

You must declare a variable with the keyword EXTERN if that variable is usedwithin other programs, within forms (field names and variables withinexpressions), or within the function expr.compile(). If the functions get.var()and put.var() are used within the program, the variables in the other programmust be declared as EXTERN.

Tables

If you use database tables and records in your program, you must declare thetables as follows:

TABLE <table name> | table name must start with a ’t’.

This declaration creates a pointer to the table. Declaration of a table impliesdeclaration of all its fields and its record buffer. It is not necessary to declarethese separately.

For a further details see Chapter 5, Database handling.

Page 24: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-8

Domains

When declaring temporary variables for storing values of database fields, youcan use normal variables of type long, double, or string. But this can causeproblems if the length or type of the table field has been changed in the datadictionary. It is preferable to use domain declarations for storing the value of adatabase table field. When you use a domain declaration, the type and length forthe declared variable are read from the data dictionary.

Variables of type enumerate or set must always be declared with a domaindeclaration.

It is also possible to declare an array by using a domain. In that case the numberof elements must be set between the brackets, the length of the elements isembedded in the data dictionary.

Examples

The following examples illustrate various domain declarations, and thedeclaration of the same variables without domains.

DOMAIN declarations

DOMAIN tst_str10 tmp_str, | String of length 10tmp_str_arr(100) | 100 strings of

| length 10DOMAIN tst_long tmp_lng1, | A long number

tmp_lng2, | Another long numbertmp_lng_matr(5,2) | A matrix 5 x 2

DOMAIN tst_double tmp_dbl, | A floating pointtmp_dbl_arr(100) | 100 floating points

STRING declarations

#define LENG 10STRING tmp_str(LENG), | String of length 10

tmp_str_arr(LENG*10,10) | 10 strings of length | 100

LONG declarations

LONG tmp_lng1, | A long numbertmp_lng2, | Another long numbertmp_lng_matr(5,2) | A matrix 5 x 2

DOUBLE declarations

#define MAXLEN=1000DOUBLE tmp_dbl, | A floating point

tmp_dbl_array(MAXLEN/10) | MAXLEN/10 floating | points

Page 25: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-9

Arrays

You use arrays to store multiple variables of the same type within one data item.Each variable can be referred to with the construction array_name(index).For example, the first element in a one-dimensional array is array_name(1).

An array can have up to four dimensions. The dimension (and, in case of a string,also the length) of an array must be stated in the declaration.

There are three types of arrays: long, double, and string.

Long arrays

You declare one-dimensional long arrays as follows:

LONG lng_array(5) | 1-dimensional array for 5 longs

The number in parentheses after the array name specifies the number of longsthat can be stored in the array.

You declare two-dimensional long arrays as follows:

LONG lng_array(2,4)

The first number after the array name indicates the number of dimensions in thearray. The second number indicates the number of longs that can be stored ineach dimension. The following diagram illustrates a two-dimensional array as amatrix:

lng_array(1,1) = 3 lng_array(2,1) = 100

lng_array(1,2) = 4 lng_array(2,2) = 98

lng_array(1,3) = 56 lng_array(2,3) = 55

lng_array(1,4) = 78 lng_array(2,4) = 77

Double arrays

A double array differs from a long array only in that it is prefixed by the keywordDOUBLE and the array elements must be filled with double values. You declarea double array as follows:

DOUBLE dbl_array(5)

Page 26: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-10

String arrays

The declaration of string arrays differs from that for other array type in that thefirst dimension contains the length of the strings to be stored in the array. Forexample:

STRING str_arr(10,5) | 5 strings of length 10STRING str_arr(10,5,5,5) | A 5 x 5 x 5 matrix of

| strings of length 10

When referencing a string array, the first dimension indicates the start position inthe string. The particular string to be accessed is indicated by the otherdimensions. It is possible to specify a length for the string to be retrieved byusing a semicolon [;] followed by the required length. If you omit the length, thetotal length of the string is taken.

Example 1 (two-dimensional string array)

STRING str_arr(6,2) Space reserved for 2 strings of 6 characterseach. For example, the first string contains"abcdef" and the second "ABCDEF".

str_arr(1,1) = "abcdef" This references the first string starting atposition 1.

str_arr(2,1;1) = "b" This references the first string starting atposition 2 with length 1.

str_arr(3,2) = "CDEF" This references the second string beginningat position 3.

Example 2 (filling string variables)

Consider a string declared as:

STRING strg(26)

The statements listed below will have the indicated results:

strg = "good morning" The words "good morning" are storedfrom the first position of strg:

"good morning"

strg(1) = "good morning" The same result but filled with spaces:

"good morning "

Page 27: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-11

strg(9) = "good morning" The string is stored from position 9onwards and filled with spaces:

" good morning "

strg(2;3) = "Hello" The letters "Hel" (3 characters) are storedfrom position 2 onwards:

" Hel good morning "

Example 3 (accessing string variables)

Suppose the string declared in the previous example has the value"ABCDEFGHIJKLMNOPQRSTUVWXYZ". The results of the statementsbelow will be as indicated:

print strg "ABCDEFGHIJKLMNOPQRSTUVWXYZ"print strg(13) "MNOPQRSTUVWXYZ"print strg(2;3) "BCD"

In these examples, strg(n) refers to the entire array from position n onwards andstrg(n;x) refers to x positions starting at position n.

Example 4 (two-dimensional string array)

Consider a 2-dimensional string array declared as:

STRING twice(6,2)

The statements below will have the indicated results.

twice(1,1) = "ABCDEF" The first string is filled from position 1onwards.

twice(1,2) = "123456" The second string is filled from position 1onwards.

print twice(3,1) "CDEF" is printed.

print twice(4,1;2) Two characters are printed starting at position4 in string 1 – that is, "DE" is printed.

Page 28: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-12

String lengths

There are two lengths associated with a string: the maximum and the currentlength. The maximum length is defined at declaration of the string and thecurrent length can vary, depending on the contents of the string.

If a string is declared as STRING strg(100), the maximum length of strg is 100.If strg is filled as strg = "hello", the current length is 5. If strg is filled as strg(1) ="hello", the current length is also is 100, as the remaining positions are filled withspaces. When you specify a start position, the string is always filled out withspaces.

If a string is declared as FIXED, the current length is always equal to themaximum length, because the string is always filled up with spaces. Also, in thecase of multi-dimensional strings, the current length is always equal to themaximum length.

Fixed and based variables

Fixed variables

A string variable can be declared as fixed so that its current length always equalsthe maximum length. For example:

STRING name(10) FIXEDname = "andrew" | the string is always filled up

| with spaces

The keyword FIXED is applicable to one-dimensional strings only. Multi-dimensional string arrays are always fixed and do not need to be declared withthe keyword FIXED.

Based variables

The BASED mechanism is applicable to strings or arrays of all possible types. Itdetermines that a variable will be based on another variable. For based variables,no memory space is reserved when they are declared. At runtime they use thesame memory space as the variable on which they are based. So by using thismechanism, the same section of memory can be accessed via different names.

You use the following construction to base one variable on another:

BASE var_1 AT var_2

In the case of a string, the based variable is always fixed. You must ensure thatthe based variable always fits in the variable on which it is based. So it will besafe to declare the basic variable as FIXED.

Page 29: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-13

Example

STRING a(10) FIXEDSTRING b(5) BASEDBASE b AT a(3) | This indicates that the space

| occupied by b is the same as the| space for a(3;5)

b(2;3) = "yes" | a(4;3) now also contains "yes"a(1;8) = "12345678" | b now contains "34567"

Variable and fixed length strings

The following points summarize the rules for variable and fixed length strings:

n Strings with variable length are 1-dimensional strings not declared as basedor fixed. All other strings are fixed– that is, database table fields, stringarrays, and variables declared as FIXED or BASED.

n Normally, variable length strings are not filled up with spaces except when astart position is specified in the assignment.

n Fixed length strings are always filled up with spaces, except when a length isspecified. In the latter case, the remaining positions are not overwritten byspaces.

n If a string (of variable or fixed length) is filled from a certain start position,the part of that string preceding the start position is filled up with spaces if itwas not filled before.

Multibyte strings

A string variable can be declared as a multibyte string, in order to handlemultibyte or bidirectional characters. For example:

STRING mb_str(10,5) MB | 5 multibyte strings of 10characters

In a single-byte string, each byte contains a single character. But in a multibytestring, characters can occupy from one to four bytes.

Example

This multibyte string contains six characters. The fourth character is a TSS (thatis, multibyte) character containing 4 bytes. Note that all TSS characters areprefixed with hex 9b.

Page 30: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-14

n In program scripts, it is not possible to assign a multibyte character (forexample, Chinese) to a multibyte string.

n The string declared as:

str(x) MB | x is the number of characters

requires a space of x * mb.factor (where mb.factor has been defined inthe user file). A Japanese character for example has a multiplication factor ofabout 2.

n The string str(x;1) contains one character, and a size of one or four bytes.If the character has a size of 4 bytes, it is a TSS character.

n It is not advisable to assign a multibyte string to a normal string, as this cancause problems regarding storage space and special manipulations likeindexing.

n You cannot use multibyte strings in combination with the BASEDmechanism.

Bidirectional strings

Bidirectional functionality is necessary to support languages that read and writefrom right to left– for example, Arabic and Hebrew. Bidirectional input issupported only on fields of type multibyte string. A string is bidirectional when itcontains at least one bidirectional character. You can check whether a stringincludes bidirectional characters by calling mb.hasbidi(). All strings, includingbidirectional, are stored in logic order – that is, the first typed character is theleftmost one in the string. This means that all regular string handling functionslike pos(), and constructors like the semicolon [;], work correctly.

Special attention must be paid when concatenating or splitting strings. Whenbidirectional and non-bidirectional strings are concatenated, one part must bereversed.

Common variables

Unlike other variables, which can be used only within the program in which theyare declared, common variables can be used in more than one program. Onlystring variables can be declared as COMMON.

Common variables are automatically based on a common memory part that canbe used by several programs. For this reason they must be declared as BASED.The fact that they are common must be indicated with the reserved wordCOMMON.

NOTES

Page 31: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-15

Declaration of common variables must be located outside every function. So theymust be declared as global variables.

Example

In program 1 and program 2, the same memory space is used for variables com_1and com_2.

Within program 1:STRING com_1(10) BASED, com_2(15) BASEDCOMMON com_1, com_2<functions which use com_1 and com_2>

Within program 2:STRING com_1(10) BASED, com_2(15) BASEDCOMMON com_1, com_2<functions which use com_1 and com_2>

As an alternative to using common variables, you can use import(), export(),get.var() and put.var() to transport the values of variables between processes.

NULL characters in strings

Technically, a string is an array of characters. The internal representation of astring has a NULL character [\0] at the end. The NULL character represents thecharacter with the value zero.

Null characters can occur within strings after use of the following functions:

seq.read()copy.mem()store.byte()store.short()store.long()store.double()store.float()

When a normal string is copied into another string, it is always copied up to thefirst NULL character. If the target string is a fixed string, then it is filled up withspaces from the NULL character to the end of the string. The copy action canresult from a normal assignment, from passing a string as a call by valueparameter to a function, or from the use of the import() and export() functions.

There is one exception to this rule. When the left or right side in an assignment isa record buffer (rcd.<table name>), all bytes in the buffer will be copied.

Page 32: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-16

For example:

table tttadv999

strbuf = rcd.ttadv999 | NULL characters are copiedrcd.ttadv999 = strbuf | NULL characters are copied

strbuf2 = strbuf | NULL characters are NOT copied

In all other cases, if NULL characters are meaningful, use copy.mem(). Thiscopies NULL characters as well as ordinary characters.

Expressions and operatorsAn expression is a combination of variables, constants, and operators, built up inaccordance with certain rules. There are two main kinds of operators: unary andbinary. All operators, except the negation operators, are binary. Expressions withunary operators have the general form:

operator operand

Expressions with binary operators have the following form, where each operandcan be another expression, variable, or constant:

operand_1 operator operand_2

The available operators can be divided into four categories: arithmetic, relational,logical, and control operators.

Class Operator Description

Arithmetic -* / + -\&

negationmultiply/divide/add/subtractremainder after divisionstring concatenation

Relational = r EQ<>or NE> or GT< or LT>= or GE<= or LE

is equal tois not equal tois greater thanis less thanis equal to or greater thanis equal to or less than

Logical AND, OR, NOT logical ‘and’, ‘or’ and negation

Control ? : question mark expression

Page 33: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-17

The question mark expression is a special type of expression. The syntax is:

<condition> ? <expr_1> : <expr_2>

If the condition is TRUE, expr_1 is executed. If the condition is FALSE, expr_2is executed. For example:

lng_1 = (a >= b) ? a : b| if condition a >= b is TRUE lng_1 gets the value of a,| else lng_1 gets the value of b.

For further information on the different operator types, see the followingsections.

Arithmetic operators

Arithmetic operators perform arithmetic operations on the operands. Allarithmetic operators, except string concatenation, must have operands ofnumerical type. If one of the two operands is a double, the other is also convertedto double, and the result is also of double type. For example:

45/30 is equal to 1 | 45 and 30 are both LONG so the result is LONG

45/30.0 is equal to 1.5 | 30.0 is a DOUBLE so the result is a DOUBLE

The concatenation operator concatenates expressions, variables, or constants ofstring type.

Examples

LONGlng_1, lng_2DOUBLE doubSTRING strg_1(16), strg_2(50), strg_3(10), strg_4(20)

Expression Result

lng_2 = 8\3 The variable lng_2 contains 2, which is theremainder after dividing 8 by 3.

lng_1 = lng_2 + 3 The variable lng_1 now contains 5.

doub = lng_1 * 2.0 The variable lng_1 is multiplied by 2.0;the result (10.0) is stored in doub.

Page 34: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-18

doub = 45 / 30 The variable doub now equals 1.0.

Note that 45 and 30 are both longs, so theresult of the expression is 1. Converted todouble for storing in the result, thisbecomes 1.0.

doub = 45 / 30.0 The variable doub now contains 1.5.

strg_1 = "hel" & "lo" The variable strg_1 now contains the value"hello".

strg_2 = strg_3 & strg_4 The contents of strg_3 and strg_4 areconcatenated and placed in strg_2.

Relational operators

Relational operators compare two operands. If the condition (equal, greater than,less than, and so on) is satisfied, the result becomes TRUE. If not, it becomesFALSE.

Relational operators can be performed on values of every available type, but theoperands of one expression must be of the same type. One exception to that ruleis that longs can be compared to doubles.

In the case of strings, the ASCII values of the strings are compared on the basisof the following rules:

n The comparison is made on the basis of the ASCII value of the strings,starting at the leftmost character of each string.

n If two characters are not equal, the string with the lower character value isconsidered to be smaller and the comparison is terminated.

n If both strings contain the same number of characters and the characters agreein all cases, the strings are equal. If one string is shorter than the other, andthe corresponding characters are equal, the shorter string is considered to besmaller than the other.

Logical operators

Logical operators perform logical operations on their operands. The operatorNOT is unary, so it has only one operand. The operands of logical operators canbe logical expressions, relational expressions, variables, or constants.

Page 35: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-19

The following table illustrates the results of logical expressions:

A B NOT A A AND B A OR B

FALSE FALSE TRUE FALSE FALSE

FALSE TRUE TRUE FALSE TRUE

TRUE FALSE FALSE FALSE TRUE

TRUE TRUE FALSE TRUE TRUE

Variables or expressions of type LONG can be used as boolean. If a longexpression results in the value zero, it is evaluated as FALSE. If the result is notequal to zero, it is evaluated as TRUE

Operator precedence

An expression can include a number of operators, variables, and constants. Theoverall result is calculated in accordance with the rules of precedence describedhere. For example, because multiplication has precedence over addition, theresult of the expression (3 + 4 * 5) is 23 and not 35.

The following table lists all operators in order of decreasing precedence.Operators with high precedence are evaluated before operators with lowerprecedence. Operators on the same line in the table have the same precedence. Ifthey occur in one expression, they are evaluated from left to right.

Operator Associativity

- (negation) right to left

* / \ left to right

& left to right

+ - (minus) left to right

= > < <> <= >= none

NOT right to left

AND left to right

OR left to right

?: right to left

You can use parentheses to force a specific precedence. For example:

The result of the expression 3+4*5 is 23The result of the expression (3+4)*5 is 35The result of the expression 10/2*5 is 25The result of the expression 10/(2*5) is 1

Page 36: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-20

In case of doubt, always use parentheses. This makes the program easier to read.

n The operators NOT and - (negation) are unary, the others are binary.

n The relational operators are non-associative. This means that A <= B <= C isnot available. This should be A <= B AND B <= C.

Assignment Operator

You use the assignment operator [=] to store variables, constants, and the resultsof expressions in a variable.

Examples (general)

LONG I, J, K(100), L(100)

STRING S(50), A, B(10)DOUBLE AMOUNT

J = 4AMOUNT = 123.45 * JL(20) = 1001S = "This is an example"

I = J | The contents of J are stored in| variable I

L(2) = L(20) | Now L(2) is equal to L(20)A = S(3;1) | The character ’i’ is placed in AB(1;2) = S(6;2) | The word ’is’ is placed in the first

| two positions of BK = L | The entire content of array L is

| copied to K

Except in the case of doubles and longs, both operators must be of the same type.For doubles and longs, the following rules apply:

Left operator Right operator and conversion

long Can be integer or double. The result is converted to integer. Incase of double, the digits after the decimal point are truncated.After truncation the value must be between -2147483648 and2147483647.

double Result converted to double.

NOTES

Page 37: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-21

Examples (longs and doubles)

LONG ADOUBLE CA = 3.14 | A is set to 3C = A | C now contains 3.0C = 45 / 30 | C now equals 1.0, because this

| division results in a long

Transfer of controlThe Baan 3GL programming language supports several statements that changethe flow of control in a program. These enable control to be transferred eitherconditionally or unconditionally to a specified point in the program.

You use the GOTO statement to transfer control unconditionally to a specifiedpoint. You use the IF...THEN...ELSE statement or the ON CASE statement forconditional transfer. These latter statements evaluate a specified condition andtransfer control if the condition is TRUE.

The GOTO statement

The GOTO statement transfers control unconditionally to a specified point in theprogram. You use a label to indicate a position to which the statement cantransfer control. The label name can consist of letters, digits, underscores [_], andperiods [.]. It must begin with an alphabetic character.

Examples of labels:

LABEL_1:START_OF_PROCESS_A:

Examples of GOTO statements:

GOTO LABEL_1GOTO START_OF_PROCESS_A

Both the GOTO statement and the label to which it refers must be within thesame function. You cannot transfer control to a label in another function.

Page 38: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-22

The IF ... THEN ... ELSE statement

The IF statement enables conditional transfer of control. The statement tests acondition, and executes the succeeding statements only if the condition is true.The condition can consist of an expression, or it can be a long variable or afunction that returns a long. When the condition is a long variable or a functionthat returns a long, the value zero is evaluated as FALSE and all other values areevaluated as TRUE.

IF...THEN

This tests a condition. If the condition evaluates to TRUE, the statementsfollowing the IF...THEN statement are executed. For example:

IF condition THENstatement(s)

ENDIF

IF...THEN...ELSE

This tests a condition. If the condition evaluates to TRUE, the statementsfollowing the IF...THEN statement are executed. If the condition evaluates toFALSE, the statements following the ELSE statement are executed. For example:

IF condition THENstatement(s)_1

ELSEstatement(s)_2

ENDIF

Examples

IF a > b THENb = b + 1

ENDIF

IF present AND found THENcount = count + 1do_something()

ENDIF

IF isspace(str1) THENmessage("String is empty")

ENDIF

IF a > b THENmax_val = a

ELSEmax_val = b

ENDIF

Page 39: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-23

The ON CASE statement

This statement has the following syntax:

ON CASE expressionCASE expr_1:

statements_1break

CASE expr_2:statements_2break

CASE expr_3:statements_3break

DEFAULT: | optionalstatements

ENDCASE

The ON CASE statement is a multiple-way decision table. It evaluates anexpression and compares the result with the expressions of each specified CASE.When a match is found, control transfers to that branch and the code for thatparticular CASE is executed. If no match is found, the DEFAULT code isexecuted. If there is no DEFAULT label, the program continues with the firststatement after ENDCASE. CASES and the DEFAULT label can occur in anyorder.

The CASE statements serve as labels. This means that after execution of thestatements related to a particular CASE, the remaining CASES continue to beevaluated. However, if two CASE expressions give the same result, only the firstis executed.

You can use the BREAK command to skip evaluation of other CASES after thecode for the matching CASE has been executed. You include this command atthe end of the code for each CASE. When the command is executed, execution ofthe ON CASE statement ends. In the case of nested CASES, the BREAKcommand cancels execution of the CASE statements at the same level only.

The ON CASE expression must be either a long expression or a stringexpression.

Long expressions

The expression after ON CASE is evaluated and compared with the variousCASE expressions that follow. All expressions in the case labels must be of typeLONG or STRING. When string expressions are used, the ASCII value of thestring is compared with the ON CASE expression.

Page 40: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-24

For example:

ON CASE weekdayCASE 1:

day = "Sunday"BREAK

CASE 2:day = "Monday"BREAK

CASE 3:day = "Tuesday"BREAK

DEFAULT:day = "other day"

ENDCASE

It is also possible to execute a statement for multiple labels. For example:

ON CASE weekdayCASE 1:CASE 2:CASE 3:CASE 4:

beginweek()BREAK

CASE 5:CASE 6:CASE 7:

endweek()BREAK

ENDCASE

String expressions

The expression after ON CASE is evaluated and compared with the variousCASE expressions that follow. Normally, when the ON CASE expression is astring expression, the CASE expressions are also strings. However, if the ONCASE expression evaluates to a non-printable character – for example, ESC(=27), this cannot be tested against a string constant. In this situation, the CASEexpressions can be integer constants that represent ASCII values. The ASCIIvalue of the ON CASE expression is then compared with the numeric values ofthe CASE labels.

Page 41: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-25

For example:

ON CASE choice_charCASE "A":CASE "E":

abort()CASE "N":

next_screen()BREAK

CASE "P":last_screen()BREAK

CASE 27:escape()BREAK

DEFAULT:message("unknown choice")

ENDCASE

IterationsIterative statements repeat the associated statements until a specified conditionbecomes FALSE.

WHILE statement

This statement has the following form:

WHILE expressionstatement(s)

ENDWHILE

The expression is evaluated. If the result is TRUE (that is, non-zero), thestatements between WHILE and ENDWHILE are executed. The process is thenrepeated until the expression is FALSE (that is, zero). When the expressionevaluates to FALSE, control passes to the statement after ENDWHILE. Forexample:

LONG countercounter = 1WHILE counter <= 10000

counter = counter + 1ENDWHILE

Page 42: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-26

FOR statement

This statement has the following form:

FOR num_var = num_expr_1 TO num_expr_2 [STEP num_expr_3]statement(s)

ENDFOR

The num_var variable is referred to as the loop variable. Num_expr_1 specifiesthe initialization of the loop variable. Num_expr_2 specifies the end value of theloop variable. Num_expr_3 specifies the step size for each iteration. The lattervariable is optional; the default step size is 1. It is possible to use a negative stepsize.

After execution of the statements within the loop, num_expr_3 is added to theloop variable. The num_expr_2 expression is then evaluated. If the loop variabledoes not exceed num_expr_2, the statements are executed again. This processcontinues until the loop variable exceeds its end value. For example:

LONG total, iFOR i = 1 TO 100 STEP 2

total = total + iENDFOR

REPEAT ... UNTIL statement

The REPEAT ... UNTIL differs from the WHILE statement, in that the REPEAT... UNTIL statement tests the condition after execution of the loop statementsinstead of before execution of the loop statements. Consequently the statement(s)within a REPEAT ... UNTIL statements are executed at least once.

The syntax of this statement is:

REPEATstatement(s)

UNTIL expression

The loop iterates as long as the result of the expression is non-zero.

Using BREAK and CONTINUE (iterations)

You can use the BREAK command in an iterative statement in order to cancelthe loop, regardless of the value of the loop condition. After a BREAK, controlpasses to the statement following the terminated loop. It is important to note thatwith nested loops the BREAK statement cancels the innermost loop only.

The CONTINUE command also interrupts an iteration loop. But, in this case, theexpression is immediately evaluated again for the next iteration.

Page 43: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-27

For example:

LONG numbers(100), iFOR i = 1 TO 100

IF numbers(i) <= 0 THENCONTINUE | Next iteration

ENDIFIF NOT process(numbers(i)) THEN

BREAK | Exit FOR statementENDIF

ENDFOR

The BREAK and CONTINUE commands can be very useful in a program, butyou should be take great care when using them.

FunctionsIn a program, a function performs a particular task that can be executed manytimes, with different values. The syntax of a function is as follows (parts betweenbrackets [] are optional):

FUNCTION [ function_type ] function_name( [ arglist ] ){

declaration of local variablesstatement(s)RETURN[( return_value )]

}

where arglist consists of one or more argument declarations with the followingsyntax:

[REFERENCE / CONST] argument_type argument_name

When including more than one argument declaration, use commas [,] to separatethe declarations. Note that the key word REFERENCE can be replaced by REF.

Function type and return value

The type declaration in a function declaration indicates the type of the function.This must be the same as the type of the return value. Functions can be of thefollowing types:

n longn doublen stringn domainn void (this means that no value is returned)

Page 44: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-28

If you do not specify a type, the function is of type void by default. In functionsof type void, the return statement cannot have any argument. For example:

FUNCTION add_one() | this function is of type void{

count = count + 1 | count is a global variableRETURN

}

Local variables

Variables declared within a function block are local variables. They areaccessible only within the function in which they are declared.

Declaration, initialization, and scope

Point of declaration In the function between the brackets { }.

Syntax of declaration <type> name

Initialization The value of local variables is undefined with eachfunction call. Local variables must always beinitialized in the function.

Scope (validity and time) Only within and during function execution.

Example

function void test(){

long I | Local variablefor i =1 to 100 | Always to be initialized by user

....endforreturn

}

Static variables

You can declare local variables as static variables. The value of a static variableis saved at the end of the function and is used again the next time the function iscalled. A static variable is automatically initialized at the start of the program.Normal local variables are undefined at each function call, and are not initializedat first call.

Page 45: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-29

Declaration, initialization, and scope

Point of declaration In the function between the brackets { }.

Syntax of declaration static <type> name

Initialization At program start:

numericset to 0strings set to ""

Scope (validity and time) Can be used only within the function but theymaintain their values throughout programexecution.

Example 1

function test(){

static long startedif (not started) then

started = true| Actions to be performed only first time around.

endif....

return}

Example 2

function void spool( long id, ref string line() ){

static long save_idstatic long lfnif ( save_id <> id ) then | Optimalization

lfn = read_new_lfn( id )save_id = id

endifseq.puts( line, lfn )

}

Page 46: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-30

Global variables

Variables declared outside any function block are global variables. You can usethem in all functions that occur after the variable declaration.

Declaration, initialization, and scope

Point of declaration Outside the functions.

Syntax of declaration <type> name

Initialization At program start:

numericset to 0strings set to ""

Scope (validity and time) Valid anywhere in the source, throughout theexecution. If any arguments or variables within afunction are declared with the same name as aglobal variable, the global variable cannot then beaccessed within that function.

Example 1

function test(){

return}long glob_var

function long dupl(){

return( glob_var * 2 )}

In this example, glob_var is a global variable. It is not accessible in the test()function as it was declared after that function block. On the other hand, glob_varis accessible in function dupl().

Example 2

long ifunction void test(){

long ii = 10 | This is the local variable

| Nothing happens to the global variable ’i’}

Page 47: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-31

External variables

An external variable is declared outside the function blocks. You can use them inall functions that occur after the variable declaration, and also in other programs(for example, forms, reports, and runtime expressions). It is possible to declareexternal variables within a function block but this is not recommended.

If a local variable has the same name as an external variable, the local variable isused within the function. The external variable is not affected.

Declaration, initialization, and scope

Point of declaration Outside the functions. (Or within a function, but thisis not recommended.)

Syntax of declaration extern <type> name

Initialization At program start:

numericset to 0strings set to ""

Scope (validity and time) Valid anywhere in the source, throughout theexecution. Also valid outside the program – forexample, on forms/reports, in runtime expressions,and by way of import() and export().

Example

extern long ifunction void test(){

i = 10 | This is the external variable}

Page 48: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-32

Function arguments

The arguments of a function are the variables declared in the function header.Arguments can be accessed only within the function.

Declaration, initialization, and scope

Point of declaration In the function between the brackets { }.

Syntax of declaration [ref|reference] <type> name

Note that array subscripts must be empty forreference arguments.

Initialization At function call.

For value arguments (see below), the values of thefunction call are copied.

For reference arguments, the same variable (or thesame memory area) is used as occupied by thevariable submitted to the function call.

Scope (validity and time) Only during function execution.

Value arguments

A value argument gets its value at the time of the function call and has its ownmemory space. For example:

FUNCTION long dupl(long val) | val is a value argument{

RETURN( val * 2 )}FUNCTION MAIN(){

message("%d", dupl(10))| the argument val gets value 10

}

Reference arguments

Reference arguments must be declared in the function header with the keywordREFERENCE or REF.

A reference argument has the same memory space as the variable used in thefunction call. Consequently, all changes made to a reference argument within thefunction block are also accessible after the function call in the variable used inthe function call. If a reference argument has array subscripts, these must beempty in the declaration as the contents and size of the call variable is used.

Page 49: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-33

If strings or large arrays are used, it is preferable to use reference argumentsinstead of returning them with the return statement. This avoids copy actions.

Example 1

Note that in this example, the reference argument is empty in the declaration.

FUNCTION LONG read_line( REF STRING buffer() ){

IF ( . . . . ) THENbuffer = . . . . . . . . . . .RETURN( 1 )

ELSEbuffer = ""RETURN( 0 )

ENDIF}

FUNCTION MAIN(){

STRING line(100)IF read_line(line) THEN

. . . .ELSE

message("No present line")ENDIF

. . . .}

Example 2

This example uses a multi-dimensional array:

FUNCTION VOID fill_array ( REF LONG array(,) ){

array(1,1) = 10array(1,2) = 20....

}

FUNCTION MAIN(){

STRING a(5,10)fill_array(a)

}

Page 50: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-34

Constant arguments

Constant arguments must be declared with the keyword CONST in the functionheader. These are similar to reference arguments in that the same memory spaceis used for the constant argument and the variable used in the function call.However, with constant arguments, it is possible to use a string constant withinthe function call. Consequently, the value of the argument after the function callis not returned in the calling function.

You cannot change a constant argument within the function. Nor can you use aconstant argument as reference in another function call. Only strings with onedimension can be used as constant arguments. The array subscript of the constantargument must be empty in the declaration because the size of the constant isused. For example:

FUNCTION print_mess( CONST STRING mesg() ){

IF NOT isspace(mesg) THENmessage("Message: " & mesg)

ENDIF}

FUNCTION MAIN(){

.....print_mess("This is a message").....

}

Varying number of arguments

It is possible to pass an (as yet) unspecified number of arguments to a functiondefinition by replacing the actual arguments with ’...’. The function call mustcontain the actual arguments required to execute the function. This enables youto use different arguments (from 0 to approximately 250) each time you call thefunction. This feature is useful, for example, if you wish to change some (not all)of the flags of a process, and you do not know beforehand precisely which flagsyou are going to change. For information on using this feature, see the arg()functions in U7167A US BaanERP Tools: Functions reference.

Page 51: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-35

Function prototypes

A function consists of three parts:

n Function prototypen Function definition (function block)n Function call

The function prototype must be exactly the same as the function header in thefunction definition. The prototype of a function is not always necessary. Forexample, it is not necessary in the following situations:

n if the function is of type void and has no arguments

n if the definition of the function occurs before any call of that function

In all other situations the prototype of the function must occur before thefunction call. For example:

prototypeFUNCTION LONG compnr_check( LONG new_compnr )

function callIF compnr_check( 999 ) THEN

. . . .ELSE

mess("pcgen00016", 999)| Comp. number %d not present

ENDIF

definitionFUNCTION LONG compnr_check( LONG new_compnr ){

TABLE tpctst999

SELECT pctst999.*FROM pctst999WHERE pctst999.compnr = :new_compnrORDER BY pctst999.compnrSELECTDO

compnr = pctst999.compnrSELECTEMPTY

RETURN(FALSE)ENDSELECTRETURN(TRUE)

}

From compiler version bic6.1 onwards, it is not necessary to use functionprototypes within the same source as the function definition.

Page 52: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-36

Function calls

The call of a function must have the same number of arguments as declared inthe function header. Value arguments can be called using a constant or avariable; reference arguments can only be called using a variable. If the calledfunction is not of type void, the function call must be assigned to a variable orused as value argument in another function call.

It is possible to use recursive function calls. This means that in a function block acall to the same function is used. However, this is currently implemented only forfunctions without local variables and arguments. In other situations, thefollowing runtime message is generated: "Recursion not yet implemented".

PreprocessorThe bic6.2 compiler for 3GL program scripts has a built in preprocessor with thefollowing functions:

n include filesn macro definitionn object identificationsn pragma codesn conditional compiling

All preprocessor directives starts with a ’#’. A preprocessor directive must be thefirst word on a source line, possibly with leading spaces or tabs.

Include files

To include files, use one of the following statements:

#include "filename"

#include <filename>

Files included between ’<’ and ’>’ are searched for in the directory’$BSE/include<rel.number>’. This directory is reserved for system headers andcannot be used for applications. Normally a file specified between quotes issearched for using the standard file redirection method.

Note that the preprocessor works only during compilation of a 3GL source, as thestandard generator std_gen6.2 does not have a preprocessor pass. So it is notpossible to use 4GL events in an included file.

Page 53: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-37

Example

Suppose the following entry occurs in $BSE/lib/fd.6.2<package_comb>:

ippmmm:/usr/bse/standard6.2

and there is an include statement as follows:

#include "ippmmmheader"

The file "/usr/bse/standard6.21/ippmmm/immmheader0" is included. If a ’/’occurs in the filename, the file is searched using the specified path name. When afile is included twice, the second include is ignored.

Macro definition

Use the following statement to define a macro:

#define macroname[(arguments)]

Use the folowing statement to undefine a macro:

#undef macroname[(arguments)]

Defining macros

The macro names in the source are expanded to the macro definition. If a macrodefinition does not fit on one line, it is possible to continue the definition on thenext line(s) by using the caret symbol ’̂ ’ at the beginning of each line. It ispossible to use arguments in the macro. For example:

#define a(x, y, z) for i = x to y^ z()^ endfor | The definition

a(1, 100, func) | The invocation

Macro definitions with the same name but with different numbers of argumentsare regarded as different. For example:

#define x definition without arguments#define x() definition with 0 arguments#define x(arg1) definition with 1 argument#define x(arg1,arg2) definition with 2 arguments#define x(...) definition with undefined

number of arguments

Note that there is a difference between a macro without arguments and a macrowith zero arguments. In the first case, you must use ’x’ in the program script tocall the macro. In the second case, you must use ’x()’ to call the macro.

Page 54: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-38

Undefining macros

The ’#undef’ statement causes the macro definition to be ignored. The number ofarguments in the ’#undef’ call must match the number of arguments in thedefinition.

For example:

#define MAXLENGTH 1000#define INCR 1#define INCR(i) i=i+INCR.....#undef MAXLENGTH#define INCR 2 | Redefines INCR.....#undef INCR(i)

An error occurs if you apply #undef to an unknown macro. To be sure that themacro was defined, use the following construction:

#ifdef INCR | without arguments#undef INCR(i)

#endif

See “Conditional compiling” later in this chapter for a detailed description of#ifdef and #endif calls.

Variable macro arguments

You can use the ellipsis notation ( , ... ) to define the macro with a varyingnumber of arguments. For example:

#define fillbuf(buf1, format, ...)^ buf1 = sprintf$(format,...)

| macro callstring buffer(100)long l_valdouble d_valfillbuf(buffer, "%d. %s = %d %5.2f", 1, "Value",^ l_val, d_val)

The macro definition can contain a number of arguments, but the ellipsis notationmust be the last argument.

Page 55: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-39

Token pasting

In the macro, you can enter a part of a variable as a macro argument. The symbol’##’ is used to distinguish macro arguments and the rest of the macro. This isomitted in the macro call. You can paste more macro arguments together as oneidentifier. This principle is called token pasting. It is used to reuse parts of thesource code, where using functions is impossible or difficult.

Example 1

#define p(x) message("%d", var##x)#define q(x,y) message("%d", x##y)#define r(x,y,z) message("%d", x##y##z)

long var1a, var1b

p(1a) | becomes: message("%d", var1a)p(1b) | becomes: message("%d", var1b)q(var, 1a) | becomes: message("%d", var1a)q(var, 1b) | becomes: message("%d", var1b)r(var, 1, a) | becomes: message("%d", var1a)r(var, 1, b) | becomes: message("%d", var1b)

Example 2

#define VRC(table,v,r,c)^ tt##table##.vers = v^ tt##table##.rele = r^ tt##table##.cust = c

VRC(adv100, "6.2", "a", "")VRC(adv200, "6.2", "a", "")VRC(adv300, "6.2", "a", "")

Object identifications

The compiler always places a default identification in an object, but you caninclude you own if you wish. You can use the UNIX command what to write allobject lines that begin with ’@(#)’ on standard output.

The default identification has the following content:

#ident "@(#)<source name>, YY/MM/DD, [HH/MM], From${logname}"

To set you own identification use the following statement:

#ident "@(#)Identification of object"

For example:

#ident "@(#)<progname>, YY/MM/DD [HH/MM], version, author"

Page 56: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-40

Pragma codes

Pragma codes represent compiler options. The following pragma codes areavailable:

#pragma nodebug Do not show the source while debugging.

#pragma debug Show the source while debugging.

#pragma nowarnings Do not give warnings about the source.

#pragma warnings Give warnings about the source.

#pragma notransactions The source contains only read actions;there are no transactions. So, it issufficient to start one database server.

#pragma warning <text> The programmer generates his ownwarning. (Warning level 15). See example.

#pragma fatal <text> The programmer generates his own error.

#pragma sticky Do not remove the object out of memorywhen the process ends.

#pragma used <component><code>

See below.

Example

#pragma warning This is not a fine solution !

| After compilation the following warning appears:| <Source(line)>: Warning(15): This is not a fine solution !

Where-used list

In some cases the where-used list is not updated automatically. For example,when a session code is entered but not expected:

message("ttadv2130m000")or

bms.send("command", event, "ttaad3100m000", pr.id)

To put this session code into the where-used list, enter the following commandline:

#pragma used session ttadv2130m000

The following example illustrates the pragma codes to update the where-usedlist:

#pragma used include <file>#pragma used table <table code>

Page 57: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-41

#pragma used field <field code>#pragma used domain <domain code>#pragma used message <message code>#pragma used question <question code>#pragma used session <session code>#pragma used menu <menu code>#pragma used dll <dll objectname>#pragma used chart <chart code>

Usually the where-used list is updated. In the case of functions, the where-usedlist is updated if the function call contains the string value. For example:

mess("ttadvs0000", 1) | Where-used list will be updated

str = "ttadvs0000"mess(str, 1) | Where-used list will not be

| updated

#pragma used message ttadvs0000

Location of pragma codes

You can place pragma codes anywhere in the source. For example, if you set thefollowing pragma at the start of the source:

#pragma nowarnings

you can enter the following pragma after a number of lines:

#pragma warnings

Conditional compiling

Directives

The preprocessor provides the following directives to enable you to compileparts of the source depending on certain conditions:

#ifdef <macro> The source after #ifdef up to#else/#elif/#endif is compiled if <macro>is defined. Otherwise this source isignored.

Page 58: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-42

#ifndef <macro> The source after #ifndef up to#else/#elif/#endif is compiled if <macro>is not defined. Otherwise this source isignored.

#if <constant expression> The source after #if up to#else/#elif/#endif is compiled if <constantexpression> is TRUE. Otherwise thissource is ignored.

#else If the condition belonging to#if/#ifdef/#ifndef/#elif is FALSE, thesource after #else up to #endif iscompiled. If the condition belonging to#if/#ifdef/#ifndef/#elif is TRUE, thesource after #else up to #endif is ignored.

#elif <constantexpression>

’#elif’ is a combination of #else and #if.For example:

#if <constant expression>...

#else#if <constant expression>

...#else

...#endif

#endif

This is equivalent to the following:

#if <constant expression>...

#elif <constant expression>...

#else...

#endif

#endif To finish a part of the source started with#ifdef/#ifndef/#if.

#undef <macro> To delete a macro definition. The macro isnot known on the next #ifdef call.

Page 59: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-43

Notes on using the directives

n The <constant expression> in #if and #elif is a numeric expression in whichyou can use only macros of type long and operators such as +, -, *, /, =, <, >,<=, >=, <>, and, or, not, ?:, ().

n It is possible to use nested #if structures.

n It is possible to define a macro when starting the compiler. You use the Doption to do this. For example:

bic6.2 -D<macro> | no value means default 1bic6.2 -D<macro>=<value>bic6.2 -D<macro>=’any token string’

These macros can also be used in the #if conditions. For example:

bic6.2 -DDEBUG -DMYTEST <source>

|source

#if DEBUG and MYTEST

message("Some debug information")

...

#endif

bic6.2 -DCUSTOMER_X -DCUSTOMER_Y <source>

bic6.2 -DSTANDARD <source>

#if STANDARD

....

#elif ( CUSTOMER_X and (not CUSTOMER_Y) )

....

#endif

n You can use #ifdef to make a part of the file inactive. For example:

#ifdef OLD

....

....

....

#endif

n The preprocessor works only during compilation of a 3GL source, as thestandard generator std_gen6.2 does not have a preprocessor pass. So it is notpossible to use 4GL events in #if, #ifdef or #ifndef.

Page 60: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-44

n It is not possible to use a #ifdef statement within an embedded SQL query.So, the following construction is not allowed:

select *

#ifdef STANDARD

...

from x

#else

...

from y

#endif

where ...

selectdo

...

endselect

But the following construction is possible:

#ifdef STANDARD

select * from x where ...

selectdo

...

endselect

#else

select * from y where ...

selectdo

...

endselect

#endif

n The following keywords provide debug information in 3GL sources:

__FILE__ : contains the name of the current source

__LINE__ : contains the line number of the currentsource

For example:

message("This is at line %d in the source %s",__LINE__, __FILE__)

Page 61: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-45

CompilerYou compile program scripts with the bic6.2 compiler. The compiler isautomatically activated after you have edited your program or report script andafter the use of std_gen6.2 and repgen6.2 at the option ’Compile’ in the datadictionary. You can also use the compiler to compile 3GL programs

The syntax for the compiler is:

bic6.2 [-ilpsV] [-wW[level]] [-o <object>] [-d dll[:dll...]] [-D <macro>] [-I <dir>] source

-I Assembler output is stored in <source>.i. Do not specify anobject file.

-l Object will run in debug mode.

-p Object will run in profiling mode for time analysis (see functiontimes.on()).

-s Generate symbol table to stdout; for more information use’bic_info6.2 -s’.

-V Print release information.

-w Suppress all warnings.

-wn Suppress warnings of level n.

-Wn Give warnings of level n.

-o <obj> Specifies the object name; when not specified, only a syntaxcheck is performed.

-d Specifies the DLL(s), separated by a colon (’:’). These are theobjects of dynamic-link libraries necessary to compile the sourceprogram.

-D<macro> Specifies a condition <macro>, see also “Preprocessor” earlier inthis chapter.

-I<dir> Specifies a directory where included files are located.

Page 62: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-46

The warnings associated with the various level numbers are as follows:

Level Warning

1 Declared but never used

For example, remove the declaration of the non-used variables.Warnings related to an include file can be prevented by entering"#pragma nowarnings" at the beginning of the include file. Allwarnings caused by the include file will then be ignored.

2 Function never used

A function is found but never called. For instance remove the function.This warning related to an include file can be prevented by entering"#pragma nowarnings".

3 Return value of function ignored

When a function yields a value, that value must be checked. The reasonis that many functions return TRUE or FALSE, depending on whetherthe action has been completed successfully or not. If the return value isof no importance, a dummy value must be assigned to the function. Forexample:

dummy = ittadv0037.search.label(....)

4 A long divided by a long gives also a long

A long divided by a long will result in a long. For example:

long along b

a = 1b = 3

a / b = 0 and not 0.33

Page 63: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-47

5 Statement/Label not reached

Occurs if a statement cannot be reached. For example:

function test.a(){if a = 0 then

...return()

else...return()

endifa = 1

}

The statement a = 1 will never be reached, so this warning indicates aprogramming error or logical error.

6 Comparison of two float types may yield unpredictable results

This warning is given when two double types are compared forequivalence. Please use the function double.cmp() to compare doublevariables, double domains, and double functions. Note that for doublefunctions the warning appears only if the function has been prototypedbefore its actual use. For example:

function double d()

function main(){domain tttst.db62 dbldomdouble a, b

if a = b then...

endifif d() > a then

...endifif a <= dbldom then

...endif

}

All the above expressions may yield unpredictable results, as notolerances have been specified.

Page 64: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-48

9 External variable ’%s’ passed as reference to function ’%s’

When an external variable is given as a call by reference to a function,the value of this variable within the function is not equal to the localvalue. Just after the return, the value of the external variable will bechanged. For example:

extern long a

function main(){a = 5make.ten(a)message("a = %d", a) | results in a = 10

}

function make.ten( ref long x ){message("a = %d", a) | results in a = 5x = 10....message("a = %d", a) | results in a = 5

}

When within the function make.ten() another function is called usingthe external variable a, the variable a still has the value 5.

10 Passing fixed variable to non-fixed call by reference argument (or non-fixed to fixed)

When a global variable is declared as fixed, the variable within afunction is still regarded as fixed, although the reference declaration isnot fixed. For example:

string a(20) fixedfunction process.variable( ref string b ){}

If the function is invoked using the argument "a", "b" is consideredfixed.

Page 65: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-49

12 External variable ’%s’ added in external symbol table

An external variable is declared within a function. For example:

function test(){extern long a....

}

13 System library <bic_stdlib> NOT included !

15 Warning given by #pragma <text>

This is a warning of your own format, see “Pragma Codes” earlier inthis chapter.

16 Missing selectdo; automatic break or Missing selectdo; loop untilselecteos

When a selectdo is missing in the select statement, an automatic breakis generated to prevent unnecessary use of cpu time. When a selectdo ismissing, while a selecteos section exists, the select statement should beexecuted. Probably this is a non optimal select statement.

18 Macro '%s' redefined

A macro is defined, which was already defined with the samearguments.

19 Function '%s' in DLL '%s' ignored taken from '%s'

A duplicate function occurs in a DLL or program script. A function issearched for in the script first and next in the libraries that are linked tothe script in the specified order. If a function is found twice, thiswarning appears.

You can specify the options for automatic compilation in the session MaintainDevelopment Parameters (tadv0110m000).

When an error is found in the program, all warnings after that error aresuppressed.

Page 66: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

3GL programming language features

Programming features

2-50

Page 67: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

3-1

OverviewThis section describes the 4GL features of the BAAN programming language.

When you create a session, the session generator generates a standard source.This standard source provides default session functionality. If the requiredfunctionality of the session is not fully implemented by the standard source, youcan program the additional functionality in a 4GL program script.

In previous versions of the software, changes or additions to the defaultfunctionality for a session were programmed in a single script that was associatedwith the session. Both user interface actions and database actions wereprogrammed in this script.

In BaanERP, user interface actions and database actions have been separated.The Data Access Layer (DAL) now handles database interaction. Programmerscreate a user interface (UI) script to change the default behavior of a session.They create a DAL script to program all the logical integrity rules for a particulartable. This section discusses UI scripts.

4GL script types

There are four types of 4GL program scripts:

n type 1 (with main table): single-occurrence (details) session

n type 2 (with main table): multi-occurrence (overview) session, with groupfields

n type 3 (with main table): multi-occurrence (overview) session, without groupfields

n type 4 (without main table): print/processing sessions

3 4GL programming features

Page 68: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-2

Event-driven programming

4GL scripts are event oriented. They consist of one or more event sections inwhich you program actions to be performed at particular states of execution ofthe standard program – for example, when a session is started, before a form isactivated, before input to a field, after input to a field, and so on. It is notnecessary to program all sections, only those for which the standard programdoes not provide the required functionality.

The statements programmed in a section can be a combination of 3GL/4GLfunctions and 3GL statements. For information about the 3GL programminglanguage, see Chapter 2, 3GL programming language features.

Event sectionsA 4GL script can contain one or more of the following types of sections:

n Program sectionsn Form sectionsn Group sectionsn Choice sectionsn Field sectionsn Zoom sectionsn Main table sections

With the exception of program sections, each section consists of a main sectionand one or more subsections. A main section indicates the object for which theprogrammed actions must be executed. A subsection specifies when the actionsmust be executed. Program sections consist of a main section only.

If you do not include a main section immediately before a subsection, thesubsection is assigned to the previous main section in the script. For example:

form.1: | main sectioninit.form: | subsection executed for form 1

...

...before.form: | subsection executed for form 1

...

...after.form: | subsection executed for form 1

...

Page 69: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-3

The following rules apply to the ordering of sections within a script:

n The declaration section must be the first section in the script.

n The functions section must be the last section in the script.

n Other sections can occur in any order, but the preferred order is: programsections, form sections, group sections, choice sections, field sections, zoomsections, main table sections.

n Do not mix sections of different types. For example, do not define a choicesection, followed by a field section, and then a choice section again.Exceptions are the declaration and functions sections, which must be thefirst and last sections respectively in the script.

Variables declared in the declaration section are global variables that you canuse in other sections. Variables declared within any other section are localvariables that you can use in that section only.

Program sectionsYou use program sections to define functions, and to declare tables and globalvariables, that you want to use in the other sections in the script. You also useprogram sections to program actions that you want to be executed when thesession starts or ends.

The following program sections are available. They are all main sections. Thereare no subsections associated with program sections.

Main sections

declaration:

Use this section to declare tables and global variables that you want to use inother sections in the script. See, “Declarations” and “Tables” in Chapter 2 fordetails of the declaration syntax. You also use this section to define functionprototypes.

before.program:

Use this section to program actions that must be executed when the session starts.For example, you can use this section to initialize or import variables or to read aspecial record. Note that the default values or imported values overwrite thefields of the main table.

Page 70: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-4

on.error:

Use this section to program actions that must be executed at the end of thesession, before the after.program section. If the session is canceled, the actionsin this section are not executed. If an error is detected, you can check thepredefined variable e for the error code.

after.program:

Use this section to program actions that must be executed at the end of thesession, after the on.error section. If the session is canceled (with the commandABORT.PROGRAM), the actions in this section are not executed.

after.update.db.commit:

Use this section to program actions that must be executed immediately after acommit.transaction() call, if the database is updated.

before.display.object:

Use this section to program actions that must be executed each time the entirerecord is displayed.

functions:

Use this section to define the functions used in the other sections. This must bethe last section in the script. The function syntax is the same as for 3GLfunctions.

Page 71: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-5

Example

declaration:table tpctst999long var01, ret

before.program:if read_parameter() then

mess("pctsts0001", 1) | Parameter not presentstop()

endif

on.error:mess("........", 1)

functions:function long read_parameter(){

select pctst999.*from pctst999order by pctst999._index1as set with 1 rowsselectdo

return(0)selectempty

return(1)endselect

}

Form sectionsYou use form sections to program actions that you want to be executed whenforms are activated or ended. Form sections consist of a main section and asubsection. The main section specifies the particular form(s) for which theactions are to be executed. The subsections specify when the actions must beexecuted – for example, when the form is activated or when the form is ended.

Main sections

form.<form number>:

The subsections associated with this section are executed for the specified form.The <form number> is the sequence number of the form, as defined in theMaintain Sessions by Package VRC session (ttadv2100m000).

Page 72: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-6

form.all:

The subsections associated with this section are executed for all forms of thesession.

form.other:

A subsection associated with this section is executed for all forms for which theparticular subsection has not been programmed in a form.<form number>section.

Subsections

init.form:

The actions programmed in this subsection are executed the first time thespecified form becomes current, immediately before the subsection before.form.You use this subsection to program the first action to be performed by the system– a first.set or first.view, for example.

before.form:

The actions programmed in this subsection are executed each time the specifiedform becomes current.

after.form:

The actions programmed in this subsection are executed each time the specifiedform is ended.

Example:

form.1:init.form:

execute(first.set)form.other:init.form:

display("disp3")form.all:before.form:

display("disp")

Note:

Only the form.all section is relevant to dynamic forms. For dynamic forms, usethe group sections instead.

Page 73: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-7

Group sectionsWith dynamic forms, the mapping of groups to forms is not fixed. Consequently,the only form section that is relevant to dynamic forms is the form.all section.When dealing with dynamic forms, you use group sections instead of formsections

You use group sections to program actions that you want to be executed whenparticular groups are activated or ended. Group sections consist of a main sectionand a subsection. The main section specifies the particular group(s) for which theactions are to be executed. The subsections specify when the actions must beexecuted – for example, when the group is activated or when the group is ended.

Note that a group becomes active when the form on which it occurs becomescurrent.

Main section

group.<group number>:

This section defines the group for which the actions programmed in the groupsubsections are executed. The group number is automatically generated when thegroup is created.

Subsections

init.group:

The actions programmed in this subsection are executed only the first time thegroup becomes active, immediately before the before.group subsection. You usethis subsection to program the first action to be performed by the system whenthe group becomes active. When the group is split across two or more forms(because not all the group fits on one form or because it is a repeating group),this subsection is executed the first time that the first form on which the groupoccurs becomes current.

Note: the init.group section for group.1 is the former init.form section forform.1. Group number 1 is not one of the groups in the form-definition.

before.group:

The actions programmed in this subsection are executed each time the specifiedgroup becomes active. When the group is split across more than one form, thissubsection is executed whenever any form on which it occurs becomes current.

Page 74: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-8

after.group:

The actions programmed in this subsection are executed each time the form onwhich the group occurs is ended. When the group is split across more than oneform, this section is executed whenever any form on which the group occurs isended.

Choice sectionsYou use choice sections to program actions that you want to be executed whenstandard commands are activated or ended. Choice sections consist of a mainsection and a subsection. The main section specifies the standard command forwhich the actions must be executed. The subsections specify when the actionsmust be executed.

Main section

choice.<standard command>:

The subsections associated with this main section are executed for the specifiedstandard command. You use the Maintain Forms by Package VRC session toselect the standard commands (ttadv3100m000) for each form. A list of standardcommands appears at the end of this help topic.

Subsections

before.choice:

The actions programmed in this subsection are executed immediately before thespecified command is executed. You can use this subsection, for example, to testdata before the command process continues. You can use the choice.again()function to stop the command.

on.choice:

The actions programmed in this subsection are executed when the specifiedcommand is activated. These actions are executed instead of the standard actionassociated with the command.

Page 75: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-9

This subsection is available for the following commands only:

n print.datan run.jobn global.deleten global.copyn bmsn all commands in type 4 programs (except modify.set, restart.input,

end.program, abort.program)

after.choice:

The actions programmed in this subsection are executed immediately after thespecified command has been executed. This subsection is not available for theend.program and abort.program commands. For example:

choice.first.view:after.choice:

execute(first.set)

Standard commands

The following table lists the available standard commands and the types ofprogram in which the various choice subsections can be programmed for eachcommand.

No Choice_option Description Before On After

01 start.set Add/start a new group inmain table

1234 ---4 1234

02 first.view View first group of maintable

1234 ---4 1234

03 next.view View next group of maintable

1234 ---4 1234

04 prev.view View previous group ofmain table

1234 ---4 1234

05 last.view View last group of maintable

1234 ---4 1234

06 def.find Find a specific record onkey

1234 ---4 1234

Page 76: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-10

07 find.data Start the set from thecurrent data in theprogram script. Use: afterimport of data in a zoomprocess. (refresh)

1234 ---4 1234

08 first.set View first set of maintable

1234 ---4 1234

09 next.set First execute anupdate.db and then viewnext set of main table

1234 ---4 1234

10 display.set Open read-only details 1234 ---4 1234

11 prev.set First execute anupdate.db and then viewprevious set of main table

1234 ---4 1234

12 rotate.curr Show amounts in othercurrency (on.choicesubsections are availablefor this command only ifno currencies are set)

1234 1234 1234

13 last.set View last set of maintable

1234 ---4 1234

14 add.set Insert a new record 1234 ---4 1234

15 update.db First test consistency ofdata and then (re)writerecord or set (save)

1234 ---4 1234

16 dupl.occur Copy the record to a newone

1234 ---4 1234

17 recover.set Undo modificationswhich are not yet writtento the database

1234 ---4 1234

18 mark.delete Delete selected records 1234 ---4 1234

19 mark.occur Select a record on thescreen

1234 ---4 1234

20 change.order Change the search key 1234 ---4 1234

Page 77: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-11

No Choice_option Description Before On After

21 modify.set Change a record stored inthe database

1234 ---- 1234

23 print.data Make a report with thecurrent data on the form

1234 1234 1234

24 create.job Add session in job 1234 ---- 1234

25 form.tab.change Go to another form insession

1234 ---- 1234

26 first.frm Go to first form 1234 ---- 1234

27 next.frm Go to next form 1234 ---- 1234

28 prev.frm Go to previous form 1234 ---- 1234

29 last.frm Go to last form 1234 ---- 1234

31 resize.frm Resize the current form 1234 1234 1234

33 cmd.options Show available formoptions

---- ---- ----

34 zoom Zoom to anothersession/menu

1234 ---- 1234

35 interrupt Do an action each timeinterval

1234 1234 1234

36 end.program End execution of thesession; the main tablewill be updated

1234 ---- ----

37 abort.program Cancel execution of thesession. The main table isnot updated

1234 ---- ----

39 text.manager Start the text manager 1234 ---- 1234

40 run.job Run job of session 1234 1234 1234

41 global.delete Delete range of records 1234 1234 1234

42 global.copy Copy range of records 1234 1234 1234

43 save.defaults Save values as defaults 1234 ---- 1234

Page 78: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-12

No Choice_option Description Before On After

44 get.defaults Get previous storeddefaults

1234 ---- 1234

45 start.chart Chart Manager is started 1234 ---4 1234

46 start.query Start query by form 1234 ---4 1234

60 ask.helpinfo Asks for session help ---- ---- ----

62 calculator Calculator will be started ---- ---- ----

63 calendar Calendar will be started ---- ---- ----

64 bms A broadcast message isreceived

1234 1234 1234

71 cmd.whats.this Asks for field help ---- ---- ----

72 help.index Asks for the help index ---- ---- ----

The following commands are supported for backward compatibility only.Support is not guaranteed in future versions of the software.

22 restart.input Restart the input after giving<Esc> during input mode

1234 ---- 1234

38 cont.process Start user defined process 1234 1234 1234

48 user.0 User option 0 1234 1234 1234

49 user.1 User option 1 1234 1234 1234

50 user.2 User option 2 1234 1234 1234

51 user.3 User option 3 1234 1234 1234

52 user.4 User option 4 1234 1234 1234

53 user.5 User option 5 1234 1234 1234

54 user.6 User option 6 1234 1234 1234

55 user.7 User option 7 1234 1234 1234

56 user.8 User option 8 1234 1234 1234

57 user.9 User option 9 1234 1234 1234

Page 79: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-13

Field sectionsYou use field sections to program actions that you want to be executed for avariety of field events. Field sections consist of a main section and a subsection.The main section specifies the field(s) for which the actions must be executed.The subsections specify when the actions must be executed.

Main sections

field.<field name>:

The subsections associated with this main section are executed for the specifiedfield. The field name you specify must correspond with the name on the form.

field.all:

The subsections associated with this main section are executed for all fields onthe form

field.other:

A subsection associated with this section is executed for all fields for which theparticular subsection has not been programmed in a field.<field name> section.

Subsections

init.field:

The actions programmed in this subsection are executed the first time that theform on which the field occurs becomes current. The subsection is executedimmediately before the init.form section of the form. You can use this section tochange field attributes.

before.field:

The actions programmed in this subsection are executed each time the focusmoves to the specified field. The subsection is executed immediately before thebefore.input or before.display subsections.

before.input:

The actions programmed in this subsection are executed immediately beforeinput to an input field commences. This section is supported for backwardcompatibility only. In BaanERP programs, use enable.fields() anddisable.fields() to enable and disable fields.

Page 80: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-14

before.display:

The actions programmed in this subsection are executed each time that thespecified field is displayed. You can use this subsection, for example, to set thevalue of a display field or to change the output format of currencies and dates (byusing attr.oformat$).

before.zoom:

When a zoom process is started on the specified field, the actions programmed inthis subsection are executed immediately before the zoom process is executed.You can use this subsection to change the zoom attributes. For example, in thefield definition in the form manager, a default zoom code can be specified. Youcan then use this subsection to change the zoom code (by setting the predefinedvariable attr.zoomcode).

before.checks:

The actions programmed in this subsection are executed after input to the fieldhas been completed and the TAB key has been pressed. The subsection isexecuted immediately before the domain and references are checked. You canuse this section, for example, to change the value of the field before the domainand reference checks.

domain.error:

The actions programmed in this subsection are executed if the domain checkcauses an error after data has been entered in the field. You can use this sectionto provide your own error message instead of the standard message.

ref.input:

The actions programmed in this subsection are executed if a reference erroroccurs. If you program this section, the standard program does not display amessage.

ref.display:

The actions programmed in this subsection are executed if there is an error in thereference display.

Page 81: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-15

check.input:

The actions programmed in this subsection are executed immediately after thedomain and reference checks. You can use this section to test for errors that arenot detected automatically. If the standard program detects an error, input isautomatically restarted. In a script, you can use set.input.error() to display anerror message and start input again.

This section is replaced by DAL functionality (if a DAL exists for the table).

on.input:

The actions programmed in this subsection are executed immediately after thecheck.input subsection. You can use this section, for example, to perform someappropriate action when the user enters a special character or to display awarning message in certain cases.

when.field.changes:

The actions programmed in this subsection are executed when the new valueentered in the specified field differs from the old value.

after.zoom:

The actions programmed in this subsection are executed when the zoom processon a specified field ends. You can use this subsection, for example, to redisplayany field that has changed as a result of the zoom process.

after.input:

The actions programmed in this subsection are executed after all checks havebeen performed on input to the specified field and after the when.field.changessubsection has been executed. In this subsection, you can use the to.field()function if the sequence deviates from the default.

after.display:

The actions programmed in this subsection are executed just after display of thespecified field. You can use this subsection, for example, to read reference tables.

Page 82: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-16

after.field:

This is the last subsection for a field. The actions programmed in this subsectionare executed after input to or display of the specified field. This section is alwaysexecuted, even if the user left the field by pressing ESC, one of the arrow keys,or a mouse button. You can use this subsection to perform special actions beforeleaving the field.

Examplefield.pctst099.item:check.input:

select pctst001.*from pctst001where pctst001.item = :pctst099.itemas set with 1 rowsselectdo

....selectempty

pctst001.dsca = "*****"set.input.error(".....")

endselectbefore.input:

if ..... thenattr.input = false

endifafter.display:

select pctst001.*from pctst001where pctst001.item = :pctst099.itemas set with 1 rowsselectempty

pctst001.dsca = "*****"endselect

field.pctst099.date:before.input:

attr.oformat$ = "%D002,2"

Page 83: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-17

Zoom.from sectionsYou use zoom.from sections to program actions that you want to be executedwhen the current session is activated as a zoom process. A zoom process can beactivated by a form-specific command of type session, by zooming on an inputfield, by pressing CTRL+B, or by calling zoom.to$() in the program script.Zoom.from sections consist of a main section and a subsection. The main sectionspecifies the process for which the actions must be executed. The subsectionsspecify when the actions must be executed.

Main sections

zoom.from.<zoom name>:

Each field has a name that can be used as a zoom name. You can specify thezoom name in this main section. The zoom name indicates which field thecurrent session was zoomed from (when the subprocess is started from a formcommand, the zoom name is "choice"). The subsections associated with thismain section are executed when the current process was zoomed to from thespecified process.

zoom.from.all:

The subsections associated with this main section are executed for all processesfrom which the current session can be zoomed to.

zoom.from.other:

A subsection associated with this section is executed for all processes for whichthe particular subsection has not been programmed in a zoom.from.<zoomname> section.

Subsections

on.entry:

The actions programmed in this subsection are executed each time the currentprocess is started from the specified process(es). You can use this subsection toimport variables.

Page 84: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-18

on.exit:

The actions programmed in this subsection are executed at the end of the currentprocess, if the current process was started from the process(es) specified in themain section. You can use this subsection to export variables.

Examplezoom.from.all:on.entry:

import("globvar", localvar)on.exit:

export("globvar", localvar)

Main table sectionsYou use main table i/o sections to program actions that you want to be executedwhen read or write actions occur on the main table. These sections are notrelevant to type 4 programs, as such programs do not have a main table. Maintable i/o sections consist of a main section and a subsection. The main section isalways main.table.io. The subsection indicates when the actions must beexecuted.

Note that main.table.io sections (except the read.view subsection) are ignoredwhen the corresponding DAL hooks are programmed in a DAL script.

Main section

main.table.io:

The subsections associated with this main section are executed either before orafter input to or output from the main table. The main table for the currentsession is defined in the data dictionary.

Subsections

before.read:

The actions programmed in this subsection are executed immediately before eachread action on the main table.

Page 85: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-19

after.read:

The actions programmed in this subsection are executed after each read action onthe main table. You can use this subsection to call skip.io() in order to skip therecord just read and to read the next record (if necessary).

before.write:

The actions programmed in this subsection are executed before each write actionon the main table. A write action occurs when a record is inserted. You can usethis subsection to call skip.io() in order to undo the write action.

after.write:

The actions programmed in this subsection are executed after each write actionon the main table. A write action occurs when a record is inserted. You can usethis subsection, for example, to write data to tables other than the main table.

after.skip.write:

The actions programmed in this subsection are executed if a write action on themain table has been skipped as a result of actions programmed in thebefore.write subsection. The actions are executed immediately after the skipaction.

before.rewrite:

The actions programmed in this subsection are executed immediately before eachrewrite of a record in the main table. A rewrite action occurs when a record ischanged. You can use this subsection to call skip.io() in order to skip the rewriteaction.

after.rewrite:

The actions programmed in this subsection are executed after each rewrite actionon the main table. A rewrite action occurs when a record is changed.

after.skip.rewrite:

The actions programmed in this subsection are executed if a rewrite action on themain table has been skipped as a result of actions programmed in thebefore.rewrite subsection. The actions are executed immediately after the skipaction.

Page 86: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-20

before.delete:

The actions programmed in this subsection are executed immediately before eachdelete action on the main table. You can use this section to call skip.io() in orderto skip the delete action.

after.delete:

The actions programmed in this subsection are executed immediately after eachdelete action on the main table. You can use this subsection, for example, fordeleting references, if this is not done automatically.

after.skip.delete:

The actions programmed in this subsection are executed if a delete action on themain table has been skipped as a result of actions programmed in thebefore.delete subsection. The actions are executed immediately after the skipaction.

read.view:

The actions programmed in this subsection are executed immediately after aview action on the main table (start.set, first.view, next.view, prev.view orlast.view). You can use this subsection to call skip.io() in order to skip an entireset of records with the same value in the view fields.

Examplemain.table.io:before.delete:

if (not pctst099.del) thenskip.io("pctsts0001")| cannot be deleted

endifread.view:

if strip$(pctst099.cprj) = "" thenskip.io("")

endif

Page 87: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-21

Flow of standard programThis section presents the general flow of the standard program. It is notcomplete, but the most important actions are included. The flow is similar forprograms of types 1, 2, 3, and 4. Any differences are indicated by comments.

Main routine

The main routine displays the first form on the screen and waits for a command.

function main(){

before.programread.form()init.referencescreate.sql.queriesif background then

get.ref.var(parent)read record

endifdb.bind(tmain) | Not in type 4if job.process then | Only type 4

before.choice.run.jobexecute(cont.process) or on.choice.run.jobafter.choice.run.jobexecute(end.program)

endifzoom.from.on.entryfor each field on form

init.fieldput.attributes()

endforchange to start index | Not in type 4init.formexecute start eventbefore.form

while trueinput.choice()if update.status and choice <> ... then | Not in

| type 4on.update.db()

| See "update database" sectionendifon case choicecase <choice.option>

before.<choice.option>on.<choice.option>after.<choice.option>break

Page 88: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-22

case .......endcase

endwhile

Choice sections

The choice sections above are given as before.choice.option andafter.choice.option. In a 4GL program, a choice section consists of the mainsection choice.choice.option and one of the subsections before.choice, on.choice,or after.choice.

Form sections

When changing from form X to form Y, the form sections are executed in thefollowing sequence:

after.form for Xinit.form for Y (only the first time)before.form for Y

The above subsections can be defined, as follows:

for all forms : form.allfor a specific form : form.<form name>for forms not specifically defined : form.other

At init.form the sequence is:

form.all: init.formform.<form name>: init.form or form.other: init.form

Page 89: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-23

At before.form the sequence is:

form.all: before.formform.<form name>: before.form or form.other: before.form

At after.form the sequence is:

form.<form name>: after.form or form.other: after.formform.all: after.form

Field sections

There are two groups of field sections:

n sections for which the field.all section is executed first:

init.fieldbefore.fieldbefore.inputbefore.displaybefore.checksbefore.zoomcheck.input | if not in DALon.input

n sections for which field.all is executed after field.<field name> or field.other:

after.inputafter.displayafter.zoomref.inputref.displaydomain.errorwhen.field.changesafter.field

The general flow of input fields is as follows:

Field.input:before.fieldif not input.field then

read.referenceif error.reference then

ref.displayelse

before.displaydisplay.field()after.display

endif

Page 90: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-24

returnendifbefore.inputif input disabled then

read.referenceif error.reference then

ref.displayelse

before.displaydisplay.field()after.display

endifreturn

endif

zoom.ret:do.input.field()if in.ret = ZOOM then

before.zoomzoom.to ...after.zoomgoto zoom.ret

endifif choice = f.to.choice or

in.ret = arrow.up/down/left/right/tab thengoto after.field

endifbefore.checkscheck.domain()

if domain.error thendomain.errorerror.messagegoto field.input

endifcheck.reference

if reference.error thenref.inputerror.messagegoto field.input

endifcheck.inputif check.input.error then

error.messagegoto field.input

endifon.input........

Page 91: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-25

when.field.changesafter.inputafter.field

End of program

The flow of the end of the program is as follows. The function end.of.program()is called when executing the standard command END.PROGRAM.

function end.of.program(){

before.end.programif e then

on.errorendifafter.formafter.programif zoomfield <> "" then

fill.zoomreturnzoom.from.on.exitif record.marked then

commit.transaction() | Not in type 4exit(exit.val)

endifendifcommit.transaction() | Not in type 4exit()

}

Zoom sections

The zoom.from.on.entry and zoom.from.on.exit sections are used In the mainroutine and in the end.of.program() function. In a 4GL program, a zoom sectionconsists of a main section (zoom.from.all, zoom.from.<zoomname>, orzoom.from.other) and a subsection (on.entry or on.exit).

The sequences in which the sections are executed differ for on.entry and on.exit.For on.entry, zoom.from.all is executed first and then zoom.from.<zoomname>or zoom.from.other. For on exit, it is the other way around.

Update database

An update of the database is necessary if a record is added, changed or deleted.The actual update is executed if one of the following actions is activated after arecord has been added, changed or deleted: start.set, def.find, find.data, first.set,next.set, prev.set, last.set, next.help, prev.halfset, change.order, cont.process.

Page 92: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-26

All these actions first call on.update.db() if a record is added, changed ordeleted. The general flow of the on.update.db() is as follows. Note that thisfunction is not relevant to programs of type 4.

on.update.db(){

if update.status = add.set or modify.set thenfor all occurrences

check.domains()if domain.error then

domain.errorerror.messagereturn

endifcheck.referencesif reference.error then

ref.inputerror.messagereturn

endiffor each field of occurrence

check.inputif check.input.error then

error.messagereturn

endifendfor

endforendifbefore.update.dbdb.retry.point()for all occurrences

before.write / before.rewrite / before.deleteif not skip then

write / rewrite / delete recordafter.write / after.rewrite / after.delete

elseafter.skip.write / after.skip.rewrite /

after.skip.deleteendif

endforback.to.old.keyafter.update.dbcommit.transaction()after.update.db.commit

}

Page 93: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-27

Main table i/o section

Most of the main table i/o are mentioned above. They are not available inprograms of type 4.

The read.view section is executed immediately after any view action on the maintable (only in type 3 programs). The function skip.io("messcode") can be usedin this section. This implies that the next or previous view is read.

Automatic import of variablesWhen you zoom from a main process to a subprocess, in some cases variablesare imported automatically.

Case 1

From the main process with main table X you have zoomed to the subprocesswith main table Y. Table X has a foreign (cross-reference) key to table Y. Forexample, X = customer table, Y = currency table. The currency field in thecustomer table refers to the currency table.

The standard program imports the field(s) from table X and stores them in theprimary key fields of table Y.

Consequences for programming in script

In the script of the subsession, only the following needs to be programmed:

if background thenexecute(find.data)(or, sometimes, for type 3 screens:

execute(first.set))else

....endif

There is no need to adjust the main session in order to import the variables intothe subsession.

Case 2

From the main process with main table X, you have zoomed to the subprocesswith main table Y. A field in table Y refers to table X. (In most cases, there is anidentifying relationship between table X and table Y – for example, order header(table X) and order lines (table Y).) The standard program imports the primarykey values from table X and stores them in the corresponding fields of table Y.

Page 94: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-28

Example

Primary key of table X is Order number; primary key of table Y is Order number,position number.

The standard program imports the order number from table X to thecorresponding field in table Y. The position number in table Y remains, ofcourse, empty.

Consequences for programming in script

See Case 1 above.

Case 3

From the main process with main table X, you have zoomed to the subprocesswith the same main table. (For example, a zoom from ’Maintain Item Data’ (type1) to ’Display Item Data’ (type 2 or 3).)

The standard program imports the primary key value from table X for the mainprocess and stores it in the primary key fields of table X for the subprocess.

Consequences for programming in script

See Case 1 above.

Case 4

From the main process with main table X you have zoomed to a subprocesswithout a main table (for example, a print program). The standard programimports the primary key values of main table X for the main process and storesthem in the primary key fields of table X (if available) for the subprocess.

Example

A zoom from ’Maintain Item Data’ to ’Print Item Data’. The main table for themain process is tstpi100. The subprocess imports values of tstpi100.cuno andtstpi100.item from the main process and stores them in the fields of thesubprocess.

Consequences for programming in script

In many cases, you must reprogram the main process in such a way that theprimary key fields of the main table for the subprocess are filled.

Page 95: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-29

Case 5

From the main process without a main table you have zoomed to a subprocesswith main table X. The standard program imports the primary key values of tableX (if available) for the main process and stores them in the primary key fields ofthe subprocess’s main table.

Example

A zoom from ’Print Item Data’ to ’Display Item Data’. The main table for thesubprocess is ttstpi100. The standard program tries to import tstpi100.cuno andtstpi100.item from the main process and stores them in the fields of the maintable for the subprocess.

Consequences for programming in script

See Case 1 above.

In many cases you must reprogram the main process in such a way that theprimary key fields of the main table for the subprocess are filled.

Example

field.item.t:before.zoom:tstpi100.cuno = cuno.ftstpi100.item = item.f

Case 6

From the main process with table X you have zoomed to a subprocess with tableY. There is no relationship between table X and table Y (none has been definedin the data dictionary). The standard program imports the primary key values oftable Y for the main process (if available) and stores them in the primary keyfields of table Y for the subprocess.

Consequences for programming in script

See Case 1 above.

Often you will have to reprogram the main process in such a way that theprimary key fields of the main table for the subprocess are filled.

Page 96: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

4GL programming features

Programming features

3-30

Example

field.tswoc150.item:before.zoom:

tstpi100.cuno = tswoc100.cunotstpi100.item = tswoc150.item

Page 97: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

4-1

OverviewBaanERP reports are used to output data from the database to a variety of devices(for example, printers, displays, and files).

The contents and layouts of reports are defined in the data dictionary. In addition,you can link a report script to a report. In a report script, you can program actionsthat you want to be performed at particular stages of the report execution. Forexample, you can create a script to perform calculations on the report data or toread records from related tables that are not automatically available to the report.You program report scripts in the same way as you program 4GL programscripts, except that report scripts use different event sections and some specialfunctions.

Event sectionsA report script consists of one or more event sections in which you programactions to be performed at particular states of execution of the report to which thereport script is linked. The statements programmed in a report script sectionconsist of a combination of 3GL language statements and report script functions.

Report scripts support the following event sections:

n program sectionsn report sectionsn text field sections

Program sectionsYou use program sections to define functions, and to declare tables and globalvariables, that you want to use in the other sections in the script. You also useprogram sections to program actions that you want executed at the start and endof the report and after the report writer receives a record.

The following program sections are available. They are all main sections. Thereare no subsections associated with program sections.

4 Report scripts

Page 98: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-2

declaration:

Use this section to declare tables and global variables that you want to use inother sections in the report script. See “Declarations” and “Tables” in Chapter 2for details of the declaration syntax. Note that there is no need to declare a tableif a field of that table is defined in the report writer as an input field. The reportwriter declares such tables automatically.

before.program:

Use this section to program actions that must be executed when the report isstarted. For example, you can use this section to initialize or import variables.

after.program:

Use this section to program actions that must be executed at the end of the report.For example, you can use this section to close files that were opened duringexecution of the report.

after.receive.data:

Use this section to program actions that must be executed whenever the reportwriter receives a record. For example, you can use this section to read or modifya variable.

functions:

Use this section to define functions that you want to use in other sections in thereport script. The syntax of functions used in a report script is the same as for3GL functions.

When included, this section must be the last section in the report script.

Report sectionsA report consists of a number of layouts, which define the content andorganization of the various parts of a report (for example, the header, footer, andbody of the report). There are a number of possible layout types, as follows:

n before.report – printed once at beginning of the report (a title page, forexample)

n after.report – printed once at the end of the report

n header – printed at the top of each page

Page 99: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-3

n footer – printed at the bottom of each page

n before.field – printed before each group of records in reports of type 3; if agroup of records spans more than one page, the before.field layout is repeatedat the top of the new page

n after.field – printed immediately after each group of records in reports of type3

n detail – used for the individual records included in the body of the report

The content and arrangement of these layouts are defined in the data dictionary.

In the report sections in a report script, you can program actions to be performedbefore and/or after execution of individual layouts of these types. Report sectionsconsist of a main section and a subsection. You use a main section to specify theparticular layout for which the programmed actions are to be executed. You mustfollow a main section with either a before.layout or an after.layout subsection.These latter specify whether the actions are to be executed before or after theparticular layout is printed.

Main sections

before.report.<layout_number>:

Actions programmed in this section are executed for a specified layout of typebefore.report.

after.report.<layout_number>:

Actions programmed in this section are executed for a specified layout of typeafter.report.

header.<layout_number>:

Actions programmed in this section are executed for a specified layout of typeheader.

detail.<layout_number>:

Actions programmed in this section are executed for a specified layout of typedetail.

before.<field name>.<layout_number>:

Actions programmed in this section are executed for a specified layout of typebefore.field.

Page 100: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-4

after.<field name>.<layout_number>:

Actions programmed in this section are executed for a specified layout of typeafter.field.

footer.<layout_number>:

Actions programmed in this section are executed for a specified layout of typefooter.

Subsections

before.layout:

Actions programmed in this subsection are executed before the specified layoutis printed.

When lattr.print is set to false, the layout is not printed and the before.layoutand after.layout sections are not executed. If you set lattr.print to false in thebefore.layout section itself, the layout is not printed and the after.layout sectionis not executed.

after.layout:

Actions programmed in this subsection are executed after the specified layout isprinted.

Text field sectionsYou use a text field section to apply certain actions to all instances of a particulartext field that are included in the report. A text field section consists of a mainsection and a subsection. The main section specifies the particular text field towhich the actions must be applied. The subsection specifies that the actions are tobe performed before the text field is printed.

For example, you could include the page(), need(), and skip() functions in a textfield section to enforce a page break or to skip a specified number of lines beforethe text field is printed. Or you could set lattr.print in the section in order toskip one text line before printing the text field.

Page 101: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-5

Main section

field.<text_field>:

Actions programmed in this section are executed for all instances of the specifiedtext field that are included in the report. The text field must have been defined asa report input field in the data dictionary.

Subsection

before.print:

Actions programmed in this section are executed before the specified text field isprinted.

Predefined variablesYou can use the following predefined variables in a report script.

R = read-only R/W = read and write

lattr.autobefores R/W A boolean indicating whether or not before.fieldlayouts are automatically repeated at the top of apage if the page break does not correspond with asort break. The default value is true.

lattr.autoreset R/W A boolean indicating whether or notreset.suppress() is automatically performed in thecase of breaks of layouts in sorting fields. Thedefault value is true.

lattr.break R A boolean that is set to true during printing ofbefore.field layouts when the layout is printed asthe result of a sort field change. It is set to falsewhen a before.field layout is printed because of apage break.

lattr.enddata R A boolean indicating whether or not the end of thedata has been reached.

lattr.header R A boolean that is set to true during printing ofheader layouts and during printing of before.fieldlayouts at the top of a page.

lattr.language$ R The language code of the report.

Page 102: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-6

lattr.lineno R The current line number.

lattr.multicol R/W Indicates whether or not multiple columns are usedwhen more than one layout fits on a line. Possiblevalues are:

MULTICOL_NONENormal output; no columns are used.

MULTICOL_ORDER_HORIZONTALOutput is arranged in multiple columns, orderedhorizontally. For example:

rec_1 rec_2 rec_3rec_4 rec_5 rec_6

MULTICOL_ORDER_VERTICALOutput is arranged in multiple columns, orderedvertically (per page). For example:

rec_1 rec_3 rec_5rec_2 rec_4 rec_6

lattr.multicol.count R/W Specifies the number of columns to use whenmultiple columns are specified (seelattr.multicol). The default value is 0. In this case,the report manager calculates the number ofcolumns based of the report width and the layoutwidth.

lattr.multicol.repeat R/W A boolean indicating whether headers and footersare automatically repeated for each column. Thedefault value is true. The width of the header andfooter layouts width must be equal to or less thanthe width of the detail layout.

lattr.pageno R/W Current page number.

lattr.print R/W Indicates whether or not a layout is to be printed.

lattr.prline R/W After expansion of a variable in a report, this isfilled with the text line that is printed.

lattr.recordtimes R/W Indicates the number of times the layout will beprinted.

Page 103: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-7

lattr.textexpand R/W A boolean indicating whether or not variablesincluded in text fields can be expanded. Thedefault is false.

lattr.textlang$ R/W The language code for printing text. The default isthe language code of the report.

lattr.textline R A string containing the source text line from thetext manager.

lattr.textlineno R The number of the line that must be printed.

lattr.textlines.max R/W The maximum number of lines in the layout.

lattr.textlines.min R/W The minimum number of lines in the layout.

Report script functionsThe statements programmed in a report script section consist of a combination of3GL language statements and the following 4GL report functions:

layout.again() Evaluate and print layout again.

need( expr ) Force a page break if the number of free lines is lessthan expr.

page() Start a new page.

reset.suppress() It is possible to suppress printing a value when it isthe same as the previous value. You can use thisfunction to suppress the value once (that is, for onevalue).

skip( expr ) Skip expr number of lines before printing the nextlayout.

skip.to( expr ) Skip to the line number indicated by expr.Intervening lines are left blank. If the specified linenumber is less than the current page number, a newpage is started.

to.page( expr ) Start a new page with number expr.

You cannot use need(), page(), skip(), skip.to(), or to.page() in header andfooter layouts.

Page 104: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Report scripts

Programming features

4-8

Expanding text variablesVariables or expressions that are included in text lines can be expanded orsubstituted for report purposes. You must set the variablelattr.textexpand=TRUE if you want this to happen. Expressions are internallyevaluated by the function expr.compile().

Customers can use variables in texts. For example, "address", "city", "salary" andso on. Customers must be informed about these variables so that they can usethem.

Syntax

The following is the syntax for variables and expressions included in text lines:

$variable or #variable${expression} or #{expression}

When the $ symbol if used, the text moves over to accommodate the expandedvariable or expression. When the # symbol is used, the expanded variable orexpression overwrites existing text.

Example

The following is an example of text created by using the text manager. The textincludes both variables and expressions that can be expanded/substituted forreport purposes.

To: $surname $christian name #date , Ede $address

$ZIP code $city

Dear $christian name:

We have the pleasure of informing you that, as of $date,your salary has been raised by 5%. For you this impliesa gross amount of${edit( salary + ( salary * 0.05 ), "ZZZZ9,ZZ" )} per

month.

Kind regards, $Mgr.

Page 105: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

5-1

OverviewBaanERP data is stored in a relational database, which is managed by aRelational Database Management System (RDBMS). The RDBMS acts as thedatabase server for BaanERP applications. BaanERP supports the followingRDBMS products:

n Informixn Oraclen Sybasen DB2n Microsoft SQL Server

The BaanERP architecture includes a database driver. This provides theapplication server (that is, the bshell) with a common interface to the databaseserver, regardless of which RDBMS product is used. This enables the applicationserver to be database independent. The database driver is responsible fortranslating database commands received from the application server intoRDBMS-specific commands. Although, the database driver’s interface with theapplication server is the same for all RDBMS products, Its interface with theRDBMS is RDBMS-specific. Therefore, there is a separate database driver foreach of the supported RDBMS products.

5 Database handling

Page 106: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-2

Database tables

A relational database presents information to the user in the form of tables. In atable, data is organized in columns and rows. Each column (also referred to as afield) represents a category of data. Each row (also referred to as a record)represents a unique instance of data for the categories defined by the columns.

A field always refers to a domain, which defines a set of values from which oneor more fields can draw their actual values. For example, the ’tcweek’ domain isthe set of all integers greater than zero and less than or equal to 53.

Primary keys

Every database table has a field, or a combination of fields, which uniquelyidentify each record in the table. This unique identifier is referred to as theprimary key. Primary keys are fundamental to database operations, as theyprovide the only record-level addressing mechanism in the relational model.Primary keys act as references to the records in a table.

Relationships/references

With a relational database, you can store data across multiple tables and you candefine relationships between the tables. This means that individual tables can bekept small and data redundancy can be minimized. A relationship exists betweentwo tables when they have one or more fields in common. So, for example, aCustomer Details table can be linked to an Orders table by including a CustomerID field in both tables. In the Customer Details table, the Customer ID field is theprimary key. In the Orders table, it is referred to as a foreign key. By linking thetwo tables in this way, there is no need for the Orders table to include customerdetails such as name and address. Note that references from one table to anothermust always use the primary key.

Page 107: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-3

Combined fields

A combined field is a field that consists of two or more child fields. You can usecombined fields as primary keys, and you can also use them for references andindexes.

Indexes

Indexes facilitate speedy searching and sorting of database tables. An index is aspecial kind of file (or part of a file) in which each entry consists of two values, adata value and a pointer. The data value is a value for some field in the indexedtable. The pointer identifies the record that contains this value in the particularfield. This is analogous to a conventional book index, where the index consists ofentries with pointers (the page numbers) that facilitate the retrieval ofinformation from the body of the book.

Note that it is also possible to construct an index based on the values of acombination of two or more fields.

Every table must have at least one index, which is an index on the primary keyfield(s). This is referred to as the primary index. An index on any other field(s) isreferred to as a secondary index.

Structured Query Language (SQL)

Baan SQL is the database query language that you use to access data in thedatabase tables. Using Baan SQL, you can construct queries to retrieve specificdata from the database. The syntax and usage of Baan SQL is discussed fully in“Baan SQL” in Chapter 5.

Page 108: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-4

Naming conventions

The naming syntax for tables, record buffers, and table fields is as follows:

tppmmmxxx | tablercd.tppmmmxxx | record buffer of tableppmmmxxx.ffffffff | logical field of table

where t stands for table, pp is the package code, mmm is the module code, xxx isthe table number (range 000 to 999), and ffffffff is a field name (maximum 8alphanumeric characters, starting with an alphabetic character).

Using tables in program scripts

If a table is used in a script it must be declared with the following statement:

table tppmmmxxx

Declaration of a table implies declaration of all its fields and its record buffer. Itis not necessary to declare these separately.

There are no special functions for opening and closing tables. A table isautomatically opened at the first database call on that table and it is automaticallyclosed at the end of the program.

You can use the record buffer of a table to save the contents of a record in atemporary string. And you can subsequently restore the record from the buffer. Ifa record contains numeric fields, you can only save and restore records. Youcannot perform any other actions on the temporary string, as the presence ofNULL characters will cause loss of data.

Data types

The data type is the internal representation of table field and domain data. Thefollowing data types are available:

DB.BITSET DB.INTEGERDB.BYTE DB.LONGDB.COMBINED DB.MAILDB.DATE DB.MULTIBYTEDB.DOUBLE DB.STRINGDB.ENUM DB.TEXTDB.FLOAT DB.TIME

Page 109: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-5

Transaction handlingWith respect to database actions, a transaction is a sequence of related actionsthat are treated as a unit. The actions that make up a transaction are processed intheir entirety, or not at all.

A transaction ends with the function commit.transaction() (all changes madeduring the transaction are stored in the database) or with the functionabort.transaction() (no changes are stored in the database). A transaction startseither at the beginning of a process, with the functionset.transaction.readonly(), with the function db.lock.table(), or after thepreceding transaction has ended.

A transaction is automatically rolled back (that is, it is undone) when a process iscanceled and if a program ends without a commit.transaction() orabort.transaction() after the last database call. Undoing a transaction is onlypossible if the underlying database system supports this.

Certain database actions cannot be placed within a transaction, because theycannot be rolled back. These actions are: db.create.table(), db.drop.table(), andset.transaction.readonly(). These functions can be called only at the start of aprogram or after the end of the preceding transaction.

You can set a retry point immediately before a transaction. In case of an error,the system returns to this point and re-executes the transaction from there.

A read-only transaction is a transaction in which you are permitted only to readrecords (without lock) from the database. You retain read consistency during theentire transaction. This means that during the transaction your view of thedatabase does not change, even if other users update the records. A read-onlytransaction starts with the function set.transaction.readonly() (this must becalled after ending the preceding transaction or at the beginning of the program)and ends with a commit.transaction() or abort.transaction(). A consistent viewconsumes a large amount of memory, so a read-only transaction must be as shortas possible; user interaction during the transaction is not recommended.

LockingDatabase inconsistencies can arise when two or more processes attempt to updateor delete the same record or table. Read inconsistencies can arise when changesmade during a transaction are visible to other processes before the transaction hasbeen completed – for example, the transaction might subsequently be abandoned.

Page 110: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-6

To avoid such inconsistencies, BaanERP supports the following lockingmechanisms:

n Record/page lockingn Table lockingn Application locking

Record/page locking

To ensure that only one process at a time can modify a record, the databasedriver locks the record when the first process attempts to modify it. Otherprocesses cannot then update or delete the record until the lock has been released.However, they can still read the record.

While one process is updating a table, it is important that other processes retainread consistency on the table. Read consistency means that a process does not seeuncommitted changes. Updates become visible to other processes only when thetransaction has been closed. Some database systems do not support readconsistency, and so a dirty read is possible. A dirty read occurs when one processupdates a record and another process views the record before the modificationshave been committed. If the modifications are rolled back, the information readby the second process becomes invalid.

Some databases, such as SYBASE, use page locking instead of record locking.That is, they lock an entire page in a table instead of an individual record. A pageis a predefined block size (that is, number of bytes). The number of recordslocked partly depends on the record size.

Supported features

INFORMIX ORACLE SYBASE DB2 SQL Server

locking row row page row page

dirty read yes no *

consistent read no yes *

transactions yes yes yes yes yes

* SYBASE will block when there is a read action (locked or not) on a record in apage that has been locked.

Page 111: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-7

Delayed locks

Locking a record for longer than required can result in unnecessarily longwaiting times. The use of delayed locks solves this problem to a great extent.

A delayed lock is applied to a record immediately before changes are committedto the database and not earlier. When the record is initially read, it is temporarilystored. Immediately before updating the database, the system reads the value ofthe record again, this time placing a lock on it. If the record is already locked, thesystem goes back to the retry point and retries the transaction. If the record is notlocked, the system compares the content of the record from the first read with thecontent from the second read. If changes have been made to the record byanother process since the first read, the error EROWCHANGED is returned andthe transaction is undone. If no changes have occurred, the update is committedto the database.

You place a delayed lock by adding the keyword FOR UPDATE to the SELECTstatement (see “BAAN SQL” later in this chapter).

For example:

table tpctst999

db.retry.point()SELECT pctst999.*FROM pctst999 FOR UPDATESELECTDO

pctst999.dsca = "...."....db.update(tpctst999, DB.RETRY)

ENDSELECT

Table locks

BaanERP provides a table locking mechanism, which enables you to lock all therecords in a specified table. A table lock prevents other processes frommodifying or locking records in the table but not from reading them. This isuseful when a particular transaction would otherwise require a large number ofrecord locks. You use the db.lock.table() function to apply a table lock.

Application locks

An application lock prevents other applications and users from reading and/ormodifying an application’s data during critical operations. It is not part of atransaction and so is not automatically removed when a transaction is committed.Instead, an application lock is removed when the application ends or whenappl.detete() is called.

Page 112: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-8

Retry pointsA retry point is a position in a program script to which the program returns if anerror occurs within a transaction. The transaction is then retried. There are anumber of situations where retry points are useful:

n During the time that a delayed lock is applied to a record/page, an error canoccur that causes the system to execute an abort.transaction(). In such cases,all that BaanERP can do is inform the program that the transaction has beenaborted. However, if retry points are used, the system can automatically retrythe transaction without the user being aware of this.

n Some database systems generate an abort.transaction() when a dirty recordis read (that is, a record that has been changed but not yet committed). Anabort.transaction() may also be generated when two or more processessimultaneously attempt to change, delete, or add the same record. In all thesesituations, BaanERP Tools can conceal the problem from the user by usingretry points. It simply retries the transaction. If there is no retry point, thetransaction is aborted and the session is terminated.

n In BaanERP, updates are buffered, so the success or failure of an update isnot known until commit.transaction() is called. If an update fails, thecommit of the transaction also fails, and the entire transaction must berepeated. If retry points are used, the system automatically retries thetransaction.

n Retry points can also resolve potential deadlock problems. If, for example,the system is unable to lock a record, it rolls the transaction back and triesagain.

It is vital that retry points are included in all update programs.

Coding retry points

The retry point for a transaction must be placed at the start of a transaction. Thefollowing example illustrates how you program retry points:

db.retry.point() | set retry pointif db.retry.hit() then

...... | code to execute when the system| goes back to retry point

else...... | initialization of retry point

endif

The function db.retry.hit() returns 0 when the retry point is generated – that is,the first time the code is executed. It returns a value unequal to 0 when thesystem returns to the retry point through the database layer.

NOTE

Page 113: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-9

When the system goes back to a retry point, it clears the internal stack offunctions, local variables, and so on that were called during the transaction. Theprogram continues from where the retry point was generated. The value of globalvariables is NOT reset.

When a commit fails, the database automatically returns to its state at the start ofthe transaction; the program is set back to the last retry point. It is vital, therefore,that the retry point is situated at the start of the transaction. The db.retry.hit()call must follow the db.retry.point() call. Do not place it in the SQL loop itselfas this makes the code very untransparent. When a retry point is placed within atransaction, the system produces a message and terminates the session.

Testing retry points

The following shell variables enable you to test the operation of retry points:

TEST_RETRY=X This variable indicates how often the system must goback to a retry point at the moment of committing. Thiscannot be used when testing different sessions with retrypoints parallel.

MAX_RETRY=X This variable indicates how often the system may returnto a retry point as a result of an abort in an update action.Default: 10

Baan SQLYou use Baan SQL (Structured Query Language) to retrieve information fromthe database. With Baan SQL’s SELECT statement, you can retrieve anyselection of data from the database, regardless of the number of tables in whichthe data is stored. The system does search through all records sequentially. Itbases its search on a number of conditions defined in the SELECT statement.

The SELECT statement does not modify the data in the database. It is usedsimply to query the data. Whereas only one user at a time can modify data, anynumber of users can query or select the data concurrently.

The SELECT statement works at the table level; the output is also a tableconsisting of 0, 1, or more records. If the query is very specific, the output mayconsist of only one record. The structure of a SELECT statement is directlyderived from the table structure. It takes the following general form:

SELECT columns ...FROM table(s) ...WHERE each row fulfills the condition(s) ...

Page 114: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-10

The following sections provide information on SQL syntax and using SQL.

SQL syntaxThe general structure of an SQL query is as follows:

SELECT <select list>[ FROM <from list> ][ WHERE <where condition> ][ GROUP BY <group list>[ HAVING <having condition> ] ][ ORDER BY <order by list> [WITH RETRY [REPEAT LAST ROW] ]][ SET SPECIFICATION ]

For full details of any of the above clauses of the SELECT statement, see thesections below.

SELECT <select list>

The SELECT clause specifies the table fields that must be represented in theoutput and the functions (if any) that must be executed on the selected fields.You can use the wildcard character [*] to specify all fields of all tables. You canspecify all fields of a particular table by suffixing the table name by the wildcardcharacter [*].

You can use the following functions in the SELECT clause:

n min(<field name>) – for the minimum value of the field

n max(<field name>) – for the maximum value of the field

n sum(<field name>) – for the sum of the values of the field

n count(<field name>) – for the number of fields selected

n count(*) – for the number of records selected

n avg(<field name>) – for the average value of the field.

These functions consider all selected records as one group and are executed onthat group. So they produce a single result – for example, the average value of aspecified table field. You usually use these functions in combination with theGROUP BY clause. With this clause, you can group the results into a number ofsubsets. The function is then performed on each subset.

Page 115: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-11

FROM <from list>

The FROM clause specifies the names of the tables from which fields must beselected. The names of fields specified in the SELECT clause include the tablename. It is not necessary to include these tables in the FROM clause as well.

In the FROM clause, you can define aliases for table names. Aliases arenecessary, for example, for double references and for references to the maintable. You define an alias as follows:

<table name> <alias name>

Include the keyword FOR UPDATE after a table name to indicate that the tablemust be read with delayed lock. If you include FOR UPDATE after the keywordSELECT in the SELECT clause, this indicates that all tables must be read withdelayed lock.

WHERE <where condition>

The WHERE clause specifies one or more conditions which the selected recordsmust meet. It has the following format:

WHERE <operand1> <operator> <operand2> [<operand3>]

Operands

Operands 1 and 2 can consist of any of the following:

n numeric constant (for example, 10, 3.1415927)

n string constant (for example, "John", "mod")

n combined constant (for example, { 10 , "xyz" })

n table field, optionally followed by array indication

n pseudo field – for example, for indexes (<table>._index1, see “Combinedfields” earlier in this chapter)

n 4GL variable or pseudo variable (see “Using program variables” later in thischapter)

n numeric expression (in which the operators +, -, *, /, \ are possible)

n string expression (in which the operator & and a substring are possible)

n special field – enum constants, date constants (using the functiondate.to.num(Y,M,D) and date.num())

Page 116: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-12

Operand 2 can also consist of the following:

n subqueries

n set definition (as subquery or a list of constants)

Operators

The following operators are possible:

n comparison operators

=, <, <=, >, >=, <>, !=#>, #>=, #<, #<= (for combined fields)

n IN operator

Here, operand2 contains a set of values (or subquery). The system tests if thevalue of operand1 is present in operand2. This operator replaces a number ofexpressions separated by the OR operator. For example, both of the followingstatements define the same condition:

WHERE ttadv200.cpac = "tc" OR ttadv200.cpac = "tt"WHERE ttadv200.cpac IN ( "tc", "tt" )

n LIKE operator

The LIKE operator compares operand1 with operand2. Operand2 can containwild cards. For example:

WHERE name LIKE "[Tt]riton.*"

In this example, "Triton2.1" and "triton" are legal values. In this case,operand2 is a regular expression. See the expr.compile() function for a list ofthe possible features that the expression can contain.

n BETWEEN / INRANGE operator

These operators check whether operand1 falls within a specified range ofvalues. Operand2 and operand3 specify the lower and upper values of therange. For example, both of the following statements define the samecondition – that is, they define a range from "tc" through "ts":

WHERE ttadv200.cpac >= "tc" AND ttadv200.cpac <= "ts"

WHERE ttadv200.cpac INRANGE "tc" AND "ts"

The operators BETWEEN and INRANGE are identical, except when you usecombined fields (see “SQL and combined fields” later in this chapter).

Page 117: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-13

n EXISTS operator

This operator tests whether certain records do or do not occur. It is used inconjunction with subqueries. The following example selects only those itemson the order list with an order quantity greater than 100:

select tiitm001.item, tiitm001.dscafrom tiitm001where exists

( select timps052.* from timps052

where timps052.item = tiitm001.item andtimps052.qana > 100 )

n REFERS TO operator

See “References” later in this chapter.

GROUP BY <group condition>

The GROUP BY clause groups the records of the output table, based on thefields specified in the clause. It combines similar records, producing a singleresult record for each group of records with the same values for each table fieldlisted in the SELECT clause. All elements of the <group condition> must bespecified in the <select list> of the SELECT clause.

The power of the GROUP BY clause is most apparent when it is used with thefunctions min, max, count, avg, and sum. In these cases, it produces summaryvalues for each group. For example:

SELECT ttadv200.cpac, ttadv200.cmod, ttadv200.csesFROM ttadv200GROUP BY ttadv200.cpac, ttadv200.cmod, ttadv200.cses

| Sessions with the same session code and different VRCs| are selected only once

SELECT ttadv200.cpac, ttadv200.cmod, ttadv200.cses, count(*)FROM ttadv200GROUP BY ttadv200.cpac, ttadv200.cmod, ttadv200.cses

| The program counts the sessions with the same| names but different VRCs.

Page 118: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-14

HAVING <having condition>

The HAVING clause sets conditions on groups defined by the GROUP BYclause (that is, HAVING does for groups what WHERE does for records). If youuse a HAVING clause, you must specify a GROUP BY clause also. Theelements in the <having condition> can be either elements from the <select list>in the SELECT clause or functions on fields from the <select list>. The <havingcondition> can contain arithmetical and string expressions. For example:

SELECT ttadv200.cpac, ttadv200.cmod, ttadv200.cses, count(*)FROM ttadv200GROUP BY ttadv200.cpac, ttadv200.cmod, ttadv200.csesHAVING count(*) > 1

ORDER BY<order by condition>

The ORDER BY clause has the following syntax:

ORDER BY <order by condition> [ WITH RETRY [REPEAT LAST ROW] ]

This clause determines the order of the records in the output table. In the <orderby condition>, you list one or more fields from the <select list> in the SELECTclause. The field listed first in the ORDER BY clause takes precedence. You canlist the fields by name or you can specify an index to their position in theSELECT clause. For each field in the <order by condition>, you can indicate ifthe order is to be ascending (default) or descending – for example, ORDER BY 1asc, 2 desc.

If retry points are included, you must use ORDER BY to ensure that thesequence after return to the retry point is identical to the one used the first time.After a jump to a retry point, it is important that the query continues at itsposition in the selected set at the time that the retry occurred. By using the WITHRETRY addition this is easy to realize. By performing a commit.transaction(),the values for the retry conditions are saved. In case of a jump to a retry point,the query continues, starting from the values saved during thecommit.transaction(). In the case of WITH RETRY the new set starts after thesaved values. In the case of WITH RETRY REPEAT LAST ROW, the set startsat the saved value; so the last record is read again. In the case of WITH RETRYREPEAT LAST ROW, enter a commit.transaction() in the SELECTEOS partof the select statement to prevent a new build-up of the query in some cases.

Page 119: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-15

Example (embedded SQL)

SELECT tisfc001.*FROM tisfc001 FOR UPDATEWHERE tisfc001.pdno < 100ORDER BY tisfc001.pdno WITH RETRYSELECTDO

tisfc001.proc = tcyesno.yesdb.update(tisfc001, DB.RETRY)commit.transaction()

ENDSELECT| In this case we do not use REPEAT LAST ROW, because the| moment retry takes place, the value present at the stage of| commit.transaction() has certainly been saved.

Set specification

Baan SQL supports the following options in relation to sets:

n Maximum set size.

With this option you can indicate the maximum number of records the querycan produce. The syntax is:

SELECT .... [from][where] AS SET WITH <number> ROWS

n Prepared set.

With this option, the entire set is retrieved before the first record is returned.The set is temporarily stored. This option is useful when a processsimultaneously selects and maintains (or deletes or adds) records. In this case,changes must not be visible in the selected records. The prepared set optionforces a consistent read. The syntax is as follows:

SELECT ... [from][where] AS PREPARED SET

n Maximum set size and prepared set.

You can combine both options as follows:

SELECT ... [from][where] AS PREPARED SET WITH <number>ROWS

Using program variablesAs a 4GL query is handled via the bshell, you can directly relate programvariables to it. Linking program variables is required for both the SELECTclause and the WHERE clause.

Page 120: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-16

SELECT clause

In the <select list> of the SELECT clause, program variables are used to indicatethe elements in which the query results must be stored. You can do this byexplicitly specifying a program variable. The general syntax is:

<select part>:<program variable>

For example:

SELECT ppmod123.field1:my_val1

Or you can directly use a program variable (a table or field name) from thecalling program in the <select list>. For example:

SELECT ppmod123.field1

In the first example, the program places the result in the <program variable>. Inthe second example, the name in the query and the name of the program variableare identical.

FROM clause

You can also use program variables in the WHERE clause. When evaluating thequery, the program loads the values of the program variables into the query andincludes them in the evaluation. This link can be realized by incorporating aprogram variable in the query, preceded by a colon [:]. For example:

WHERE ppmod123.field1 = :myval1

Note

A table field can be a program variable as well as a query variable. Note that thefollowing query:

select tccom010.*where tccom010.cuno = tccom010.cuno

has a different result from:

select tccom010.*where tccom010.cuno = :tccom010.cuno

The latter selects one record; the former selects all records from the tabletccom010, as tccom010.cuno by definition equals tccom010.cuno for each row.

Page 121: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-17

References

Retrieving references to a record

In the standard SQL interface, you can retrieve references to a record as follows:

| Suppose that tiitm001 has a reference to tccom010| (field ’cuno’), and to tccom011 (field ’suno’)table ttiitm001table ttccom010table ttccom011

SELECT tiitm001.*, tccom010.*, tccom011.*FROM tiitm001, tccom010, tccom011WHERE tiitm001.cuno = tccom010.cuno AND

tiitm001.suno = tccom011.suno

Retrieving references using REFERS TO

To simplify the retrieval of references, you can specify references (using thekeyword REFERS TO) in the WHERE clause. Apart from simplifying the query,this also optimizes query handling. As references always refer to a primary key,they can be found immediately. Moreover, the program fills a field withreference characters if it does not find a reference. The following implements theprevious example by using REFERS TO:

table ttiitm001table ttccom010table ttccom011

SELECT tiitm001.*, tccom010.*, tccom011.*WHERE tiitm001.cuno REFERS TO tccom010 AND

tiitm001.suno REFERS TO tccom011

| OR

SELECT tiitm001.*, tccom010.*, tccom011.*WHERE tiitm001 REFERS TO tccom010 AND

tiitm001 REFERS TO tccom011

Page 122: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-18

REFERS TO syntax

A REFERS TO statement has the following form:

<from> REFERS TO <to> [PATH <path> [,<path>...]][UNREF<mode>]

The following table explains the various parts of the statement:

<from> The referring table field or table.

<to> The table referred to.

<path> The path via which reference is reached (always table fields). IfPATH is specified, specifying a table field for <from> ismandatory. For example:

WHERE table1.field REFERS TO table4.fieldPATH table2.field, table3.field

<mode> A mode indicating system action if reference does not exist;possible values are:

SKIPIf a reference cannot be found, the record is skipped.

CLEARIf a reference is empty or absent, the referring record is filledwith spaces or 0 (numeric).

SETUNREFThe value of an undefined reference is filled with an ’undefinedreference’ sign, defined in the data dictionary, or with 0(numeric).

CLEARUNREFThe referred record is filled with spaces or 0 (zero) whenreference fields are empty. When the reference is undefined thereferred record is filled with an ’undefined reference’ sign.

Depending on the reference definition in the data dictionary, thedefault reference mode is:

reference mode in DD UNREF mode

mandatory SETUNREFmandatory unless empty CLEARUNREFnot mandatory CLEAR

Page 123: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-19

Example

SELECT ttadv100.*FROM ttadv100, ttadv101WHERE ttadv101.cmod BETWEEN "aaa" and "azz"AND ttadv101 REFERS TO ttadv100 UNREF <UNREF_mode>AND ttadv100.cpac BETWEEN " " and "zz"

The evaluation order of this query is as follows:

1 Find all rows / records in ttadv101 that match the BETWEEN "aaa" and "azz"condition.

2 Find all references from each row from step 1 in table ttadv100.

3 Find all rows selected in step 2 which match the BETWEEN " " and "zz"condition

When some reference does not exist in ttadv100 (step 2 fails), because of thecondition on the referenced table, the whole row is rejected.

Using aliases with REFERS TO

You can use aliases to refer from one table to another with two references. In thefollowing example, there are two references from ttadv300 to ttaad110, viattadv300.lanl and via ttadv300.clan. Both are searched for in the followingconstruction:

string desc.clan(20), desc.lanl(20)table tttadv300SELECT ttadv300.desi, ttadv300.cfrm, ttadv300.clan,

tclan.dsca:desc.clan, ttadv300.lanl, tlanl.dsca:desc.lanl

FROM ttadv300, ttaad110 tlanl, ttaad110 tclanWHERE ttadv300.desi = :designer AND

ttadv300.clan REFERS TO tclan UNREF SETUNREF ANDttadv300.lanl REFERS TO tlanl UNREF SETUNREF

Using program variables or constants with REFERS TO

You can also retrieve references by using a program variable or a constant. Thisavoids the program first reading the <from> table. In the following exampletiitm001 has a reference to tccom010 (field ’cuno’), and a reference to tccom011(field ’suno’) and the value of tiitm001 is known:

Table ttccom010Table ttccom011

SELECT tccom010.*, tccom011.*FROM tccom010, tccom011

Page 124: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-20

WHERE :tiitm001.cuno = tccom010.cuno AND:tiitm001.suno = tccom011.suno

In the following example, the REFERS TO clause is used to achieve the sameresult. If the program does not find the reference, it fills the field with referencecharacters.

Table ttccom010Table ttccom011

SELECT tccom010.*, tccom011.*WHERE :tiitm001.cuno REFERS TO tccom010 AND

:tiitm001.suno REFERS TO tccom011

In this case the REFERS TO statement has the following from:

<from> REFERS TO <to> [UNREF <mode>]

The following table explains the various parts of the statement:

<from> The referring program variable or constant. If a combinedconstant is used, all fields must be filled.

<to> The table referred to (refers to primary key of the table). This canalso be a field provided that a unique index to this field exists.

<mode> A mode indicating system action if reference does not exist;possible values are:

SKIPIf a reference cannot be found, the record is skipped.

CLEARIf a reference is empty or absent, the referring record is filledwith spaces or 0 (numeric).

SETUNREFThe value of an undefined reference is filled with an ’undefinedreference’ sign, defined in the data dictionary, or with 0(numeric).

CLEARUNREFThe referred record is filled with spaces or 0 (zero) whenreference fields are empty. When the reference is undefined thereferred record is filled with an ’undefined reference’ sign.

As no dictionary default is available, SETUNREF has beendefined as the default action.

Page 125: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-21

ExampleSELECT tccom010.*FROM tccom010, tiitm001WHERE tiitm001.cuno = :tiitm001.cuno AND

tiitm001.cuno REFERS TO tccom010

This is equal to the following:

SELECT tccom010.*WHERE :tiitm001.cuno REFERS TO tccom010

Company numbersThe company number used during execution of a BAAN 4GL query is thecurrent company number. The current company number is:

n The default company number (defined in the session "Maintain User Data" )

n A company number specified by the compnr.check() function

The <table._compnr field

The <table>._compnr field enables the use of different company numbers. Thisfield specifies the actual company number of the table. When this field isundefined, the current company number is taken as the default. ’Undefined’ isdenoted by the value -1.

When a record is selected with ’select <table>.*’, the field <table>._compnr inthe record contains the company number of the table. When inserting a record ina table with a specific company number, you must fill <table>._compnr with thecorresponding company number. The function db.insert() takes care of this andwrites the record in the correct (physical) table. No special file pointers arenecessary (for example, by using db.bind()).

Example

The record where the field ttadv100._compnr = 000 belongsto the (physical) table ttadv100000The record where the field ttadv100._compnr = 200 belongsto the (physical) table ttadv100200

Page 126: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-22

Using <table>._compnr in the WHERE clause

You can also use <table>._compnr in the WHERE clause of a Baan SQLstatement. In this case it is used as a search condition. For example:

SELECT ttadv100.*FROM ttadv100WHERE ttadv100._compnr = 200 AND ttadv100.cpac = ’tt’

This query lists all records from table ttadv100200 where ttadv100.cpac has thevalue ’tt’.

You can use <table>._compnr in the following ways:

n <table>._compnr = <number> or <number> = <table>._compnr where<number> specifies an integer number. The value of <number> is taken asthe company number. It must be a 3-digit number.

n <table>._compnr = <string> where <string> specifies a list of companynumbers, separated by commas [,]. This construction can be used to check acondition for a range of company numbers. The string can contain only digitsand commas. (So, you specify company numbers 0 and 23 by<table>._compnr = "000,023"). For example:

SELECT ttadv100.*WHERE ttadv100._compnr = "200,300" AND <condition>

This query results in a list of the records from the table ttadv100 (withcompany numbers 200 and 300) that match <condition>.

n <table>._compnr IN <set specification> where <set specification> is a set ofconstants or a subquery.Sets must not contain duplicate values. See IN operator in “WHERE<where condition>” section earlier in this chapter.

Combining <table>._compnr conditions

n A list of AND conditions can contain only one condition that includes<table>._compnr. So, the following construction is possible:

WHERE <table>._compnr = 100 AND <condition>

but the following is not possible:

WHERE <table>._compnr = 100 AND <table>._compnr = 200

Page 127: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-23

n In a list of OR conditions, each condition must have a condition on<table>._compnr, or none of them. So, the following construction is possible:

WHERE (<table>._compnr = 100 OR <table>._compnr = 200)AND <condition>

but the following is not possible:

WHERE (<table>._compnr = 100 OR <other_field> = <value>)AND <condition>

SQL and combined fieldsDefining a query that can be handled efficiently by the query handler is acomplex task. This is especially true if there are combined fields (which consistof a number of child fields), as each field must be specified separately.

Specifying a combined field

As the designer can usually judge best which index should be used for anoptimum result, the following construction enables the designer to specify acombined field:

WHERE ppmod001.comb1 = {"adv", "099", "123"}

A child field can be an expression, a BAAN 4GL variable, or a pseudo variable.A comparison operator (=, >, >=, etc.) for a combined field applies to thecombination of all child fields. For example:

| suppose the combined field ppmod001.comb1 consists of the

| fields ppmod001.modu, ppmod001.tblno and ppmod001.compno:

WHERE ppmod001.comb1 >= {"adv", "000", "100"}

| The above statement is equal to the following statement

WHERE ( ppmod001.modu > "adv" ) OR( ppmod001.modu = "adv" AND ppmod001.tblno >

"000" ) OR( ppmod001.modu = "adv" AND ppmod001.tblno =

"000" AND ppmod001.compno >= "100" )

Page 128: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-24

Comparison operators for combined fields

The comparison operators #>, #>=, #<, #<= for a combined field apply to eachchild field separately. For example:

WHERE ( ppmod001.comb1 #>= {"adv", "000", "100"} ANDppmod001.comb1 #<= {"zzz", "999", "200"} )

This represents the following:

WHERE ppmod001.modu >= "adv" ANDppmod001.modu <= "zzz" ANDppmod001.tblno >= "000" ANDppmod001.tblno <= "999" ANDppmod001.compno >= "100" ANDppmod001.compno <= "200"

If a child field of a combined field is not specified, the value of this field is freeand is not included in the condition. For example:

WHERE ppmod001.comb1 #>= {"adv", "000", "100"} ANDppmod001.comb1 #<= {"zzz", "999"}

This represents the following:

WHERE ppmod001.modu >= "adv" ANDppmod001.modu <= "zzz" ANDppmod001.tblno >= "000" ANDppmod001.tblno <= "999" ANDppmod001.compno >= "100"

As the field ppmod001.compno has no upper limit, all values greater than orequal to 100 are fetched.

Indexes as combined fields

You can specify an index as a combined field even if a combined field is notpresent in the data dictionary. The index name is table._indexY where:

table is the name of the table or alias of a table

_index is a prefix to indicate that an index field is involved (a condition forthis syntax is that there are no field names having this format)

Y is the sequence number of the index defined in the data dictionary

As a combined field is being used, the value must always be enclosed by ’{’ and ’}’.For example:

WHERE tiitm001._index1 = { :item }

Page 129: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-25

As with other combined fields, children of index fields for which no value isspecified are not included in the condition. However, you can leave fieldsunspecified only at the end of the index, not in the middle.

An index’s pseudo field cannot be used in the query preceded by ’:’.

Meanings of upper and lower limits

In connection with combined fields, the combination of upper/lower limit canhave two meanings (compare ’>’ and ’#>’).

n Firstly, it can mean that each field of a record that meets the conditions liesbetween the boundaries specified. For example:

WHERE( ppmod001.comb1 #>= {"adv", "000", "100"} ANDppmod001.comb1 #<= {"zzz", "999", "200"} )

Here, {"adv", "050" "123"} meet the conditions, but the combination {"uvw","123", "300"} does not, because of the last child field.

For this construction we define the INRANGE statement. With INRANGE,the preceding example becomes:

WHEREppmod001.comb1INRANGE {"adv", "000", "100"} AND

{"zzz", "999", "200"}

With INRANGE, the boundaries indicated apply to each separate field (usualin print sessions).

n Secondly, it can mean that all records are selected for which the combinedfield (regarded as one single field) lies between the boundaries indicated. Forexample:

WHERE ( ppmod001.comb1 >= {"adv", "000", "100"} ANDppmod001.comb1 <= {"zzz", "999", "200"} )

Here, {"uvw", "123", "300"} meets the condition as "uvw"&"123"&"300"lies between "adv"&"000"&"100" and "zzz"&"999"&"200" (’&’ meansconcatenation).

For this purpose we use a BETWEEN statement. With BETWEEN, thepreceding example becomes:

WHERE ppmod001.comb1BETWEEN {"adv", "000", "100"} AND

{"zzz", "999", "200"}

With BETWEEN, the fields in the combined are regarded as one field; theboundaries apply to the combined field as a whole.

Page 130: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-26

If the field consists of one single element, INRANGE and BETWEEN areequivalent.

SQL subqueriesBaan SQL permits the use of subqueries. These are SELECT statements in theWHERE clause of another SELECT statement.

Defining nested queries can be very difficult. It is best to define the subquery ofthe lowest level first and the main question last.

Example 1

Select those prices from the item file that are above average. When calculatingthe average, the system should not take prices less than or equal to zero intoaccount.

SELECT tiitm001.copr | cost priceFROM tiitm001WHERE tiitm001.copr >

( SELECT avg(tiitm001.copr)WHERE tiitm001.copr > 0 )

ORDER BY tiitm001.copr

In this case, the subquery should only produce one result (here the average costprice). If the subquery produces more than one result, use the operators IN andEXISTS.

Example 2

Select the numbers and names of all suppliers who have yet to deliver.

SELECT tccom020.suno, tccom020.namaFROM tccom020 | SuppliersWHERE EXISTS

( SELECT *FROM timps053 | Purchase ordersWHERE timps053.suno = tccom020.suno )

SELECT tccom020.suno, tccom020.namaFROM tccom020WHERE tccom020.suno IN

( SELECT timps053.sunoFROM timps053GROUP BY timps053.suno )

Page 131: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-27

SQL programmingThere are two ways to use Baan SQL in a Baan 4GL program. You can embed itin the language (embedded SQL), or you can use Baan 4GL functions (dynamicSQL).

Embedded SQL

Syntax

The following loop structure enables the use of SQL as part of the language:

SELECT < set definition (= actual query, see "SQL Syntax"earlier in this chapter) >

[ SELECTBIND ( number, var) ] ...[ WHEREBIND (number, expression) ] ...[ SELECTDO

< operation(s) on all selected records > ][ SELECTEOS

< operation(s) after last selected record > ][ SELECTEMPTY

< operation(s) if nothing has been selected > ][ SELECTERROR

< operation(s) in case of an error condition > ]ENDSELECT

Description

Data is selected on the basis of the condition specified in the SELECT statement.The operations between SELECTDO and ENDSELECT are performed on eachrecord from the selected set. The loop ends either when the program has handledthe entire set or the program encounters a BREAK command.

In the case of an error, the program executes the SELECTERROR part. ACONTINUE statement in the SELECTERROR part causes the next record to beprocessed. If there is no SELECTERROR section, the program generates aBREAK as the default action. Note that errors are returned only if the shellvariable ERROR.BYPASS = 1.

The SELECTEOS part is executed after the SELECTDO of the last selectedrecord. The intention of the SELECTEOS part is that before the programencounters a ’break’ from the loop you can give a commit.transaction(), while acommit.transaction() may cause a retry. If a commit.transaction(), given afterthe ENDSELECT part, causes a retry, then the whole query must be regenerated.

Page 132: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-28

If the SELECTDO part is suppressed, the program encounters a ’break’ from theloop after the first selected record. If the SELECTDO part is suppressed but theSELECTEOS part occurs, the program will select the whole set of records.

In order to bind pseudo variables, the functions SELECTBIND andWHEREBIND have been added. Pseudo variables have the form ’:<number>’. Aspecial bind function is then used to link a program variable to the pseudovariable. For example:

SELECT ppmod123.field1:5, ppmod123.field2:6SELECTBIND(5, my_val1)SELECTBIND(6, my_val2)SELECTDO

....ENDSELECT

This is equal to ’SELECT ppmod123.field1:my_val1’, but using a bind function.

It is also possible to use a pseudo variable in the WHERE clause. TheWHEREBIND function is then used to link a value to the pseudo variable. Forexample:

SELECT ....WHERE ppmod123.field1 = :1WHEREBIND(1, 10 + sqrt(a+b))SELECTDO

....ENDSELECT

Used BAAN 4GL variables (with ’:’) are ’bound’ automatically.

Example

table tppmod090long total, m_val

m_val = 25SELECT ppmod090.fld1, count(*):1FROM ppmod090, ppmod091 | this line is optionalWHERE ppmod090.fld2 = ppmod091.fld5 AND

ppmod091.fld3 > :m_valGROUP BY ppmod090.fld1ORDER BY 2SELECTBIND(1,total)SELECTDO

print_info(ppmod090.fld1, total)SELECTERROR

message("Error %d occurred", db.error)break

ENDSELECT

Page 133: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-29

See “Dynamic SQL” below for an example of the same query executed usingdynamic SQL.

Dynamic SQL

Dynamic SQL enables a program to form an SQL statement during execution, sothat the contents of the statement can be determined, for example, by user input.

Functions

To use Dynamic SQL, the following functions are available:

Functions Description

sql.parse() Query definition.

sql.set.rds.full() This sets the size of the RDBMS buffer.

sql.select.bind()sql.where.bind()

These functions link program variables to thequery's pseudo variable. In Dynamic SQL, allnon-external program variables used in thequery must be linked to a pseudo variable withthese functions.

sql.exec() This function initializes the query. It gives thevariables their proper values.

sql.fetch() This function executes the query. It reads oneresult on which operations can be performed.This function must be invoked for each separaterecord from the selected set.

sql.break() Stops execution of the query. Any interimresults are cleared.

sql.close() Deletes (all) internal information belonging tothis query.

See the Dynamic SQL functions, in U7167A US BaanERP Tools: Functionsreference, for more information and a description of the syntax of thesefunctions.

Page 134: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-30

Sequence of actions

By using these functions a query, once defined, can be reused optimally. Thesequence of the actions is then:

sql.parse, sql.bind, sql.exec, sql.fetch, sql.fetch, ...,sql.break

sql.bind, sql.exec, sql.fetch, sql.fetch, ...,sql.break

sql.close

In this way you can prevent expensive sql.parse() calls, while still working withnew arguments.

This flow is automatically generated from an embedded SQL program by bic6.2.Usually, the programmer will therefore opt for embedded SQL, the more so,since it automatically binds 4GL variables.

Example

Table tppmod090Long sqlLong total, m_val

m_val = 25if ( not sql ) then

sql = sql.parse("select ppmod090.fld1, count(*):1 " &"from ppmod090, ppmod091 " &"where ppmod090.fld2 = ppmod091.fld5 AND " &

"ppmod091.fld3 > :2 " &"group by ppmod090.fld1 " &"order by 2")

endifsql.select.bind(sql, 1, total)sql.where.bind(sql, 2, m_val)sql.exec(sql)while ( true )on case ( sql.fetch(sql) )

case eendfile:break

case 0:print_info(ppmod090.fld1, total)continue

default: | errormessage("Error %d occurred", db.error)

endcasebreak

endwhilesql.break(sql)

Page 135: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-31

sql.close(sql) | After sql.close, a new sql.parse must besql = 0 | executed to give sql a correct value. If

| the last two lines are skipped, sql| retains a correct value.

See “Embedded SQL” earlier in this chapter for an example of the same queryexecuted using embedded SQL.

SQL and delayed locksThe purpose of delayed locking is to postpone the physical lock of a record aslong as possible. The program places the physical lock immediately beforeupdating. During updating, the value of the record at the moment of selectionmust be known, as this is compared to the value at the moment of updating.During comparison, the relationships between fields are taken into account.

For a record to be delayed-locked when selected, the keyword FOR UPDATEmust be included in the SELECT statement. In SQL, 'normal' record locking isnot possible.

When placing a delayed lock on a record, the program fills the field<table>._dlock with an identification number linked to the record. This fieldidentifies the original record. This guarantees a fast search procedure. This fieldwill be overwritten when changing the record buffer.

Updates in combination with SELECT FOR UPDATE are executed with thefollowing functions:

db.insert(table, DB.RETRY [, eflag])db.update(table, DB.RETRY [, eflag])db.delete(table, DB.RETRY [, eflag])

The DB.RETRY flag indicates that we are dealing here with updates withSELECT FOR UPDATE and retry points. This flag ensures that the actualupdate action is postponed until the commit. The db.update() and db.delete()functions with the DB.RETRY flag can be invoked only in combination withSELECT FOR UPDATE. The use of db.insert() with the DB.RETRY flag, onthe other hand, is not linked to the use of SELECT FOR UPDATE.

Page 136: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-32

SQL trace optionsIt is possible to monitor whether the SQL compiler and optimizer are taking theright decisions. If the results indicate that the design is incorrect, the query mustbe changed. The optimizer can never emulate the programmer. The Baanprogramming language therefore enables the programmer to instruct thecomputer what it has to do to a considerable degree of detail. You can definewhich index to use; also, a number of special (non-standard SQL) functions havebeen built in.

You can use the environment variable TT_SQL_TRACE to trace what happensinside the SQL processor. TT_SQL_TRACE is used to trace SQL processing inthe client (that is, bshell6.2), as well as in the server process (that is,bisam_srv6.2). The methods involved are different for client and server.

Client tracing

When TT_SQL_TRACE is set, the output from the client process is written tostderr. To keep this information, you must call the bshell with the options "-keeplog" and "-logfile <log file name>". For example:

bx6.1 -- -keeplog -logfile mylogfile -setTT_SQL_TRACE=02000

This enables TT_SQL_TRACE with value 02000. The output is written to thefile "mylogfile" in the current working directory.

Server tracing

When TT_SQL_TRACE is set, the output is written to a file named "dbs.log".This file is located in the current working directory when the Database Serverruns locally (on same host as Display Server). When the database is remote, it iswritten in the login directory of the corresponding user on that remote system. Toenable logging of TT_SQL_TRACE in the file "dbs.log", you must also set theenvironment variable DBSLOG, as follows:

DBSLOG=02000

The "02000" is an octal value, and can be OR-ed with other variables. Themeaning of the other values is described in a separate document (LoggingDatabase Information (DBSLOG)).

Page 137: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-33

Query identification

A QueryIdentifier (QID) identifies each query. This makes it easy to find outwhich output in the Client log file is related to the output of the Server log file.

Trace options

The following values for TT_SQL_TRACE are available (C indicates that anoption can be used for the client; S indicates that it can be used for the server):

1. TT_SQL_TRACE=040 (C) Show queries with their QID2. TT_SQL_TRACE=02000 (C) Show calls of internal SQL

functions3. TT_SQL_TRACE=0200 (C) Show query execution times4. TT_SQL_TRACE=04000 (C+S) Show query evaluation plan5. TT_SQL_TRACE=020000 (S) Show FullTableScan6. TT_SQL_TRACE=010000 (S) Show Query Evaluation Plan

You can combine trace options by assigning several different flags toTT_SQL_TRACE at the same time. For example:

TT_SQL_TRACE=010200 export TT_SQL_TRACEbshell6.2 2>sql.dbg

In sql.dbg, this produces the results of both options 010000 and 0200.

TT_SQL_TRACE=040

Shows all queries (query text) which are evaluated. For example:

Evaluated Query (QID : 4)select ttadv450.vers, ttadv450.rele, ttadv450.cust,

ttadv450.expi, ttadv450.messwhere ttadv450._index1 = {:clan, :1, :2}

TT_SQL_TRACE=02000

Shows calls of internal SQL functions, including their arguments. For example:

[SqlParse: before parse] SqlId : 200db008 - QID : 4 - Status : 0Trans 1 Mode 0 Query:select ttadv450.vers, ttadv450.rele, ttadv450.cust, ttadv450.expi,

ttadv450.messwhere ttadv450._index1 = {:clan, :1, :2}

[SqlParse: after parse (e = 0)]SqlId : 200db008 - QID : 4 - Status : 2

[SqlWhereBind for clan] SqlId : 200db008 - QID : 4 - Status : 2Value(str): ’2’

[SqlWhereBind for 1] SqlId : 200db008 - QID : 4 - Status : 2Value(str): ’tt’

[SqlWhereBind for 2] SqlId : 200db008 - QID : 4 - Status : 2Value(str): ’gfdmnucal ’

Page 138: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-34

[SqlExec (CompNr 000)] SqlId : 200db008 - QID : 4 - Status : 2[SqlFetch] SqlId : 200db008 - QID : 4 - Status : 3[SqlFetch returns 0 errno 0 msg ]

SqlId : 200db008 - QID : 4 - Status : 4’6.1 ’ ’b ’ ’ ’ 2 ’Calendar

’[SqlBreak] SqlId : 200db008 - QID : 4 - Status : 4

The line following the message "SqlFetch returns .." shows the result of thefetch. The order of the fields is not always the order as mentioned in theSELECT clause.

TT_SQL_TRACE=0200

Shows query execution times. For example:

================================================Fetch times of Query (QID : 12) in SqlBreak :select ttdsk360.*

where(ttdsk360.user = :logname$ or ttdsk360.user = :1)

order by ttdsk360.user desc, ttdsk360.cpac desc,ttdsk360.rsst desc, ttdsk360.rsid desc

------------------------------------------------Nr Rows Fetched : 39Fetch Time for 1st Row : 0.060 secMax Fetch Time : 0.060 secAverage Fetch Time : 0.000 secAverage Fetch Time (except Max) : 0.000 sec================================================

A value 0.000 means that the time to fetch was too small to be measured. Thiscan happen when the result is already available in the client. In that case, fetchingis (globally seen) only copying from one memory location to another.

TT_SQL_TRACE=04000

Show the query evaluation tree. There is different output for client and server.The client shows how the query is distributed over different databases (normallythere is one database). The server shows how the query is evaluated. This can bedifferent for different databases. The example shows the evaluation in a non-SQLdatabase driver. In the examples, the same query is used as in the example ofTT_SQL_TRACE=040.

Client Side:Expression Tree (QID : 4):[11] flag 011 cost 0 next_eval 12 next 12cost 0 0 nr 0Operand1:

Database View Id 0 - Drivers:

WARNING:

Page 139: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-35

Database View - Tables:ttadv450 (dd: ttadv450) flag 1000 cost 0

Database View - Expression:[10] flag 031 cost 0 next_eval -1 next -1

cost 0 0 nr 0Operand1: CombColumn: ttadv450._index1

Combined {(1) ttadv450.clan(2) ttadv450.cpac(3) ttadv450.cmes(4) ttadv450.vers(5) ttadv450.rele(6) ttadv450.cust

}Operator: =Operand2: Combined {

(1) Host var: ’clan’ = ’2’(2) Host var: ’1’ = ’tt’(3) Host var: ’2’ = ’gfdmnucal ’

}Database View - Host Variables:

Host var: ’clan’ = ’2’Host var: ’1’ = ’tt’Host var: ’2’ = ’gfdmnucal ’

Database View - Output Columns:ttadv450.versttadv450.relettadv450.custttadv450.expittadv450.mess

Database View - RDS Out:Dump Info on RDS: MalId 15 - Size 143 164 - Flag 2[ 1] type 6 dept 1 size 4 offset 0[ 2] type 6 dept 1 size 2 offset 4[ 3] type 6 dept 1 size 4 offset 6[ 4] type 1 dept 1 size 1 offset 10[ 5] type 7 dept 1 size 132 offset 11

Operator: DBViewOperand2: --

AND (011)[12] flag 011 cost 0 next_eval -1 next -1

[1] End of Query

-End of Tree --

Server:Generated Query Execution Tree:Sql id 6 company 000 sid 1 flag 1 (QID : 4)Output Columns (total 5)[ 0] vers idx 0 type 6 size 4 depth 1

Page 140: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-36

[ 1] rele idx 1 type 6 size 2 depth 1[ 2] cust idx 2 type 6 size 4 depth 1[ 3] expi idx 3 type 1 size 1 depth 1[ 4] mess idx 4 type 7 size 132 depth 1

Rds Out:Dump Info on RDS: MalId 6 - Size 143 164 - Flag 2[ 1] type 6 dept 1 size 4 offset 0[ 2] type 6 dept 1 size 2 offset 4[ 3] type 6 dept 1 size 4 offset 6[ 4] type 1 dept 1 size 1 offset 10[ 5] type 7 dept 1 size 132 offset 11All tablesttadv450 flag 12

Query 200a207c flag 00Tablesttadv450 (a) dep 1 flag 012

ttadv450(a).cmesttadv450(a).cpacttadv450(a).clanttadv450(a).messttadv450(a).expittadv450(a).custttadv450(a).relettadv450(a).vers

Output Columns (total 5)ttadv450.vers idx 0 type 6 size 4 depth 1ttadv450.rele idx 1 type 6 size 2 depth 1ttadv450.cust idx 2 type 6 size 4 depth 1ttadv450.expi idx 3 type 1 size 1 depth 1ttadv450.mess idx 4 type 7 size 132 depth 1

View bindvers : type 6 size 4 flag 9rele : type 6 size 2 flag 9cust : type 6 size 4 flag 9expi : type 1 size 1 flag 9mess : type 6 size 132 flag 9

View expression[15] flag 011 cost 0 next_eval 17 next 17Table View on ’ttadv450’Expression:

[14] flag 011 cost 3 next_eval 16 next 16SrchOper for ttadv450 compnr 000 index 1 (mode 0)Field clan:

Equal: [=] Bind (Col clan) Value: ’2’Field cpac:

Equal: [=] Bind (Col cpac) Value: ’tt’Field cmes:

Equal: [=] Bind (Col cmes) Value: ’gfdmnucal ’Field vers:Field rele:

Page 141: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-37

Field cust:AND (011)[16] flag 011 cost 0 next_eval -1 next -1

cost 0 0 nr 0Operand1:Operator: QpsPermOperOperand2: ’-1’

AND (011)[17] flag 011 cost 0 next_eval -1 next -1

[1] End of Query

There are a lot of numbers/state values in this tree. Most of them are for internaluse only.

TT_SQL_TRACE=020000

Shows all tables for which FullTableScan is performed. This can depend onwhich database is used. For example:

FullTableScan for table ttdsk355 (QID : 2)

The QID refers to the query. This can be found in the client trace file.

TT_SQL_TRACE=010000

Shows Query Evaluation Plan (QEP). This also depends on which database isused. For example:

Query Evaluation Plan (QID : 30)------------------------------------------------Table tccom000 (alias: a): IndexSearch with condition(s):SrchOper for tccom000 compnr 000 index 1 (mode 0)Field ncmp:

Equal: [=] Bind (Col ncmp) Value: ’812’Forced Order: Ascending (index 1)Table tcmcs046 (alias: b): IndexSearch with condition(s):SrchOper for tcmcs046 compnr 000 index 1 (mode 6)Field clan:

Equal: [REF (clear)] Index Col key 1 mode 5 equal 0tccom000(a).clanTable tcmcs002 (alias: c): IndexSearch with condition(s):SrchOper for tcmcs002 compnr 000 index 1 (mode 6)Field ccur:

Equal: [REF (clear)] Index Col key 1 mode 5 equal 0tccom000(a).ccur================================================

Page 142: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-38

The query which belongs to this QEP is shown in the client log file(TT_SQL_TRACE=040) as follows:

Evaluated Query (QID : 30)Select tccom000.*, tcmcs002.*, tcmcs046.*

From tccom000, tcmcs002, tcmcs046Where tccom000.ncmp = :company.nrAnd tccom000.ccur refers to tcmcs002 unref clearAnd tccom000.clan refers to tcmcs046 unref clearorder by tccom000.ncmp

From the QEP, the following information can be retrieved:

1 There are three tables: tccom000 (alias: a), tcmcs046 (alias: b), tcmcs002(alias: c). The alias name is used in case of SQL databases. This alias name isonly one or two characters in order to keep the SQL statement for the SQLdatabase as short as possible.

2 The order of evaluation of the tables is from top-to-bottom in the QEP, sofirst tccom000, then tcmcs046, then tcmcs002.

3 Searching in tccom000 is done on the primary index (index 1). The field’ncmp’ has value ’812’ and has been specified by some ’=’ operation. In thequery above, this comes from the line containing"where tccom000.ncmp = :company.nr".

4 The query has an ORDER BY part. The ORDER BY can be eliminated byreading tccom000 on index 1, in ascending order. This is denoted by: "ForcedOrder: Ascending (index 1)".

5 Next table to be read is tcmcs046. Here also index 1 is used for reading. Thekey is specified by some "unref clear" operation. The field ’clan’ is filled tosearch in the table. This field specifies the whole primary key (index 1).

6 Last evaluated table is tcmcs002, in the same way as tcmcs046. Here, thefield ’ccur’ is used.

Page 143: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-39

Error handlingThere are two broad categories of errors. Errors generated by the operatingsystem (numbers 1 - 99) and errors generated by the database system (numbers100 - 900). See Chapter 10, Errors.

To keep the messages to be sent over the network to a minimum, databaseactions and messages must be buffered as much as possible. Buffering updatesmeans that as few updates as possible return error codes. These, after all, cause arollback and a return to a retry point. It is therefore possible to allocate flags toupdates indicating the action to be taken by the system when a database actionfails. The database server will then no longer execute a rollback, but a follow-upaction.

Fatal and non-fatal errors

There are fatal and non-fatal errors. Fatal errors terminate the session. Non-fatalerrors are those that are temporary (for example, elocked), or that are caused by amulti-user situation (for example, a record is deleted by two processes, oneprocess receiving enorec). Non-fatal errors cause the program to go back to thelast retry point. If this is missing, the session is terminated. Fatal errors are errorscaused by:

n Errors in the (logical) database (for example, enotable, eddcorrupt, enoserver)

n Errors in the underlying (R)DBMS (for example, ebadkey)

n Program errors (for example, enotinrange)

The following error codes result in a return to the retry point:

elocked (107) record is lockedeflocked (113) file (table) is lockedemlocked (210) record in mirroring is lockedereflocked (601) reference record is locked

edupl (100) duplicate recordenorec (111) record not present

erowchanged (201) record modified since last readeabort (850) rollback in (R)DBMS

Page 144: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-40

The eflag

For a number of errors it is possible to indicate which action the system mustcarry out when the error occurs. You can add these to a database action with the<eflag>. For example:

db.insert(table, DB.RETRY [, eflag])db.update(table, DB.RETRY [, eflag])db.delete(table, DB.RETRY [, eflag])

The following flags are available for eflag:

db.exit.on.norec stop session if no record was found

db.skip.norec skip update/delete action if no recordwas found

db.exit.on.dupl stop session if duplicates occur

db.skip.dupl skip update/insert action if duplicatesoccur

db.exit.on.rowchanged stop session if record has been changedafter delayed lock

db.skip.rowchanged skip action if record has been changedafter delayed lock

db.return.error * return error code

db.return.norec * return error code if no record was found

db.return.dupl * return error code if duplicates occur

db.return.ref.exists * return error code if reference exists

db.return.ref.not.exists * return error code if reference does notexist

db.return.rowchanged * return error code if record has beenchanged after delayed lock

* These flags store the contents of the buffer to the database if an error occurs.The program does not return to the retry point.

Note that you can combine flags by using the ’+’ sign.

Page 145: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-41

Exampletable ttiitm001

db.retry.point()SELECT tiitm001.*FROM tiitm001 FOR UPDATEWHERE tiitm001.item between :item.f and :item.t

SELECTDO......db.insert(ttiitm001, DB.RETRY, db.skip.dupl)

ENDSELECT

In this case, the flag ’db.skip.dupl’ causes the system neither to go back to theretry point nor return an error code when adding an already existing record.

Hints for using SQL

1 In the WHERE clause:

− use as few conditions as possible:− use as many conditions with indexes as possible− use as many conditions with combined fields as possible− use BETWEEN/INRANGE when an upper and lower boundary are

specified for a field.

2 Use REFERS TO if references have been defined in the data dictionary.

3 Use as few overlapping OR conditions as possible. For the following:

cpac&cmod >= ’ttadv’ (only if there is no index to cpac&cmod)

do not use the following construction:

WHERE ttadv200.cpac > ’tt’ ORttadv200.cpac >= ’tt’ AND ttadv200.cmod >= ’adv’

instead use the following construction:

WHERE ttadv200.cpac > ’tt’ ORttadv200.cpac = ’tt’ AND ttadv200.cmod >= ’adv’

Use BETWEEN or INRANGE if there is an index to cpac&cmod. Forexample:

WHERE ttadv200._index1 BETWEEN {’tt’, ’adv’} and { }

4 Only select fields of tables necessary in the flow of the program.

Page 146: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-42

5 It is not necessary to bind external variables and database fields used in thequery as substitution variables. In embedded SQL local variables are boundautomatically.

6 The program executes the query the first time the function sql.fetch() iscalled. If reading in the entire set is unnecessary (so no order by, group by,and so on), the program only physically retrieves records at each sql.fetch().This avoids an entire set being retrieved when only part of it is used. Whenthe set is no longer necessary call sql.break() to clear the remaining records.

7 Use ORDER BY to ensure that the records are retrieved in the correctsequence. If an index can be used for the ORDER BY, no sort action willtake place beforehand.

8 The program will execute a Full Table Scan (FTS) if the operators NOTINRANGE, IN, LIKE are used or if no index (or part of an index) is used.This means that the system checks beforehand whether all records in the tablemeet the conditions of the query. This precludes optimization. If only the firstpart of an index (combined or normal field) is used, the system uses thatindex to search the table.

When GROUP BY is used, the system first determines the entire set(prepared set), before producing the first record. The same thing happens ifthe operator is preceded by an expression –for example, WHERE<table.field1> & <table.field2> = "...........". Note that the varioussubexpressions separated by AND or OR cannot be combined foroptimization.

9 It is possible to have the program carry out commits at certain points in theselect loop. If retry points are included, use of ORDER BY is required toensure that the sequence after return to the retry point is identical to the oneused the first time. See also the practical examples.

10 If a transaction adds or processes records, it depends on the database if thesame transaction can also process new records without a select being carriedout again. To ensure that new records are processed in any case, a commitand a new select are required. To ensure that new records are not processed,define the set at the point of the select (prepared set).

11 When using transactions, the first priority should be that the actions withinthe transaction constitute a logical unit. For reasons of performance, update,insert, and delete actions can be combined up to a number of 256 (this is anaverage, not a limit) per transaction. For example, programs processingorders should execute one commit.transaction() for each order.

Page 147: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-43

12 It may be necessary to know how far the program had advanced before itmoved back to the retry point. If the key consists of more than one field, it isprobably possible to have the program execute a commit.transaction() whena particular key field changes. If a key consists of order number and orderline, for instance, a commit by order number would be preferable to a commitby order line. Care should be taken in programs that print and process data inone run. An abort transaction restores the database but not the output to theprinter. In such cases a commit must be executed for each print line toprevent lines being printed twice.

For example:

save.orno = startselect for update order line.orno order line.ponofrom order linewhere order line.orno >= :save.ornoselectdo

if ( save.orno <> order line.orno ) thencommit.transaction()save.orno = order line.orno

endifupdate actions()

endselect commit.transaction()

13 A db.retry.point() must be included in each update program.

Hints for using db.retry.pointFor programs of type 1, 2 or 3, this is generally the retry.point of the standardprogram which has a retry just after ’before choice’ of update.db and in the readsection where also the references are read.

To have clearly structured sources, never use more than one leveldb.retry.point(). Only one above the first level of select. Use retry in thefollowing situations:

Situation for Select Commit perfetch

Commit overmultiple fetch

db.update/db.insert/db.delete 1 2Collecting 3 3Combination 4 5

A skip back to a retry point can be indicated by a problem in:

n db.update(), db.delete() or db.insert() with argument db.retry

n commit.transaction()

Page 148: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-44

Situation 1: Only update actions, commit per fetch

The function ’with retry’ can be used here. For example:

db.retry.point()select tisfc001.*from tisfc001 for updatewhere tisfc001.pdno inrange :pdno.f and :pdno.torder by tisfc001._index1 with retryselectdotisfc001.proc = tcyesno.yesdb.update(ttisfc001,db.retry)commit.transaction()

endselect

In this case REPEAT LAST ROW is not used, because when retry is done, thevalue which was present at the stage of commit.transaction() has certainly beensaved.

Situation 2: Only update actions, commits over fetches

In this case we can also use the ’with retry’ option. For example:(commit perorder and not per fetch !):

save.pdno = 0db.retry.point()select ticst001.*from ticst001 for updatewhere ticst001.pdno inrange :pdno.f and :pdno.torder by ticst001._index1 with retry repeat last rowselectdoif ticst001.pdno <> save.pdno then

if save.pdno <> 0 thencommit.transaction()

endifsave.pdno = ticst001.pdno

endifticst001.proc = tcyesno.yesdb.update(ticst001,db.retry)

selecteoscommit.transaction()

endselect

Both db.update() and commit.transaction() can result in a retry. So selecteos isused. Notice that REPEAT LAST ROW is used because the present value at thetime of doing the save is already the value of the next order.

Page 149: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-45

Situation 3: only print / collect actions (no commit)

There is no transaction or dependency between records / fetches. For example:

total.quant = 0select ticst001.*from ticst001where ticst001.pdno inrange :pdno.f and :pdno.torder by ticst001._index1selectdo

total.quant = total.quant + ticst001.quanprint.row(1)

endselect

Situation 4: Update actions plus print/collect withcommit per fetch

For example, update of print status plus print and collect:

total.quant = 0db.retry.point()select ticst001.*from ticst001 for updatewhere ticst001.pdno inrange :pdno.f and :pdno.torder by ticst001._index1 with retryselectdo

ticst001.proc = tcyesno.yesdb.update(ticst001,db.retry)commit.transaction()total.quant = total.quant + ticst001.quanprint.row()

endselect

Notice that this works only when the db.update() and commit.transaction() aredone before the print and the collect statement. An alternative to this solution isdescribed in situation 5.

Situation 5: Update actions plus print/collect withcommit over fetches

For example, update of print status plus print and collect per order:

save.pdno = 0save.pono = 0total.select.quan = 0db.retry.point()total.order.quan = 0select ticst001.*from ticst001 for updatewhere ticst001.pdno inrange :pdno.f and :pdno.t

Page 150: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Database handling

Programming features

5-46

order by ticst001._index1 with retry repeat last rowselectdoif ticst001.pdno <> save.pdno then

if save.pdno <> 0 thentotal.order.quan = 0commit.transaction()

endifsave.pdno = ticst001.pdno

endifif ticst001.pdno > lsp.pdno or

(ticst001.pdno = lsp.pdno andticst001.pono > lsp.pono ) then

print.row()total.select.quan = total.select.quan + ticst001.quanlsp.pdno = ticst001.pdnolsp.pono = ticst001.pono

endiftotal.order.quan = total.order.quan + ticst001.quanticst001.proc = tcyesno.yesdb.update(ticst001,db.retry)

selecteoscommit.transaction()

endselect

lsp stands for last processed. pdno and pono are together the index of cst001. The’lsp.’ variables should always be used for this kind of saving within selects. Thesevariables save which record has already been printed/collected. Thetotal.order.quan can always be added because setting to zero is done for eachretry again.

Page 151: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

6-1

OverviewIn BAAN applications, the standard program (STP) provides much of the defaultfunctionality for a session. In previous versions of the software, changes oradditions to the default functionality for a session were programmed in a singlescript that was associated with the session. Both user interface actions anddatabase actions were programmed in this script.

In BaanERP, user interface actions and database actions have been separated.The Data Access Layer (DAL) now handles database interaction. Programmerscreate a user interface (UI) script to change the default behavior of a session.They create a DAL script to program all the logical integrity rules for a particulartable. So the DAL ensures the logical integrity of the database. As in previousversions of the software, the database server ensures the referential integrity ofthe database.

The DAL script for a particular table has the same name as that table. It isimplemented as a DLL that can be accessed by user interface scripts (via thestandard program), by other DALs, and by external programs (via the CommonData Access Server (CDAS). The following diagram illustrates the overallrelationship of these components.

6 Data Access Layer (DAL)

Page 152: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-2

Database integrity checks

The following are examples of some logical integrity rules that could beprogrammed in a DAL script:

n When customers have reached their credit limit, they cannot order furtheritems.

n If the invoice for an order has been printed, the order cannot be changed.

n If the current VRC of a user is not equal to the package VRC of the programscript, the script cannot be compiled.

Programming database integrity checks in a separate DAL script has two mainadvantages:

n Code reuse: The integrity rules do not have to be replicated in each sessionthat uses a particular table.

n External access: External applications can access the database via the CDASand the DAL.

For an overview of the interaction between the user interface, the standardprogram, and the DAL, see “DAL, UI, and STP interaction” later in this chapter.

Business methods

In addition to performing data integrity checks, the DAL provides businessmethods for handling non-interactive database modifications such as printingsales orders or posting all orders to history.

A business method is a function that performs a task that involves manipulatingand/or checking one or more tables in the database. The function is programmedin a DAL script and can be called directly from a UI script. It must beprogrammed in the DAL script of the most relevant table.

Users can activate a business method with a single command. There is then nofurther user interaction. The UI script calls the relevant function in the DALscript. The function performs all operations to complete the required task. Theuser must wait until the business method finishes before continuing with othertasks. However, if a progress window is provided, the user can cancel thebusiness method by clicking on the Cancel button.

The UI script starts a business method by calling thedal.start.business.method() function.

Page 153: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-3

DAL terminologyClass A description of a group of objects with similar properties,

common behavior, common relationships, and commonsemantics. A DAL class corresponds to a BAAN tabledefinition.

Object An instance of a class. It consists of data and the methods(code) to manipulate the data. The data of a DAL objectcorresponds to a record in a BAAN table.

Object set All objects of a class, as stored in the database. A DALobject set corresponds to a BAAN table.

Property An attribute of an object. A DAL property corresponds to afield in a record in a BAAN table.

Method The implementation of an operation for a particular class. Itprovides a means of retrieving and manipulating data(properties) in objects. Method is another name for anoperation or function.

Hook A logic integrity rule. Hooks are implemented in the DAL asfunctions.

UI, DAL, and STP interaction

Overview

A DAL script contains all the logic integrity rules for a particular object set.These rules are referred to as hooks and they can be programmed for everypossible manipulation of an object in the object set. For each session with a maintable, the standard program ensures that the integrity rules for the table arechecked each time an update, delete, insert, or read operation is performed on anobject of the table.

If there is no DAL script for the particular object set being accessed, no logicintegrity checks are performed (unless they are programmed in the UI scriptitself).

A DAL script can contain hooks that prevent access to the database and hooksthat prevent data being passed back to the user interface. The former are executedbefore the database action. The latter are performed after the database action.

Page 154: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-4

Example

If a user changes the address of a customer on a form, the standard programchanges the address for that customer in the database via the DAL. If you wantcertain restrictions to apply to the update action, you can program a propertyhook in the DAL of the session’s main table to impose these restrictions. Forexample:

when the address changes:if changed into something valid then

acceptelse

rejectendif

UI function calls

The UI script can use either the db.* functions or the DAL Data Access Methods(DAM) to manipulate the database. The db.* functions are direct database calls.They do not use the DAL. In this case, any logic integrity checks required mustbe programmed in the UI script itself. This means that they cannot be reused byother sessions. In preference, use the DAL Data Access Methods. These accessthe database via the DAL, so all necessary checks are automatically performed.

Function flow

When the DAL is used to manipulate the database, the main steps involved are asfollows:

1 The user issues a command through the user interface to access a record inthe database.

2 The standard program loads the appropriate DAL and calls the hooks in theDAL to check the integrity rules for the object.

3 If the particular database action is permitted, the standard program issues theappropriate database call.

4 After the database has been updated, the DAL can perform further checks todetermine whether or not data is passed back to the user interface.

5 The standard program passes data back to the user interface (provided that theintegrity rules permit this).

Page 155: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-5

The following diagram illustrates this flow:

One-way interaction

Note that because the DAL can be used in situations where there is no userinterface, the DAL cannot call functions in the UI.

DAL hooksA hook is a function, with a predefined name, that the DAL programmerprograms in a DAL script. The function is used to program logic integrity rulesfor database access. The DAL script is compiled into a DLL.

When a user issues a command to access the database, the standard programloads the DAL DLL for the object being accessed and calls the hooks to performthe integrity checks. Provided that a DAL script exists for an object set beingaccessed, the standard program always ensures that the hooks in the DAL arecalled at the appropriate times.

A DAL script can contain two types of hooks:

n Property hooksn Object hooks

Page 156: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-6

Property hooksProperty hooks are hooks that relate to a specific property (that is, a table field).

Property hooks replace the check.input event sections for fields of the maintable. If there is a DAL for an object set, the property hooks are called to performthe necessary field checks. Any check.input sections in the UI script are ignored.So, if a UI script contains check.input sections for fields of the main table, youmust replace these by property hooks in the DAL. In the UI script, check.inputsections are retained for non-database form fields. Such sections are executedeven if a DAL exists.

Currently there is only one property hook: fieldname.check(). The standardprogram calls this hook when inserting or updating an object.

fieldname.check()

Syntax

function extern long ppmmmvss.bbbb.check( long has_changed[, long element] )

Description

Use this hook to program logical integrity rules for a specified field. The functionname is ppmmmvss.bbbb.check(), where pp is the package code, mmm is themodule code, vss is the table number, and bbbb is the field name.

Arguments

has_changed This indicates whether the value of the field has changed. It isset by the standard program and can be tested in the hook.Possible values are:

0 not changedDAL_NEW change caused by inserting a new objectDAL_UPDATE change caused by updating an existing object

element This is set for array fields only. It indicates the index of thearray element that must be checked.

Return values

This hook returns 0 if the value of the field is accepted. It returns a negativevalue (DALHOOKERROR) if the value is not accepted.

Page 157: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-7

See also

“Property methods” later in this chapter

Example

A property hook programmed in DLL tdsls040:

function extern long tdsls040.oqua.check(long has_changed){

if tdsls040.stat = tdsls.stat.invoiced and has_changed then

dal.set.error.message("tdsls44041")| Order is already invoiced, cannot change| quantity

return(DALHOOKERROR)endif...return(0)

}

Object hooksObject hooks are used for checking the logic integrity of objects (that is, recordsin a table).

Object hooks replace the before.read, after.read, before.write, after.write,before.rewrite, after.rewrite, before.delete, and after.delete subsections in themain.table.io section of the UI script.

If there is a DAL for an object set, the standard program calls the object hooks inthe DAL every time that a DAM is executed for that object set. The object hooksperform the necessary checks to ensure the logical integrity of the objects beingaccessed. Any of the above mentioned sections in the UI script are ignored. So, ifa UI script contains any of these sections, you must replace these by object hooksin the DAL.

Available object hooks

Open object set hook

before.open.object.set()

Get object hooks

before.get.object()after.get.object()

Destroy object hooks

Page 158: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-8

before.destroy.object()after.destroy.object

Save object hooks

before.save.object()after.save.object()

After commit transaction hook

after.commit.transaction()

Method is allowed hook

method.is.allowed()

Return values and errors

Only the before hooks can prevent a database action. The after.get.object() hookcan prevent a record from being sent to the UI. Both these types of hook blockcontinuation of the calling method if the return value is set toDALHOOKERROR (a negative constant). If the return value is zero, the methodcontinues.

The following table indicates how return values and error messages are handled.The STP column indicates how the standard program reacts if a hook returns aDALHOOKERROR. The Messages column indicates what happens to messageswhen an error occurs. The Warnings column indicates what happens to messageswhen no error is returned. The DAM column indicates how Data AccessMethods react when an error occurs.

Hook STP Messages Warnings DAM

before.open.object.set() exit display display return

before.get.object() ignore ignore ignore return

after.get.object() skip ignore ignore return

before.destroy.object() return display display return

after.destroy.object() ignore ignore ignore return

before.save.object() return display display return

after.save.object() ignore ignore ignore return

Page 159: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-9

before.open.object.set()

Syntax

function extern long before.open.object.set()

Description

Use this to program checks that determine whether opening of the object set ispermitted.

If this hook exists, it is executed after the before.program event section for themain table. It is also called for every first access to a DAL by business methodsor Data Access Methods.

You can also use this section to program query extensions.

Return values

The hook returns 0 if opening of the object set is permitted. If the hook returns anegative value (DALHOOKERROR), the session is aborted (if the hook is calledby the STP) or the method returns an error (if the hook is called by a DAM or abusiness method).

before.get.object()

Syntax

function extern long before.get.object( long dir )

Description

Use this to program checks that determine whether reading a record is permitted.The dir argument is set by the STP or CDAS and specifies the object being read.The possible values are:

DAL_GET_FIRST DAL_GET_NEXT DAL_GET_PREVDAL_GET_LAST DAL_GET_FIND DAL_GET_CURR

This object hook replaces the before.read subsection of the main.table.io eventsection in a UI script. If there is a DAL for an object set, this hook is called toperform the necessary checks. Any before.read sections in the UI script areignored. So, if a UI script contains before.read sections for the main table, youmust replace these by before.get.object() hooks in the DAL.

Page 160: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-10

Return value

The hook returns 0 if reading of the record is permitted. Negative return values(DALHOOKERROR) are ignored by the calling program.

Example

function extern long before.get.object( long dir ){

return(0)}

after.get.object()

Syntax

function extern long after.get.object( long dir )

Description

Use this to program checks that determine whether reading a record is permitted.The checks are performed after the record has been retrieved from the database.The dir argument is set by the STP or CDAS and specifies the object being read.The possible values are:

DAL_GET_FIRST DAL_GET_NEXT DAL_GET_PREVDAL_GET_LAST DAL_GET_FIND DAL_GET_CURR

This object hook replaces the after.read subsection of the main.table.io eventsection in a UI script. If there is a DAL for an object set, this hook is called toperform the necessary checks. Any after.read sections in the UI script areignored. So, if a UI script contains after.read sections for the main table, youmust replace these by after.get.object() hooks in the DAL.

Notes

It is preferable to use a query extension in the before.program section of the UIscript instead of this hook. So, only use this hook if a query extension is notpossible.

The standard program ignores messages set in this hook.

Return value

The hook returns 0 if reading of the record is permitted. If the hook returns anegative value (DALHOOKERROR), the object is skipped.

Page 161: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-11

Example

| after.get.object hook

function extern long after.get.object(long dir){

on case dircase DAL_GET_FIRST:

…break

case DAL_GET_NEXT:…break

case DAL_GET_PREV:…break

case DAL_GET_LAST:…break

case DAL_GET_FIND:…break

case DAL_GET_CURR:…break

default:…break

endcaseif ttadv100.cpac = "tt"

return(DALHOOKERROR)| Error messages from after.get.object are| ignored by the standard program

endifreturn(0)

}

| Query extension with the same result| Use this in preference

before.program:query.extend.where("ttadv100.cpac <> ""tt"" ")

Page 162: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-12

before.destroy.object()

Syntax

function extern long before.destroy.object()

Description

Use this to program checks that determine whether deleting a record is permitted.

This object hook replaces the before.delete subsection of the main.table.ioevent section in a UI script. If there is a DAL for an object set, this hook is calledto perform the necessary checks. Any before.delete sections in the UI script areignored. So, if a UI script contains before.delete sections for the main table, youmust replace these by before.destroy.object() hooks in the DAL.

Return value

The hook returns 0 if deleting the record is permitted. If the hook returns anegative value (DALHOOKERROR), the transaction is aborted.

Example

function extern long before.destroy.object(){

if tdsls040.stat = tdsls.stat.invoiced thendal.set.error.message("tdsls44041")

| You cannot delete an invoiced transactionreturn(DALHOOKERROR)

endif...return(0)

}

after.destroy.object()

Syntax

function extern long after.destroy.object()

Description

Use this to update referenced tables after the current object has been deleted.

This object hook replaces the after.delete subsection of the main.table.io eventsection in a UI script. If there is a DAL for an object set, this hook is called toperform the necessary actions. Any after.delete sections in the UI script are

Page 163: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-13

ignored. So, if a UI script contains after.delete sections for the main table, youmust replace these by after.destroy.object() hooks in the DAL.

Return value

The hook returns 0 if successful. Negative return values (DALHOOKERROR)are ignored by the calling program.

Example

function extern long after.destroy.object{

return(0)}

before.save.object()

Syntax

function extern long before.save.object( mode )

Description

Use this to program checks that determine whether saving a record is permitted.The mode argument is set by the standard program. The possible values are:

DAL_NEW indicates a new recordDAL_UPDATE indicates a record being updated

This object hook replaces the before.write and before.rewrite subsections of themain.table.io event section in a UI script. If there is a DAL for an object set, thishook is called to perform the necessary checks. Any before.write andbefore.rewrite sections in the UI script are ignored. So, if a UI script containsbefore.write and before.rewrite sections for the main table, you must replacethese by before.save.object() hooks in the DAL.

Return value

The hook returns 0 if saving the record is permitted. If the hook returns anegative value (DALHOOKERROR), the transaction should be canceled.

If the hook was called directly by the standard program, the transaction iscanceled automatically. If the hook was not called by the standard program, thetransaction must be canceled by calling abort.transaction() or abort.io(),typically in the UI script.

Page 164: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-14

Example

function extern long before.save.object(long mode){

if mode = DAL_NEW then| this is code from before.write subsection

else| this is code from before.rewrite subsection

endifreturn(0)

}

after.save.object()

Syntax

function extern long after.save.object( mode )

Description

Use this to update referenced tables after a record has been added or updated.The mode argument is set by the standard program. The possible values are:

DAL_NEW indicates a new recordDAL_UPDATE indicates a record being updated

This object hook replaces the after.write and after.rewrite subsections of themain.table.io event section in a UI script. If there is a DAL for an object set, thishook is called to perform the necessary actions. Any after.write andbefore.rewrite sections in the UI script are ignored. So, if a UI script containsafter.write and after.rewrite sections for the main table, you must replace theseby after.save.object() hooks in the DAL.

Return values

The hook returns 0 if successful. Negative return values (DALHOOKERROR)are ignored by the calling program.

Example

function extern long after.save.object( long mode ){

if mode = DAL_NEW then| this is code from after.write subsection

else| this is code from after.rewrite subsection

endif}

Page 165: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-15

after.commit.transaction()

Syntax

function extern void after.commit.transaction()

Description

Use this to update other database tables after an update of the current table hasbeen committed to the database.

This object hook replaces the after.update.db.commit event section in a UIscript. If there is a DAL for an object set, this hook is called to perform therequired actions. Any after.update.db.commit sections in the UI script areignored. So, if a UI script contains a after.update.db.commit section for themain table, you must replace it by an after.commit.transaction() hooks in theDAL.

This hook is called only by the STP and CDAS. It is not called by Data AccessMethods or commit.transaction().

method.is.allowed()

Syntax

function extern long method.is.allowed( long method )

Description

This is a special hook for handling centralized authorizations. Use it to performchecks that determine whether certain Data Access Methods are permitted for anobject. The method argument specifies the method to check.

The hook can be called from the UI script, but it is also called from the standardprogram to check if certain operations are allowed.

Return values

TRUE the method is permittedFALSE the method is not permitted

Page 166: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-16

Example

function extern long method.is.allowed( long meth ){

on case methcase DAL_NEW:

if .... thendal.set.error.message("error message")return(false)

endifbreak

case DAL_UPDATE:...break

case DAL_DESTROY:...break

endcasereturn(true)

}

Data Access Methods (DAM)You use Data Access Methods (DAM) to update the database via the DAL. In aUI script, you can use the methods to update any object set. In a DAL script, youcan use the methods to update objects in an object set other than the one withwhich the script itself is associated.

There are three Data Access Methods:

n dal.update()

n dal.new()

n dal.destroy()

These functions encapsulate the db.update(), db.insert() and db.delete()functions respectively, together with the DAL hooks of the object set.

Page 167: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-17

Property methods

Setting properties

In order to notify the DAL about a change in the value of a property, you mustuse the dal.set.property() function to change the value. Using this functionensures that the relevant property hooks are executed when the value is changed.If you use an assignment or the db.* functions to change a property value, theDAL is not notified of the change. Consequently, the property checks in the DALare not executed.

You can call this function from both UI and DAL scripts.

Retrieving properties

You can retrieve the value of the has_changed flag (see “Property hooks” earlierin this chapter) for any property by calling dal.get.property.flag(). The propertymust have been changed by the dal.set.property() function.

You can call this function from both UI and DAL scripts.

Query extensionsQuery extensions define conditions that the standard program adds to theSELECT, FROM, and/or WHERE clauses of a database query in order tominimize the number of fields read from the main table and in order to retrieveall reference table fields required by the UI and/or DAL scripts.

BaanERP provides the following functions for constructing query extensions:

n query.extend.select()n query.extend.select.in.zoom()n query.extend.from()n query.extend.from.in.zoom()n query.extend.where()n query.extend.where.in.zoom()

You can program query extensions in the UI script and/or the DAL script. In theUI script, you program the extensions in the before.program or before.zoomsections. In the DAL script, you program the extensions in thebefore.open.object.set() hook.

For a full discussion of query extensions, see “SQL Query extensions” inU7167A US BaanERP Tools: Functions reference.

Page 168: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-18

Communication with STP and CDASBaanERP provides the following functions to enable the standard program andexternal applications to retrieve and display DAL error messages:

n dal.count.error.messages()n dal.get.error.message()n dal.get.first.error.message()n dal.reset.error.messages()n dal.set.error.message()

You use dal.set.error.message() to specify a message to be displayed when theDAL returns an error (that is, a negative value). This function is called in theDAL script and not in the UI script.

UI scripts can call dal.get.first.error.message() to retrieve DAL messages.External applications use dal.get.error.message() to retrieve DAL messages.

The following example illustrates the use of these functions in a UI script:

db.retry.point()

nr.of.errors = dal.count.error.messages()if db.retry.hit() then

| Remove the error messages since last commitdal.reset.error.messages( nr.of.errors )

endif……commit.transaction()nr.of.errors = dal.count.error.messages()

…commit.transaction()while dal.get.error.message( message ) >= 0

report.message( message )

Transition issues (BAAN IV to BaanERP)

4GL event sections

This table lists the 4GL event sections that have been moved to the DAL inBaanERP. It also lists the DAL methods that replace these sections.

If a DAL script exists for a particular table, the standard program calls themethods in the DAL to perform the relevant integrity checks. Any corresponding4GL event sections in the UI script are ignored. If there is no DAL for the table,the 4GL event sections are executed.

Page 169: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-19

4GL event sections DAL methods

field.<x>:check.input:

function extern long <x>.check()

main.table.io:before.read:

function extern long before.get.object()

main.table.io:after.read:

function extern long after.get.object()

main.table.io:before.write:

function extern long before.save.object()

main.table.io:after.write:

function extern long after.save.object()

main.table.io:before.rewrite:

function extern long before.save.object()

main.table.io:after.rewrite:

function extern long after.save.object()

main.table.io:before.delete:

function extern long before.destroy.object()

main.table.io:after.delete:

function extern long after.destroy.object()

4GL functions

This table lists those 4GL UI functions that have DAL equivalents. If a DALexists for a particular table, it is preferable to use the DAL functions instead ofthe 4GL UI functions.

4GL function DAL functionon.main.table() with.object.set.do()on.old.occ() with.old.object.values.do()set.input.error() dal.set.error.message()

return(DALHOOKERROR)skip.io() dal.set.error.message()

return(DALHOOKERROR)

Page 170: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-20

abort.io() dal.set.error.message()return(DALHOOKERROR)

db.update() dal.update()db.delete() dal.destroy()db.insert() dal.new()

If a function is used only in the DAL, you should move it to the DAL. If afunction is used in both the DAL and the UI, you can move it to the DAL (the UIcan call functions in the DAL but not vice versa). Alternately, you can store thefunction in a separate DLL that is linked to both the UI and the DAL.

Session codes

The DAL does not recognize session codes (prog.name$) and so cannot evaluatethem. However, in the case where integrity checks must be session dependent, asolution is to evaluate properties instead of session codes. For example, youcould identify a field or a combination of fields whose value(s) uniquely identifythe session. Or you could add a property to the object set and give this property avalue that is unique to the session.

Predefined variables

The predefined variable previous.choice is not supported in the DAL, as theDAL does not recognize standard commands. Instead, the first argument in thebefore.save.object() and after.save.object() hooks indicates if an insert orupdate operation caused the save operation. Note that for the DAL, the copycommand is an insert operation.

The predefined variable before.update.check is not supported in the DAL. InBaanERP, field checks are executed both after field input and before the databaseoperation. The programmer cannot influence when these checks are performed.Note that in the CDAS, checking is programmed in the dal.set.property() hookand not in the dal.after.save.object() hook.

Questions

It is not possible to ask for user input during the execution of DAL hooks. Ifhooks contain conditions that depend on user input, set the condition before thehook is called. Alternately, handle the user input and check the conditions aftercompletion of the database operations.

Page 171: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-21

Messages

The DAL cannot display error messages directly. However, you can set an errormessage in the DAL with the dal.set.error.message() method. The DAL cannotify the calling process of an error by returning the value DALHOOKERROR.The process can then display the error message. Messages can be stacked beforethey are retrieved by the UI.

Non-table fields

Only table fields are checked in the DAL. Checks for non-database fields muststill be programmed in the UI script.

Include files

When writing a Data Access Layer, you must include bic_dal. To use progressindicators and Data Access Methods in your UI, you must include bic_dam.

Page 172: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Data Access Layer (DAL)

Programming features

6-22

Page 173: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

7-1

OverviewThe BAAN bshell provides the execution environment for BAAN applications.Whenever a user logs on to the BAAN system, a separate bshell process isactivated for that user. So, when multiple users log on to the same BAANsystem, or when the same user logs on multiple times, multiple bshell processesare activated on the execution platform.

The BAAN bshell provides a multitasking execution environment for BAANapplications. Each bshell can execute and schedule multiple parallel processes.So, it blocks individual processes only while they are waiting for user input, andnot while other processes are waiting for user input.

This section provides an overview of how processes and user interfaceinteraction are managed by the bshell.

The following diagram provides a schematic overview of the relationshipsbetween the scheduler, process queues, and the display server.

7 Multitasking and the GUI

Page 174: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-2

The bshell is a single-threaded process. The complete bshell blocks when adatabase action is performed by the database driver.

Bshell schedulerThe bshell scheduler is responsible for managing and scheduling processes. Itmaintains four process queues, as follows:

n running queuen blocking queuen sleeping queuen terminating queue

The scheduler keeps all processes in one or other of the above process queues,depending on their current state.

Running queue

The scheduler schedules processor time only for those processes in the runningqueue. It schedules each process in the running queue in turn, in order of priority.Each scheduled process receives a number of ticks, and the execution of eachinstruction costs the process a certain number of ticks. When the process hasused up all its ticks, the bshell schedules another process.

The scheduler always schedules the process with the highest priority.

When a process is started, it gets a default priority (this depends on its nicevalue). While it is in the running queue, the process’s priority is incremented eachtime that another process is scheduled. In this way, the process’s priorityincreases until it has the highest priority in the running queue. It is thenscheduled. When a process has been scheduled, its priority returns to its defaultvalue.

Blocking queue

When a process is waiting for input, the scheduler moves it from the runningqueue to the blocking queue. So, the running queue contains only processes thatcan be run. When a blocked process receives an event, it is moved back from theblocking queue to the running queue.

NOTE

Page 175: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-3

Sleeping queue

Processes in the sleeping queue are suspended until some external action wakesthem again. Processes can be put in a sleeping state (and so in the sleepingqueue) only by the functions sleep(), suspend(), receive.bucket$(), and relatedfunctions.

Terminating queue

When a process ends, it is stripped of almost all allocated data and moved to theterminating queue. When the scheduler has scheduled another process to run, itthen ’cleans up’ the terminating queue. That is, it removes all processes exceptzombie processes. A zombie process is a process that has ended but whose parentprocess has not yet caught its exit signal.

Context switchesEach running process receives a number of ticks when it is scheduled. This is theequivalent of a UNIX time slice. The execution of each instruction costs theprocess a number of ticks. When the process has used up all its ticks, the bshellschedules another process. The switch to another process is referred to as acontext switch.

Forcing a context switch

Normally, the bshell executes context switches automatically. Functions such asbms.send(), appl.set(), and start.session() also cause a context switch. Andprogrammers can force a context switch by calling suspend(0).This is usefulwhen the immediate response of another process is required.

Allocating bonus ticks

The database locking mechanism prevents two or more processes from updatingor deleting the same record or table simultaneously. When a process is modifyingthe database, the relevant record or table is locked. Other processes cannotmodify that record or table until the lock is released.

Some database management systems use a page locking mechanism instead of arecord locking mechanism. That is, they lock a predefined block size that caninclude several records. This can result in a deadlock when two processes withinthe same bshell attempt to lock records that are positioned very close to eachother in the database. To prevent this happening, you can boost the number ofticks assigned to a process by using the bonus tick mechanism.

Page 176: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-4

When this mechanism is enabled, the bshell assigns bonus ticks to a processwhen it locks a database record (note that a lock is applied when the first update,insert, or delete is performed by a database transaction) . This means that theprocess is not scheduled out before the lock is released (the lock is released whenthe transaction is committed or aborted).

You can configure the bonus tick mechanism by means of environment variablesor user resources.

User resource Environment variable Value

bonus_enable BSE_BONUS_ENABLE 0 bonus ticks off(default)

1 bonus ticks on

bonus_timeslice BSE_BONUS_TIMESLICE

The number of bonus ticks toassign to a process. The defaultis 1073741824.

bonus_timeout_warning

BSE_BONUS_TIMEOUT_WARNING

0

1

2

3

Warning mechanism off.

Warning mechanism on. Awarning message isdisplayed when a processis about to loose its timeslice. The message is alsodisplayed when a contextswitch is forced.

This is similar to 1, exceptthat when the object is indebug mode, the processstops and the debuggerpoints to the nextinstruction.

This is similar to 2, exceptthat the process is aborted.

Page 177: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-5

EventsBaanERP programs are designed to respond to events. Usually, they consist of amain loop that waits for events to occur. When an event occurs, the programperforms the appropriate actions to process the event. It then returns to itswaiting state.

Event types

There are four broad categories of events, as listed below. For a full list ofevent types, see Chapter 17, Events, in U7167A US BaanERP Tools:Functions reference.

n User action events.

Most of the events that occur in a BAAN application relate to userinteraction. When a user performs an action in the user interface (forexample, clicking the mouse or pressing a keyboard key), this generates anevent.

n Timer events.

A process can start a timer that sends an event to the calling process atspecified intervals. See Chapter 46, Timers, in U7167A US BaanERP Tools:Functions reference.

n Client events.

A process can send client events to another process by using the send.event()function. The sending and receiving processes can determine their ownprotocol.

n Bucket message events.

A process can broadcast bucket message events to other processes by usingthe bms.send() function.

Note that functions such as keyin$() and data.input() are based internally onevents.

Event flow

When a UI object generates an event, the display server sends that event to thebshell. The bshell distributes received events to the event queues of theappropriate process groups; note that events are sent to process groups and notindividual processes. The bshell never requests events; the display server alwaysacts independently.

Page 178: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-6

When one of the processes in the bshell requires input, the bshell checks whetherany event is present in the event queue of the process group to which the processbelongs. If there are no events in the event queue, it checks the connectionbetween the bshell and the display server. If it finds events there, it distributesthem to the appropriate process groups.

Event masks

A process can set the event mask of a UI object in order to specify the types ofevents in which it is interested; the object then generates only events of thesetypes (see the select.event.input() function). Normally, event masks areautomatically set for keyboard and mouse events. However, programmers shouldnot assume any default settings for an event mask. Note that the following eventtypes are always selected and cannot be masked: client events, timer events,bucket message events.

Event functions

BAAN Tools provides the following functions for handling events:

n next.event( event )n peek.event( event )n pending.events( )n send.event( event )n select.event.input( object_id, mask )

Event arrays

The event argument included in the next.event(), peek.event(), and send.event()functions consists of an array of longs (of size EVTMAXSIZE) that containsdetails of the incoming or outgoing event. You retrieve the contents of an eventarray by using the set of parameters defined for the particular event type. See“Event array parameters” in Chapter 17 in U7167A US BaanERP Tools:Functions refence.

Page 179: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-7

Sample code

The following example illustrates the basic principle of event handling that isused by almost every event driven program.

#include <bic_event>

function main_event_loop(){

long event( EVTMAXSIZE )

while next.event( event )on case evt.type( event )case EVTBUTTONPRESS:case EVTBUTTONRELEASE:

x = evt.button.x( event )y = evt.button.y( event )button = evt.button.button( event )if button = EVTBUTTON1 then

print "left button pressed"refresh()

endifbreak

default:print "not a button press/release"refresh()return

endcaseendwhile

}

Requests, inquiries, and repliesA request is a message sent by the bshell to the display server requesting someaction – for example, the creation of a window or some other UI object. Itconsists of a package of information that tells the display server what action toperform and the parameters to use for that action. Requests are asynchronous, sothe bshell does not wait for a reply from the display server. Consequently, if anerror occurs, the bshell does not detect it. The display server, however, maygenerate an error message on screen and/or in a log file.

An inquiry is a request for which a result is returned in the form of a reply.Normally, inquiries are used to retrieve information about existing UI objects.When a process sends an inquiry to the display server, it waits for the server toprocess the inquiry and send a reply. Consequently, inquiries are more time-consuming than asynchronous requests. When response time is important, avoidusing the inquiry/reply mechanism.

Page 180: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-8

For example, when retrieving information that does not change, you can store thedata in variables and retrieve it from those variables instead of sending queries tothe display server.

The following example illustrates the use of requests, inquiries, and replies:

#include <bic_gpart>

gpart_id = first.gpart( window_id ) | Inquiry-| reply

while gpart_idget.gpart( window_id, part_id, type, x, y ) | Inquiry-

| replyif type = GPLINE then

destroy.gpart( window_id, gpart_id ) | Requestendifgpart_id = next.gpart( window_id, gpart_id ) | Inquiry-

| replyendwhile

Processes, process groups, and mainwindows

Processes

A process consists of a program object, a date, and a state. A process that hasbeen started can be in any one of the following states:

n RunningThe process is in the running queue. It has been scheduled to run, or is readyto be scheduled.

n BlockingThe process is in the blocking queue. It is waiting for input.

n SleepingThe process is in the sleeping queue. It has been suspended and requires anexternal action to wake it up again.

n TerminatingThe process is in the terminating queue. It has ended but not all its resourceshave yet been removed.

Each process stores information about the current main window, the currentmenu, and current character window. Other information about display objects isnot directly available to it.

Page 181: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-9

Process groups

A process group is a group of related, interdependent processes. One process isthe group leader. Child processes are started by the leader or by one of itschildren. All processes belong to a process group.

The following are some of the characteristics of process groups:

n Each process group has its own event queue. Events are sent to the processgroup, not to individual processes.

n When one process within a group starts a child process, the child process isautomatically placed in the same process group as its parent. However, youcan use the function set.pgrp() to place the process in a different processgroup.

n When a process is killed or ended, its parent is automatically awakened,unless the parent and child are in different groups.

n You use the grab.mwindow() function to set the process group to which amain window sends its events. After calling this function, all events thatoccur in the main window are sent to the specified process group.

Main windows

A main window acts as the frame window for both sessions and 3GLapplications. It is used for starting processes and for creating graphical andcharacter windows. It is not used directly for handling user input or displayingprogram output. Usually, a main window consists of a border, title bar, menu bar,status area, control menu box, sizing controls, and a work area. The objects usedby an application for user interaction are created within the work area of a mainwindow and are managed by that main window.

Each process can have zero, one, or more main windows.

Process groups and main windows

Process groups and main windows are used:

n To ensure unambiguity of input focusn To keep related processes dependentn To enable parent and child processes to be independent of each other

Page 182: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-10

Unambiguity of input focus

To ensure that there is never any ambiguity as to where the events generated by aparticular window are sent, when you create a main window, you define a singleprocess group to which that main window sends its events. You do this with thegrab.mwindow() function. After calling this function for a main window, allevents that occur in that window are sent to the specified process group. Inprinciple, there is only one running process in a process group at any time; so theevents are sent to that process.

In principle, each process could have its own event queue. However, there are anumber of situations where this would cause problems. For example:

n When the input focus is on an input field and the user zooms to anotherprocess to select a value. In this case, the parent process is moved to thesleeping queue and will be awakened when the child process ends.

However, if the user types in the input field after the zoom process has startedbut before the zoom process has created its own windows, the characterstyped are sent to the sleeping process and not to the zoom process for whichthey were intended. When the windows of the zoom process appear, the usermust then restart the selection. However, when the zoom process exits, thecharacters sent to the parent process are displayed in the input field and notthose entered in the zoom process. This is because, when awakened, theparent process finds those characters in its process queue.

n A similar problem can arise when a uses ends a number of nested processesby repeatedly pressing the EXIT key and also when processes aresynchronized by using bucket functions.

These problems are avoided by enabling related, interdependent processes toshare the same process group (and so the same event queue).

Page 183: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-11

Keeping related processes dependent

When a process is started by the functions activate(), act.and.sleep(), orwait.and.activate(), by default the new process inherits the process group andmain window of its parent. The parent process is moved to the sleeping queuewill be awakened automatically when the child process ends.

The following diagram illustrates this.

A process with the same ID as its process group is referred to as the group leader.For the group leader, the predefined variable background is set to FALSE, Forchild processes, this variable is set to TRUE.

A process group keeps track of the number of processes that belong to it. Whenno processes remain in the group, the group is automatically destroyed. You candestroy all processes in a particular group simultaneously by calling kill.pgrp().

Page 184: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-12

Making related processes independent

When a process starts a child process, by default the child process inherits theprocess group and main window of its parent, and the parent is suspended untilthe child exits. However, it is possible to create a new process group and mainwindow for the child process and so keep the parent and child processesindependent. The following diagram illustrates this.

The code for disconnecting a child process from its parent can be included eitherin the parent process or in the child process. In the following example, it isincluded in the parent process.

old.mwindow = current.mwindow()new.mwindow = create.mwindow( title, mode, flags)change.mwindow( new.mwindow )child.pid = act.and.sleep( program.name, arglist )if child.pid then

set.pgrp( child.pid, child.pid )grab.mwidow( new.mwindow, child.pid )reactivate( child.pid )

endifchange.mwindow ( old.mwindow )destroy.mwindow( new.mwindow )

In this example, the parent process first creates a new main window for the childprocess. It then starts the child process and calls set.pgrp() to place the childprocess in a different process group. By specifying the same ID for the processand the process group in the set.pgrp() call, a new process group is automaticallycreated with the same ID as the process. The process becomes the leader of thenew process group. The parent process then calls grab.mwindow() to link thenew process group to the new main window.

Page 185: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-13

In this example, it is important to start the child process with act.and.sleep() andto reactivate the process only after it has been placed in the new process group. Ifthe process is started with activate(), and a context switch occurs immediatelyafter the child process is started, then the process would be scheduled with theincorrect process group.

Note that if a process is moved to another process group, it will be impossible toswitch it back to the original group if that group is destroyed in the meantime.

Synchronizing processes with the wait()functionThe wait() function enables synchronization of parent and child processes. Itcauses the parent process to wait for one or all of its children to exit beforecontinuing. Each child process sends an exit signal to the parent process when itends.

The parent can choose to ignore child signals or not. If it wants to ignore childsignals, the parent process calls:

signal(SIGCHLD, SIGIGN)

If it does not want to ignore child signals, it calls:

signal(SIGCHLD, SIGNOIGN)

When a parent process issues a wait() call but is ignoring child signals, childprocesses exit without any action by the parent. They exit, send an exit signal tothe parent, and are removed. The parent process blocks until it receives an exitsignal from the last process. The exit value and process ID of the last child arereturned in the return value and prodess_id argument respectively of the wait()function.

Page 186: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-14

The following diagram illustrates this situation.

When a parent process issues a wait() call and is not ignoring child signals, theexit signal of every child process is caught by the wait() function (including exitsignals from children in other process groups). So, each child waits after exitinguntil its parent process calls the wait() function. While it is waiting for the parentprocess to catch its exit value, the child process becomes a zombie process. It isplaced in the terminating process queue, but is not removed until the parentcatches its exit signal.

Page 187: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-15

The following diagram illustrates this situation.

Note that if a parent ends while some of its children are zombie process, thosechildren are removed automatically.

Page 188: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Multitasking and the GUI

Programming features

7-16

Page 189: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

8-1

OverviewBaanERP Tools supports the use of dynamic-link libraries (DLLs). A DLLconsists of a library of functions that are compiled, linked, and stored separatelyfrom the processes that use them. The functions are resources that can be sharedby multiple programs that are running concurrently. Only one copy of the DLLneeds to be present in memory. Each program that uses the DLL links to it atruntime, at the time it calls one of the DLL’s functions.

For example, consider the sprintf$() function. This is a very common function,used by many programs. Instead of including a copy of the function in eachprogram that uses it, you can program the function in a separate DLL. Multipleprograms can then share this one copy of the function, by linking to the DLL atruntime.

The following are some of the benefits of using DLLs:

n Instead of programming common functions in each program that uses them,you can program the functions in one or more DLLs. The code can then beshared by all the programs that use it. By implementing DLLs in BaanERPapplications, you can reduce the size of objects to a minimum, as the standardprogram is not merged with each 4GL program script.

n You can upgrade a function within a DLL without recompiling all theapplications that use it.

n You can upgrade an application without recompiling all the DLLs it uses.

n A DLL is loaded only when required. It is also loaded only once, thoughmultiple programs can share its code.

The following sections describe how you handle DLLs.

8 Dynamic-link libraries

Page 190: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-2

Function declarationsFor functions programmed within a DLL to be accessible to other programs, theymust be declared as external functions – that is, they must be declared with thekeyword EXTERN.

For example:

function extern long funct_a( long arg ){.....}

Functions declared without the EXTERN keyword are local functions. They areaccessible only within the program in which they are declared. A DLL usuallycontains both local and external functions.

Scope of variables across DLLs

Global variables

Global variables are declared outside the functions in a script, without theEXTERN keyword. They are only known within the DLL in which they aredeclared. For example:

long var_1

External variables

External variables are declared outside the functions in a script, with theEXTERN keyword. They are known within all DLLs in the process in whichthey are declared. For example:

extern long var_2

Database fields

Database tables are declared as follows:

table t<table_name>

Declaration of a table implies declaration of all its fields also. Though a tabledeclaration does not include the EXTERN keyword, tables fields are knownwithin all DLLs in the process in which they are declared. When one DLL in aprocess reads a record, the values of the record fields are shared by all DLLs inthe same process.

Page 191: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-3

Sharing DLL object codeDLL objects contain both a program code part and a data part. The program codeof a DLL object is loaded into memory when one of the DLL’s functions iscalled. The data part defines the memory part available for variables. Memory isallocated for a variable the first time that variable is used.

The program code part of a DLL can be loaded into a common virtual memoryaddress space. This enables two or more sessions, within one or more bshells onthe same system, to share the program code. The data part is not loaded intoshared memory and so cannot be shared.

By default, the program code of BaanERP DLLs can be shared only within thesame bshell. Once the DLL has been loaded, it is shared by all process within thebshell.

For process within all bshells on the same system to be able to share the programcode, you must specify the object name in the file $BSE/lib/srdd_tabx.x (wherex.x is the bshell version). The object will be loaded automatically and its codewill be shared by sessions within all bshells on the same system. It is advisable touse this method for all DLLs that are frequently used by several users. For moredetails, consult the Shared memory manager section in the BaanERP ToolsTechnical Manual.

Dynamic linkingDLLs can be linked to a program script either at compile time or at runtime.

Dynamic linking at compile time

For dynamic linking at compile time, you must specify the libraries that belongto a program script when you create or update that script. Which libraries belongto a program script depends on which external functions the program uses. It isnecessary to specify the libraries at compile time because the compiler locatesthe functions and checks the types of arguments and return values with thefunction prototypes. Note that a DLL object is loaded into memory and linked tothe executable program at runtime, at the time a DLL function is called.

You must compile the libraries before you compile the program script that usesthose libraries. However, since loading and linking take place at runtime, when alibrary is changed, you need only compile the library and restart the program.

Page 192: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-4

The are two ways to compile the libraries and program script:

n Use the BaanERP Tools. Choose the Compile option in the sessions"Maintain Libraries" and "Maintain Program Scripts".

n Use the bicx.x compiler (where x.x is the bhsell version). For example:

$ bic6.2 dll1 -o odll1

$ bic6.2 dll2 -o odll2

$ bic6.2 dll3 -o odll3

$ bic6.2 <program> -o<object> -d odll1:odll2:odll3

Note that, at runtime, external functions are searched for in the order in which theDLLs were supplied during compilation. In above example, dll1 is first.

Dynamic linking at runtime

This is used in cases where the DLL(s) that must be linked to a program areknown only at runtime.

For example, consider a programmer’s interface that receives a string containingthe library or external function to be called. The return value of the function call(if any) is sent back to the calling process. In this case dynamic linking atruntime must be used, because only at runtime is it known which externalfunction must be called.

A number of functions are available for handling dynamic linking at runtime.Using these functions, you can load a specific DLL and execute one or more ofits functions. See Chapter 14, DLL functions (executing), in U7167A USBaanERP Tools: Functions reference.

Function overloadingWhen DLLs are dynamically linked at runtime, instead of at compile time,function overloading is possible. This means that an external function containedin a loaded DLL can be replaced by overloading another DLL that contains afunction with the same name and arguments.

You use the load_dll() function to load DLLs dynamically. When you call thisfunction, you can specify whether the DLL is to be overloaded or not. Whensearching for an external function called by a program, the bshell alwayssearches in overloaded DLLs first.

Page 193: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-5

Specifying which DLLs belong to an object

There are three methods for specifying which DLLs belong to an object.

n Specify the DLL dynamically, with overload, in the source code. Forexample:

load_dll( <dll_object>, DLL_OVERLOAD )

n Specify the DLL statically at compile time. There are three ways to do this:

− use the option "Define Libraries" in the session "Maintain ProgramScripts"

− use the following syntax when starting the bicx.x compiler (where x.x isthe bshell version)

bicx.x script -o object -d dll_object

− use the following pragma code in the script

#pragma used dll <dll_object>

n Specify the DLL dynamically, without overload, in the source code. Forexample:

load_dll( <dll_object>, 0 ) orload_dll( <dll_object> ) | 0 is default

Function search algorithm

When a DLL function is called for the first time, the function address isunresolved. The bshell attempts to resolve the function address by searching forthe function using the search method described below. After a function address isresolved, that address is used for all subsequent function calls with the samefunction name and arguments. So once a function address is resolved, thefunction cannot be replaced by overloading a different DLL containing afunction of the same name and arguments.

The bshell searches DLLs in the following order:

1 All dynamically overloaded DLLs – that is, DLLs loaded by callingload_dll() with the overload flag set to DLL_OVERLOAD. For example:

load_dll(dll_object, DLL_OVERLOAD)

The bshell searches the overloaded DLLs in reverse order. So, the DLL thatwas overloaded last is searched first.

2 The first DLL where the function was found during compilation.

Page 194: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-6

3 All statically specified DLLs.

First the bshell searches in the DLLs specified in the compilation commandwith the –d option. The DLLs are searched in the order they are specified inthe command. For example:

bic6.2 script -o object -d odll1:odll2:odll3

Next the bshell searches in DLLs specified using the following pragmastatement:

#pragma used dll <dll_object>

4 All dynamically loaded DLLs – that is, DLLs loaded by calling load_dll()without the overload flag or with the overload flag set to 0. For example:

load_dll(dll_object, 0)

The bshell searches the loaded DLLs in the order in which they were loaded.So, the DLL that was loaded first is searched first.

Note that you can change the search order of dynamically loaded DLLs bycalling load.dll() for a loaded DLL and changing the value of the overloadflag.

Function overloading – example

Compile

bic6.2 dll -o odllbic6.2 dll_new -o odll_newbic6.2 script -o object -d odll –DDEBUG

Script code

function main(){

#ifdef DEBUGif ( debug flag ) then

| Load dynamically DLL 'dll_new' to| overload the DLL 'dll'

load_dll("odll_new", 1)| Argument '1' means overload

endif#endif

dll_function()}

Page 195: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-7

dll code

function extern dll_function(){

...}

dll_new code

function extern dll_function(){

...}

Object information toolTo display information about an object, use the object information toolbic_infox.x (where x.x is the bshell version). Note that maximum information isdisplayed when the object has been compiled with the debug option.

Syntaxbic_infox.x [-aidshwcV] [-eu] [-f[flags]] object

Options

-a Show all available object information (default).

-I Show instructions in object (Disassembler). This is only possiblewhen the object is compiled with the debug option.

-d Show used DLLs and where the external functions used aredefined.

-s Show list of used variables, (global) functions, string constants, anddouble constants.

-h Show Object header.

-w Show #ident <strings>.

-c Check checksum.

exit(0) okexit(1) corrupted

Page 196: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-8

-V Show version/release and portings information of bic_infox.x.

-e Show prototypes of all external functions defined in the object.

-u Show the general usage of the library (see below).

-f Show flags.

-f<flag> Check flags. When this options is used, all other options areignored. <flag> can be a combination of the following:

1 NOTRANSACTION2 DEBUG4 PROFILE8 DLL

exit(0) flag(combination) is in objectexit(1) flag(combination) is not in object

Combining -e and -u displays the description of the object and the descriptionsand prototypes of all external functions within the object (see below).

Object and function descriptions

You specify an object’s description between the keywords DLLUSAGE andENDDLLUSAGE in the program script. You place the information outside allfunctions so that it is global for the entire program. The description shouldexplain the general usage of the object. The description is added to the object andyou can retrieve it with the command bic_infox.x -u <object>.

You also specify a function’s description between the keywords DLLUSAGEand ENDDLLUSAGE in the program script. However, you place the informationwithin the body of the function, between the { and } characters. The descriptionshould explain the general usage of the object, its arguments, and its return value,for example. You can retrieve function descriptions and prototypes with thecommand bic_infox.x –eu <object>.

Page 197: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-9

Example

dllusageThis is the object description.

enddllusage

function extern long abs( long arg ){dllusage

This function returns the absolute value of thespecified argument.

Input:ARG The value for which the absolute value is to be

returned.Output:Return the positive value of ARG.

enddllusage

return ( arg >= 0 ? arg : -arg )}

DLL compilation and runtime errors

Compilation errors

A compilation error occurs when a function is not found in the specified DLLs orif there is an argument mismatch.

Runtime errors

The following runtime error message is displayed when a script calls a functionthat has been removed from the DLL and only the DLL has been recompiled:

Dynamic Link Failure function %s

The following runtime error messages are displayed when a function’s argumentsare changed within a DLL without recompilation of programs that call thechanged function:

Arg error <function name>(<argument name>) type ...expected ...

or

Illegal number of args (%d) for function %s expected %d

To avoid runtime errors, it is advisable to recompile programs whenever youchange the programmer’s interface of a DLL that is linked to those programs.

Page 198: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Dynamic-link libraries

Programming features

8-10

Page 199: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

9-1

OverviewThe BAAN debugger is an interactive statement interpreter that enables you tocontrol and test the execution of a program. Its principal features include:

n Simultaneous program execution and display of debug information

n Source instructions and debug information are displayed in their ownwindows, separate from the application

n Source instructions are displayed in a window that you can move and resize

n On non-graphical displays, debug information is displayed in screen columns81 to 132

n The debugger supports variable tracing during program execution (that is, allchanges to the values of specified variables are displayed during programexecution)

n The debugger is fully symbolic – machine addresses are not used

n The debugger is fully integrated with the bshell.

The debugger works only with source programs that have been compiled with thedebug option (-l in the case of the BAAN Compiler). When you start such aprogram, two additional windows are displayed. One displays the source codebeing executed (the line currently being processed is highlighted). The other is acommand window where you input debugger commands and where commandresults and error messages are displayed.

For information about other debug facilities, the “Logic Server” section in theBaanERP Tools Technical Manual.

CommandsDebugger commands consist of from one to three words; the words can beseparated from each other by one or more spaces. The assignment command is anexception. Here the variable and the value to be assigned are separated by a ':='sign. Most commands require a line number and/or a source name. If no sourcename is specified, the default is the current source.

9 The BAAN debugger

Page 200: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-2

When you start the debugger for an object, the source used by the debugger isfirst searched for by using the directions in the file fdx.x.<pack.comb.> (wherex.x is the bshell version), then it is searched for in the $BSE/tmp directory, andfinally in the current directory.

Command Action

b [[source] line_number] Set a break point on the current or specifiedline of the current or specified source. Theline is highlighted.

Note that you cannot set break points inincluded parts in a source. Instead the breakpoint must be set in the included file.

B [source] Display all set break points in the current orspecified source.

c [number] Continue (execute the source) up to the nextbreak point. If you specify a number, thedebugger skips that number of break points.The executed source lines are not displayed.

C [number] Same as ’c’, except that the executed sourcelines are displayed.

cc Change the size of the command window.This is valid only when application anddebugger are in the same window.

cs Change the size of the source window. This isvalid only when the application and debuggerare in the same window.

d [source line_number] Delete the break point on the specified linenumber in the source. If you do not specify aline number, the debugger provides theopportunity to interactively delete any breakpoint in the current source file.

D [source] Delete all set break points in the specified orcurrent source.

delete all Delete all traces and stop instructions.

delete number Delete a specified trace or stop instruction.

Page 201: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-3

Command Action

ds Delete the source window.

dd Generate a dump of the data dictionary.

<expression> Execute the specified expression.

f [noarg|noname]

[number]

Display stack trace (present nesting offunctions), with the arguments of thefunctions. If you specify a number, only thatnumber of nestings is displayed.

noarg only the names of functions aredisplayed

noname arguments are displayed but nottheir names

fdebug Show the open tables on the commandwindow.

Fdebug Print the open tables to the spooler.

g [source] line_number Continue program execution at the specifiedline number (goto).

help (or ?) Start the Help Viewer for debugger options.

instr Generate a symbolic dump of the object.

l Display the full list of program variables.

L Display the list of program variables thathave a value, and display their current values.To stop displaying the contents of an array,enter ’n’ at the question ’More ?’.

lp Print the output of the ’l’ command.

Lp Print the output of the ’L’ command.

mem Generate a dump including information aboutthe memory allocated.

p Go to the source line currently beingprocessed (this is useful after the view or seekcommand). The line is indicated by a greaterthan (>) sign before the line number.

Page 202: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-4

Command Action

q Exit the debugger (quit).

return Continue execution until the end of thecurrent function.

s [number] Execute the program step by step, thespecified number of instructions at a time(default is 1). During execution, theintermediate source lines are not displayed.

S [number] Similar to ’s’, except that a function call isexecuted as a single statement.

slow [number] Reduce the rate of running source code. Themaximum number is 100; the minimum (anddefault) number is 0.

split number Split the command and source window. Thespecified number is the last line of thecommand window. This is often used afterresizing the Debugger window.

status

[trace|stop|number]

Display traced variables and/or stopinstructions. If you specify a number, onlythat traced variable or stop instruction isdisplayed.

stop if <expression> Stop execution when expression is True.

stop in <function> Stop execution when function is entered.

sym Generate a dump of the symbol table.

trap off Disables ‘trap on’. This command is availableonly when the bshell was started with the -dbgcpu flag.

trap on The debugger stops after execution of everyfunction call. This command is available onlywhen the bshell was started with the -dbgcpu flag.

Page 203: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-5

Command Action

t variable Trace the specified variable during programexecution. The execution of the programstops every time the value of the variable ischanged. You cannot trace array variables orcommon variables.

T variable [value] Same as ’t’, except that program execution isnot stopped when the variable changes. If youspecify a value, execution stops when thevariable gets that value.

u [variable] Stop tracing the specified variable. If novariable is specified, you can stop tracingeach variable interactively.

U Stop tracing all variables currently beingtraced.

v [source] line_number Display a specified source line in the sourcewindow (view). If line_number is greater thanthe total number of lines, the last line isdisplayed.

v {+-} number Shift the display to the source line that isnumber lines before or after the currentsource line.

/pattern Seek a matching text pattern in the currentsource and display that line.

[function.]variable

[/option]

Display the value of a specified variable. Ifyou specify a function, the value of the localvariable of that function is displayed.Otherwise, the value of the variable of thecurrent function or the global variable isdisplayed. If a variable has no value (emptystring or zero number), the value is notdisplayed.

/option can have the following values:

Page 204: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-6

Command Action

/Use to display the value of a variable that hasthe same name as a Debugger command. Forexample, ‘b/’ displays the value of variable b.

/dPrint the flags of the variable and thedimension for arrays.

/DDisplay the number of bytes allocated in along or double variable. Display the numberof bytes for one element in a string array.

The following options are useful for recordbuffers and binary data. They display thevalue of a string variable with its full declaredlength, regardless of NUL characters.

/xNUL characters are displayed as ‘^@’.

/XCharacters with values 0 to 31 are displayedas ‘\x<value in hex>’.

/bAll characters are displayed as ‘\x<value inhex>’.

variable := value Assign a value to a variable. The value canbe:

n A string constant or expressionn A numeric constant or expressionn A variable name

vi Activate the vi editor for the current source atthe current source line. Changing the sourcehas no influence on the source displayed bythe debugger in the source window.

width value Change the width of command and sourcewindow. You can specify any value in therange 80 to 132.

Page 205: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-7

Command Action

<Ctrl>D/<Ctrl>U Page down or up in source.

Command Action

<Esc> Toggle between normal and history mode.

<Arrow up>/ <Arrowdown>

In history mode, these display previouslyexecuted commands on the command line. Innormal mode, these move the cursor throughthe source.

Debugger mouse actionsThe Debugger supports the following mouse actions in the source window:

n Click on a line number to set a break point on that line.n Click on a source line to move the cursor to that line.n Click on a variable to display its value.

Page 206: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

The BAAN debugger

Programming features

9-8

Page 207: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

10-1

There are three categories of errors:

n Error numbers 1-99 are operating system errors

n Error numbers 100-899 are database errors

n Error numbers 900-999 are network errors

Notes

To retrieve errors with error codes greater than 1000, subtract 1000 from theerror number. The result is the database error code. For example, the error code1510 represents the database error code 510 (that is, 1510 – 1000).

When a fatal error occurs, information about the error is stored in the log files inthe directory $BSE/log. For example, if bdbpost6.2 causes an error, this isreported in the file log.bdbpost6.2.

UNIX errors

1 EPERM Not owner

This indicates an attempt to modify a file that cannot bemodified, except by its owner or by a super user. This isalso generated when ordinary users attempt an action thatonly a super user is permitted to carry out.

2 ENOENT No such file or directory

This occurs when a specified file name should exist butdoes not, or when one of the directories in a path namedoes not exist.

3 ESRCH No such process

This occurs when a specified process cannot be found.

10 Errors

Page 208: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-2

4 EINTR Interrupted system call

This indicates that an asynchronous signal (such asinterrupt or quit), which the user has elected to catch,occurred during a system call. If the system resumesexecution after processing the signal, it will appear as ifthe interrupted system call returned this error code.

5 EIO I/O error

This indicates some physical I/O error. In some cases, thiserror can point to the call following the one to which itactually applies.

6 ENXIO No such device or address

This occurs when I/O on a special file refers to asubdevice that either does not exist, or is beyond the limitsof the device. It may also occur when, for example, a tapedrive is not online or no disk pack is loaded on a drive.

7 E2BIG Arg list too long

This occurs when an argument list longer than 5120 bytesis presented to a member of the exec family system calls.

8 ENOEXEC Exec format error

This indicates that a request has been made to execute afile which, although it has the appropriate permissions,does not start with a valid magic number. See a.out(5).

9 EBADF Bad file number

This indicates either that a file descriptor does not refer toan open file, or that a write request has been made to a filethat is opened only for reading, or that a read request hasbeen made to a file that is opened only for writing.

10 ECHILD No child processes

This occurs when a wait is executed by a process that hasno existing or unwaited-for child processes.

11 EAGAIN No more processes

This indicates that a fork has failed, either because thesystem’s process table is full or because the user is notallowed to create any more processes.

Page 209: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-3

12 ENOMEM Not enough space

This occurs during an exec or sbrk, when a program asksfor more space than the system is able to supply. This isnot a temporary condition. The maximum space size is asystem parameter.

This error can also occur when the arrangement of text,data, and stack segments requires too many segmentationregisters, or if there is not enough swap space during afork.

13 EACCES Permission denied

This occurs when an attempt is made to access a file in amanner forbidden by the protection system.

14 EFAULT Bad address

This occurs if the system encounters a hardware faultwhen it attempts to use an argument of a system call.

15 ENOTBLK Block device required

This occurs when a nonblock file is specified where ablock device is required – for example, in mount.

16 EBUSY Device busy

This indicates an attempt to mount a device that wasalready mounted, or an attempt to dismount a device onwhich there is an active file (open file, current directory,mounted-on file, active text segment). This error alsooccurs when an attempt is made to enable accountingwhen it is already enabled.

17 EEXIST File exists

This occurs when an existing file is specified in aninappropriate context (for example, as a new link name inthe link function).

18 EXDEV Cross-device link

This occurs when an attempt is made to link to a file onanother device.

Page 210: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-4

19 ENODEV No such device

This occurs when an attempt is made to apply aninappropriate system call to a device – for example, whenan attempt is made to read from a write-only device.

20 ENOTDIR Not a directory

This indicates that a nondirectory was specified where adirectory is required – for example, in a path prefix or asan argument to chdir(S).

21 EISDIR Is a directory

This indicates an attempt to write to a directory.

22 EINVAL Invalid argument

This indicates an invalid argument. For example,dismounting a nonmounted device, specifying anundefined signal in signal or kill, reading or writing a filefor which lseek has generated a negative pointer. Thiserror is also used by the math functions described in the(S) entries of the UNIX manual.

23 ENFILE File table overflow

This indicates that the system's table of open files is full,and that temporarily no more open commands can beaccepted.

24 EMFILE Too many open files

This occurs when an attempt is made to open more thanthe maximum number of files. No process can have morethan 20 file descriptors open at a time.

25 ENOTTY Not a typewriter

This indicates that the specified device does not have theproperties of a terminal.

26 ETXTBSY Text file bus

This occurs when an attempt is made either to execute apure-procedure program that is currently open for writingor reading, or to open for writing a pure-procedureprogram that is being executed.

Page 211: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-5

27 EFBIG File too large

This indicates that the size of a file exceeded themaximum file size (1,082,201,088 bytes) or ULIMIT. Seeulimit(S).

28 ENOSPC No space left on device

This occurs during a write to an ordinary file when there isno free space left on the device.

29 ESPIPE Illegal seek

This occurs when an lseek is issued to a pipe.

30 EROFS Read-only file system

This occurs when an attempt is made to modify a file ordirectory on a read-only device.

31 EMLINK Too many links

This indicates an attempt to make more than the maximumnumber of links (1000) to a file.

32 EPIPE Broken pipe

This indicates an attempt to write on a pipe for whichthere is no process to read the data. This conditionnormally generates a signal; the error is returned if thesignal is ignored.

33 EDOM Math arg out of domain of func

This indicates that an argument of a math function isoutside the defined domain of the function.

34 ERANGE Math result not representable

This indicates that the value of a function in the mathpackage cannot be represented within machine precision.

Page 212: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-6

Database errors

100 EDUPL This indicates that a duplicate value exists.

101 ENOTOPEN This indicates that the specified table is notopen.

102 EBADARG This indicates that an illegal argument hasbeen specified.

103 EBADKEY This indicates that an Illegal key descriptionhas been specified. Use the bdbpre andbdbpost tools to resolve.

107 ELOCKED This indicates that the specified record islocked. You can either wait until the lock isreleased or you can remove the lock yourself.

108 EKEXISTS This indicates that the specified key alreadyexists.

110 EENDFILE This indicates that the end of file has beenreached.

111 ENOREC This indicates that no record was found thatmatches the query criteria.

112 ENOCURR This indicates that there is no current record.

113 EFLOCKED This indicates that the table is locked. Youcan either wait until the lock is released oryou can remove the lock yourself.

201 EROWCHANGED This indicates that the record was changedafter a delayed lock.

202 EDBLOCKED This indicates that the database is locked.You can either wait until the lock is releasedor you can remove the lock yourself.

203 ETRANSACTIONON This occurs when you attempt an action thatis not allowed within the transaction.

204 EISREADONLY This indicates that the transaction is readonly.

Page 213: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-7

205 ENOTINRANGE This indicates that the field value is out ofrange and does not agree with the domaindefinition.

206 ENOTLOCKED This indicates that the record is not locked.

207 EAUDIT This indicates an audit trailer error.

208 EPERMISSION This occurs when you attempt an action thatis not allowed at this time.

209 EMIRROR This indicates an error in the mirroring of thedatabase. The tables are inconsistent. Youcan use the bdbpre and bdbpost tools to copythe tables correctly.

210 EMLOCKED This indicates either that the record is lockedin the mirrored database, or that the tablesare inconsistent, or that the mirroringdefinition in tabledef6.2 is not compatible.

213 ETRANSACTIONOPEN This indicates that the transaction wasstarted, but not updated. This is an internalbshell error.

214 EUNALLOWEDCOMPNR This indicates that the operation for mappingcompany numbers is not allowed. If thelogical company is not equal to the physicalnumber, then you are not allowed to performa drop or clear table operation.

251 EAUDSETUP This occurs when the audit server setup is notcorrect. See the log.audit file for moreinformation.

252 EAUDCORRUPT This indicates that an audit file is corrupt.See the log.audit file for more information.

253 EAUDLOCKED This indicates that the audit file is locked byanother user. See the log.audit file for moreinformation.

254 EAUDABORT This indicates that a commit transaction hasfailed in the audit server. See the log.auditfile for more information.

Page 214: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-8

301 ESQLQUERY This indicates a general SQL error. It occurswhen the SQL query is syntacticallyincorrect.

302 ESQLSYNTAX This indicates that the SQL syntax is notcorrect.

303 ESQLREFER This indicates that a reference in the querycannot be found.

305 ESQLWRONGROW This occurs when a wrong record wasreturned. It probably means either that thetable index is corrupt or that the RDBMS hasa different sorting order than the BaanERPsoftware.

501 EMEMORY This indicates an internal memory error.

502 EBDBON This indicates that the user is already loggedon.

503 EBADADRS This occurs when an illegal address is used.

504 EBADFLD This indicates an undefined column.

505 ENOSERVER This indicates either that there is no serverspecified in tabledef6.2 or that the servercannot be started. See the log file for moreinformation.

506 ENOTABLE This indicates that the table does not exist.

507 ETABLEEXIST This indicates that the table you are trying tocreate already exists.

508 EBDBNOTON This indicates that you are not logged on to adatabase.

509 EBADCURSOR This indicates that you have a bad memorycursor or that a bad table pointer has beenspecified.

510 EDBNOTON This indicates that the database has not beenstarted. Start the database to correct theproblem.

511 EWRONGVERSION This indicates that client and server versionsare incompatible.

Page 215: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-9

512 EDDCORRUPT This indicates a corrupt data dictionary. Youcan use the bdbpre and bdbpost tools torepair it.

513 ENODD This indicates that the data dictionary wasnot found.

514 ESECURITY (ORACLE) This indicates a security error. Itprobably means that you do not have thecorrect user or group permission.

515 ELICENSEERROR This indicates a license error; probably anunpatched binary.

516 EUPDSEGM This occurs during the making or filling ofrollback segments. It probably means that thedisk is full.

517 EDELAYED This indicates a general delayed lockingerror.

518 ENOSESSION This occurs when an invalid session code isspecified.

519 ENOCOMPNR This occurs when no company number isspecified or when an illegal company numberis specified. A valid company number is anumber between 0 and 999.

520 EBUFUPD This occurs when flushing of bufferedupdates fails. The flushing can fails due to alock or to a referential integrity constraint.

521 ENOSHM This indicates that shared memory has notbeen loaded. Load shared memory to correctthe problem (see BaanERP Tools TechnicalManual for more information).

600 EREFERENCE This indicates a general reference error. Seethe log file for more information.

601 EREFLOCKED This indicates that the reference table islocked. You can either wait until the lock isreleased or remove the lock yourself.

Page 216: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Errors

Programming features

10-10

602 EUNDEFREF This indicates an undefined reference. Thisprobably means that there is a problem in theruntime data dictionary. See the log file formore information.

604 EREFUPDATE This indicates that a reference could not beupdated.

605 EREFEXISTS This indicates that the record cannot bedeleted while a reference exists. See the logfile for more information.

606 EREFNOTEXISTS This indicates that the reference does notexist.

607 ENOREFTBL This indicates that the reference table couldnot be found. This may mean that the datadictionary is not correct. See the log file formore information.

608 ENOREFCNT This indicates that no reference counter fieldsare present.

609 EUPDREFCNT This indicates an error during updating of thereference counter.

700 ESETLOCALE This indicates an error during setting of thelocale. See the log file for more information.

850 EABORTONLOCK Automatic rollback on lock error. Thedatabase driver aborts the transaction.

Page 217: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

11-1

Reportsn Sorting doubles correct to 6 decimal places

n Maximum 253 fields on a report (including array elements)

Bshelln Maximum string buffer size is 4K – be careful when concatenating strings

with '&' sign

n Maximum function stack depth is 75

Bicn Maximum 255 arguments per function

n Maximum 32K variables per compilation

n Maximum BRANCH of 32K (BRANCH refers to the amount of generatedcode per function, including macros etc.)

SQLn Maximum of 50 AND conditions within WHERE clause – otherwise the

following error message appears:

"Stack overflow [QueryId = XX]"

Tablesn Maximum record length is 3072 bytes

n Maximum number of fields is 1024

n Maximum field length is 3072 bytes

11 Known limits

Page 218: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Known limits

Programming features

11-2

Indexesn Maximum index length is 120 bytes

n Maximum number of fields is 32 (no combined fields)

n Maximum number of index parts is 8

Page 219: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

12-1

Character Decimal Hexadecimal Character Decimal Hexadecimal

0 00 128 80

^A 1 01 129 81

^B 2 02 130 82

^C 3 03 131 83

^D 4 04 132 84

^E 5 05 133 85

^F 6 06 134 86

^G 7 07 135 87

^H 8 08 136 88

^I 9 09 137 89

^J 10 0A 138 8A

^K 11 0B cf$(0) 139 8B

^L 12 0C cf$(1) 140 8C

^M 13 0D cf$(2) 141 8D

^N 14 0E cf$(3) 142 8E

^O 15 0F cf$(4) 143 8F

^P 16 10 cf$(5) 144 90

^Q 17 11 cf$(6) 145 91

^R 18 12 cf$(7) 146 92

^S 19 13 cf$(8) 147 93

^T 20 14 cf$(9) 148 94

^U 21 15 cf$(10) 149 95

12 ASCII table (ISO 8859-1)

Page 220: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

ASCII table (ISO 8859-1)

Programming features

12-2

Character Decimal Hexadecimal Character Decimal Hexadecimal

^V 22 16 cf$(11) 150 96

^W 23 17 cf$(12) 151 97

^X 24 18 cf$(13) 152 98

^Y 25 19 cf$(14) 153 99

^Z 26 1A cf$(15) 154 9A

ESC 27 1B 155 9B

^\ 28 1C 156 9C

^] 29 1D 157 9D

^^ 30 1E 158 9E

^_ 31 1F 159 9F

SP 32 20 NBSP 160 A0

! 33 21 ¡ 161 A1

" 34 22 ¢ 162 A2

# 35 23 £ 163 A3

$ 36 24 ¤ 164 A4

% 37 25 ¥ 165 A5

& 38 26 ¦ 166 A6

' 39 27 § 167 A7

( 40 28 ¨ 168 A8

) 41 29 © 169 A9

* 42 2A ª 170 AA

+ 43 2B « 171 AB

, 44 2C ¬ 172 AC

- 45 2D SHY 173 AD

. 46 2E ® 174 AE

/ 47 2F ¯ 175 AF

Page 221: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

ASCII table (ISO 8859-1)

Programming features

12-3

Character Decimal Hexadecimal Character Decimal Hexadecimal

0 48 30 ° 176 B0

1 49 31 ± 177 B1

2 50 32 ² 178 B2

3 51 33 ³ 179 B3

4 52 34 ´ 180 B4

5 53 35 µ 181 B5

6 54 36 ¶ 182 B6

7 55 37 · 183 B7

8 56 38 ¸ 184 B8

9 57 39 ¹ 185 B9

: 58 3A º 186 BA

; 59 3B » 187 BB

< 60 3C ¼ 188 BC

= 61 3D ½ 189 BD

> 62 3E ¾ 190 BE

? 63 3F ¿ 191 BF

@ 64 40 À 192 C0

A 65 41 Á 193 C1

B 66 42 Â 194 C2

C 67 43 Ã 195 C3

D 68 44 Ä 196 C4

E 69 45 Å 197 C5

F 70 46 Æ 198 C6

G 71 47 Ç 199 C7

H 72 48 È 200 C8

I 73 49 É 201 C9

Page 222: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

ASCII table (ISO 8859-1)

Programming features

12-4

Character Decimal Hexadecimal Character Decimal Hexadecimal

J 74 4A Ê 202 CA

K 75 4B Ë 203 CB

L 76 4C Ì 204 CC

M 77 4D Í 205 CD

N 78 4E Î 206 CE

O 79 4F Ï 207 CF

P 80 50 Ð 208 D0

Q 81 51 Ñ 209 D1

R 82 52 Ò 210 D2

S 83 53 Ó 211 D3

T 84 54 Ô 212 D4

U 85 55 Õ 213 D5

V 86 56 Ö 214 D6

W 87 57 × 215 D7

X 88 58 Ø 216 D8

Y 89 59 Ù 217 D9

Z 90 5A Ú 218 DA

[ 91 5B Û 219 DB

\ 92 5C Ü 220 DC

] 93 5D Ý 221 DD

^ 94 5E Þ 222 DE

_ 95 5F ß 223 DF

` 96 60 à 224 E0

a 97 61 á 225 E1

b 98 62 â 226 E2

c 99 63 ã 227 E3

Page 223: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

ASCII table (ISO 8859-1)

Programming features

12-5

Character Decimal Hexadecimal Character Decimal Hexadecimal

d 100 64 ä 228 E4

e 101 65 å 229 E5

f 102 66 æ 230 E6

g 103 67 ç 231 E7

h 104 68 è 232 E8

i 105 69 é 233 E9

j 106 6A ê 234 EA

k 107 6B ë 235 EB

l 108 6C ì 236 EC

m 109 6D í 237 ED

n 110 6E î 238 EE

o 111 6F ï 239 EF

p 112 70 ð 240 F0

q 113 71 ñ 241 F1

r 114 72 ò 242 F2

s 115 73 ó 243 F3

t 116 74 ô 244 F4

u 117 75 õ 245 F5

v 118 76 ö 246 F6

w 119 77 ÷ 247 F7

x 120 78 ø 248 F8

y 121 79 ù 249 F9

z 122 7A ú 250 FA

{ 123 7B û 251 FB

| 124 7C ü 252 FC

} 125 7D ý 253 FD

Page 224: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

ASCII table (ISO 8859-1)

Programming features

12-6

Character Decimal Hexadecimal Character Decimal Hexadecimal

~ 126 7E þ 254 FE

DEL 127 7F ÿ 255 FF

Page 225: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Programming features

13-1

3

3GL programming language..... 1-1, ............................................... 2-1constants ................................ 2-3expressions and operators.... 2-16iterations .............................. 2-25overview ................................ 2-1transfer of control ................ 2-21variables................................. 2-5vocabulary ............................. 2-1

4

4GL programming featuresautomatic import of variables ......

......................................... 3-27event sections......................... 3-2flow of standard program..... 3-21overview ................................ 3-1

A

after.commit.transaction() ....... 6-15after.destroy.object()................ 6-12after.get.object() ...................... 6-10after.save.object() .................... 6-14arithmetic operators ................. 2-17ASCII table.............................. 12-1assignment operator................. 2-20

B

based variables......................... 2-12before.destroy.object()............. 6-12before.get.object()...................... 6-9before.open.object.set() ............. 6-9before.save.object() ................. 6-13

C

CASE statement....................... 2-23combined fields......5-23, 5-24, 5-25commands..................3-8, 3-9, 3-12common variables........... 2-14, 2-15compiler ................................... 2-45conditional compiling .............. 2-41constants ......................2-3, 2-4, 2-5context switches......................... 7-3

D

DAL overview .................... 6-1, 6-2Data Access Layer

communication with STP andCDAS .............................. 6-18

data access methods............. 6-16hooks...................................... 6-5object hooks.................... 6-7, 6-8property hooks ....................... 6-6property methods ................. 6-17query extensions .................. 6-17terminology............................ 6-3transition issues (BAAN IV to

BaanERP) ........................ 6-18UI DAL and STP interaction . 6-3

database handlingerror handling ...................... 5-39hints for using db.retry.point 5-43hints for using SQL.............. 5-41overview ................................ 5-1transaction handling............... 5-5using program variables....... 5-15

debugger .................................... 9-1debugger commands .................. 9-1debugger mouse actions............. 9-7delayed locks .................... 5-7, 5-31

13 Index

Page 226: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Index

Programming features

13-2

dynamic-link libraries................ 8-1

E

embedded SQL ........................ 5-27error codes ............................... 10-1errors............................... 10-1, 10-6events.................................. 7-5, 7-6external variables..................... 2-31

F

fixed variables ......................... 2-12FROM clause........................... 5-11

G

global variables........................ 2-30GOTO statement...................... 2-21GROUP BY clause .................. 5-13

H

HAVING clause ...................... 5-14

I

include files ............................. 2-36

L

layout.again()............................. 4-7limits........................................ 11-1local variables.......................... 2-28locking .........................5-5, 5-6, 5-7logical operators ...................... 2-18

M

macro definition.............. 2-37, 2-38main windows..................... 7-8, 7-9method.is.allowed() ................. 6-15multitasking and the GUI .......... 7-1

overview ......................... 1-3, 7-1requests

inquiriesreplies ............................ 7-7

synchronizing processes with thewait() function ................. 7-13

N

NULL characters ............ 2-15, 2-16

O

ORDER BY clause .................. 5-14

P

page()......................................... 4-7pragma codes .................. 2-40, 2-41predefined variables................... 4-5preprocessor............................. 2-36

R

REFERS TO clause ................. 5-20relational operators .................. 2-18report scripts

event sections......................... 4-1expanding text variables ........ 4-8functions ................................ 4-7overview ................................ 4-1program sections.................... 4-1report sections................. 4-2, 4-3text field sections ................... 4-4

reports ........................................ 4-1report scripts .......................... 4-1

reset.suppress() .......................... 4-7retry points.......................... 5-8, 5-9

S

scheduler............................. 7-2, 7-3SELECT clause........................ 5-10SELECT statement .................. 5-10SQL................................... 5-9, 5-10SQL programming................... 5-27SQL syntax .............................. 5-10SQL trace options .................... 5-32static variables ......................... 2-28subqueries ................................ 5-26

W

wait()........................................ 7-13WHERE clause ........................ 5-11

Page 227: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Index

Programming features

13-3

WHILE statement........... 2-25, 2-26

Page 228: BaanERP Tools Programming features - baansupport.combaansupport.com/docs/Baan5/...Programming-features.pdf · Chapter 1 provides a brief introduction to Baan 3GL/4GL programming features

Index

Programming features

13-2