UniBasic Commands Reference - Rocket Documentation Library
Transcription
UniBasic Commands Reference - Rocket Documentation Library
Rocket UniData UniBasic Commands Reference Version 8.1.1 December 2015 UDT-811-BASR-1 Notices Edition Publication date: December 2015 Book number: UDT-811-BASR-1 Product version: Version 8.1.1 Copyright © Rocket Software, Inc. or its affiliates 1985-2015. All Rights Reserved. Trademarks Rocket is a registered trademark of Rocket Software, Inc. For a list of Rocket registered trademarks go to: www.rocketsoftware.com/about/legal. All other products or services mentioned in this document may be covered by the trademarks, service marks, or product names of their respective owners. Examples This information might contain examples of data and reports. The examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental. License agreement This software and the associated documentation are proprietary and confidential to Rocket Software, Inc. or its affiliates, are furnished under license, and may be used and copied only in accordance with the terms of such license. Note: This product may contain encryption technology. Many countries prohibit or restrict the use, import, or export of encryption technologies, and current use, import, and export regulations should be followed when exporting this product. 2 Corporate information Rocket Software, Inc. develops enterprise infrastructure products in four key areas: storage, networks, and compliance; database servers and tools; business information and analytics; and application development, integration, and modernization. Website: www.rocketsoftware.com Rocket Global Headquarters 77 4th Avenue, Suite 100 Waltham, MA 02451-1468 USA To contact Rocket Software by telephone for any reason, including obtaining pre-sales information and technical support, use one of the following telephone numbers. Country Toll-free telephone number United States 1-855-577-4323 Australia 1-800-823-405 Belgium 0800-266-65 Canada 1-855-577-4323 China 800-720-1170 France 08-05-08-05-62 Germany 0800-180-0882 Italy 800-878-295 Japan 0800-170-5464 Netherlands 0-800-022-2961 New Zealand 0800-003210 South Africa 0-800-980-818 United Kingdom 0800-520-0439 Contacting Technical Support The Rocket Customer Portal is the primary method of obtaining support. If you have current support and maintenance agreements with Rocket Software, you can access the Rocket Customer Portal and report a problem, download an update, or find answers to in the U2 Knowledgebase. To log in to the Rocket Customer Portal or to request a Rocket Customer Portal account, go to www.rocketsoftware.com/support. In addition to using the Rocket Customer Portal to obtain support, you can send an email to [email protected] or use one of the following telephone numbers. Country Telephone number North America +1 800 729 3553 United Kingdom/France +44 (0) 800 773 771 or +44 (0) 20 8867 3691 Europe/Africa +44 (0) 20 8867 3692 Australia +1 800 707 703 or +61 (0) 29412 5450 New Zealand +0800 505 515 3 Contents Notices................................................................................................................................................................................... 2 Corporate information......................................................................................................................................................... 3 Chapter 1: UniBasic commands and functions................................................................................................................ 14 Elements of syntax statements............................................................................................................................. 14 !.................................................................................................................................................................................14 #................................................................................................................................................................................14 #<..............................................................................................................................................................................14 #>..............................................................................................................................................................................14 $BASICTYPE............................................................................................................................................................. 15 $DEFINE................................................................................................................................................................... 15 $IFDEF...................................................................................................................................................................... 16 $IFNDEF................................................................................................................................................................... 17 $INCLUDE.................................................................................................................................................................18 $INSERT................................................................................................................................................................... 19 $UNDEFINE.............................................................................................................................................................. 19 &............................................................................................................................................................................... 19 *................................................................................................................................................................................ 19 **.............................................................................................................................................................................. 20 *=.............................................................................................................................................................................. 20 +................................................................................................................................................................................20 +=..............................................................................................................................................................................21 -................................................................................................................................................................................ 21 -=.............................................................................................................................................................................. 22 /................................................................................................................................................................................ 22 /=.............................................................................................................................................................................. 23 :.................................................................................................................................................................................23 ^................................................................................................................................................................................23 :=...............................................................................................................................................................................24 <................................................................................................................................................................................24 <=..............................................................................................................................................................................24 <>..............................................................................................................................................................................25 =................................................................................................................................................................................25 =>..............................................................................................................................................................................25 =<..............................................................................................................................................................................25 ><..............................................................................................................................................................................25 >................................................................................................................................................................................26 >=..............................................................................................................................................................................26 @.............................................................................................................................................................................. 26 []............................................................................................................................................................................... 29 {}............................................................................................................................................................................... 30 ABORT...................................................................................................................................................................... 31 ABS........................................................................................................................................................................... 32 acceptConnection................................................................................................................................................... 32 ACOS........................................................................................................................................................................ 33 ACTIVATEKEY........................................................................................................................................................... 34 addAuthenticationRule...........................................................................................................................................35 addCertificate..........................................................................................................................................................36 addRequestParameter............................................................................................................................................37 ALPHA...................................................................................................................................................................... 38 amInitialize.............................................................................................................................................................. 38 amReceiveMsg.........................................................................................................................................................39 4 Contents amReceiveRequest..................................................................................................................................................40 amSendMsg............................................................................................................................................................. 41 amSendRequest...................................................................................................................................................... 42 amSendResponse................................................................................................................................................... 43 amTerminate...........................................................................................................................................................44 analyzeCertificate................................................................................................................................................... 45 AND.......................................................................................................................................................................... 45 ASCII......................................................................................................................................................................... 46 ASIN..........................................................................................................................................................................46 ASSIGN..................................................................................................................................................................... 47 ATAN.........................................................................................................................................................................47 BITAND.....................................................................................................................................................................48 BITNOT.....................................................................................................................................................................49 BITOR....................................................................................................................................................................... 49 BITXOR..................................................................................................................................................................... 50 BPIOCP.....................................................................................................................................................................50 BPIOCPN.................................................................................................................................................................. 51 BREAK...................................................................................................................................................................... 52 BYTELEN.................................................................................................................................................................. 53 CALCULATE.............................................................................................................................................................. 53 CALL......................................................................................................................................................................... 54 CALLC....................................................................................................................................................................... 56 CASE......................................................................................................................................................................... 57 CAT........................................................................................................................................................................... 59 CATS......................................................................................................................................................................... 60 CHAIN....................................................................................................................................................................... 60 CHANGE................................................................................................................................................................... 61 CHAR........................................................................................................................................................................ 61 CHARLEN..................................................................................................................................................................62 CHARS...................................................................................................................................................................... 63 CHECKSUM.............................................................................................................................................................. 63 CLEAR.......................................................................................................................................................................64 CLEARCOMMON.......................................................................................................................................................64 CLEARDATA..............................................................................................................................................................65 CLEARFILE................................................................................................................................................................66 CLEARINPUT............................................................................................................................................................ 67 CLEARSELECT.......................................................................................................................................................... 67 CLEARSQL................................................................................................................................................................ 68 CLOSE.......................................................................................................................................................................68 CLOSESEQ................................................................................................................................................................69 closeSocket............................................................................................................................................................. 70 CLOSEXMLDATA.......................................................................................................................................................70 COL1.........................................................................................................................................................................71 COL2.........................................................................................................................................................................71 COMMON..................................................................................................................................................................72 CONTINUE................................................................................................................................................................74 CONVERT................................................................................................................................................................. 75 CONVERT................................................................................................................................................................. 76 COS...........................................................................................................................................................................77 COUNT..................................................................................................................................................................... 77 COUNTS................................................................................................................................................................... 78 createCertificate......................................................................................................................................................79 createCertRequest.................................................................................................................................................. 80 createRequest......................................................................................................................................................... 82 createSecureRequest..............................................................................................................................................83 createSecurityContext............................................................................................................................................ 85 5 Contents CRT........................................................................................................................................................................... 86 DATA.........................................................................................................................................................................86 DATE.........................................................................................................................................................................87 DBTOXML................................................................................................................................................................. 87 DCOUNT................................................................................................................................................................... 88 DEACTIVATEKEY.......................................................................................................................................................89 DEBUG......................................................................................................................................................................90 DEFFUN.................................................................................................................................................................... 91 DEL........................................................................................................................................................................... 92 DELETE.....................................................................................................................................................................93 DELETE.....................................................................................................................................................................95 DELETELIST............................................................................................................................................................. 96 DELETEU.................................................................................................................................................................. 96 DIM........................................................................................................................................................................... 97 DIGEST..................................................................................................................................................................... 99 DIR..........................................................................................................................................................................100 DISABLEDEC...........................................................................................................................................................101 DISPLAY..................................................................................................................................................................102 DISPLAYWIDTH...................................................................................................................................................... 102 DOWNCASE............................................................................................................................................................ 102 DQUOTE................................................................................................................................................................. 103 DROUND.................................................................................................................................................................103 EBCDIC................................................................................................................................................................... 104 ECHO...................................................................................................................................................................... 104 ENABLEDEC........................................................................................................................................................... 105 ENCODE................................................................................................................................................................. 106 ENCRYPT................................................................................................................................................................ 107 END.........................................................................................................................................................................109 ENTER.................................................................................................................................................................... 109 EQ........................................................................................................................................................................... 110 EQS.........................................................................................................................................................................111 EQU........................................................................................................................................................................ 111 EREPLACE.............................................................................................................................................................. 113 EXECUTE................................................................................................................................................................ 114 EXECUTESQL......................................................................................................................................................... 116 EXIT........................................................................................................................................................................ 119 EXP......................................................................................................................................................................... 119 EXTRACT................................................................................................................................................................ 120 FIELD...................................................................................................................................................................... 121 FIELDSTORE...........................................................................................................................................................122 FILEINFO................................................................................................................................................................ 123 FILELOCK............................................................................................................................................................... 126 FILEUNLOCK.......................................................................................................................................................... 127 FIND........................................................................................................................................................................128 FINDSTR................................................................................................................................................................. 129 FLUSH.................................................................................................................................................................... 130 FMT.........................................................................................................................................................................131 FOOTING................................................................................................................................................................ 133 FORMLIST.............................................................................................................................................................. 134 FOR/NEXT.............................................................................................................................................................. 135 FUNCTION..............................................................................................................................................................137 GARBAGECOLLECT................................................................................................................................................ 138 GE........................................................................................................................................................................... 138 generateKey.......................................................................................................................................................... 139 GES......................................................................................................................................................................... 140 GET......................................................................................................................................................................... 141 6 Contents getCipherSuite.......................................................................................................................................................142 GETENV.................................................................................................................................................................. 143 getHTTPDefault.....................................................................................................................................................143 getIpv..................................................................................................................................................................... 144 GETLIST..................................................................................................................................................................145 GETPTR.................................................................................................................................................................. 146 GETPU.................................................................................................................................................................... 147 GETQUEUE.............................................................................................................................................................147 GETREADU............................................................................................................................................................. 148 getResponseHeader..............................................................................................................................................149 getSocketInformation...........................................................................................................................................150 getSocketOptions..................................................................................................................................................151 GETUSERGROUP................................................................................................................................................... 152 GETUSERID............................................................................................................................................................ 152 GETUSERNAME...................................................................................................................................................... 153 GOSUB................................................................................................................................................................... 153 GOTO......................................................................................................................................................................154 GROUP................................................................................................................................................................... 155 GROUPSTORE........................................................................................................................................................156 GT........................................................................................................................................................................... 158 GTS......................................................................................................................................................................... 158 HASH...................................................................................................................................................................... 159 HEADING................................................................................................................................................................ 160 HUSH......................................................................................................................................................................161 ICONV..................................................................................................................................................................... 162 ICONV Date (D)......................................................................................................................................................164 ICONV Group (G)................................................................................................................................................... 167 ICONV Length (L)...................................................................................................................................................167 ICONV Masked Character (MC).............................................................................................................................168 ICONV Masked Decimal (MD)............................................................................................................................... 169 ICONV Left Justify (ML).........................................................................................................................................170 ICONV Packed Decimal (MP)................................................................................................................................171 ICONV Packed Decimal (MP1).............................................................................................................................. 172 ICONV Right Justify (MR)......................................................................................................................................172 ICONV Time (MT)...................................................................................................................................................173 ICONV Hex (MX | HEX), Octal (MO), Binary (MB)..................................................................................................174 ICONV Pattern Match (P)......................................................................................................................................176 ICONV Range (R)................................................................................................................................................... 176 ICONV SOUNDEX (S)............................................................................................................................................. 177 ICONV Text Extraction (T).................................................................................................................................... 177 ICONV File Translation (Tfile)...............................................................................................................................178 ICONVS...................................................................................................................................................................178 IF/THEN/ELSE........................................................................................................................................................ 179 IN............................................................................................................................................................................ 181 INDEX..................................................................................................................................................................... 181 INDICES.................................................................................................................................................................. 182 initSecureServerSocket function......................................................................................................................... 183 initServerSocket....................................................................................................................................................184 INMAT.....................................................................................................................................................................184 INPUT..................................................................................................................................................................... 186 INPUT @................................................................................................................................................................ 188 INPUTCLEAR.......................................................................................................................................................... 190 INPUTERR.............................................................................................................................................................. 190 INPUTIF.................................................................................................................................................................. 191 INPUTNULL............................................................................................................................................................191 INPUTTRAP............................................................................................................................................................ 192 7 Contents INS..........................................................................................................................................................................193 INSERT................................................................................................................................................................... 194 INT..........................................................................................................................................................................195 ISMB....................................................................................................................................................................... 195 ISNV........................................................................................................................................................................195 ISNVS......................................................................................................................................................................196 ITYPE...................................................................................................................................................................... 197 LE............................................................................................................................................................................199 LEN......................................................................................................................................................................... 199 LENS.......................................................................................................................................................................200 LES......................................................................................................................................................................... 201 LISTUSER............................................................................................................................................................... 201 LN........................................................................................................................................................................... 202 loadSecurityContext............................................................................................................................................. 202 LOCATE.................................................................................................................................................................. 203 LOCK...................................................................................................................................................................... 206 LOOP/REPEAT....................................................................................................................................................... 207 LOWER................................................................................................................................................................... 209 LT............................................................................................................................................................................210 LTS......................................................................................................................................................................... 211 MAT........................................................................................................................................................................ 211 MATBUILD.............................................................................................................................................................. 212 MATCH....................................................................................................................................................................214 MATCHFIELD.......................................................................................................................................................... 215 MATPARSE............................................................................................................................................................. 216 MATREAD............................................................................................................................................................... 217 MATREADL............................................................................................................................................................. 219 MATREADU.............................................................................................................................................................220 MATWRITE..............................................................................................................................................................222 MATWRITEU........................................................................................................................................................... 224 MAXIMUM............................................................................................................................................................... 225 MBLEN....................................................................................................................................................................226 MDPERFORM..........................................................................................................................................................226 MINIMUM................................................................................................................................................................228 MOD........................................................................................................................................................................229 NE........................................................................................................................................................................... 230 NEG........................................................................................................................................................................ 230 NES.........................................................................................................................................................................231 NFAUSER................................................................................................................................................................231 NOCONVERT.......................................................................................................................................................... 232 NOT........................................................................................................................................................................ 232 NOTS...................................................................................................................................................................... 233 NULL.......................................................................................................................................................................233 NUM........................................................................................................................................................................234 NUMS..................................................................................................................................................................... 234 OCONV................................................................................................................................................................... 235 OCONV byte level (CB)..........................................................................................................................................237 OCONV Date (D).................................................................................................................................................... 237 OCONV Group (G)..................................................................................................................................................239 OCONV Length (L)................................................................................................................................................. 240 OCONV Masked Character (MC)........................................................................................................................... 241 OCONV Masked Decimal (MD)..............................................................................................................................242 OCONV Left Justify (ML)....................................................................................................................................... 244 OCONV Packed Decimal (MP).............................................................................................................................. 245 OCONV Packed Decimal (MP1)............................................................................................................................ 246 OCONV Right Justify (MR).................................................................................................................................... 246 8 Contents OCONV Time (MT)................................................................................................................................................. 248 OCONV Hex (MX | HEX), Octal (MO), Binary (MB)................................................................................................ 249 OCONV Pattern Match (P).................................................................................................................................... 250 OCONV Range (R)..................................................................................................................................................251 OCONV SOUNDEX (S)............................................................................................................................................252 OCONV Text Extraction (T)...................................................................................................................................252 OCONV File Translation (Tfile)............................................................................................................................. 253 OCONVS................................................................................................................................................................. 254 ON/GOSUB.............................................................................................................................................................255 ON/GOTO............................................................................................................................................................... 256 OPEN...................................................................................................................................................................... 257 openSecureSocket function.................................................................................................................................259 OPENSEQ............................................................................................................................................................... 260 openSocket............................................................................................................................................................262 OPENXMLDATA...................................................................................................................................................... 263 OR...........................................................................................................................................................................264 OSBREAD............................................................................................................................................................... 264 OSBWRITE..............................................................................................................................................................266 OSCLOSE................................................................................................................................................................268 OSDELETE.............................................................................................................................................................. 269 OSOPEN................................................................................................................................................................. 270 OSREAD..................................................................................................................................................................271 OSWRITE................................................................................................................................................................ 272 PAGE.......................................................................................................................................................................273 PAUSE.................................................................................................................................................................... 274 PCPERFORM.......................................................................................................................................................... 275 PERFORM............................................................................................................................................................... 276 PRECISION............................................................................................................................................................. 276 PREPAREXML......................................................................................................................................................... 276 PRINT..................................................................................................................................................................... 277 PRINTER.................................................................................................................................................................279 PRINTER CLOSE.................................................................................................................................................... 279 PRINTERR.............................................................................................................................................................. 280 PROCREAD............................................................................................................................................................. 282 PROCWRITE........................................................................................................................................................... 284 PROGRAM.............................................................................................................................................................. 285 PROMPT................................................................................................................................................................. 285 protocolLogging.................................................................................................................................................... 286 PWR........................................................................................................................................................................287 QUOTE................................................................................................................................................................... 287 RAISE......................................................................................................................................................................288 READ.......................................................................................................................................................................288 READBCK................................................................................................................................................................290 READBCKL..............................................................................................................................................................291 READBCKU............................................................................................................................................................. 293 READFWD............................................................................................................................................................... 295 READFWDL............................................................................................................................................................. 297 READFWDU............................................................................................................................................................ 299 READL.....................................................................................................................................................................301 READLIST............................................................................................................................................................... 303 READNEXT..............................................................................................................................................................304 READNEXTTUPLE...................................................................................................................................................306 READSELECT..........................................................................................................................................................307 READSEQ................................................................................................................................................................308 readSocket.............................................................................................................................................................308 READT.................................................................................................................................................................... 309 9 Contents READU.................................................................................................................................................................... 311 READV.....................................................................................................................................................................313 READVL...................................................................................................................................................................314 READVU.................................................................................................................................................................. 316 READXBCK..............................................................................................................................................................317 READXFWD............................................................................................................................................................. 318 READXMLDATA.......................................................................................................................................................319 RECORDLOCKED....................................................................................................................................................320 RECORDLOCKL...................................................................................................................................................... 321 RECORDLOCKU......................................................................................................................................................322 RELEASE.................................................................................................................................................................323 RELEASEXML..........................................................................................................................................................324 REM........................................................................................................................................................................ 325 REMOVE................................................................................................................................................................. 325 REMOVE................................................................................................................................................................. 328 REPLACE................................................................................................................................................................ 329 RESIZET..................................................................................................................................................................331 RETURN..................................................................................................................................................................332 REUSE.................................................................................................................................................................... 332 REWIND.................................................................................................................................................................. 333 RND........................................................................................................................................................................ 334 RNDSEED............................................................................................................................................................... 335 RQM........................................................................................................................................................................335 SADD...................................................................................................................................................................... 335 saveSecurityContext............................................................................................................................................. 336 SCMP...................................................................................................................................................................... 337 SDIV........................................................................................................................................................................ 337 SELECT................................................................................................................................................................... 338 SELECTINDEX.........................................................................................................................................................340 SELECTINFO...........................................................................................................................................................342 SEND...................................................................................................................................................................... 342 SEQ.........................................................................................................................................................................344 SEQS.......................................................................................................................................................................344 setAuthenticationDepth....................................................................................................................................... 344 setCipherSuite....................................................................................................................................................... 345 setClientAuthentication........................................................................................................................................346 SETENV.................................................................................................................................................................. 347 setHTTPDefault..................................................................................................................................................... 347 setIpv..................................................................................................................................................................... 349 SETINDEX............................................................................................................................................................... 349 setPrivateKey........................................................................................................................................................ 352 setRandomSeed.................................................................................................................................................... 353 setRequestHeader.................................................................................................................................................354 setSocketOptions..................................................................................................................................................355 showSecurityContext............................................................................................................................................356 SIGNATURE............................................................................................................................................................ 357 SIN..........................................................................................................................................................................358 SLEEP..................................................................................................................................................................... 359 SMUL...................................................................................................................................................................... 360 SOAPCreateRequest..............................................................................................................................................360 SOAPCreateSecureRequest.................................................................................................................................. 361 SOAPGetDefault.................................................................................................................................................... 362 SOAPGetFault........................................................................................................................................................ 363 SOAPGetResponseHeader.................................................................................................................................... 364 SOAPRequestWrite................................................................................................................................................365 SOAPSetDefault.....................................................................................................................................................366 10 Contents SOAPSetParameters............................................................................................................................................. 367 SOAPSetRequestBody.......................................................................................................................................... 368 SOAPSetRequestContent......................................................................................................................................368 SOAPSetRequestHeader.......................................................................................................................................369 SOAPSubmitRequest............................................................................................................................................ 370 SORT...................................................................................................................................................................... 371 SOUNDEX............................................................................................................................................................... 371 SPACE.....................................................................................................................................................................372 SPACES.................................................................................................................................................................. 373 SPLICE....................................................................................................................................................................373 SQLAllocConnect...................................................................................................................................................374 SQLAllocEnv.......................................................................................................................................................... 375 SQLAllocStmt........................................................................................................................................................ 376 SQLBindCol............................................................................................................................................................376 SQLBindParameter............................................................................................................................................... 378 SQLCancel..............................................................................................................................................................380 SQLColAttributes...................................................................................................................................................380 SQLColumns.......................................................................................................................................................... 382 SQLConnect...........................................................................................................................................................384 SQLDescribeCol.....................................................................................................................................................385 SQLDisconnect...................................................................................................................................................... 386 SQLError................................................................................................................................................................ 387 SQLExecDirect....................................................................................................................................................... 388 SQLExecute............................................................................................................................................................390 SQLFetch................................................................................................................................................................391 SQLFreeConnect....................................................................................................................................................392 SQLFreeEnv........................................................................................................................................................... 392 SQLFreeStmt......................................................................................................................................................... 393 SQLGetInfo............................................................................................................................................................ 394 SQLGetTypeInfo.................................................................................................................................................... 396 SQLNumParams.................................................................................................................................................... 399 SQLNumResultCols............................................................................................................................................... 400 SQLParamOptions................................................................................................................................................ 400 SQLPrepare............................................................................................................................................................402 SQLRowCount....................................................................................................................................................... 403 SQLSetConnectOption..........................................................................................................................................404 SQLSetParam........................................................................................................................................................ 406 SQLSpecialColumns..............................................................................................................................................406 SQLStatistics......................................................................................................................................................... 409 SQLTables..............................................................................................................................................................412 SQLTransact.......................................................................................................................................................... 413 SQRT...................................................................................................................................................................... 415 SQUOTE................................................................................................................................................................. 415 SSUB...................................................................................................................................................................... 416 STATUS.................................................................................................................................................................. 416 STOP...................................................................................................................................................................... 417 STR......................................................................................................................................................................... 418 STRS....................................................................................................................................................................... 418 submitRequest...................................................................................................................................................... 419 SUBROUTINE......................................................................................................................................................... 420 SUBROUTINE (Update Trigger)............................................................................................................................ 422 SUBROUTINE (Delete Trigger)..............................................................................................................................424 SUBSTRINGS..........................................................................................................................................................426 SUM........................................................................................................................................................................ 427 SWAP......................................................................................................................................................................427 SYSTEM.................................................................................................................................................................. 429 11 Contents TAN.........................................................................................................................................................................432 TIME....................................................................................................................................................................... 432 TIMEDATE...............................................................................................................................................................433 TRANSACTION ABORT.......................................................................................................................................... 433 TRANSACTION COMMIT........................................................................................................................................ 434 TRANSACTION START........................................................................................................................................... 435 TRIM....................................................................................................................................................................... 436 TRIMB.....................................................................................................................................................................438 TRIMF..................................................................................................................................................................... 438 TRIMS..................................................................................................................................................................... 439 UDOArrayAppendItem.......................................................................................................................................... 440 UDOArrayDeleteItem............................................................................................................................................ 440 UDOArrayGetItem................................................................................................................................................. 441 UDOArrayGetNextItem..........................................................................................................................................441 UDOArrayGetSize.................................................................................................................................................. 442 UDOArrayInsertItem..............................................................................................................................................442 UDOArraySetItem..................................................................................................................................................443 UDOClone.............................................................................................................................................................. 443 UDOCreate.............................................................................................................................................................444 UDODeleteProperty.............................................................................................................................................. 444 UDOFree.................................................................................................................................................................445 UDOGetLastError...................................................................................................................................................445 UDOGetNextProperty............................................................................................................................................445 UDOGetOption.......................................................................................................................................................446 UDOGetProperty................................................................................................................................................... 446 UDOGetPropertyNames........................................................................................................................................447 UDOGetType..........................................................................................................................................................448 UDOIsTypeOf......................................................................................................................................................... 448 UDORead............................................................................................................................................................... 448 UDOSetOption.......................................................................................................................................................449 UDOSetProperty....................................................................................................................................................449 UDOWrite............................................................................................................................................................... 450 UDTEXECUTE......................................................................................................................................................... 450 UNASSIGNED......................................................................................................................................................... 451 UNLOCK................................................................................................................................................................. 452 UPCASE.................................................................................................................................................................. 452 WAKE...................................................................................................................................................................... 453 WEOF......................................................................................................................................................................454 WEOFSEQ...............................................................................................................................................................455 WRITE.....................................................................................................................................................................456 WRITELIST..............................................................................................................................................................458 WRITESEQ.............................................................................................................................................................. 458 WRITESEQF............................................................................................................................................................ 459 writeSocket............................................................................................................................................................460 WRITET...................................................................................................................................................................461 WRITEU.................................................................................................................................................................. 463 WRITEV...................................................................................................................................................................465 WRITEVU................................................................................................................................................................ 467 XDOMAddChild...................................................................................................................................................... 468 XDOMAppend.........................................................................................................................................................469 XDOMClone............................................................................................................................................................470 XDOMClose............................................................................................................................................................ 471 XDOMCreateNode................................................................................................................................................. 472 XDOMCreateRoot.................................................................................................................................................. 474 XDOMEvaluate....................................................................................................................................................... 475 XDOMGetAttribute.................................................................................................................................................476 12 Contents XDOMGetChildNodes............................................................................................................................................ 477 XDOMGetElementById.......................................................................................................................................... 477 XDOMGetElementsByName..................................................................................................................................478 XDOMGetElementsByTag......................................................................................................................................479 XDOMGetNodeName.............................................................................................................................................480 XDOMGetNodeType.............................................................................................................................................. 481 XDOMGetNodeValue............................................................................................................................................. 482 XDOMGetOwnerDocument................................................................................................................................... 482 XDOMGetUserData................................................................................................................................................ 483 XDOMImportNode................................................................................................................................................. 484 XDOMInsert............................................................................................................................................................485 XDOMItem..............................................................................................................................................................486 XDOMLength..........................................................................................................................................................488 XDOMLocate.......................................................................................................................................................... 488 XDOMLocateNode................................................................................................................................................. 489 XDOMOpen............................................................................................................................................................ 491 XDOMRemove........................................................................................................................................................492 XDOMReplace........................................................................................................................................................ 493 XDOMSetNodeValue..............................................................................................................................................494 XDOMSetUserData................................................................................................................................................ 495 XDOMTransform.................................................................................................................................................... 496 XDOMValidate........................................................................................................................................................497 XDOMValidateDom................................................................................................................................................498 XDOMWrite.............................................................................................................................................................498 XLATE..................................................................................................................................................................... 500 XMAPAppendRec................................................................................................................................................... 500 XMAPClose............................................................................................................................................................. 501 XMAPCreate........................................................................................................................................................... 502 XMAPOpen............................................................................................................................................................. 502 XMAPReadNext......................................................................................................................................................503 XMAPToXMLDoc.................................................................................................................................................... 504 XMLError................................................................................................................................................................ 505 XMLExecute........................................................................................................................................................... 505 XMLGetError.......................................................................................................................................................... 508 XMLGetOptions......................................................................................................................................................509 XMLGetOptionValue.............................................................................................................................................. 510 XMLSetOptions...................................................................................................................................................... 510 XMLTODB............................................................................................................................................................... 511 Appendix A: ASCII character codes..................................................................................................................................513 Appendix B: UniBasic@variables..................................................................................................................................... 520 @variables............................................................................................................................................................. 520 Delimiter @variables............................................................................................................................................ 522 @SYSTEM.RETURN.CODE values......................................................................................................................... 522 Appendix C: Operators in UniBasic................................................................................................................................. 525 Arithmetic operators............................................................................................................................................ 525 Boolean operators................................................................................................................................................ 525 Relational operators.............................................................................................................................................526 Appendix D: Reserved words........................................................................................................................................... 527 Appendix E: Commands affected by BASICTYPEs and UDT.OPTIONS.......................................................................... 533 Appendix F: Commands that set STATUS() return values............................................................................................. 537 13 Chapter 1: UniBasic commands and functions This section contains a detailed alphabetic listing of UniBasic commands, functions, and operators that include descriptions and working examples. Functions perform specialized operations that augment and enhance commands. You always use functions as expressions or in expressions following a command. Elements of syntax statements This reference manual uses a common method to present syntax for Rocket UniData commands. The syntax statement includes the command name, required arguments, and options you can use with the command. Italics represents a variable you can replace with any valid option. ! ! is a synonym for the * and REM commands, which you can use to create comments. It also is a synonym for the OR operator. For information about creating comments, see REM. For information about the OR operator, see OR, on page 264. Synonyms *, REM, OR # # is a synonym for the NE relational operator. For more information, see NE, on page 230. Synonyms <>, ><, NE #< #< is a synonym for the GE relational operator. For more information, see GE, on page 138. Synonyms <=, >=, GE #> #> is a synonym for the LE relational operator. 14 $BASICTYPE For more information, see LE, on page 199. Synonyms >=, =<, LE $BASICTYPE The UniBasic $BASICTYPE command compiles data in a specified BASICTYPE. The $BASICTYPE statement must be the first noncomment statement in the program or subroutine. You can include only one $BASICTYPE statement per file (main program or subroutine), but you can split a program into separately cataloged subroutines for the purpose of changing BASICTYPE. If you do not specify $BASICTYPE, UniData compiles the program in the BASICTYPE specified in the ECL BASICTYPE command. The default type is U. Note: The BASICTYPE param must be in quotation marks. Syntax $BASICTYPE "param" Parameters The following table describes each parameter of the syntax. Parameter Description U UniBasic P Pick BASIC R Advanced Revelation BASIC M McDonnell Douglas BASIC/ Reality BASIC Related commands Language Command UniData BASICTYPE For information, see the UniData Commands Reference. $DEFINE The UniBasic $DEFINE command defines a control variable you can use later to direct compilation. Tip: Keep $DEFINE statements in a separate INCLUDE file to facilitate recompiling programs with different definitions. Syntax $DEFINE var 15 Chapter 1: UniBasic commands and functions Examples In the following example, SMALL is defined when the program segment is compiled, and UniData defines array1 as a 10-element array initialized with 0: $DEFINE SMALL $IFDEF SMALL DIM array1(10) MAT array1 = 0 $ENDIF Related commands Language Command UniBasic $UNDEFINE, EQU $IFDEF The UniBasic $IFDEF command conditionally compiles UniBasic statements depending on the existence of a variable definition. Variables are defined by $DEFINE. Syntax $IFDEF var statements1 [$ELSE statements2] $ENDIF The following table describes each parameter of the syntax. Parameter Description var Specifies variable to check to determine whether to compile statements1 or statements2. statements1 Specifies statements to compile if var is defined. statements2 Specifies optional statements to compile if var is not defined. Examples In the following example, when you compile the program segment, the system defines array1 as a 10element array initialized with 0: $DEFINE SMALL $IFDEF SMALL DIM array1(10) MAT array1 = 0 $ENDIF In the next example, when you compile the program segment, the system defines array1 as a 100element array and initializes it with 1: $UNDEFINE SMALL $IFDEF SMALL PRINT 'SMALL was defined' $ELSE DIM array1(100) MAT array1 = 1 16 $IFNDEF $ENDIF Related commands Language Command UniBasic $DEFINE, $IFNDEF $IFNDEF The UniBasic $IFNDEF command conditionally compiles UniBasic statements depending on the absence of a variable definition. Variables are defined by $DEFINE. Syntax $IFNDEF var statements1 [$ELSE statements2] $ENDIF Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies variable to check to determine whether to compile statements1 or statements2. statements1 Specifies statements to compile if var is defined. statements2 Specifies optional statements to compile if var is not defined. Examples In the following example, the program segment nests the $IFDEF and $IFNDEF statements. Upon compilation of this program, the size of array A might be 1000, 10, or 100 depending on whether LARGE or SMALL is defined. If both are undefined, the size of A is 100 elements, and the initialized value of array A might be 1 or 0, depending on whether ONE is defined. $IFDEF LARGE DIM A(1000) $IFDEF ONE MAT A = 1 $ELSE MAT A = 0 $ENDIF $ELSE $IFNDEF SMALL DIM A(100) $ELSE DIM A(10) $ENDIF $IFDEF ONE MAT A = 1 $ELSE MAT A = 0 $ENDIF $ENDIF 17 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic $DEFINE, $IFNDEF $INCLUDE The UniBasic $INCLUDE and $INSERT commands insert UniBasic source code from the file you specify into the program being compiled. The third form of the syntax inserts code from a UNIX, or Windows platform sequential file. Note: In $BASICTYPEs P and M, you can enter $INCLUDE or INCLUDE. Syntax $INCLUDE record [FROM [DICT] filename] $INCLUDE filename {, | | > } record $INCLUDE [pathname {, | | > }] seq.filename Synonyms $INSERT Parameters The following table describes each parameter of the syntax. Parameter Description record Specifies the record that contains the code you want to insert. filename Specifies the name of a UniData directory containing the record. If you do not specify filename, the system searches for record in the current file where the program being compiled resides. pathname Specifies the directory containing seq.filename. If you do not specify pathname, the system searches for seq.filename in the current directory. The delimiter between the path and the file or record can be a space, comma (,) or a greater than sign (>). seq.filename Specifies the name of an operating system sequential file. Note: filename can identify a remote file as determined by the VOC entry. The code to be inserted can also contain $INCLUDE or $INSERT statements. Examples In the following example, the program statement inserts into the program being compiled the code contained in file code_seg1 in directory BP: $INCLUDE code_seg1 FROM BP The next example demonstrates the use of the $INCLUDE command in UniData for UNIX. The program statement inserts into the program being compiled the code contained in sequential file my_code in directory /usr/ud/mydir: 18 $INSERT $INCLUDE /usr/ud/mydir/my_code $INSERT $INSERT is a synonym for the $INCLUDE command. For more information, see $INCLUDE, on page 18. Synonyms $INCLUDE $UNDEFINE The UniBasic $UNDEFINE command deletes the definition of var previously defined by $DEFINE. Syntax $UNDEFINE var Related commands Language Command UniBasic $DEFINE, EQU & & is a synonym for the AND Boolean operator. For more information, see AND, on page 45. Synonyms AND * The * arithmetic operator multiplies the expressions on either side of the operator. The asterisk (*) also is a synonym for the ! and REM commands, which you can use to create comments. For information about creating comments, see REM, on page 325. Note: You must include the REUSE function to apply arithmetic operations to all elements of a dynamic array. Syntax expr * expr 19 Chapter 1: UniBasic commands and functions Synonyms !, REM Examples The following program segment uses the * operator to multiply VAR1 and VAR2: X = VAR1 * VAR2 Related commands Language Command UniBasic REM, SMUL ** ** is a synonym for the ^ arithmetic operator. For more information, see ^, on page 23. Synonyms ^ *= The *= arithmetic operator multiplies the value of a variable by the number you specify. Tip: Using the *= operator is a more efficient way of multiplying a variable. For example, LINES *= 2 is more efficient than LINES = LINES * 2. Note: You must include the REUSE function to apply arithmetic operations to all elements of a dynamic array. Syntax var *= expr Examples In the following example, the variable LINES is multiplied by 2, which sets LINES equal to 14: LINES = 7 LINES *= 2 + In the first version of the syntax, the + arithmetic operator adds the two numbers on either side of the operator. 20 += In the second version of the syntax, + acts as a unary plus operator (same as multiplying by +1). Syntax expr + expr +expr Examples The following program segment is taken from the sample program in Developing UniBasic Applications. The third statement places the cursor at the location computed by 9+ENTRY, then the program displays the seventh element of the array ORDER.REC at that location. FOR ENTRY = 1 TO NUM_ENTRIES NEW.PRICE = "" DISPLAY @(10,9+ENTRY):OCONV(ORDER.REC<7,ENTRY>,"MR2$,"): INPUT @(45,9+ENTRY):NEW.PRICE NEW.PRICE = OCONV(NEW.PRICE,"MCN") IF NEW.PRICE # '' AND NUM(NEW.PRICE) THEN ORDER.REC<7,ENTRY> = NEW.PRICE NEED.TO.WRITE = 1 END NEXT ENTRY Related commands Language Command UniBasic ABS, NEG, SADD, SUM += The += arithmetic operator increments the value of a variable by the number you specify. Tip: Using the += operator is a more efficient way of incrementing a variable. For example, LINES += 1 is more efficient than LINES = LINES + 1. Syntax var += expr Examples In the following example, the variable LINES is incremented by 1, which sets LINES equal to 8: LINES = 7 LINES += 1 In the first version of the syntax, the - arithmetic operator subtracts the expr on the right from the expr on the left of the operator. 21 Chapter 1: UniBasic commands and functions In the second version of the syntax, - acts as a unary minus operator, which produces the same result as multiplying by -1. Syntax expr -expr -expr Examples In the following example, VAR2 is subtracted from VAR1 and the result is assigned to the variable X: X = VAR1 - VAR2 In the next example, the - operator is used as the unary minus and changes the sign of VAR: VAR = -VAR Related commands Language Command UniBasic ABS, NEG -= The -= arithmetic operator decrements the value of a variable by the number you specify. Tip: Using the -= operator is a more efficient way to decrement a variable. For example, LINES = 1 is more efficient than LINES = LINES -1. Syntax var -= expr Examples In the following example, the variable LINES is decremented by 1, which sets LINES equal to 6: LINES = 7 LINES -= 1 / The / arithmetic operator divides the two numbers on either side of the operator. Syntax expr1 / expr2 Examples The following statement divides price by cost to determine quantity: 22 /= PRICE / COST = QUANTITY Related commands Language Command UniBasic SDIV /= The /= arithmetic operator divides the value of a variable by the number you specify. Tip: Using the /= operator is a more efficient way of dividing a variable. For example, LINES /= 2 is more efficient than LINES = LINES/2. Syntax var /= expr Examples In the following example, the variable LINES is divided by 2, which sets LINES equal to 10: LINES = 20 LINES /= 2 : : is a synonym for the CAT function. For more information, see CAT, on page 59. Synonyms CAT ^ The ^ arithmetic operator raises expr1 to the power of expr2. Syntax expr1^expr2 Synonyms ** 23 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment raises variable X to the power of 3, first using an exponentiation operator **, second using the PWR function, and last using the exponentiation operator ^. The results are identical. X = 2 PRINT X**3 PRINT PWR(X,3) PRINT X^3 Related commands Language Command UniBasic PWR := The := arithmetic operator concatenates the value of an expression to a variable. Tip: Using the := operator is a more efficient way of concatenating a variable. For example, LINES := 0 is more efficient than LINES = LINES CAT 0. Syntax var := expr Examples In the following example, the variable LINES is concatenated with 0, which sets LINES equal to 100: LINES = 10 LINES := 0 < < is a synonym for the LT (less than) relational operator. For more information, see LT, on page 210. Synonyms LT <= <= is a synonym for the LE relational operator. For more information, see LE, on page 199. 24 <> Synonyms #<, =<, LE <> The UniBasic <> function retrieves, inserts, or replaces elements in a dynamic array. It also acts as the not equal to relational operator. For information about retrieving, see EXTRACT, on page 120. For information about inserting and replacing, see REPLACE, on page 329. For information about the not equal to relational operator, see NE, on page 230. Synonyms #, ><, NE = = is a synonym for the EQ relational operator. For more information, see EQ, on page 110. Synonyms EQ => => is a synonym for the GE relational operator. For more information, see GE, on page 138. Synonyms #<, <=, GE =< =< is a synonym for the LE relational operator. For more information, see LE, on page 199. Synonyms #<, <=, LE >< >< is a synonym for NE relational operator. For more information, see NE, on page 230. 25 Chapter 1: UniBasic commands and functions Synonyms #, <>, NE > > is a synonym for the GT relational operator. For more information, see GT, on page 158. Synonyms GT >= >= is a synonym for the GE relational operator. For more information, see GE, on page 138. Synonyms #>,=>, GE @ The UniBasic @ function positions the cursor on the video screen. In the first form, the system positions the cursor at the column and row you specify. In the second form, you can specify various terminal functions by num.expr. Any reference to @ functions turns off automatic screen pagination. Tip: Assign @ functions to variables if you expect to use the @ function more than once. Use the @ function in a PRINT statement to direct the terminal to take some action before printing. Syntax @(col.expr [,row.expr]) @(-num.expr) The following table describes each parameter of the syntax. Parameter Description col.expr Specifies the column position to place the cursor. Can be a literal value or variable. Must be a positive numeric value. Value 0 is the leftmost column on the screen. For most terminals, col.expr can range from 0 to 79 (the right-hand side of the screen). 26 @ Parameter Description ,row.expr Specifies the row at which to place the cursor. Defaults to the current row. Can be either a literal value or variable. Must be a positive value. Value 0 is the top of the screen. For most terminals, row.expr can range from 0 to 23 (the last row on the screen). -num.expr Specifies an @ terminal function. For valid @ terminal functions and their effects, see the next table. Tip: Use PRINT, DISPLAY, and CRT in combination with the UniBasic @ function to position the cursor on the screen before printing or to execute other terminal functions. Execute the ECL REUSE.ROW command to determine whether a line feed is executed when the UniBasic PRINT @ function references column only. For example, PRINT @(10) rather than PRINT @(3,10). @ Function Options The following @ function options direct the terminal to take an action. Option Description -1 Clear screen, home cursor. -2 Home cursor. -3 Clear from cursor to end of screen. -4 Clear from cursor to end of line. -5 Enter blink mode. -6 Stop blink mode. -7 Enter protected mode. -8 Stop protected mode. -9 Backspace one character. -10 Move cursor up one line. -11 Enter half-intensity mode. -12 Stop half-intensity mode. -13 Enter reverse video mode. -14 Stop reverse video mode. -15 Enter underlining mode. -16 Stop underlining mode. -17 Down one line. -18 Nondestructive space (cursor right). -19 Audible signal (bell). -20 Delete character. -21 Insert character. -22 Delete line. -23 Add new blank line. -24 Turn on the printer. -25 Turn off the printer. -26 Print contents of the screen. 27 Chapter 1: UniBasic commands and functions Option Description -27 Start alternate character set. -28 End alternate character set. -29 to -49 Reserved for color combinations. -50 Sent by the backspace key. -51 Sent by the clear screen or erase key. -52 Sent by the delete character key. -53 Sent by the insert character key. -54 Sent by the delete line key. -55 Sent by the insert line key. -56 Sent by the home key. -57 Sent by the left arrow key. -58 Sent by the up arrow key. -59 Sent by the down arrow key. -60 Sent by the right arrow key. -61 Sent by the clear-to-end-of-line key. -62 Sent by the clear-to-end-of-screen key. -63 Sent by function key F0. -64 Sent by function key F1. -65 Sent by function key F2. -66 Sent by function key F3. -67 Sent by function key F4. -68 Sent by function key F5. -69 Sent by function key F6. -70 Sent by function key F7. -71 Sent by function key F8. -72 Sent by function key F9. -73 Sent by function key F10. -74 Sent by the next-page key. -75 Sent by the previous-page key. -76 Sent by the scroll forward/down key. -77 Sent by the scroll backward/up key. -78 Sent by the set-tab key. -79 Sent by the terminal up arrow key. -80 Out of “keypad transmit” key. -81 Turn bold on. -82 Turn bold off. -83 Turn standout on. -84 Turn standout off. Examples In the following example, the statement prints the message HI in the fifth column from the left of the screen and the tenth row down from the top: PRINT @(5,10):"HI" 28 [] In the next example, the program segment prints two messages at different points on the screen: ROW = 0 ; COL = 0 PRINT @(COL,ROW):"TOP":@(COL,ROW+21):"BOTTOM" In the next example, the program segment initiates reverse video mode, prints a prompt, and then stops reverse video mode: PRINT @(-13) PRINT "ENTER NAME:": PRINT @(-14) In the next example, the program segment clears the screen and places the cursor in the home position (0,0): CLS = @(-1) PRINT CLS Related commands Language Command UniBasic @variables UniData REUSE.ROW For information, see the UniData Commands Reference. [] The UniBasic [] (square brackets) function extracts or replaces strings. Null value handling With null value handling on, when UniBasic encounters the null value in a command parameter where a number is expected (num.expr1, num.expr2), it displays a warning message and uses 0. Note: In BASICTYPE M and P, the [] (square brackets) function can remove a substring entirely and can also remove parts of the substring. Syntax string.expr [num.expr1,num.expr2] = expr expr = string.expr [num.expr1, num.expr2] Parameters The following table describes each parameter of the syntax. Parameter Description string.expr In the first form, the function replaces part or all of string.expr. In the second form, the function extracts part or all of string.expr. 29 Chapter 1: UniBasic commands and functions Parameter Description num.expr1 Indicates the starting position for the operation. It refers to the character position where the replacement or extraction operation occurs. num.expr2 Indicates the number of characters involved in the operation. If UniData performs an extraction, it returns that number of characters. If UniData performs a replacement, it replaces that number of characters. Examples In the following example, the program segment extracts the first character of the variable LAST.NAME (in this case, an S): LAST.NAME = 'Smith' L.INITIAL = LAST.NAME[1,1] In the next example, the program segment changes the first letter of the word Bind in the variable TITLE to W. The resulting string is “Gone with the Wind”. TITLE = 'Gone with the Bind' TITLE[15,1] = 'W' In the next example, the program segment changes the substring 234 spaces: A = "12345" A[2,3] = "" In BASICTYPE U, system output is as follows: A = "1 5" In BASICTYPEs M and P, the substring is extracted as follows: A = "15" The following program inserts the null value into string X, which contains 12345, and then prints this element before and after converting @NULL to the printable string “@NULL”: X=12345 X[3,1]=@NULL PRINT "X[3,1] is printed on the next line." PRINT X[3,1] X = CHANGE(X[3,1], @NULL,"@NULL") PRINT "X[3,1] is printed on the next line." PRINT X This program prints the following text: X[3,1] is printed on the next line. X[3,1] is printed on the next line. @NULL {} {}is a synonym for the CALCULATE function. 30 ABORT For more information, see CALCULATE, on page 53. Synonyms CALCULATE ABORT The UniBasic ABORTcommand terminates the program or subroutine in progress, returning the user to the UniData system level. ABORT returns the user to the UniData prompt, whether the aborted program was called by another program or executed through a UniData menu or paragraph. ABORT can include an optional string exprto display when the program aborts. The expression can contain variables, functions, and/or arithmetic or string operators. The UniBasic commands ABORT and PRINTERR return the system message whose ID you specify in the command. You can also retrieve system messages using a UniBasic program by opening the system message file and reading a message record by ID. Note: ENGLISH.MSG is the default system message file that is activated when you install UniData. If you execute udtlang.config to select a language group, a different system message file could be activated. To find out which language is installed on your system, execute the ECL command SET.LANG CURRENT. For more information, see UniData International. The ABORT command in BASICTYPE P provides additional functions. ABORT prints either a userdefined message specified by the string expr, or a UniData system message identified by message-id: ABORT [message-id] ABORT [expr,...] In the first form of the syntax, the message-id must be a variable that evaluates to a key contained in the UniData message file. If no message exists, the number entered in message-id is returned. In the second form of the above syntax, you can specify more than one expr. Note: You can use the ECL ON.ABORT command so that ABORT does not terminate the process. For information about the ECL ON.ABORT command, see the UniData Commands Reference. Syntax ABORT [expr] Examples In the following program segment, the user is prompted if an error flag ERR.FLAG has been set. The user’s input is read into the variable “answer”. If “answer” equals “Y”, the program aborts. ERR.FLAG = 1 IF ERR.FLAG THEN PRINT "ABORT PROGRAM?" INPUT answer IF ANS = "Y" THEN ABORT ... 31 Chapter 1: UniBasic commands and functions In the next example, in BASICTYPE P, an error message prints and the program terminates when CLIENTS cannot be opened: EID = "Error Message Text." ERR_MSG = "CAN'T OPEN FILE" OPEN "CLIENTS" TO CLIENTS.FILE ELSE ABORT ERR_MSG, EID END In the next example, in BASICTYPE P, the program segment prints the error message from record 10075 in the error message file if the program aborts: $BASICTYPE "P" OPEN 'CLIENTS' TO CLIENT.FILE ELSE STOP "CANNOT OPEN" READ REC FROM CLIENT.FILE, "99" ELSE ABORT 10075 Related commands Language Command UniBasic PRINTERR, STOP UniData ABORT, CLEAR.ONABORT For information, see the UniData Commands Reference. ABS The UniBasic ABS function returns the positive numeric value (absolute value) of the argument. expr can be any numeric expression. Syntax ABS(expr) Examples In the following example, the program segment prints the absolute value of the variable NUM, which is 999: NUM = -999 PRINT ABS(NUM) In the next example, the program statement replaces the variable NUM with its absolute value: NUM = ABS(NUM) Related commands Language Command UniBasic NED acceptConnection Use the acceptConnection function to accept an incoming connection attempt on the server side socket. 32 ACOS Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax acceptConnection(svr_socket, blocking_mode, timeout, in_addr, in_name, socket_handle Parameters The following table describes each parameter of the syntax. Parameter Description svr_socket The handle to the server side socket returned by initServerSocket(). blocking_mode 0 - default (blocking) 1 - blocking. In this mode and the current blocking mode of svr_socket is set to blocking, acceptConnection() blocks the caller until a connection request is received or the specified time_out has expired. 2 - non-blocking. In this mode if there are no pending connections present on the queue, acceptConnection() returns an error status code. In this mode, time_out is ignored. time_out Timeout in milliseconds. in_addr The buffer that receives the address of the incoming connection. If NULL, it will return nothing. in_name The variable that receives the name of the incoming connection. If NULL, it will return nothing. socket_handle The handle to the newly created socket on which the actual connection will be made. The server will use readSocket(), writeSocket(), and so forth, with this handle to communicate with the client. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. ACOS The UniBasic ACOS function returns the trigonometric arc cosine (inverse cosine) of a numeric expression in degrees. expr must be a value between -1 and +1. ACOS returns a value expressed as the degree of the arc cosine of the input, which ranges from 0 to 180. If expr evaluates to a value outside the range of -1 to +1, UniData displays an error message and returns 0 as the result. With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, ACOS returns the null value when expr is the null value. 33 Chapter 1: UniBasic commands and functions Syntax ACOS(expr) Examples In the following example, the program statement assigns 60, the arc cosine of 0.5, to ARCCOS: ARCCOS = ACOS(0.5) In the next example, the program statement prints out the arc cosine of -0.5, which is 120: PRINT ACOS(-0.5) Related commands Language Command UniBasic ASIN, ATAN, COS, SIN, TAN ACTIVATEKEY Use the ACTIVATEKEY command to activate a key or wallet. It is necessary to activate a key if you want to supply a password for key protection. Note: You can activate only keys with password protection with this command. Keys that do not have password protection are automatically activated. Syntax ACTIVATEKEY <key.id>, <password> [ON <NFA_SERVER>] [ON ERROR <statements>] The following table describes each parameter of the syntax. Parameter Description key.id The key ID or wallet ID to activate. If you provide a Wallet ID, UniData activates all keys in the wallet. password The password corresponding to key.id. ON NFA_SERVER The name of the NFA_SERVER on which you want to activate the encryption key. The syntax for NFA_SERVER can be either: ▪ @domain.var where domain.var specifies the ID for a VOC entry that contains the NFA server connection parameters. OR ▪ “MACHINE <host> PORT <port> [, UDTHOME <udthome>]” NFA files are always encrypted and decrypted on the remote machine by the NFA server. ON ERROR statements If you specify ON ERROR statements and an error occurs, UniData executes the statements following the ON ERROR clause. Otherwise, UniData executes the next statement. STATUS codes The ACTIVATEKEY statement returns the following STATUS codes regarding wallet operations: 34 addAuthenticationRule STATUS code Description 0 Operation successful 1 Key is already activated or deactivated. This applies to a single key, not a wallet operation 2 Operation failed. This applies to a single key, not a wallet operation 3 Invalid wallet ID or password 4 No access to wallet 5 Invalid key ID or password 6 No access to one of the keys in the wallet 9 Other error Examples The following example illustrates how to activate an encryption key: ACTIVATEKEY "test","myunidata" ON ERROR PRINT "Unable to activate key" addAuthenticationRule The addAuthenticationRule function adds an authentication rule to a security context. The rules are used during SSL negotiation to determine whether or not the peer is to be trusted. UniData currently supports the following rules: ▪ Verification Strength rule – The rule governs the SSL negotiation and determines whether or not an authentication process is considered successful. There are two levels of security, generous and strict. If you specify generous, the certificate need only contain the subject name (common name) that matches the one you specify by “Peer Name” to be considered valid. If you specify strict, the incoming certificate must pass a number of checks, including signature check, expiry check, purpose check, and issuer check. ▪ PeerName rule – If you specify the PeerName rule and provide common names separated by attributes marks in ruleString, UniData stores trust server/client names in the context. For more information about the addAuthenticationRule function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax addAuthenticationRule(context, serverOrClient, rule, ruleString) Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. ServerOrClient Flag 1 – Server Flag 2 – Client UniData treats any other value as a value of 1. 35 Chapter 1: UniBasic commands and functions Parameter Description Rule The rule name string. Valid settings are PeerName or VerificationStrength. RuleString Rule content string. May be attribute mark separated. The following table describes the status of each return code. Return codes Status 0 Success 1 Invalid Security Context handle 2 Invalid rule name 3 Invalid rule content addCertificate The addCertificate function loads a certificate, or multiple certificates, into a security context for UniData to use as a server or client certificate. Alternatively, this function can specify a directory which contains the certificates that are either used as CA (Certificate Authority) certificates to authenticate incoming certificates, or act as a Revocation list to check against expired or revoked certificates. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. For detailed information about the addCertificate function, see UniBasic Extensions. Syntax addCertificate(certPath, usedAs, format, algorithm, context Parameters The following table describes each parameter of the syntax. Parameter Description certPath A string containing the name of the OS-level file that holds the certificate, or the directory containing certificates. usedAs 1– Used as a client/server certificate. 2 – Used as an issuer certificate. 3 – Used as a Certificate Revocation List (CRL) format 1 – PEM format 2 – DER format algorithm 1 – RSA key 2 – DSA key context The Security context handle. The following table describes the status of each return code. 36 Return codes Status 0 Success addRequestParameter Return codes Status 1 Invalid Security Context handle. 2 Certificate file could not be opened or directory does not exist. 3 Unrecognized format. 4 Corrupted or unrecognized certificate contents. 5 Invalid parameter value(s). addRequestParameter The addRequestParameter function adds a parameter to the request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax addRequestParameter(request_handle, parameter_name, parameter_value, content_handling The following table describes each parameter of the syntax. Parameter Description request_handle The handle to the request. parameter_name The name of the parameter. parameter_value The value of the parameter. content_handling The dynamic MIME type for the parameter value. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid request handle. 2 Invalid parameter. 3 Bad content type. For a GET request, content_handling is ignored. For a POST request with default content type, the default for content_handling is “Content-Type:text/plain” if content_handling is not specified. For a POST request with “Multipart/*” content-type, content_handling is a dynamic array containing Content-* strings separated by field marks (@FM). They will be included in the multipart message before the data contained in parameter_value is sent. An example of content_handling: Content-Type: application/XML @FM Content-Dispostion: attachment; file=”C:\drive\test.dat” @FM Content-Length: 1923 Specifically, for a POST request with content type “multipart/form-data”, a “Content-Dispostion: formdata” header will be created (or, in the case of Content-Dispostion already in content_handling, “formdata” will be added to it). For both a GET and a POST request with either no content type specified or specified as “application/ x-www-form-urlencoded”, as described in createRequest(), URL encoding is performed on data in parameter_value automatically. Basically, any character other than alpha-numeric is considered 37 Chapter 1: UniBasic commands and functions “unsafe” and will be replaced by %HH where HH is the ASCII value of the character in question. For example, ‘#’ is replaced by %23, and ‘/’ is replaced by %2F, etc.. One exception is that by convention, spaces (‘ ‘) are converted into ‘+’. For a POST method with other MIME-type specified, no encoding is done on data contained in parameter_value. ALPHA The UniBasic ALPHA function tests a string to see if it is composed entirely of alphabetic characters. If str.expr is made entirely of alphabetic characters (not special characters, escape sequences, or the null value), the function returns 1. If numeric or other characters are present in str.expr, or if str.expr evaluates to an empty string or the null value, the function returns 0. Because UniBasic does not recognize multibyte characters as alphabetic, ALPHA returns 0 instead of converting them. Syntax ALPHA("str.expr") Examples In the following example, the program statement prints 0 because the literal string contains the numeric character 2: PRINT ALPHA("ABCDEFGHIJK2") In the next example, the program segment prints 1 because the string ALPHA contains only alphabetic characters: ALPHA.T=ALPHA("CORONA") PRINT ALPHA.T In the next example, the program statement prints 0 because the string does not contain any characters. An empty string is not considered to be an alphabetic character. PRINT ALPHA("") amInitialize The amInitialize function creates and opens an AMI session. The output parameter, hsession, is a session handle that is valid until the session is terminated. This function returns a status code indicating success, warning, or failure. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amInitialize(hSession,appName, policyName, reasonCode Parameters The following table describes each parameter of the syntax. 38 amReceiveMsg Parameter Description hSession Upon successful return, holds a handle to a session. You can then use the handle in other UniData WebSphere MQ API calls. [OUT] appName An optional name that you can use to identify the session. [IN] policyName The name of a policy. If you specify ““ (null), UniData uses the system default policy name. [IN] reasonCode Holds an AMI reason code when the function returns a status indicating an AMI warning, or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. 115 – U2AMI_ERR_SESSION_IN_USE An active session already exists (under a different hSession variable than the one being passed in). Other A non-AMI error occurred. amReceiveMsg The amReceiveMsg function receives a message sent by the amSendMsg function. For detailed information about amReceiveMsg, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amReceiveMsg(hSession,receiverName,policyName, selMsgName, maxMsgLen, dataLen, data, rcvMsgName, reasonCode) The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by amInitialize. [IN] receiverName The name of a receiver service. If you do not specify a name, UniData uses the system default receiver name. [IN] policyName The name of a policy. If you do not specify a name, UniData uses the system default policy name. [IN] selMsgName Optional parameter specifying the name of a message object containing information (such as a Correl ID) that UniData uses to retrieve the required message from the queue. See UniBasic Extensions for detailed information about this parameter. [IN] 39 Chapter 1: UniBasic commands and functions Parameter Description maxMsgLen The maximum message length the application will accept. Specify as -1 to accept messages of any length. See UniBasic Extensions for detailed information about this parameter. [IN] dataLen The length of the retrieved message data, in bytes. Specify ““ (null) if not required. [OUT] data The received message data. [OUT] rcvMsgName The name of a message object for the retrieved message. You can specify ““ (null) for this parameter, in which case UniData uses the system default name (constant AMSD_RCV_MSG). See UniBasic Extensions for detailed information about this parameter. [IN] reasonCode Holds an AMI reason code when the function returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. amReceiveRequest The amReceiveRequest function receives a request message. For detailed information about this function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amReceiveRequest(hSession, receiverName, policyName, maxMsgLen, dataLen, data, rcvMsgName, senderName, reasonCode) Parameters The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by the amInitialize function. [IN] receiverName policyName 40 The name of a receiver service. If you specify ““ (null), UniData uses the system default receiver name. [IN] The name of a policy. If you do not specify a policy name, UniData uses the system default policy name. [IN] amSendMsg Parameter Description maxMsgLen The maximum message length the application will accept. Specify -1 to accept messages of any length. See UniBasic Extensions for detailed information about this parameter. [IN] dataLen The length of the message data, in bytes. Specify ““(null) if this is not required. [OUT] data The received message data. [OUT] rcvMsgName The name of the message object for the received message. If you specify ““(null) for this parameter, UniData uses the system default receiver name. UniData uses the value for rcvMsgName in the subsequent call to the amSendResponse function. [IN] senderName reasonCode The name of a special type of sender service known as a response sender, to which the response message will be sent. This sender name must not be defined in the repository. If you do not specify a name, UniData uses the system default response sender service. [IN] Holds an AMI reason code when the function returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. amSendMsg The amSendMsg function sends a datagram (send and forget) message. For detailed information about this function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amSendMsg(hSession, senderName, policyName, data, sndMsgName, reasonCode) Parameters The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by the amInitialize function. [IN] 41 Chapter 1: UniBasic commands and functions Parameter Description senderName The name of a sender service. If you specify ““(null), UniData uses the system default receiver name. [IN] policyName The name of a policy. If you specify ““(null), UniData uses the system default policy name. [IN] data The message data to be sent. [IN] sndMsgName The name of a message object for the message being sent. If you specify ““(null), UniData uses the system default policy name. [IN] reasonCode Holds an AMI reason code when the function returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. amSendRequest The amSendRequest function sends a request message. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amSendRequest(hSession, senderName, policyName, data, sndMsgName, reasonCode) The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by the amInitialize function. [IN] senderName 42 The name of a sender service. If you specify ““(null), UniData uses the system default sender name. [IN] policyName The name of a policy. If you specify ““(null), UniData uses the system default policy name. [IN] responseName The name of the receiver service to which the response to this send request should be sent. Specify ““(null) if you do not require a response. [IN] dataLen The length of the message data, in bytes. [IN] data The message data to be sent. [IN] amSendResponse Parameter Description sndMsgName The name of a message object for the message being sent. If you specify ““(null), UniData uses the system default message name (constant AMSD_SND_MSG). [IN] reasonCode Holds an AMI reason code when the functions returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. amSendResponse The amSendResponse function sends a request message. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amSendResponse(hSession, senderName, policyName, rcvMsgName, data, sndMsgName, reasonCode) The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by amInitialize. [IN] senderName The name of the sender service. It must be set to the senderName you specify for the amReceiveRequest function. [IN] policyName The name of a policy. If you specify ““(null), UniData uses the default policy name. rcvMsgName The name of the received message to which this message is a response. It must be set to the rcvMsgName you specify for the amReceiveRequest function. [IN] dataLen The length of the message data, in bytes. [IN] data The message data to be sent. [IN] sndMsgName The name of a message object for the message being sent. If you specify ““(null), UniData uses the system default message name (constant AMSD_SND_MSG). 43 Chapter 1: UniBasic commands and functions Parameter Description reasonCode Holds an AMI reason code when the function returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. [OUT] The following table describes the status of each return code. Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. amTerminate The amTerminate function closes a session. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax amTerminate(hSession, policyName, reasonCode) The following table describes each parameter of the syntax. Parameter Description hSession The session handle returned by amInitialize. [IN/OUT] policyName The name of a policy. If you specify ““(null), UniData uses the system default policy name. [IN] reasonCode Holds an AMI reason code when the function returns a status indicating an AMI warning or an AMI error occurred. You can use the AMI reason code to obtain more information about the cause of the warning or error. See the MQSeries Application Messaging Interface manual for a list of AMI reason codes and their descriptions. The following table describes the status of each return code. 44 Return codes Status 0 – AMCC_SUCCESS Function completed successfully. 1 – AMCC_WARNING A warning was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the warning. 2 – AMCC_FAILED An error was returned from AMI. The reasonCode output parameter contains an AMI reason code with further details about the error. Other A non-AMI error occurred. analyzeCertificate analyzeCertificate The analyzeCertficate function decodes a certificate and inputs plain text in the result parameter. The result parameter then contains such information as the subject name, location, institute, issuer, public key, other extensions, and the signature of the issuer. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax analyzeCertificate(cert, format, result) The following table describes each parameter of the syntax. Parameter Description cert A string containing the certificate file name. format 1 – PEM 2 – DER result A dynamic array containing parsed cert data, in ASCII format. The following table describes the status of each return code. Return codes Status 0 Success 1 Failed to open cert file 2 Invalid format 3 Unrecognized cert 4 Other errors AND The AND Boolean operator combines a set of expressions. If expr1 or expr2 is false, the combined expression is false. Both expressions must be true for a true condition. Syntax expr1 AND expr2 Synonyms & Examples In the following example, the program segment combines two expressions (X < Y) and (Y < Z). Both expressions must be true for the program to call subroutine RETRY. X = 1 ; Y = 2 ; z = 3 45 Chapter 1: UniBasic commands and functions IF (X < Y) AND (Y < Z) THEN GOSUB RETRY: Related commands Language Command UniBasic NOT, OR ASCII The UniBasic ASCII function converts a string in EBCDIC format to the corresponding ASCII values. Even though the ASCII function works with data in any format, its results are meaningful only when it is applied to EBCDIC data. For more information about ASCII character codes, see ASCII character codes, on page 513. Note: Use the UniBasic commands CHAR and SEQ to convert between ASCII character and decimal value. Syntax ASCII(expr) Examples In the following example, the program statement converts the EBCDIC data in the variable E.VAR to ASCII format and assigns the value to the variable A. VAR:A.VAR=ASCII(E.VAR) Related commands Language Command UniBasic CHAR, CHARS, EBCDIC, SEQ ASIN The UniBasic ASIN function returns the trigonometric arc sine (inverse sine) of a numeric expression. expr must be a value between -1 and +1. ASIN returns a value expressed as the degree of the arc sine of the input, which ranges from -90 to +90. If expr evaluates to a value outside the range of -1 and +1, then UniData displays an error message and returns 0 as the result. With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, ASIN returns the null value when expr is the null value. Syntax ASIN(expr) Examples In the following example, the program statement assigns 30, the arc sine of 0.5, to ARCSIN: ARCSIN = ASIN(0.5) 46 ASSIGN In the next example, the program statement prints -30, the arc sine of -0.5: PRINT ASIN(-0.5) Related commands Language Command UniBasic ACOS, ATAN, COS, SIN, TANASSIGN ASSIGN The UniBasic ASSIGN command redefines some system-level parameters. The value in option changes to the value you specify with expr. Syntax ASSIGN expr TO SYSTEM(option) The following table describes each parameter of the syntax. Parameter Description 2 Page width 3 Page length 5 Page number 7 Terminal type For parameters 2, 3, and 5, expr must be numeric. For parameter 7, expr must be a string representing a valid terminal type and must be enclosed in quotation marks. Examples In the following example, the program resets the page width to 40, page length to 30, and terminal type to vt100: ASSIGN 40 TO SYSTEM(2) ASSIGN 30 TO SYSTEM(3) ASSIGN "vt100" TO SYSTEM(7) Related commands Language Command UniData TERM For information, see the UniData Commands Reference. ATAN The UniBasic ATAN function returns the trigonometric arc tangent (inverse tangent) of a numeric expression expr in degrees. 47 Chapter 1: UniBasic commands and functions With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, ATAN returns the null value when expr is the null value. Syntax ATAN(expr) Examples In the following example, the program segment prints the arc tangent of the variable VAL. VAL is set to 45. VAL = 1 PRINT ATAN(VAL) Related commands Language Command UniBasic ACOS, ASIN, COS, SIN, TAN BITAND The UniBasic BITAND function performs the bit-wise AND logical function on the arguments num.expr1 and num.expr2. Syntax BITAND(num.expr1,num.expr2) With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. BITAND returns the null value when num.expr1 or num.expr2 is the null value. The following table shows the results of the BITAND function on various sets of input. num.expr1 num.expr2 Result 0 0 0 0 1 0 1 0 0 1 1 1 3 9 1 23 87 23 Examples In the following example, the program statement prints a 0: PRINT BITAND(0,1) 48 BITNOT BITNOT The UniBasic BITNOT function performs the bit-wise NOT logical function on the argument num.expr. Syntax BITNOT(num.expr) With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, BITNOT returns the null value when num.expr is the null value. The following table shows the results of the BITNOT function on the valid input: 0 and 1. num.expr Results 0 1 1 0 Examples In the following example, the program statement prints 1: PRINT BITNOT(0) BITOR The UniBasic BITOR function performs the bit-wise OR logical function on the arguments num.expr1 and num.expr2. Syntax BITOR(num.expr1,num.expr2) With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, BITOR returns the null value when num.expr1 or num.expr2 is the null value. The following table shows the results of the BITOR function on various sets of input. num.expr1 num.expr2 Result 0 0 0 0 1 1 1 0 1 1 1 1 3 9 11 23 87 87 Examples In the following example, the program statement prints a 1: PRINT BITOR(0,1) 49 Chapter 1: UniBasic commands and functions BITXOR The UniBasic BITXOR function performs the bit-wise XOR logical function on the arguments num.expr1 and num.expr2. Syntax BITXOR(num.expr1,num.expr2) With null value handling on, the result of any mathematical operation, function, or comparison involving the null value is the null value. Therefore, BITXOR returns the null value when num.expr1 or num.expr2 is the null value. The following table shows the results of the BITXOR function on various sets of input. num.expr1 num.expr2 Result 0 0 0 0 1 1 1 0 1 1 1 0 3 9 10 23 87 64 Examples In the following example, the program statement prints 1: PRINT BITXOR(0,1) BPIOCP The UniBasic BPIOCP command turns automatic pagination on. Syntax BPIOCP With pagination on, printing to a terminal (without using cursor addressing) pauses at the bottom of each screen display. The user is prompted before the next screen is displayed as follows: Enter <New Line> to continue... Three user responses are valid for this prompt, which are listed in the following table. 50 Input Description ENTER Pressing ENTER displays another screen of data. N Continues display and disables automatic pagination (no pause at bottom of each screen display). Q Quits the current process and returns to the previous process. BPIOCPN Examples The page control process is automatically disabled if the @ function is executed. For example, all of the following statements disable terminal pagination: PRINT @(1) CRT @(2) VARIABLE = @(3) With page control disabled, UniData assumes that the program will control the paging of data. To turn automatic pagination on from within a UniBasic program, use BPIOCP. An example is provided with the BPIOCPN command. Related commands Language Command UniBasic BPIOCPN BPIOCPN The UniBasic BPIOCPN command turns off automatic pagination. With pagination off, printing to a terminal does not pause at the bottom of each screen display. Syntax BPIOCPN Examples In the following example, the program prints the first 60 records of the INVENTORY file with pagination disabled by @(0,0). Then the BPIOCP command enables automatic pagination. The next 23 records are printed, and the user is prompted to press ENTER to continue. At this point, the user also can enter N to disable pagination. After all 60 records have printed, BPIOCPN executes. A prompt displays this information. When the user presses ENTER at the prompt, 60 records print with pagination off. JUNK = @(0,0) ; * Disable pagination OPEN 'INVENTORY' READONLY TO INVENTORY.FILE ELSE NULL SELECT INVENTORY.FILE PRINT "Printing after terminal addressing: @(0,0)" FOR X = 1 TO 60 READNEXT REC THEN PRINT REC<1> NEXT X PRINT "Sixty rec ids printed." PRINT "BPIOCP executing." BPIOCP ; *Enable pagination FOR X = 1 TO 60 READNEXT REC THEN PRINT X:" ":REC<1> NEXT X PRINT "Sixty rec ids printed." PRINT "BPIOCPN executing." INPUT var BPIOCPN ; *Disable pagination FOR X = 1 TO 60 READNEXT REC THEN PRINT X:" ":REC<1> NEXT X 51 Chapter 1: UniBasic commands and functions PRINT "Sixty rec ids printed." CLEARSELECT END Related commands Language Command UniBasic BPIOCP BREAK The UniBasic BREAK command enables or disables the interrupt key to exit a program to the ‘!’ debugger prompt and displays the current program line number. The program must have been compiled and run with debugger options. For instructions, see the ECL BASIC and RUN commands in the UniData Commands Reference. The system increments a counter each time BREAK OFF executes and decrements that same counter when BREAK ON executes. Until the system counter is less than or equal to zero (more BREAK ON statements executed than BREAK OFF statements), the interrupt key is not operational. This status continues even if you exit a program with the interrupt key disabled. Syntax BREAK [KEY] {ON | OFF | expr } Parameters The following table describes each parameter of the syntax. Parameter Description KEY KEY is optional and has no effect. It is included for backward compatibility only. ON Enables the terminal interrupt key to stop the execution of a UniBasic program and enter the UniBasic debugger. OFF Disables the interrupt key. Pressing the interrupt key has no effect on program execution. expr Enables the terminal interrupt key (to stop the execution of a UniBasic program and enter the UniBasic debugger) if the expression is valid. Examples In the following example, the program statement decrements the system counter and enables the interrupt key if the break counter is less than or equal to zero: BREAK ON In the next example, a numeric expression determines whether to enable the interrupt key. If X is greater than 0, UniData enables the interrupt key. BREAK X > 0 52 BYTELEN Related commands Language Command UniData PTERM For information, see the UniData Commands Reference. BYTELEN The UniBasic BYTELEN function returns the number of bytes required to store a character. From one to four bytes could be required. Syntax BYTELEN (string) Examples The following figure illustrates a string that shows below each “character” the number of bytes required to store that character. The string contains eight bytes. Therefore, BYTELEN would return 8 for this string. Related commands Language Command UniBasic CHARLEN, DISPLAYWIDTH, ISMB, LEN, MBLEN CALCULATE The UniBasic CALCULATE or {} (braces) function executes a virtual attribute. The dictionary.item must be a valid virtual attribute within the dictionary previously opened to the @DICT variable with an OPEN statement. Note: Before you use this function, you must compile the dictionary of the file you will open to the @DICT variable by using the ECL COMPILE.DICT or CD command. In the CALCULATE() form, the dictionary.item can be a quoted string or a UniBasic variable. The expression uses the data from the current @RECORD during the evaluation process. In the {} form, the dictionary.item must be the literal dictionary name with no quotation marks. You must open a dictionary to @DICT and read the data record into @RECORD for the function to work properly. 53 Chapter 1: UniBasic commands and functions If these functions are successful, they update the values in @CONV, @FORMAT, and @HEADER. You can then use these @ variables in other UniBasic functions, such as ICONV, OCONV, and FMT. For more information about @ variables, see UniBasic@variables, on page 520. Syntax CALCULATE(dictionary.item) {dictionary.item} Examples In the following example, the program segment opens the ORDERS file to the variable ORDER.FILE and the dictionary of the ORDERS file to the special @DICT variable. After selecting the ORDERS file, the program reads the value of each record ID into @ID, reads the value of the order record into @RECORD, then uses the {} (braces) function to evaluate the order balance (storing the total in TOTAL.DUE). The braces function updates the @CONV and @FORMAT variables, which are used to print the total with the correct format. OPEN 'ORDERS' TO ORDER.FILE ELSE STOP 'NO ORDER FILE' END OPEN 'DICT','ORDERS' TO @DICT ELSE STOP 'NO DICTIONARY FOR ORDERS FILE' END TOTAL.DUE = 0 SELECT ORDER.FILE MORE = 1 LOOP READNEXT @ID ELSE MORE = 0 UNTIL NOT(MORE) DO READ @RECORD FROM ORDER.FILE,@ID ELSE @RECORD = '' END TOTAL.DUE += {GRAND_TOTAL} REPEAT TOTAL.DUE = OCONV(TOTAL.DUE,@CONV) PRINT "Total Accounts Receivable":FMT(TOTAL.DUE,@FORMAT) CLEARSELECT END Related commands Language Command UniBasic ITYPE CALL The UniBasic CALLv command transfers program control to an external subroutine. ▪ The first form of the syntax calls a globally cataloged subroutine. ▪ The second form of the syntax calls a subroutine named in a variable. ▪ The third form of the syntax calls a subroutine directly. The called program or subroutine must contain a RETURN statement, which returns control to the calling program or subroutine. 54 CALL You can nest subroutines up to 1,024 levels deep. Note: You must catalog subroutines before using them in a UniBasic CALL statement. You must separate individual arguments by commas and enclose the set of arguments within parentheses. You can place arguments on multiple lines. Each continued line must end with a comma. Regardless of placement, the number and type of arguments in the CALL statement must match the number and type of arguments in the SUBROUTINE statement within the external subroutine. Arrays and singlevalued arguments can be passed in the same CALL statement. Tip: You can also pass variables through named and unnamed common areas. Variables stored in common area(s) are accessible to both calling and called programs without being passed as arguments. You cannot use the same variable name in both a SUBROUTINE argument and a common variables list. Syntax CALL *sub.name [[(argument1[,argument2][MAT array1 [,MAT array2]]...)] [ASYNC | SYNC] [ON connection] CALL @var [[(argument1[,argument2][MAT array1 [,MAT array2]]...)] [ASYNC | SYNC] [ON connection] CALL sub.name [[(argument1[,argument2][MAT array1 [,MAT array2]]...)] [ASYNC | SYNC] [ON connection] Parameters The following table describes each parameter of the syntax. Parameter Description sub.name The name of the called subroutine. @var A variable that contains the name of the subroutine to call. argument1, argument2 Any valid argument passed to the subroutine. MAT array1, MAT array2 Any valid array passed to the subroutine. ASYNC | SYNC UniData no longer supports this parameter, but it remains for syntax compatibility. ON connection UniData no longer supports this parameter, but it remains for syntax compatibility. Examples Note: A sample program that calls an external subroutine is provided in Developing UniBasic Applications. In the following example, the program statement calls the subroutine VID, passing the variables TITLE and ST: CALL VID(TITLE,ST) In the next example, the program segment calls the subroutine MONTHTOTAL by calling @var VID, which holds the string “MONTHTOTAL”. Note that VID is defined before it is called. VID = "MONTHTOTAL" 55 Chapter 1: UniBasic commands and functions CALL @VID(TOTAL) In the next example, the program segment calls the contents of cell (1,12) in the array cells, thus calling the subroutine RECEIPTS with the argument “MON1_12”. In the use of @matrices, you can select the array element by the use of an index (a variable within the dimensions of the array). "SUBROUTINE MONTHTOTAL(TOTAL)" SALES(1,12) = "RECEIPTS" CALL @SALES(1,12)(MON1_12) In the next example, the program statement calls the globally cataloged subroutine PROMPT.ROUTINE: CALL *PROMPT.ROUTINE In the following example, the CALL statement is invalid because subroutine SUBS, which is shown after this example, has a different number of arguments than the CALL statement. Called and calling programs must pass the same number of parameters. CALL SUBS(X,Y,Z) The subroutine SUBS, which the program in the previous example calls, follows: SUBROUTINE SUBS(X) Related commands Language Command UniBasic CHAIN, COMMON, ENTER, GOSUB, RETURN, SUBROUTINE CALLC The UniBasic CALLC command transfers program control to an external function (c.sub.name). The second form of the syntax calls a function whose name is stored in a UniBasic variable (@var). The program could pass back return values in variables. CALLC arguments can be simple variables or complex expressions, but not arrays. CALLC can be used as a command or function. Syntax CALLC c.sub.name [(argument1[,argument2]...)] CALLC @var [(argument1[,argument2]...)] Calling a C Program in UNIX You must link the C program to UniData before calling it from a UniBasic program. Perform the following procedure to prepare UniData for CALLC: 1. 2. 3. 4. Write and compile the C program. Define the C program call interface. Build the runtime version of UniData (containing the linked C program). Write, compile, and execute the UniBasic program. For more information about this procedure, see Developing UniBasic Applications. 56 CASE Calling a Function on Windows Platforms The CALLC implementation in UniData for Windows Platforms uses the Microsoft Windows Dynamic Link Library (DLL) facility. This facility allows separate pieces of code to call one another without being permanently bound together. Linking between the separate pieces is accomplished at runtime (rather than compile time) through a DLL interface. For CALLC, developers create a DLL and then call that DLL from UniData. E-type VOC entries for each function called from a DLL communicate interface information to UniData. For additional information and examples, see Administering UniData on UNIX or Administering UniData on Windows Platforms. Examples In the following example, the called subroutine draws a circle with its center at the twelfth row and twelfth column and a radius of 3: RADIUS = 3 CENTER = "12,12" CALLC DRAW.CIRCLE(RADIUS,CENTER) In the next example, the subroutine name is stored in the variable SUB.NAME, and it is called indirectly: SUB.NAME = DRAW.CIRCLE CALLC @SUB.NAME(RADIUS,CENTER) In the next example, CALLC is used as a function, assigning the return value of the subroutine PROGRAM.STATUS in the variable RESULT: RESULT = CALLC PROGRAM.STATUS Related commands Language Command UniBasic CALL CASE The UniBasic CASE command creates a series of branches based on conditional expressions. Case structures must always begin with BEGIN CASE and terminate with END CASE. The number of CASE commands within BEGIN CASE and END CASE is unlimited. The number of statements within each CASE branch is unlimited. CASE statements can be nested. The CASE command tests each of the expressions in sequence. If an expression evaluates as true, the system executes the statements that follow it. When one of the CASE expressions is found to be true, the system does not test any subsequent expressions. If none of the conditions is true, the system does not execute any statements. With null value handling turned on, a test of the null value returns a negative result. For an overview of how the null value affects UniBasic, see Developing UniBasic Applications. Syntax BEGIN CASE [ CASE expression1 CASE expression2 statements1 statements2]... 57 Chapter 1: UniBasic commands and functions [ CASE1 expression statements]END CASE Parameters The following table describes each parameter of the syntax. Parameter Description CASE expression1 Any UniBasic conditional expression. If the expression is true, execute statements1. statements1 The UniBasic statements to execute if expression1 is true. CASE expression2 Any UniBasic conditional expression. If the expression is true, execute statements2. statements2 The UniBasic statements to execute if expression2 is true. CASE 1 statements This clause always evaluates as true. By placing it at the end of the CASE statements, you can specify a set of statements to execute if all previous statements evaluate as false. Examples Note: An example of the use of CASE is included in the sample program in Developing UniBasic Applications. In the following example, if the variable DUE.DATE is greater than the system date, the program calls the subroutine PRINT.OVERDUE. (Notice that both dates are in internal format.) If DUE.DATE is less than or equal to the system date, the program prints the message “Okay” on the display terminal. BEGIN CASE CASE DUE.DATE > DATE() GOSUB PRINT.OVERDUE: CASE DUE.DATE <= DATE() PRINT "Okay" END CASE Tip: The multiline indented statement layout shown in these examples makes the code easier to read. In the next example, the program segment transfers program control to either “CHARGE:” or “CHECK:” based on the value of the variable VAL. If VAL is not 1 or 2, the program executes the statements after the CASE 1 clause. PRINT "Option number?" ; INPUT VAL BEGIN CASE CASE VAL = 1 GOSUB CHARGE: CASE VAL = 2 GOSUB CHECK: CASE 1 PRINT "Answer 1 or 2 only" END CASE In the following example, the statement is invalid because the evaluation expression appears on the BEGIN CASE line: BEGIN CASE VAR 1 58 CAT In the next example, the statement is invalid because BEGIN CASE must appear before the first CASE statement: CASE VAL Related commands Language Command UniBasic IF/THEN/ELSE, LOOP/REPEAT CAT The UniBasic CAT arithmetic operator concatenates expr1 to expr2. Syntax expr1 CAT expr2 Synonyms : Examples In the following example, the program segment concatenates A to B, and then prints 123456: A = "123" B = "456" C = A CAT B PRINT C The following program segment compiles and runs only with null value handling on. The program concatenates two strings, one ending with the null value, and another beginning with ‘123.’ This produces the string @AM@NULL123@AM456. The called subroutine, print.setup, converts UniData delimiters and the null value to printable characters. (This subroutine is printed in the entry for CHANGE). PRT.STG = '' Z=123:@AM:456 Y=@AM:@NULL STG = Y CAT Z CALL print.setup(STG,PRT.STG) PRINT PRT.STG Related commands Language Command UniBasic CATS, SPLICE 59 Chapter 1: UniBasic commands and functions CATS The UniBasic CATS function concatenates array1 to array2. Each element of array2 is concatenated to its corresponding element in array1. Syntax CATS(array1,array2) Examples In the following example, the program segment concatenates array A to array B and prints 300A}400B}401C}402D}100E: A = 300:@VM:400:@VM:401:@VM:402:@VM:100 B = "A":@VM:"B":@VM:"C":@VM:"D":@VM:"E" C = CATS(A,B) PRINT C Related commands Language Command UniBasic CAT, SPLICE CHAIN The UniBasic CHAIN command terminates the current UniBasic program and executes the ECL command str.expr. CHAIN performs a function similar to the EXECUTE statement, except that control is not returned to the original program. UniData treats str.expr as a command you type at the ECL colon (:) prompt. If str.exp executes a UniBasic program, variables could be passed through common areas, but all other variables are reinitialized when the new program begins. Tip: Use this command to avoid system-imposed limitations on program size by sequentially running several smaller programs rather than one large program. UDT.OPTIONS 6 and 40 affect the operation of the CHAIN command. For more information, see the UDT.OPTIONS Commands Reference. Syntax CHAIN "str.expr" Examples In the following example, the program terminates and UniData executes the ECL command “RUN BP FORMLET”. FORMLET is a compiled UniBasic program. UniData does not return control to the original program when FORMLET terminates. CHAIN "RUN BP FORMLET" In the next example, the current program terminates and the paragraph RUN.ACCOUNTS executes: CHAIN "RUN.ACCOUNTS" 60 CHANGE Related commands Language Command UniBasic CALL, COMMON, ENTER, GOSUB CHANGE The UniBasic CHANGE function replaces all occurrences of old.substring in string with new.substring. If old.substring is an empty string, the system does not change string. CHANGE supports multibyte languages. Syntax CHANGE(string, old.substring, new.substring) Parameters The following table describes each parameter of the syntax. Parameter Description string Specifies the original text string. old.substring Specifies the text string to replace with new.substring. new.substring Specifies the text string with which to replace old.substring. Examples In the following example, the program segment prints “UniBasic Release 6.1”: STRA = "UniBasic Release 6.1" OLDRELEASE = "6.0" NEWRELEASE = "6.1" STRB = CHANGE(STRA, OLDRELEASE,NEWRELEASE) PRINT STRB In the next example, the program segment prints “NEW STRC = A23A24A25A26”: STRC = "123124125126" PRINT "NEW STRC =":CHANGE(STRC,"1","A") The following subroutine converts UniData delimiters and the null value to printable characters. (This subroutine compiles only with null value handling turned on.) SUBROUTINE PRINT.SETUP(STG, PRT.STG) PRT.STG = CHANGE(STG, @NULL, "@NULL") PRT.STG = CHANGE(PRT.STG, @AM, "@AM") PRT.STG = CHANGE(PRT.STG, @VM, "@VM") RETURN CHAR The UniBasic CHAR function changes a numeric expression to its ASCII character string equivalent. expr can be a constant, variable, numeric function, or any combination of these. expr must evaluate 61 Chapter 1: UniBasic commands and functions to a positive number from 0 to 255 (the range of ASCII character codes). CHAR supports multibyte languages. Not all ASCII codes are printable. Some represent terminal controls, and others are reserved for special uses. For more information about ASCII character codes, see ASCII character codes, on page 513. Tip: Use @variables to represent UniData delimiters and the null value. We recommend that you not use the UniBasic functions CHAR or CHARS to insert these variables because the ASCII code that represents it varies with language group. Syntax CHAR(expr) Examples In the following example, the program segment assigns the ASCII string equivalent of the numeric expression VAL to the variable VSTRING. The final numeric value of the argument is 90, so VSTRING becomes Z, the character equivalent of 90 in ASCII code. VAL=90 VSTRING=CHAR(VAL) In the next example, the program statement sends the ASCII code 12 to the current print device. In ASCII, this is a form feed. PRINT CHAR(12) Related commands Language Command UniBasic ASCII, CHARS, EBCDIC, SEQ CHARLEN The UniBasic CHARLEN function returns the number of characters in a character string. A multibyte character could require from one to four bytes to encode. Syntax CHARLEN (string) Examples The following figure illustrates a string of four multibyte characters. CHARLEN would return 4 for this string. 62 CHARS Related commands Language Command UniBasic BYTELEN, DISPLAYWIDTH, ISMB, LEN, MBLEN CHARS The UniBasic CHARS function changes a numeric value in array to its ASCII character string equivalent. array elements can contain a constant, variable, numeric function, or any combination of these. array elements must evaluate to a positive number 0–255 (the range of ASCII character codes). CHARS supports multibyte languages. Not all ASCII codes are printable. Some represent terminal controls, and others are reserved for special uses. For more information about ASCII character codes, see ASCII character codes, on page 513. Note: Use @variables to represent UniData delimiters and the null value. We recommend that you not use the UniBasic functions CHAR or CHARS to insert these variables because the ASCII code that represents it varies with language group. Syntax CHARS(array) Examples In the following example, the program segment assigns the ASCII string equivalent of the elements of array VAL to the variable VARRAY. VARRAY now contains W}X}Y}Z, the character equivalent of 87,88,89, and 90 in the ASCII code system. VAL = 87:@VM:88:@VM:89:@VM:90 VARRAY = CHARS(VAL) Related commands Language Command UniBasic ASCII, CHAR, EBCDIC, SEQ CHECKSUM The UniBasic CHECKSUM function computes the positional checksum of the string str.expr you specify. The positional checksum is the sum of the ASCII value of each character in the string, multiplied by the position of the character in the string. For more information about ASCII characters values, see ASCII character codes, on page 513. Tip: You can use the CHECKSUM function to check whether data was copied correctly, or whether information processed properly, by comparing the CHECKSUM of the original data with the CHECKSUM of the copy. 63 Chapter 1: UniBasic commands and functions Syntax CHECKSUM(str.expr) Examples In the following example, the program statement prints out 2445, the checksum of string “123456789”: PRINT CHECKSUM("123456789") CLEAR The UniBasic CLEAR command sets the values of all variables stored in local memory to 0, including all array elements. Variables assigned to named or unnamed common areas are not affected. Note: CLEAR can be used at any point within a program. CLEAR performs differently with BASICTYPEs M and P. All variables in unnamed common areas are also set to 0. Syntax CLEAR Examples In the following example, the program statement clears all variables not held in common if the variable INITIALIZE is true and BASICTYPE is U. The variable INITIALIZE also set to 0 (false) if the variable is not held in common. IF INITIALIZE THEN CLEAR In the next example, the program segment sets X, Y, and all elements in NAME, to zero in BASICTYPEs P and M: COMMON NAME(100) X = 4 Y = X - 1 CLEAR Related commands Language Command UniBasic COMMON, CLEARCOMMON UniData DELETECOMMON For information, see the UniData Commands Reference. CLEARCOMMON The UniBasic CLEARCOMMON command sets all variables in a named common area to zero. If you do not specify common.label, CLEARCOMMON sets all variables specified in the unnamed common area to zero. 64 CLEARDATA The CLEARCOMMON command behaves differently depending on the BASICTYPE you are using. In BASICTYPE “U” and BASICTYPE “R” CLEARCOMMON clears the entire unnamed common area. In BASICTYPE “P” and BASICTYPE “M” the unnamed common area is not cleared. Syntax CLEARCOMMON [/common.label/] Synonyms CLEAR COMMON, CLEARCOM, CLEAR COM Examples In the following example, the program statement sets to zero all variables named in COM_1: CLEARCOMMON /COM_1/ In the next example, the program statement sets to zero all variables held in common areas if the variable INITIALIZE.COMMON is true: IF INITIALIZE.COMMON THEN CLEAR COMMON Related commands Language Command UniBasic CLEAR, COMMON UniData DELETECOMMON, STACKCOMMON For information, see the UniData Commands Reference. CLEARDATA The UniBasic CLEARDATA command clears data stored by any executed DATA statements. Subsequent INPUT statements request data from the keyboard because the input queue is empty. Syntax CLEARDATA Examples In the following example, a DATA statement sets up an input queue. An INPUT statement then reads the first item (100) into the variable VAL. Because the value of VAL is 100, a CLEARDATA statement executes and clears the remaining list of data items. The last INPUT statement then requests information from the keyboard rather than getting it from the input queue. If the first value had not been 100, 120 would have been assigned from the second item in the input queue. DATA 100,120,105,54,120 INPUT VAL IF VAL = 100 THEN CLEARDATA PRINT "VALUE": ; INPUT VAL2 65 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic DATA, INPUT CLEARFILE The UniBasic CLEARFILE command clears all records from a file, but does not delete the file itself. You can clear only one file at a time with a CLEARFILE statement. Tip: The CLEARFILE statement clears any of the files that you can open, even if they reside in a remote account. The CLEARFILE command will not work if there is a DELETE event trigger on the file. Syntax CLEARFILE [file.var] [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var Optional. Specifies a dictionary or data file to clear. The file must have been opened previously with an OPEN statement. If you do not specify a file.var, the system reads from the default file. If no default file is open, a fatal READ error occurs. A default file is one for which no file variable is assigned in the OPEN statement. ON ERROR statements Specifies statements to execute if a fatal error occurs because the file is not open or is read-only. If you do not specify the ON ERROR clause, the program terminates under fatal error conditions. Examples In the following example, the program statement removes all records from the file PASTDUE. The dictionary of PASTDUE remains unchanged after the execution of this statement. CLEARFILE PASTDUE Related commands Language Command UniBasic OPEN, OPENSEQ, OSOPEN UniData CLEARFILE For information, see the UniData Commands Reference. 66 CLEARINPUT CLEARINPUT The UniBasic CLEARINPUT command clears the terminal type-ahead buffer so the next INPUT statement forces a response from the user. Syntax CLEARINPUT Synonyms INPUTCLEAR Examples In the following example, the CLEARINPUT statement clears the terminal type-ahead buffer so the user must respond to the prompt: CLEARINPUT PRINT "DO YOU WANT TO DELETE THIS FILE?(Y OR N)"; INPUT X,1 Related commands Language Command UniBasic CLEARDATA, INPUT, SYSTEM, CLEARSELECT CLEARSELECT The UniBasic CLEARSELECT command clears active select lists. You can specify a particular ID list by specifying num.expr as 0 through 9. ALL clears all active select lists. If you do not specify a parameter, UniData clears the default ID list (zero). If you specify an ID list outside the valid range, a runtime error occurs. You generally create active lists by executing the ECL SELECT, SSELECT, or GET.LIST commands, or the UniBasic SELECT or GET.LIST commands. These commands report or process a specific subset of IDs within a file. Because multiple select lists can be active at one time, the CLEARSELECT statement could clear one or all of the currently active lists. Syntax CLEARSELECT [num.expr] [ALL] Examples In the following example, the program segment clears select list 1: ID.LIST=1 CLEARSELECT ID.LIST In the next example, the program statement clears the default list 0: CLEARSELECT 67 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic SELECT, GETLIST UniQuery GETLIST, SELECT, SSELECT For information, see Using UniQuery CLEARSQL The UniBasic CLEARSQL command clears all active temporary tables that were created during the current session (for example, created with the EXECUTESQL command with a corresponding TO clause). If you do not specify file.name.expr, CLEARSQL clears all the UniData SQL file variables created during this UniBasic session. Note: When a program returns to the UniData prompt, UniData clears all UniData SQL file variables regardless of whether you execute CLEARSQL. Syntax CLEARSQL [file.name.expr] Related commands Language Command UniBasic EXECUTESQL CLOSE The UniBasic CLOSE command closes a dictionary or data file. Note: You can use the OPEN command to access an unlimited number of files in a single UniData process. However, the operating system could limit the number of files that can be opened across numerous processes and users. Syntax CLOSE [file.var] [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies a dictionary or data file to close. If you do not specify file.var, the default file is closed. If no default file is open, the command has no effect. A default file is created by omitting the file variable in the OPEN statement. 68 CLOSESEQ Parameter Description ON ERROR statements Specifies statements to execute if a fatal error occurs because the file is not open. If you do not specify the ON ERROR clause, the program terminates under fatal error conditions. Examples In the following example, the program segment opens and closes the file INVENTORY: OPEN 'INVENTORY' TO INVENTORY.FILE ELSE STOP CLOSE INVENTORY.FILE Related commands Language Command UniBasic OPEN CLOSESEQ The UniBasic CLOSESEQ command closes a sequential file that you opened with the OPENSEQ or OSOPEN command. The CLOSESEQ command releases the exclusive file lock set by the OPENSEQ command. If any new lines (sequential records) were added to the file, UniData writes a new end-offile mark after the new lines. Syntax CLOSESEQ seq.file.var [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description seq.file.var Specifies a sequential access file to close. ON ERROR statements The file must have been opened previously with an OPENSEQ or OSOPEN statement. Specifies statements to execute if a fatal error occurs because the file is not open. If you do not specify the ON ERROR clause, the program terminates under such fatal error conditions. Examples In the following example, the statement closes the sequential file referred to by the file variable DATA.59: CLOSESEQ DATA.59 69 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic CLOSE, OPENSEQ, OSCLOSE, OSOPEN closeSocket Use the closeSocket function to close a socket connection. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax closeSocket(socket_handle) Parameters The following table describes each parameter of the syntax. Parameter Description socket_handle The handle to the socket you want to close. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. CLOSEXMLDATA The CLOSEXMLDATA function closes the dynamic array variable for an XML document. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax CLOSEXMLDATA(xml_data_handle) Parameters The following table describes each parameter of the syntax. Parameter Description xml_data_handle The name of the XML data file handle created by the OPENXMLDATA function. The return value is one of the following: XML.SUCCESS: Success 70 COL1 XML.ERROR: Failure XML.INVALID.HANDLE2: Invalid xml_data_handle Examples The following example illustrates use of the CLOSEXMLDATA function: status = CLOSEXMLDATA(STUDENT_XML) COL1 The UniBasic COL1 function returns the column position preceding a substring found by the FIELD function. The COL1 function has no arguments. If you do not execute the FIELD function before executing COL1, the function returns 0. COL1 supports multibyte languages. The FIELD function examines a string for a particular delimiter and returns the substring marked by the specified occurrence of that delimiter. While the FIELD function returns the substring itself, the COL1 function returns the position preceding the substring. Syntax COL1( ) Examples In the following example, the FIELD function searches the string STRING for the third occurrence of the delimiter “,”. FIELD retrieves the substring “10” in the variable SSTR. The COL1 function assigns column 6, the column position of the character before “10”, to the variable SPOS. STRING = "11,20,10,15,20,15" SSTR = FIELD(STRING,",",3) SPOS = COL1() Related commands Language Command UniBasic COL2, FIELD, INDEX COL2 The UniBasic COL2 function returns the column position following a substring found by the FIELD function. The COL2 function has no arguments. If you do not execute the FIELD before executing COL2, the function returns a zero. COL2 supports multibyte languages. The FIELD function examines a string for a particular delimiter and returns the substring marked by the specified occurrence of that delimiter. While the FIELD function returns the substring itself, the COL2 function returns the position immediately after the substring within the string sent to the FIELD function. Syntax COL2( ) 71 Chapter 1: UniBasic commands and functions Examples In the following example, the FIELD function searches the string STRING for the third occurrence of the delimiter “,”. FIELD assigns the substring “10” to the variable SSTR. The COL1 function assigns column 9, the column position of the character after “10”, to the variable SPOS2. STRING = "11,20,10,15,20,15" SSTR = FIELD(STRING,",",3) SPOS2 = COL2() Related commands Language Command UniBasic COL1, FIELD, INDEX COMMON The UniBasic COMMON command stores variables that can be accessed from any subroutine or program. You can declare one unnamed common area and multiple named common areas. The number of variables that a common area can contain depends on the virtual memory of your system. For information about virtual memory, see Administering UniData on UNIX or Administering UniData on Windows Platforms. Syntax COMMON [/common.name/] var1 [,var2][ARR1]...[,] Synonyms COM Parameters The following table describes each parameter of the syntax. Parameter Description /common.name/ Specifies a name for a named common variable. common.name can have any valid variable name no longer than seven characters. Default (no common name provided) stores the variable in unnamed common. var1 A variable to place in the named or unnamed common. ,var2 A second variable to place in the named or unnamed common areas. ARR1 An array to place in the named or unnamed common area. Do not declare common arrays with a DIM statement. Arrays in a common cannot be dynamically redimensioned. , You can enter a COMMON statement on several lines by terminating each line to be continued with a comma. Constraints and Considerations Keep the following points in mind when writing programs that use common to pass variables: ▪ 72 Common variables are not passed when you execute CHAIN to another UniBasic program. COMMON ▪ ▪ ▪ ▪ ▪ Unnamed common is removed when you return to the ECL prompt, but named common remains in memory until deleted with the ECL DELETECOMMON command, even if the program aborts. COMMON must be the first noncomment statement in the called program. CLEARCOMMON sets the common variable to 0. DELETECOMMON removes common variables. Variables in a common area must be declared the same type, dimension, and in the same order by all programs accessing them. Programs can declare more or fewer variables, and can change the name of the variables. The order of the names in a program’s COMMON statement determines which names go with which values. Common names are limited to a length of seven characters. No error message is returned when longer names are truncated during compilation. In the following example, STRING2 overwrites STRING1 because both names, commons1 and commons2, are truncated to “commons”: COMMON commons1 STRING1 COMMON commons2 STRING2 COMMON BASICTYPEs You can pass variables using common in any BASICTYPE. Here are some notes: ▪ With BASICTYPEs M and P, use of COMMON is more flexible because in these BASICTYPEs no zero element is maintained in arrays. For example, two programs declare COMMON, which are described in the following table. First Program Second Program Declares COMMON as: A,B(5) Declares COMMON as: U,V,W,X,Y,Z Assigns values of: A = 4 and B(3) = 5 ▪ ▪ Therefore: U = 4 and X = 5 STACKCOMMON defaults to OFF in BASICTYPEs R and U, but is always ON in BASICTYPEs P and M. You can use the PASSCOM option for compatibility purposes, but its use is not needed to pass common variables. STACKCOMMON The ECL STACKCOMMON command makes use of common areas more flexible, although it requires additional memory. STACKCOMMON settings have the following effects: ▪ If STACKCOMMON is off when one program executes another, the contents of unnamed common areas are passed to the executed program and back to the executing program. ▪ If STACKCOMMON is on when one program executes another program, the contents of unnamed common areas are not passed to the program you execute. Instead, they are saved, and the called program’s unnamed common areas are initialized to 0. When control is passed back to the calling program, it is restored to its value before the program call. Unnamed common areas are never passed to a phantom program. Examples In the following example, the COMMON statement declares the arrays NAME and DATES, and declares the variable DCHANGE in unnamed common: COMMON NAME(100),DATES(100,2),DCHANGE In the next example, the program segment creates two named common areas. The second COMMON statement continues on a second line. The comma (,) continuation character ends the continued line. COMMON /MENU/ X,Y,XDIM,YDIM,S.CHAR COMMON /CALC/ RATE(10),AMOUNT(10),DATE1,DATE2,LATE 73 Chapter 1: UniBasic commands and functions In the following example, the program segment is invalid because COMMON is not the first statement in the called program, and because variables in COMMON cannot be reassigned new values in a called program: VALUE = 253 COMMON VALUE,SUBVALUE,ATTRIBUTE The following two programs demonstrate passing a variable through common. The FIRST_PROG establishes the common variable VAR, and then NEXT_PROG declares this variable, adds 1 to it, and prints it. FIRST_PROG COMMON VAR VAR = 1 PRINT "IN FIRST_PROG" PRINT VAR CALL NEXT_PROG NEXT_PROG *Program NEXT_PROG COMMON VAR PRINT "IN NEXT_PROG" VAR = VAR+1 PRINT VAR Here is the output from these programs: :RUN BP FIRST_PROG IN FIRST_PROG 1 IN NEXT_PROG 2 Related commands Language Command UniBasic CLEAR, CLEARCOMMON UniData DELETECOMMON, STACKCOMMON For information, see the UniData Commands Reference. CONTINUE The UniBasic CONTINUE command transfers control to the next iteration of a FOR/NEXT or LOOP/ REPEAT statement. Tip: Use CONTINUE instead of GOTO in structured programs. Generally, the statements within a FOR/NEXT or LOOP/REPEAT structure execute one by one. If you want to break the sequence to begin the next iteration without a CONTINUE statement, you could use the GOTO statement. However, this makes the code more difficult to read and maintain. By using CONTINUE, you can clearly express the program logic without degrading program structure. 74 CONVERT Syntax CONTINUE Examples In the following example, the program segment prints the value of I until I reaches eight. When I is equal to eight, the CONTINUE statement drops out of the FOR/NEXT loop, and the next statement in the program executes. FOR I = 1 TO 10 IF I > 8 THEN CONTINUE PRINT "I = ":I NEXT I The preceding code produces the following output: I = I = I = ... I = 1 2 3 8 Related commands Language Command UniBasic EXIT CONVERT The UniBasic CONVERT command changes all occurrences of the substring expr1 in var to the string expr2. UniBasic compares each character of the replacement string expr2 and, if necessary, replaces each character of the target string expr1 on an individual basis. UniBasic does not compare and insert strings as a whole. CONVERT supports multibyte languages. CONVERT can delete characters from a string, but it does not insert additional characters. If the replacement substring expr2 contains more characters than are in the substring it replaces (expr1), the extra characters are ignored. Syntax CONVERT expr1 TO expr2 IN var Parameters The following table describes each parameter of the syntax. Parameter Description expr1 Specifies the target string to replace with expr2. expr2 Specifies the string with which to replace expr1. var Specifies the string to search for expr1. 75 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment converts all occurrences of 1 to 3 and all occurrences of 2 to 4. The new contents of NSTRING becomes 34,0,03,35,44. NSTRING = "12,0,01,15,22" CONVERT "12" TO "34" IN NSTRING In the next example, the program segment converts all occurrences of AC to X, which sets NSTRING equal to XBDEFG (notice that C is deleted): NSTRING = "ABCDEFG" CONVERT "AC" TO "X" IN NSTRING In the following example, the replacement string of “F,G” is longer than the string it is intended to replace, so the extra characters, “,G”, are ignored. After the conversion, NSTRING equals F,C,D,E. NSTRING = "A,C,D,E" CONVERT "A" TO "F,G" IN NSTRING Related commands Language Command UniBasic CONVERT function, SWAP CONVERT The UniBasic CONVERT function changes all occurrences of the substring expr1 in expr3 to the string expr2. The system compares each character of the replacement string expr2 and, if necessary, replaces each character of the target string expr1 on an individual basis. UniBasic does not compare and insert strings as a whole. CONVERT supports multibyte languages. CONVERT can delete characters from a string expression, but it does not insert additional characters. If the replacement substring expr2 contains more characters than are in the substring it replaces (expr1), the extra characters are ignored. Syntax CONVERT(expr1, expr2, expr3) Parameters The following table describes each parameter of the syntax. 76 Parameter Description expr1 Specifies the target string to replace with expr2. expr2 Specifies the string with which to replace expr1. var Specifies the string to search for expr1. COS Examples In the following example, the program segment changes OLDSTR to NEWSTR, which now contains “868,848,838,808”: OLDSTR = "767,747,737,707" NEWSTR = CONVERT("7","8",OLDSTR) In the next example, the program segment displays 1AA33BB667. Note that the fives in X are dropped because no corresponding substitute is provided. X = "122334455667" PRINT CONVERT("245","AB",X) In the following example, Z becomes kakakakaka because the extra character “t” in S2 is ignored: Y="sasasasasa" S1="s" S2="kt" Z=CONVERT(S1,S2,Y) PRINT Z Related commands Language Command UniBasic CONVERT command, SWAP COS The UniBasic COS function returns the trigonometric cosine of a numeric expression. Syntax COS(expr) Examples In the following example, the program statement assigns the cosine of a 60-degree angle to the variable COSINE. COSINE is assigned the value of 0.5. COSINE = COS(60) In the next example, the program statement prints the cosine of the variable VAL plus 10: PRINT COS(VAL+10) Related commands Language Command UniBasic ACOS, ASIN, ATAN, COS, SIN, TAN COUNT The UniBasic COUNT function returns the number of times a substring appears within a string. The string you want to search, str.expr1, must be longer than the substring str.expr2. After str.expr2 is 77 Chapter 1: UniBasic commands and functions found, the system searches the string again with the new starting point after the entire first occurrence of str.expr2. If str.expr2 is not found, the COUNT function returns 0. COUNT supports multibyte languages. Note: In BASICTYPEs P and M, after UniData finds str.expr2, it searches the string again with the new starting point after the first character of the first occurrence of str.expr2. UniData can find overlapping character strings. Syntax COUNT(str.expr1, str.expr2) Parameters The following table describes each parameter of the syntax. Parameter Description str.expr1 Specifies the string to search. This string must be longer than str.expr2. str.expr2 Specifies the target string to search for and count occurrences of in str.expr1. Examples In the following example, the program segment searches the string STRING for the number of occurrences of the substring II. It returns this number, 2, in the variable IC. STRING = "JAWSII,ROCKYIII,STARTREKIV" IC = COUNT(STRING,"II") In the next example, the same program segment compiled under BASICTYPE P or M searches the string STRING for the number of occurrences of the substring II and assigns that number, 3, to the variable IC. It counts two occurrences of the substring II in ROCKYIII. $BASICTYPE "P" STRING = "JAWSII,ROCKYIII,STARTREKIV" IC = COUNT(STRING,"II")COUNTS COUNTS The UniBasic COUNTS function returns the number of times a substring appears within each element of an array. The elements in the array you want to search, expr, must be longer than the substring str.expr. After str.expr is found, the system searches the array again with the new starting point after the entire first occurrence of str.expr. If str.expr is not found, COUNTS returns 0. COUNTS supports multibyte languages. Note: In BASICTYPEs P and M, after UniData finds str.expr, it searches the string again with the new starting point after the first character of the first occurrence of str.expr. UniData can find overlapping character strings. Syntax COUNTS(expr,str.expr) 78 createCertificate Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies the array to search. The elements of this array must be longer than str.expr. str.expr Specifies the target string to search for and count occurrences of in elements of expr. Examples In the following example, the program segment searches the string STR for the number of occurrences of substring I, and returns the answer in the variable IC. After execution, IC contains 2}3}1. STR = "JAWSII":@VM:"ROCKYIII":@VM:"STARTREKIV" IC = COUNTS(STR,"I") In the next example, the same program segment compiled under BASICTYPE P or M searches the string STR for the number of occurrences of the substring II and assigns the values to the variable IC. After execution, IC contains 1}2}0. $BASICTYPE "P" STR = "JAWSII":@VM:"ROCKYIII":@VM:"STARTREKIV" IC = COUNTS(STR,"II") If the preceding code is compiled in BASICTYPE U or R, COUNTS returns “1}1}0” in the variable IC. createCertificate The createCertificate function generates a certificate. The certificate can either be a selfsigned certificate as a root CA that you can use later to sign other certificates, or it can be a CA signed certificate. The generated certificate conforms to X509V3 standard. The difference between CA-signing and leaf-CA-signing is that, for CA-signing, the resultant certificate can serve as an intermediate CA certificate to sign other certificates, while leaf-CA-signing generates certificates that are intended for end user use only. This function is provided mainly for the purpose of enabling application development and testing. As such, the certificate generated contains only a minimum amount of information and does not allow any extensions specified by the X509 standard and that are supported by many other vendors. It is recommended that you implement a complete PKI solution partnered with a reputed PKI solution vendor. For detailed information about the createCertificate function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax createCertificate(action, req, signKey, keyPass, CAcert, days, extensions, certOut) 79 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description action 1 - Self-signing 2 - CA-signing 3 - leaf-CA-signing req A string containing the certificate request file name. signKey A string containing the private key file name. keyPass A string containing the pass phrase to protect the private key. CAcert A string containing the CA certificate. days The number of days for which the certificate is valid. The default is 365 days. extensions A string containing extension specifications. certOut A string containing the generated certificate file. The following table describes the status of each return code. Return codes Status 0 Success. 1 Cannot read certificate request file. 2 Cannot read the key file. 3 Cannot read the CA certificate file. 4 Cannot generate the certificate. createCertRequest The createCertRequest() function generates a PKCS #10 certificate request from a private key in PKCS #8 form and a set of user specified data. The request can be sent to a CA or used as a parameter to createCertificate() to obtain an X.509 public key certificate. The certificate request will typically contain the information described in the following table. Item Description Version Defaults to 0. Subject The identification data of the certificate holder. This includes, country, state/province, locality (city), organization, unit, common name, email address, and so forth. Public key The key’s algorithm (RSA or DSA) and value. Signature The signature of the requester, (signed by the private key). The subject data must be provided by the requester through the dynamic array, subjectData. It contains @FM separated attributes in the form of “attri=value”.The following table describes the commonly used subjectData attributes. 80 Item Description Examples C Country C=US ST State ST=Colorado createCertRequest Item Description Examples L Locality L=Denver O Organization O=MyCompany OU Organization Unit OU=Sales CN Common Name [email protected] Email Email Address [email protected] For detailed information about creating a certificate request, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax createCertRequest(key, inFormat, keyLoc, algorithm, digest, passPhrase, subjectData, outFile, outFormat) Parameters The following table describes each parameter of the syntax. Parameter Description key A string containing the key or name of the file storing the key. inFormat The key format. 1 - PEM 2 - DER keyLoc 1 - Put the key into string privKey/pubKey. 2 - Put the key into a file. algorithm 1 - RSA 2 - DSA digest 1 - MD5 2 - SHA1 passPhrase A string storing the pass phrase to protect the private key. subjectData The identification information of the requester. outFile A string containing the path name of the file where the certificate request is stored. outFormat The generated certificate format. 1 - PEM 2 - DER The following table describes the status of each return code. Return codes Status 0 Success. 1 Private key file cannot be opened. 2 Unrecognized key or certificate format. 3 Unrecognized key type. 81 Chapter 1: UniBasic commands and functions Return codes Status 4 Unrecognized encryption algorithm. 5 Unrecognized key (corrupted key or algorithm mismatch). 6 Invalid pass phrase. 7 Invalid subject data (illegal format or unrecognized attribute, etc.). 8 Invalid digest algorithm. 9 Output file cannot be created. 99 Cert Request cannot be generated. createRequest The createRequest function creates an HTTP request and returns a handle to the request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax createRequest(URL, http_method, request_handle) Parameters The following table describes each parameter of the syntax. Parameter Option URL A string containing the URL for a resource on a web server. An accepted URL must follow the specified syntax defined in RFC 1738. The general format is: http://<host>:<port>/<path>?<searchpart>. The host can be either a name string or IP address. The port is the port number to which you want to connect, which usually defaults to 80 and is often omitted, along with the preceding colon. The path tells the web server which file you want, and, if omitted, means “home page” for the system. The search path can be used to send additional information to a web server. http_method A string which indicates the method to be performed on the resource. See the table below for the available (case-sensitive) methods. request_handle A handle to the request object. The following table describes the available methods for http_method. 82 Method Description GET Retrieves whatever information, in the form of an entity, identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. createSecureRequest Method Description POST [:<MIME-type>] For this method, it can also have an optional MIME-type to indicate the content type of the data the request intends to send. If no MIME-type is given, the default content type will be “application/x-wwwform-urlencoded”. Currently, only “multipart/form-data” is internally supported, as described in function addRequestParameter() and submitRequest(), although other “multipart/* data can also be sent if the user can assemble it on his/her own. (The multipart/form-data format itself is thoroughly described in RFC 2388). HEAD The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining meta information about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. OPTIONS The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. HTTP 1.1 and later. DELETE The DELETE method requests that the origin server delete the resource identified by the Request-URI. HTTP 1.1 and later. TRACE The TRACE method is used to invoke a remote, application-layer loopback of the request message. HTTP 1.1 and later. PUT The PUT method requests that the enclosed entity be stored under the supplied Request-URI. HTTP 1.1 and later but not supported. CONNECT /* HTTP/1.1 and later but not supported */ The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid URL (Syntactically). 2 Invalid method (For HTTP 1.0, only GET/POST/HEAD) Note: If URL does include a searchpart, it must be in its encoded format (space is converted into +, and other non-alphanumeric characters are converted into %HH format. See addRequestParameter() for more details). However, host and path are allowed to have these “unsafe” characters. UniBasic will encode them before communicating with the web server. createSecureRequest The createSecureRequest function behaves exactly the same as the createRequest() function, except for the fourth parameter, a handle to a security context, which is used to associate the security context with the request. If the URL does not start with “https” the parameter is ignored. If the URL starts with “https” but an invalid context handle or no handle is provided, the function aborts and returns with an error status. 83 Chapter 1: UniBasic commands and functions Syntax createSecureRequest(URL, http_method, request_handle, security_context) Parameters The following table describes each parameter of the syntax. Parameter Description URL A string containing the URL for a resource on a web server. An accepted URL must follow the specified syntax defined in RFC 1738. The general format is: http://<host>:<port>/<path>?<searchpart>. The host can be either a name string or IP address. The port is the port number to which you want to connect, which usually defaults to 80 and is often omitted, along with the preceding colon. The path tells the web server which file you want, and, if omitted, means “home page” for the system. The search path can be used to send additional information to a web server. http_method A string which indicates the method to be performed on the resource. See the table below for the available (case-sensitive) methods. request_handle A handle to the request object. securityContext A handle to the security context. The following table describes the available methods for http_method. 84 Method Description GET Retrieves whatever information, in the form of an entity, identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. POST [:<MIME-type>] For this method, it can also have an optional MIME-type to indicate the content type of the data the request intends to send. If no MIME-type is given, the default content type will be “application/x-wwwform-urlencoded”. Currently, only “multipart/form-data” is internally supported, as described in function addRequestParameter() and submitRequest(), although other “multipart/* data can also be sent if the user can assemble it on his/her own. (The multipart/form-data format itself is thoroughly described in RFC 2388). HEAD The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining meta information about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. OPTIONS The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. HTTP 1.1 and later. createSecurityContext Method Description DELETE The DELETE method requests that the origin server delete the resource identified by the Request-URI. HTTP 1.1 and later. TRACE The TRACE method is used to invoke a remote, application-layer loopback of the request message. HTTP 1.1 and later. PUT The PUT method requests that the enclosed entity be stored under the supplied Request-URI. HTTP 1.1 and later but not supported. CONNECT /* HTTP/1.1 and later but not supported */ The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid URL (Syntactically). 2 Invalid method (For HTTP 1.0, only GET/POST/HEAD) Note: If URL does include a searchpart, it must be in its encoded format (space is converted into +, and other non-alphanumeric characters are converted into %HH format. See addRequestParameter() for more details). However, host and path are allowed to have these “unsafe” characters. UniBasic will encode them before communicating with the web server. createSecurityContext The createSecurityContext function creates a security context and returns a handle to the context. A security context is a data structure that holds all aspects of security characteristics that the application intends to associate with a secured connection. Specifically, the following information may be held for each context: ▪ Protocol version ▪ Sender’s certificate to be sent to the peer ▪ Issuer’s certificate or certificate chain to be used to authenticate incoming certificate ▪ Certificate verification depth ▪ Certificate Revocation List ▪ Sender’s private key for signature and key exchange ▪ Flag to perform client authentication (useful for server socket only) ▪ Context ID and time stamp For detailed information about the createSecurityContext function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax createSecurityContext(context, version) 85 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description context The security context handle. version A string with the following values: SSLv2, SSLv3, or TLSv1. The following table describes the status of each return code. Return codes Status 0 Success. 1 Security context could not be created. 2 Invalid version. CRT The UniBasic CRT command sends output to the display terminal regardless of the use of the PRINTER ON/OFF command. print.expr can consist of any of the following: ▪ String data. ▪ Any number of strings or numeric variables. ▪ UniBasic functions. Tip: Use the UniBasic @ function before the CRT command to position the cursor on the screen or execute other terminal functions before printing to the terminal. Set UDT.OPTIONS 5 on if you want the display to pause at the end of each page. For information about UDT.OPTIONS, see the UDT.OPTIONS Commands Reference. To suppress the line feed at the end of displayed text, end the CRT or DISPLAY statement with a colon. Syntax CRT [print.expr] Synonyms DISPLAY DATA The UniBasic DATA command places data in an input queue stored in @DATA. ASCII character 013 (CR) delimits elements in the queue. Each subsequent INPUT statement reads one element. @DATA is read-only. For more information about @ variables, see UniBasic@variables, on page 520. The expressions (expr1 and expr2) can be literal strings or variables. You can continue DATA statements over several lines by placing a comma at the end of each line to be continued. UniData places data in the queue in order of execution of DATA commands. The queue processes on a first-in, first-out basis. When the input queue is empty, UniData requests input from the terminal. The 86 DATE input queue remains available through program CHAIN and EXECUTE operations, but is cleared when control returns to the UniData ECL prompt (:). Tip: You can load inline prompts in paragraphs with the DATA command. For instructions, see the UniData Commands Reference. Syntax DATA expr1 [,expr2]... Examples In the following example, the program segment executes a DATA statement containing variables and constants of both string and numeric types. The first value, 10, is read by a subsequent input statement and assigns the value to the variable COUNT. DATA 10,"William","James",TESTVAL,135, "Test Run" INPUT COUNT DATE The UniBasic DATE function returns the current system date in internal format. Internal format is the number of days after December 31, 1967. Syntax DATE( ) Examples The following statement prints the current system date in external format: PRINT OCONV(DATE(),"D") Related commands Language Command UniBasic ICONV Date (D), OCONV Date (D), TIMEDATE DBTOXML Creates an XML document from the UniData database. Syntax DBTOXML(xml_document, doc_location, u2xmap_file, u2xmap_location, condition, status) Parameters The following table describes each parameter of the syntax. 87 Chapter 1: UniBasic commands and functions Parameter Description xml_document The name of the XML document to create. doc_flag A flag defining the type of xml_documentxml_document. Valid values are: XML.FROM.FILE - xml_document is a file name. XML.FROM.STRING - xml_document is the name of variable containing the XML document. u2xmap_file The name of the U2XMAP file to use to produce the XML document. u2xmap_location The location of the U2XMAP file. XML.FROM.FILE - u2xmap_file is a file name. XML.FROM.STRING - is u2xmap_file the name of variable containing the mapping rules. condition A query condition for selecting data from the UniData file, for example, WHERE SCHOOL = "CO002" status XML.SUCCESS or XML.FAILURE. Note: The XML options set previously at the session level through the XMLSetOptions command or through the XMLSetOptions() API are used when you run the DBTOXML API in the current UniData session. DCOUNT The UniBasic DCOUNT function returns the number of substrings delimited by delim in a string. If str is an empty string, UniData returns 0. If str contains data but no delimiter, UniData returns 1. DCOUNT supports multibyte languages. Syntax DCOUNT(str,delim) Parameters The following table describes each parameter of the syntax. Parameter Description str Specifies the string to search for occurrences of substrings delimited by delim. delim Specifies the delimiter to use in searching str. Examples In the following example, the program segment finds three occurrences of the value mark and prints 3: STR = 123:@VM:456:@VM:789 SUBS = DCOUNT(STR,@VM) PRINT SUBS In the next example, the program segment prints 1 because no delimiter is found in the string: STR = 123 88 DEACTIVATEKEY DCOUNT(STR,@VM) PRINT SUBS The following example prints 3: STR="A/B/C" PRINT DCOUNT(STR,"/") Related commands Language Command UniBasic COUNT, COUNTS DEACTIVATEKEY Use the DEACTIVATEKEY command to deactivate a key or a wallet. This command is useful to deactivate keys to make your system more secure. Note: You can deactivate only keys with password protection with this command. Keys that do not have password protection are automatically activated and cannot be deactivated. Syntax DEACTIVATEKEY <key.id>, <password> [ON <NFA_SERVER>] [ON ERROR <statements>] Parameters The following table describes each parameter of the syntax. Parameter Description key.id The key ID or wallet ID to deactivate. If you provide a Wallet ID, UniData deactivates all keys in the wallet. password The password corresponding to key.id. ON NFA_SERVER The name of the NFA_SERVER on which you want to deactivate the encryption key. The syntax for NFA_SERVER can be either: @domain.var where domain.var specifies the ID for a VOC entry that contains the NFA server connection parameters OR MACHINE <host> PORT <port> [, UDTHOME <udthome>] NFA files are always encrypted and decrypted on the remote machine by the NFA server. ON ERROR statements If you specify ON ERROR statements and an error occurs, UniData executes the statements following the ON ERROR clause. Otherwise, UniData executes the next statement. STATUS codes The DEACTIVATEKEY statement returns the following STATUS codes regarding wallet operations: 89 Chapter 1: UniBasic commands and functions STATUS code Description 0 Operation successful 1 Key is already activated or deactivated. This applies to a single key, not a wallet operation 2 Operation failed. This applies to a single key, not a wallet operation 3 Invalid wallet ID or password 4 No access to wallet 5 Invalid key ID or password 6 No access to one of the keys in the wallet 9 Other error Examples The following example illustrates deactivating an encryption key: DEACTIVATEKEY "test","myunidata" ON ERROR PRINT "Unable to deactivate key" DEBUG The UniBasic DEBUG command stops program execution, turns control over to the interactive UniBasic debugger, and then displays the debugger prompt (!). Pressing the interrupt key also gives control to the debugger. For information about the UniBasic debugger, see Using the UniBasic Debugger. To use the DEBUG command to display the contents of variables, you must compile the program with the D option. Note: The setting of UDT.OPTIONS 14 determines where to return control after exiting a UniBasic program when you are using the UniBasic debugger and enter ABORT or END. For information about UDT.OPTIONS, see the UDT.OPTIONS Commands Reference. When you enter the debugger, a message similar to the following displays, and the cursor is placed at the debugger prompt: DEBUGGER called before line 1 of program BP/TEST ! Syntax DEBUG Related commands Language Command UniBasic ABORT UniData BASIC, DEBUG.FLAG, DEBUGLINE.ATT, DEBUGLINE.DET, ON.ABORT, RUN, SETDEBUGLINE, UNSETDEBUGLINE For information, see the UniData Commands Reference. 90 DEFFUN DEFFUN The UniBasic DEFFUN command declares a user-written function, making the function available in a UniBasic program. You must declare the function before you can use it in a program. Note: You also must define the function with the UniBasic FUNCTION command in a separately cataloged file before you can call it. Syntax DEFFUN function.name [([MAT] arg.1[,[MAT]arg.2]...)] [CALLING catalog.name] Function Naming The function name used in the DEFFUN statement must be the same as the name of the cataloged file that contains the FUNCTION statement. Either of the following statements declares the function cataloged under the name func.name: ▪ ▪ DEFFUN func.name(arg, arg,...) DEFFUN name(arg, arg,...) CALLING func.name Within the calling program, the name used in the DEFFUN statement and the name used to call the function must be the same. This does not need to be the same name as the cataloged program file or the name used in the FUNCTION statement. Parameters The following table describes each parameter of the syntax. Parameter Description function.name Specifies the function name that the calling statement uses in this program. (MAT arg.1 ,MAT arg.2...) Specifies the arguments to be passed to the function. You must enclose arguments in parentheses and separate them with commas. Precede an argument with MAT to indicate that the argument is an array. CALLING file.name Specifies the function’s cataloged file name. Include this statement if the cataloged program name differs from function.name. Can be a literal or variable. Examples The DEFFUN statement in the following example declares myfunc. The CALLING clause indicates that the name of the cataloged file that contains the FUNCTION statement is called yourfunc. In the first print statement, the function is called and the return value is printed. DEFFUN myfunc(a, MAT b, c) CALLING "yourfunc" ;* Declare function. DIM b(10) ;* Define array. a = 2 ;* Set upper bound. FOR i = 1 TO a ;* Initialize array. b(i) = i NEXT i PRINT "r from FUNCTION: ":myfunc(a, MAT b, c) PRINT "c from FUNCTION: ":c 91 Chapter 1: UniBasic commands and functions The preceding program calls the following function. The name of this cataloged file is yourfunc. This is the name that must match the DEFFUN statement in the program above. Notice that the function definition uses yet another name for the function (anotherfunc). FUNCTION anotherfunc(a, MAT b, c) definition. DIM b(-1) r = 0 c = 1 back. FOR i = 1 TO a in: r += b(i) c *= b(i) NEXT i RETURN r ;* Start function ;* Declare array. ;* Initialize return value. ;* Initialize value passed ;* To the upper bound passed ;* Sum array members. ;* Multiply array members. ;* Return value. The following screen example shows the command that runs the program and the output from the program: :RUN BP FUNCTION.CALL r from FUNCTION: 3 c from FUNCTION: 2 The following example calls a user-defined function named CALC.SALES.TAX: PRINT @(-1) DEFFUN CALC.SALES.TAX(arg.1,arg.2) PROMPT '' PRINT 'Enter county name':;INPUT COUNTY.NAME PRINT 'Enter sales amount ':;INPUT SALES.AMT TAX.AMT=0 TAX.AMT=CALC.SALES.TAX(COUNTY.NAME,SALES.AMT) PRINT 'County name =':COUNTY.NAME PRINT 'Sales amount =':SALES.AMT PRINT 'Tax amount =':TAX.AMT END Related commands Language Command UniBasic FUNCTION DEL The UniBasic DEL command deletes an attribute, value, or subvalue from a dynamic array. The corresponding delimiter is also removed. The DELETE function and the command perform the same action. Warning: DEL destroys the data and the corresponding delimiters. Use the DEL command with caution. 92 DELETE Syntax DEL dyn.array.var <attrib.expr[,val.expr [,subval.expr]]> Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies the dynamic array on which to perform the delete operation. attrib.expr Specifies which attribute of the dynamic array to delete. If val.expr is omitted, DEL deletes the entire attribute, including all values and subvalues. ,val.expr Specifies which value of the dynamic array attribute to delete. If subval.expr is omitted, DEL deletes the entire value, including the subvalues. ,subval.expr Specifies which subvalue of the dynamic array attribute value to delete. Examples The following program segment is taken from Developing UniBasic Applications. It deletes the attribute in the variable POSITION. This removes one order for a particular client from the CLIENTS file in the demo database. DELETE_RECORD: * (Assuming the order #'s are on line 12) READVU ORDER_LINE FROM CLIENT_FILE,CLIENT_NUMBER,12 THEN LOCATE ORDER_NUMBER IN ORDER_LINE<1> SETTING POSITION THEN DEL ORDER_LINE<1,POSITION> END In the following example, the program segment deletes the third attribute of the dynamic array ARRAY1. The attribute removed is ‘Anne’. ARRAY1 = '#543':@AM:'Dorothy':@AM:'Anne':@AM:'Parker' DEL ARRAY1<3> In the following example, the statement is invalid. The DEL statement has too many parameters: ARRAY1 = '#543':@AM:'Dorothy':@AM:'Anne':@AM:'Parker' DEL ARRAY<13,0,1,4> Related commands Language Command UniBasic DELETE, EXTRACT, INSERT, REMOVE, REPLACE, SUBSTRINGS DELETE The UniBasic DELETE command deletes a record from a UniData file. In addition, the DELETE command releases any locks on the record that have been set by previous commands. 93 Chapter 1: UniBasic commands and functions If DELETE is trying to delete an item that does not exist, UniData sets @SYSTEM.RETURN.CODE to 0. If the DELETE command was successful, UniData sets @SYSTEM.RETURN.CODE to the number of items deleted. If the DELETE statement contained an error, UniData sets @SYSTEM.RETURN.CODE to -1. Note: The DELETEU command also deletes a record, but it does not release locks. This is the only difference between DELETE and DELETEU statements. UniBasic locks are advisory only. For more information, see Developing UniBasic Applications. Syntax DELETE [file.var,] record.ID.expr [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file from which to delete the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal DELETE error occurs. record.ID.expr ON ERRORstatements A default file is one for which no file variable is assigned in the OPEN statement. Specifies the record to delete. Specifies UniBasic statements to execute if the DELETE statement fails because UniData cannot find the file, or a default file is not open. If you do not specify the ON ERROR clause, the program terminates. Examples The following program statement eliminates the record with the ID of PEANUT from the default file: DELETE "PEANUT" The following program segment deletes the record whose ID is specified by the variable DEL_ID from the file previously opened to the PARTS variable: DEL_ID = "HOOK" DELETE PARTS, DEL_ID The following statement is invalid because the file variable is specified incorrectly in the DELETE statement: OPEN 'CUSTOMER'TO CUST ELSE STOP 'NO CUST' DELETE CUSTOMER, C.ID The following program segment is taken from Developing UniBasic Applications. The DELETE command deletes the record in the ORDERS file after the corresponding attribute is deleted from the CLIENTS file. Both steps are necessary to remove the order record itself, and to remove the reference to the order in the client record (the attribute in the CLIENTS file). DELETE_RECORD: * (Assuming the order #'s are on line 12) READVU ORDER_LINE FROM CLIENT_FILE,CLIENT_NUMBER,12 THEN LOCATE ORDER_NUMBER IN ORDER_LINE<1> SETTING POSITION THEN 94 DELETE DEL ORDER_LINE<1,POSITION> END WRITEV ORDER_LINE ON CLIENT_FILE, CLIENT_NUMBER, 12 END * DELETE ORDERS_FILE, ORDER_NUMBER RELEASE CLIENT_FILE,CLIENT_NUMBER RETURN Related commands Language Command UniBasic DEL, DELETE function, DELETEU DELETE The UniBasic DELETE function deletes an attribute, value, or subvalue from a dynamic array. The corresponding delimiter is also removed. The DELETE function and the DEL command perform the same action. Syntax DELETE(dyn.array, attrib.expr[,val.expr [,subval.expr]]) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies the dynamic array from which to delete. attrib.expr Specifies which attribute of the dynamic array to delete. If val.expr is omitted, DELETE deletes the entire attribute, including all values and subvalues. ,val.expr Specifies which value of the dynamic array attribute to delete. If subval.expr is omitted, DELETE deletes the entire value, including all subvalues. ,subval.expr Specifies which subvalue of the dynamic array attribute value to delete. Examples In this first example, the program segment deletes the first attribute (125) and the attribute mark from the dynamic array ARRAY: ARRAY = 125:@AM:1:@VM:62:@VM:3:@AM:132:@VM:4:@VM:5:@SM:1 ARRAY=DELETE(ARRAY,1,0,0) In the next example, the program statement removes the first subvalue of the first value of the second attribute in ARRAY. The modified array is assigned to ARRAY2. ARRAY2=DELETE(ARRAY,2,1,1) 95 Chapter 1: UniBasic commands and functions In the next example, the program segment deletes the third attribute, including A, B, and C: ARRAY = 1:@AM:2:@AM:'A':@VM:'B':@VM:'C' ARRAY = DELETE(ARRAY,3,0,0) Related commands Language Command UniBasic DEL, DELETE command, DELETEU DELETELIST The UniBasic DELETELIST command deletes a saved select list. Select lists are saved by the UniQuery SAVE.LIST command and the UniBasic WRITELIST command. list.name.expr is the name of the saved list to be deleted. If the list you specify cannot be found, UniData displays an error message and takes no action. Syntax DELETELIST list.name.expr Examples The following statement deletes the saved list CUST in the current account: DELETELIST "CUST" Related commands Language Command UniBasic FORMLIST, READLIST, SELECT, SELECTINDEX, SELECTINFO, WRITELIST UniData SQLSELECT For information, see the UniData Commands Reference. UniQuery DELETELIST, GETLIST, SAVE.LIST, SELECT, SSELECT For information, see the UniQuery Commands Reference DELETEU The UniBasic DELETEU command deletes the specified record from a UniData file. The DELETEU command retains record locks that were set by the same user process. This allows UniData to delete a record and re-create it while retaining a lock on it. Note: The DELETE command also deletes a record, but it releases locks. This is the only difference between DELETE and DELETEU statements. UniBasic locks are advisory only. For information about UniData file and record locks, see Developing UniBasic Applications. 96 DIM Syntax DELETEU [file.var,] record.ID.expr [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var, Specifies the file from which to delete the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal DELETE error occurs. A default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies the record to delete. ON ERROR statements Specifies UniBasic statements to execute if the DELETE statement fails because UniData cannot find the file, or a default file is not open. If you do not specify the ON ERROR clause, the program terminates. Examples In the following example, the statement eliminates the record with the record ID of JONES from the most recently opened default file: DELETEU "JONES" The following segment deletes the record. The record ID is stored in the variable DEL_ID. The file was opened to the variable DISCOUNT. DEL_ID = "ACTION_FILMS" DELETEU DISCOUNT, DEL_ID Related commands Language Command UniBasic DEL, DELETE, RELEASE DIM The UniBasic DIM command creates and determines the dimensions of a dimensioned array. You can specify arrays with one dimension (rows) or two dimensions (rows or rows, cols). In addition, the following limitations apply: ▪ You must dimension any array before you use it within a program. ▪ Zero elements other than 0,0 (such as 0,5 or 1,0) are invalid. ▪ The maximum number of elements you can specify is based on the total amount of virtual memory available on your system. ▪ Arrays passed to a subroutine cannot be redimensioned within the subroutine. For information about system configurations, see Administering UniData on UNIX or Administering UniData on Windows Platforms. 97 Chapter 1: UniBasic commands and functions MATREAD, MATWRITE, and MATPARSE load and empty an array from left to right and from top to bottom beginning with element 1,1 and ending by placing excess data in element 0,0. Note: BASICTYPEs M and P do not support position 0,0 in arrays. You could lose data if an array is too small for the amount of data you are attempting to load into it with MATPARSE. Syntax DIM name1(rows[,cols]) [,name2(rows[,cols])]... Synonyms DIMENSION Parameters The following table describes each parameter of the syntax. Parameter Description name1 Specifies the name of the array. rows Specifies the number of rows in the array. ,cols Specifies the number of columns in the array. If cols is omitted, the array is one-dimensional. INMAT function return values After you execute DIM, the UniBasic INMAT function returns one of the values described in the following table. Value Description 0 The dimensioned array was not created. UniData returns an error message, but program execution continues. 1 Memory was insufficient to create the dimensioned array. UniData returns an error message, but program execution continues. n The dimensioned array was created. n is the number of elements in the array. Resizing Arrays You can use the DIM statement to dynamically redimension an array without losing any data if the size of the redimensioned array is large enough to contain all data in the original array. When you redimension, UniBasic places the old data elements into the new array from left to right and from top to bottom. All leftover data is placed in the 0,0 element. Although you can change the size of an array during program execution, its configuration cannot change. For example, a two-dimensional array cannot be changed to one-dimensional and vice versa. Examples In the following example, the program statement creates three arrays: one-dimensional NAME, onedimensional TITLES, and two-dimensional DATES. DIM NAME(100),TITLES(100),DATES(100,2) 98 DIGEST In the next example, two DIMENSION statements are included in the same program, although because the new array is smaller than the original, all excess data is placed in element 0,0. After the execution of the second DIMENSION statement, the array has the dimension of 100 by 10. DIM WAGES(50,100) DIM WAGES(100,10) The following program segment creates the array TEST by setting variable A to 30, and then declaring TEST as a one-dimensional array of 30 elements: A = 30 DIM TEST (A) The following sample code is invalid because array size is declared with nonnumeric variables “(” and “)” and because you cannot use a variable in a dimension statement: TEST = "(10,5)" DIM TEST In contrast, the following statement is valid: DIM TEST (10,5) Related commands Language Command UniBasic INMAT, MAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATREADU, MATWRITE, MATWRITEU DIGEST The DIGEST function generates a message digest of supplied data. A message digest is the result of a one-way hash function (digest algorithm) performed on the message. Message digest has the unique properties that alight change in the input results in a significant difference in the resulting digest. Therefore, the probability of two different messages resulting in the same digest (collision) is very unlikely. It is also virtually impossible to reverse to the original message from a digest. Message digest is widely used for digital signatures and other purposes. The desired digest algorithm is specified in algorithm. You specify data and its location are with data and dataLoc, respectively. UniData puts the arrived digest into a dynamic array in result. Since digest is short and has a fixed length, it is always put into a string, and no file option is provided. The result can be in either binary or hex format. Syntax DIGEST(algorithm, data, dataLoc, result) Parameters The following table describes each parameter of the syntax. 99 Chapter 1: UniBasic commands and functions Parameter Description algorithm A string containing the digest algorithm name (uppercase or lowercase). UniData supports the following algorithms: ▪ “md2” ▪ “md4” ▪ “md5” ▪ “mdc2” ▪ “rmd160” ▪ “sha” ▪ “sha1” data Data or the name of the file containing the data to be digested. dataLoc 1 - Data in a string 2 - Data in a file result A string to store the digest result. The following table describes the status of each return code. Return codes Status 0 Success 1 Unsupported digest algorithm 2 The data file cannot be read 3 Message digest cannot be obtained 4 Invalid parameters DIR The UniBasic DIR function returns the file size (in bytes), the last date and time the file was modified (in internal format), and the privileges for the file. UniData stores these values in the first four attributes of the return value.file.expr must evaluate to a file name at the operating system level. If you do not specify a path, UniData searches the current directory. Syntax DIR(file.expr) Examples The following UNIX program segment retrieves the file statistics on the UniData file stored in the subdirectory /usr/accounting/gl. The first attribute contains the file size in bytes, the second attribute contains the date the file was last updated, and the third attribute contains the time the file was last updated. UniData stores the second and third attributes in internal format, and the example converts them to the external format. FILESTAT = DIR("/usr/accounting/gl") SIZE = FILESTAT <1> DATE.MOD = OCONV(FILESTAT<2>,'D2/') TIME.MOD = OCONV(FILESTAT<2>,'MT') PRINT 'The gl file is ':SIZE 100 DISABLEDEC PRINT 'And was last modified: ':DATE.MOD,TIME.MOD DISABLEDEC Use the DISABLEDEC command to turn off decryption on a file or fields you specify. Syntax DISABLEDEC <filename> [, <multilevel-filename>], {ALL |<field_list> [ON ERROR <statements>] Parameters The following table describes each parameter of the syntax. Parameter Description filename The name of the file on which you want to disable decryption. ALL If you specify ALL, UniData will disable decryption on all encrypted fields of this file field_list A comma-separated list of fields for which you want to disable decryption. Do not enter spaces between the field names. ON ERROR statements If you specify ON ERROR statements and an error occurs, UniData executes the statements following the ON ERROR clause. Otherwise, UniData executes the next statement. STATUS codes DISABLEDEC has the following STATUS codes: STATUS code Description 0 No error, operation successful 1 Decryption is already disabled 2 General operation failure, such as an open file error 3 File is not an encrypted file 4 Attempting operation on a WHOLERECORD encrypted file 5 Field(s) is not an encrypted field 6 Cannot locate information to disable decryption 7 Field is not a valid field in this file Examples The following example illustrates disabling decryption on two fields in a file using a quoted string: DISABLEDEC "CUSTOMER","NAME,PHONE" ON ERROR PRINT "Unable to disable decryption” The next example illustrates disabling decryption on two fields using variables: CUST="CUSTOMER" FIELDS="NAME,PHONE" DISABLEDEC CUST,FIELDS ON ERROR PRINT "Unable to disable decryption" 101 Chapter 1: UniBasic commands and functions DISPLAY DISPLAY is a synonym for the CRT command. For further information, see CRT, on page 86. Synonyms CRT DISPLAYWIDTH The UniBasic DISPLAYWIDTH function returns the number of bytes needed to display a string expression. For instance, the display width of English characters is one. In languages that use multibyte characters, the display width of a character can be 1, 2, 3, or 4 bytes, depending on the language and the character. Syntax DISPLAYWIDTH (string) Examples The following illustration shows a string that indicates below each “character” the number of bytes required to display that character. The string contains eight bytes. Therefore, DISPLAYWIDTH would return 8 for this string. Related commands Language Command UniBasic BYTELEN, CHARLEN, ISMB, LEN, MBLEN DOWNCASE The UniBasic DOWNCASE function converts all characters in a string (str.expr) to lowercase. Special characters, including the null value, are not converted by this function. DOWNCASE does not convert multibyte characters. Syntax DOWNCASE(str.expr) 102 DQUOTE Examples In the following example, the program segment converts the contents of the variable USTRING to lowercase letters: USTRING = "WHY am I HAPPY?" DSTRING = DOWNCASE(USTRING) DSTRING now contains “why am i happy?”. Related commands Language Command UniBasic ICONV Masked Character (MC), OCONV Masked Character (MC), UPCASE DQUOTE DQUOTE is a synonym for the QUOTE function. For more information, see QUOTE, on page 287. Synonyms QUOTE DROUND The UniBasic DROUND function performs double-precision rounding on a value. Double-precision rounding uses two words to store a number, accommodating a larger number than in single-precision rounding, which stores each number in a single word. Note: DROUND affects the internal representation of the numeric value. It performs the rounding without conversion to and from string variables. This increases the speed of calculation. Syntax DROUND(val.expr [,precision.expr]) Parameters The following table describes each parameter of the syntax. Parameter Description val.expr Specifies the value to round. ,precision.expr Specifies the precision for the rounding. The valid range is 0 to 14. Default precision is four places. Examples In the following example, the DROUND statement results in 18.84955596. The equation is resolved, and then the result is rounded to eight decimal places. A= DROUND((3.14159265999*2*3),8) 103 Chapter 1: UniBasic commands and functions PRINT A Related commands Language Command UniBasic PRECISION UniData FLOAT.PRECISION For information, see the UniData Commands Reference. EBCDIC The UniBasic EBCDIC function converts the ASCII data in expr to its corresponding EBCDIC values. Note: BASICTYPE U, the standard application, converts data to EBCDIC format before the data is written to tape. Syntax EBCDIC(expr) Examples In the following example, the program statement first prints a message, and then prints the EBCDIC equivalent of the ASCII variable VAL: PRINT "EBCDIC equivalent":EBCDIC(VAL) Related commands Language Command UniBasic ASCII, CHAR, CHARS, SEQ ECHO The UniBasic ECHO command controls whether characters display on the terminal screen as you type them on the keyboard. Note: Use ECHO for security purposes when the entry of an ID or password should not display on the terminal screen. Syntax ECHO [ON | OFF | expr] Parameters The following table describes each parameter of the syntax. 104 Parameter Description ON Enables the display of characters as you type them on the keyboard. ENABLEDEC Parameter Description OFF Disables the display of characters as you type them on the keyboard. expr When expr is 0, ECHO is set to OFF. When expr is not 0, ECHO is set to ON. expr must be numeric. Examples The following program segment enables echoing because A+B is not 0: A = 1 B = 3 ECHO A+B ENABLEDEC Use the ENABLEDEC command to activate decryption on a file or fields you specify. Syntax ENABLEDEC <filename> [,<multilevel-filename>], {ALL | <field_list>} [ON ERROR <statements>] Parameters The following table describes each parameter of the syntax. Parameter Description filename The name of the file on which you want to enable decryption. ALL If you specify ALL, UniData enables decryption on all encrypted fields of this file. field_list A comma-separated list of fields for which you want to enable decryption. Do not enter spaces between the field names. ON ERROR statements If you specify ON ERROR statements and an error occurs, UniData executes the statements following the ON ERROR clause. Otherwise, UniData executes the next statement. STATUS codes ENABLEDEC has the following STATUS codes: STATUS code Description 0 No error, operation successful 1 Decryption is already enabled 2 General operation failure, such as an open file error 3 File is not an encrypted file 4 Attempting operation on WHOLERECORD encrypted file 5 Field(s) is not an encrypted file 6 Cannot locate information to disable encryption 7 Field is not a valid field in this file 105 Chapter 1: UniBasic commands and functions Examples The following example illustrates enabling decryption on two fields in a file using a quoted string: ENABLEDEC "CUSTOMER","NAME,PHONE" ON ERROR PRINT "Unable to enable decryptiON The next example illustrates enabling decryption on two fields using variables: CUST="CUSTOMER" FIELDS="NAME,PHONE" ENABLEDEC CUST,FIELDS ON ERROR PRINT "Unable to enable decryption" ENCODE The ENCODE() function performs data encoding on input data. Currently, UniData supports only Base64 encoding. Base 64 encoding is designed to represent arbitrary sequences of octets that do not need to be humanly readable. A 65-character subset of US-ASCII is used, enabling 6-bits to be represented per printable character. The subset has the important property that it is represented identically in all versions of ISO646, including US-ASCII, and all characters in the subset are also represented identically in all versions of EBCDIC. The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters. The encoded output stream must be represented in lines of no more than 76 characters each. All line breaks must be ignored by the decoding process. All other characters not found in the 65-character subset should trigger a warning by the decoding process. The function can perform either encoding or decoding, as specified by action. The data can either be in the dynamic array, data, or in a file whose name is specified in data, determined by dataLoc. URL encoding, is a mechanism for encoding information in a URI (Uniform Resource Identifier) under certain circumstances. Although it is known as URL encoding it is, in fact, used more generally within the main Uniform Resource Identifier (URI) set, which includes both Uniform Resource Locator (URL) and Uniform Resource Name (URN). URL encoding is also used in the preparation of data of the "application/x-www-form-urlencoded" media type which is often used in the submission of HTML form data in HTTP requests. URL Encoding replaces spaces with "+" signs, and unsafe ASCII characters with "%" followed by their hex equivalent. Safe characters are defined in RFC 3986. Syntax ENCODE(algorithm, action, data, dataLoc, result, resultLoc) Parameters The following table describes each parameter of the syntax. Parameter Description algorithm A string containing the encode method name. UniData currently only supports the Base64 method. Base64 - Encoding of data with a linefeed after every 64th character. Base64A - Base64 encoding of data on one line. URLENCODE- Encodes special characters into a hexadecimal representation of that character. (See RFC3986 for more information.) 106 ENCRYPT Parameter Description action 1 - Encode 2 - Decode data Data or the name of the file containing the data to be encoded or decoded. dataLoc 1 - Data in a string 2 - Data in a file result Encoded or decoded data or the name of the file storing the processed data. resultLoc 1 - Result in a string 2 - Result in a file. The following table describes the status of each return code. Return codes Status 0 Success. 1 Unsupported algorithm. 2 Invalid parameters (invalid data or result location type, and so forth). 3 The data cannot be read. 4 The data cannot be encoded or decoded. Examples The following program illustrates the ENCODE function. 0001 RESULT="" 0002 DEC="" 0003 STR="ABC D=E=F" 0004 STAT=ENCODE("URLENCODE", 1, STR, 1, RESULT, 1) 0005 STAT=ENCODE("URLENCODE",2,RESULT,1,DEC,1) 0006 PRINT "Original String: ":STR 0007 PRINT "Encoded String: ":RESULT 0008 PRINT "Decoded String: ":DEC Original String: ABC D=E= Encoded String: ABC+D%3DE%3DF Decoded String: ABC D=E=F ENCRYPT The ENCRYPT() function performs symmetric encryption operations. You can call various block and stream symmetric ciphers through this function. The supported ciphers are listed in UniData Security Features. You specify ciphers by algorithm, and they are not case sensitive. You can specify Base64 encoding and decoding with the action parameter. If you specify encoding, the encrypted data is Base64 encoded before being entered into result. If you specify decoding, the data is Base64 decoded before being encrypted. Specify the data and its location using data and dataLoc, respectively. You can explicitly specify Key, read it from a file, or, alternatively, derived it on the fly by specifying keyAction, in which case the key string is used as a pass phrase to derive the actual key. The encrypted or decrypted data is put into the dynamic array result, or a file, as specified by resultLoc. 107 Chapter 1: UniBasic commands and functions Salt is used to provide more security against certain kinds of crypt analysis attacks, such as dictionary attacks. If you specify an empty salt, UniData uses an internally generated salt in deriving the key. UniData ignores Salt when action is set to decrypt. UniData uses IV (Initialization Vector) to provide additional security to some block ciphers. It does not need to be secret but should be fresh, meaning different for each encrypted data. If you supply an existing key, IV is generally needed. However, if the encryption key is to be derived from a pass phrase, IV can be generated automatically. Both salt and IV must be provided in hexadecimal format. Syntax ENCRYPT(algorithm, action, data, dataLoc,key, keyLoc, keyAction, salt, IV, result, resultLoc) Parameters The following table describes each parameter of the syntax. Parameter Description algorithm A string containing the cipher name. action 1 - Encrypt 2 - Base64 encode after encryption 3 - Decrypt 4 - Base64 decode before decryption 5 - One-line Base64 encoding, which does not place line breaks in the result. 6 - One-line Base64 decoding, which does not place line breaks in the result. data Data or the name of the file containing the data to be processed. dataLoc 1 - Data in a string 2 - Data in a file key The actual key (password) or file name containing the key. keyLoc 1 - Key in data 2 - Key in file keyAction 1 - Use actual key 2 - Derive key from pass phrase 3 - Use user-specified key directly in the same manner as OpenSSL 4 - Derive the actual key using a user-specified value and an MD5 algorithm in the same manner as OpenSSL 5 - Derive actual key using a user-specified value and a SHA1 algorithm in the same manner as OpenSSL Note: keyAction 1 and 2 may be used to exchange encrypted data between UniVerse and UniData systems. However, if you want to exchange encrypted data between UniData or UniVerse and third party products such as OpenSSL-based programs, Java programs, or MicroSoft.Net programs, you should use keyActions 3-5. 108 Salt A string containing the Salt value. IV A string containing IV. END Parameter Description result The result buffer or the name of the file storing the result. resultLoc 1 - Result in a string 2 - Result in a file. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid cipher. 2 Invalid parameters (location/action value is out of range, etc.). 3 The data cannot be read. 4 The key cannot be derived. 5 Base 64 encoding/decoding error. 6 Encryption/decryption error. END The UniBasic END command declares the end of a program or a block of statements. UniBasic does not require you to use END at the end of a program. Syntax END Examples In the following example, the END declares the end of the program segment. (The first END ELSE ends the THEN clause in the IF/THEN/ELSE statement.) A = 0 PRINT "Enter a number: ": INPUT X IF X>0 THEN PRINT "Incrementing." A += 1 END ELSE PRINT "Decrementing." A -= 1 END PRINT A ENTER The UniBasic ENTER command passes control to the program you specify. It terminates the program that is passing control and executes the cataloged program. The ENTER command allows variables to pass through common areas, but all other variables are reinitialized when the new program begins. 109 Chapter 1: UniBasic commands and functions Note: This command does not return control to the original program by default. For structured programming, use GOSUB and RETURN. This makes the program easier to read and maintain. The ENTER command processes faster than the CHAIN command. Syntax ENTER filename ENTER @variable Examples In the following example, the program statement transfers control to cataloged program CHECK_1: ENTER CHECK_1 In the next example, the program segment transfers control to cataloged program CHECK_2: NO = 2 PROG = "CHECK_":NO ENTER @PROG Related commands Language Command UniBasic CALL, CHAIN, COMMON, GOSUB EQ The UniBasic EQ operator serves as an assignment operator and a relational operator. As an assignment operator, it assigns expr to variable. As a relational operator, it tests whether expression expr1 is equal to expr2.expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Relational operators make the comparisons that direct program flow in conditional statements like the following: IF VAR1 = VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 = VAR2 Syntax variable = expr expr1 EQ expr2 Synonyms = Parameters The following table describes each parameter of the syntax. 110 EQS Parameter Description variable Specifies the variable to which to assign the contents of expr. expr Specifies a value, string, expression, or variable the value of which variable is assigned to. Examples In the following example, the program statement assigns the value of 60 to the variable PAGELENGTH: PAGELENGHTH EQ 60 In the next example, the EQ relational operator is used in a conditional test. The program segment tests whether A equals B. In this case, the message “NOT EQUAL” prints. A = 24 B = 23 IF A EQ B THEN PRINT "EQUAL" END ELSE PRINT "NOT EQUAL" END Related commands Language Command UniBasic EQS EQS The UniBasic EQS function compares each value in array1 to its corresponding value in array2. UniData returns an array with 1 in each position where values are equal, and 0 in each position for values that are not equal. Syntax EQS(array1,array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY 2 and returns ARRAY3. After EQS, ARRAY3 contains 1}1}1}0}0. ARRAY1 = '11':@VM:'12':@VM:'13':@VM:'20':@VM:'21' ARRAY2 = '11':@VM:'12':@VM:'13':@VM:'19':@VM:'22' ARRAY3 = EQS(ARRAY1,ARRAY2) EQU The UniBasic EQU command replaces a constant with an array, function, number, string, or variable name when the program is compiled. The only difference between the statements using TO and those using LITERALLY is the use of quotation marks. In the TO form, you cannot enclose literals in quotation marks. In the LITERALLY form, you must enclose literals in quotation marks. 111 Chapter 1: UniBasic commands and functions After the execution of an EQUATE statement, you can use the constant symbols and variables interchangeably at all levels of the program. EQUATE variables are available from within the UniBasic debugger. The variable literal string limit is 2,048 characters. EQUATE has the same limit. Tip: EQUATE enables you to use longer, more meaningful names as you write code. These names are replaced with the actual value when the program is compiled. EQUATE also lets you equate a control character to a meaningful name. UniData does not use memory for a constant symbol because the replacement takes place during compilation. Syntax EQU constant1 TO value1 [[,constant2 TO value2]...] EQU constant1 {LITERALLY | LIT} string2 [[,constant2 {LITERALLY | LIT} string2]...] Synonyms EQUATE Parameters The following table describes each parameter of the syntax. Parameter Description constant Specifies the constant to be replaced with value when the program is compiled. value Specifies the value to replace constant with when the program is compiled. string Specifies a literal string, in quotes, to replace constant with when the program is compiled. Examples In the following example, all occurrences of the constant SB are replaced with the value CHAR(8) (clear screen) during program compilation: EQUATE SC TO CHAR(8) In the next example, UniData replaces every occurrence of the constant TITLE with the string ALGONQUIN: EQUATE TITLE LITERALLY "ALGONQUIN" In the next example, UniData replaces every occurrence of the constant TRUE with the value 1, and every occurrence of the constant FALSE with the value 0: EQUATE TRUE to 1, FALSE to 0 IF TRUE PRINT "Income less than target figure." END IF FALSE PRINT "Income equal to or greater than target!" END 112 EREPLACE In the next example, UniData replaces every occurrence of the constant FULLNAME with the expression in the EQUATE statement. The program segment prints “Mary Jones”. EQUATE FULLNAME LITERALLY "FIRST_NAME:' ':LAST_NAME" FIRST_NAME = "Mary" LAST_NAME = "Jones" PRINT FULLNAME After the program is compiled, the print statement looks like this: PRINT FIRST_NAME:' ':LAST_NAME The following example shows the same program segment using the TO form of the statement syntax. In this case, the quotation marks around FIRST_NAME:' ':LAST_NAME are removed. EQUATE FULLNAME TO FIRST_NAME:' ':LAST_NAME FIRST_NAME = "Mary" LAST_NAME = "Jones" PRINT FULLNAME EREPLACE The EREPLACE function replaces substring in expression with another substring. If you do not specify occurrence, each occurrence of substring is replaced. Syntax EREPLACE(expression, substring, replacement [,occurrence [,begin] ] ) Parameters The following table describes each parameter of the syntax. Parameter Description expression The expression in which you want to replace substring. substring The substring you want to replace. If substring is an empty string, replacement is prefixed to expression. If replacement is an empty string, all occurrences of substring are removed. replacement The replacement value for substring. occurrence Specifies the number of occurrences of substring to replace. To replace all occurrences, specify occurrence as a number less than 1. begin Specifies the first occurrence of substring to replace. If you omit begin, or specify a value less than 1, it defaults to 1. If expression evaluates to the null value, null is returned. If substring, replacement, occurrence, or begin evaluates to the null value, the EREPLACE function fails and the program terminates with a run-time error message. Note: The EREPLACE function behaves like the CHANGE function except when substring evaluates to an empty string. 113 Chapter 1: UniBasic commands and functions EXECUTE The UniBasic EXECUTE command executes an ECL or UniData SQL command from within a UniBasic program. You can execute multiple commands with a single EXECUTE statement by separating each command by attribute marks. When the EXECUTE statement executes, UniData separates each command and executes them in order. Note: The settings of UDT.OPTIONS affect the way ECL commands execute. For information about these options, see the UDT.OPTIONS Commands Reference. For information about UDT.OPTIONS that could affect that command, see the appropriate ECL command in the UniData Commands Reference. When you compile EXECUTE and PERFORM in BASICTYPE P, a different parser is used. The Ptype parser scans a file of commands that are defined in the Spectrum-SMA standards or in the McDonnell Douglas REALITY operating system. If the command is found in this file, it is parsed using the P-type parser. If the command is not found in the REALITY file, it is parsed as if the program had been compiled with BASICTYPE U. Because all REALITY commands are uppercase, using lowercase commands will always result in the use of the standard UniData parser. If you want to execute a standard UniData, UniQuery, or ECL command from within a program compiled with BASICTYPE P, use the UniBasic command UDTEXECUTE. Syntax EXECUTE "str.expr" [[ASYNC | SYNC] ON connection [ON ERROR statements]] [PASSLIST list.num.expr] [RTNLIST list.num.expr] [CAPTURING dyn.array.var] [RETURNING dyn.array.var] [PASSCOM] Synonyms PERFORM Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a UniData command with appropriate parameters. If you pass a file name to PERFORM, you must use the actual file name, not a file variable (which is assigned in the OPEN statement). ASYNC | SYNC UniData no longer supports this parameter, but it remains for syntax compatibility. ON connection UniData no longer supports this parameter, but it remains for syntax compatibility. ON ERROR statements UniData no longer supports this parameter, but it remains for syntax compatibility. CAPTURING, dyn.array.var The CAPTURING clause stores the output in a dynamic array instead of on the display terminal. Each line of the text becomes an attribute in the array. Output sent to the printer is not affected by this clause. The order of CAPTURING and RETURNING is interchangeable. 114 EXECUTE Parameter Description RETURNING, dyn.array.var The RETURNING clause captures error messages resulting from the command executed with PERFORM. This variable contains a string of error message numbers separated by spaces. If the executed command creates a spooler hold file, UniData also returns the hold file number in the same variable. RTNLIST int.expr The RTNLIST clause must be an integer from 0–9, designating the select list to return to the calling program. You can use the resulting list with subsequent READNEXT statements or in the PASSLIST clause of an EXECUTE statement. If an expression is not given after RTNLIST, the generated select list replaces the contents of list 0. If RTNLIST is not specified, no list is returned. If you use EXECUTE to call a UniBasic program, no select list is returned even though you specify RTNLIST. On the other hand, PASSLIST is always effective and transfers a select list to the called program. PASSLIST int.expr PASSCOM The PASSLIST clause must evaluate to an integer 0, 1 or 2, designating the select list to be sent to the called program. If you do not specify int.expr, list 0 is assumed. The passed list can be the result of previous SELECT or GETLIST commands, or the result of the RTNLIST clause of a PERFORM statement. This parameter is provided for backward compatibility for releases before 3.1. Remember: The error message numbers you capture with RETURNING will vary, depending upon which version of UniData you are running. The ECL STACKCOMMON Command The ECL STACKCOMMON command makes use of common areas more flexible, although it requires additional memory. STACKCOMMON settings have the following effects: ▪ If STACKCOMMON is off when one program executes another, the unnamed common is passed to the executed program and back to the executing program. ▪ If STACKCOMMON is on when one program executes another program, the unnamed common is not passed to the program you execute. Instead, unnamed common is saved, and the unnamed common of the called program is initialized to 0. When control is passed back to the calling program, unnamed common is restored to its value before the program call. Unnamed common is never passed to a phantom program. Note: STACKCOMMON is always on in BASICTYPEs P and M. STACKCOMMON is off by default in BASICTYPEs R and U. Examples In the following example, the program statement performs the command in cmd3 and sends output to a dynamic array cpt_var: PERFORM cmd3 CAPTURING cpt_var In the next example, the program segment executes a variable containing a UniData command: LIST.PER = "LIST PERSONNEL WAGETYPE AGE" 115 Chapter 1: UniBasic commands and functions PERFORM LIST.PER In the next example, the EXECUTE statement creates a record ID list using the SELECT statement. The select list is then used to read records from the file. EXECUTE 'SELECT CLIENTS WITH COUNTRY = "Canada"' EXECUTE "SAVE.LIST 'canadians'" OPEN 'CLIENTS' TO CLIENT.FILE ELSE ABORT GETLIST 'canadians' SETTING LIST.CNT ELSE PRINT CLIENT:" SAVEDLISTS ID ‘canadians’ CANNOT BE FOUND";STOP PRINT @(-1) FOR I = 1 TO 22 READNEXT ID ELSE EXIT READ REC FROM CLIENT.FILE, ID THEN PRINT @(5,I):REC<1>:@(20,I):REC<2> END ELSE PRINT "CANNOT FIND RECORD":ID END NEXT I CLEARSELECT END In the next example, the program segment executes a paragraph from within a UniBasic program using the EXECUTE statement: PARA = "PA":@AM:"DISPLAY HELLO" EXECUTE PARA This paragraph displays the word HELLO on the terminal screen. Related commands Language Command UniBasic COMMON, EXECUTESQL, MDPERFORM, MDPERFORM UniData STACKCOMMON For information, see the UniData Commands Reference. EXECUTESQL The UniBasic EXECUTESQL command executes a UniData SQL statement within a UniBasic program. If the UniData SQL statement includes a SELECT statement with the intent to process internal program items, the SELECT statement must contain a TO clause with a resulting file name. Otherwise, UniData displays the result of the statement. If you select only the @ID attribute, UniData stores the @IDs in a select list. If the UniData SQL statement includes a TO clause, the data is stored in the output file and is then available to the UniBasic program via the READNEXTTUPLE statement. Note: After you execute a SELECT statement and complete processing of the selected records, you must execute the CLEARSQL command to clear the select list and make all records in the file available for further processing. 116 EXECUTESQL Syntax EXECUTESQL str.expr [ASYNC | SYNC] [ON connection [ON ERROR statements]] Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a valid UniData SQL statement for UniData to execute. ASYNC | SYNC UniData no longer supports this parameter, but it remains for syntax compatibility. ON connection UniData no longer supports this parameter, but it remains for syntax compatibility. ON ERROR statements UniData no longer supports this parameter, but it remains for syntax compatibility. Examples In the following example, the program segment executes a UniData SQL command: OUT.COMMAND = "SELECT NAME, ADDRESS, CITY" OUT.COMMAND := " FROM CLIENTS;" EXECUTESQL OUT.COMMAND CLEARSELECT The following output displays on the terminal screen when you execute the preceding program: Page 1 Name Address City ------------------------------ ------------------------- -------------Paul Castiglione 45, reu de Rivoli Paris Fredrick Anderson 854, reu de Rivoli Paris Beverly Ostrovich 7925 S. Blake St. Sydney Cal di Grigorio 913 Montreal Ave. Regina Franklin Sears 213 Midland St. Perth Gino Lee 483 E. Silverman St. Fonthill JoAnn Casey 4024 South Ivywood Circle Omaha In the next example, the program segment executes the same UniData SQL command with a TO clause that stores the UniData SQL output in a file that you can access using the READNEXTTUPLE statement. (This program uses the CLIENTS file in the demo database.) OUT.COMMAND = "SELECT NAME, ADDRESS, CITY, STATE" OUT.COMMAND := " FROM CLIENTS TO SQL_INPUT;" EXECUTESQL OUT.COMMAND DONE = 0 FOR X = 1 TO 5 READNEXTTUPLE CLIENT.INFO FROM "SQL_INPUT" ELSE STOP CONVERT @AM TO " " IN CLIENT.INFO PRINT CLIENT.INFO NEXT X CLEARSELECT END 117 Chapter 1: UniBasic commands and functions This program produces the following results: Paul Castiglione 45, reu de Rivoli Paris Fredrick Anderson 854, reu de Rivoli Paris Beverly Ostrovich 7925 S. Blake St. Sydney NSW Cal di Grigorio 913 Montreal Ave. Regina Saskatchewan Franklin Sears 213 Midland St. Perth In the next example, the UniData SQL statement selects an @ID only. UniData uses a select list instead of storing the output. In this case, the UniData SQL command does not require a TO clause, and the UniBasic READNEXT statement processes the IDs selected. OPEN 'CLIENTS' TO CLIENT.FILE ELSE PRINT 'Open Error.' OUT.COMMAND = "SELECT @ID" OUT.COMMAND := " FROM CLIENTS" OUT.COMMAND := " WHERE CITY = 'Paris';" EXECUTESQL OUT.COMMAND DONE = 0 LOOP READNEXT @ID ELSE DONE = 1 UNTIL DONE DO GOSUB PROCESS.RECS REPEAT CLEARSELECT PROCESS.RECS: *print records for clients in Paris." READ REC FROM CLIENT.FILE,@ID THEN PRINT REC RETURN END The program output is: Paul}Castiglione}Chez Paul}45, reu de Rivoli}Paris}}75008}France}3342425544|3342664857}Work|Fax Fredrick}Anderson}Otis Concrete}854, reu de Rivoli}Paris}}75008}France}3342482815|3342481924}Work|Fax Antonette}Larnelle}Monde Cable}19, rue Jean Goujon}Paris}}75008}France}3438291902|3438295512}Work|Fax Pierre}Edmond}JT Engineering}70, avenue d'Iena}Paris}}75016}France}3391928392|3391992193}Work|Fax Pierre}Logni}Wine College}70, avenue d'Iena}Paris}}75016}France}3393688924|3393688523}Work|Fax Omar}Saulnier}Maurice Salon}4, avenue Valencia}Paris}}75016}France}3348756898 |3348589782 }Work|Fax David}Silvers}Qinton Systems}9, avenue Valencia}Paris}}75016}France}3441831291|3441830107}Work|Fax Fernando}Ducrot}Monde Cable}19, rue Jean Goujon}Paris}}75008}France}3344587968|3344668871}Work|Fax Related commands 118 Language Command UniBasic EXECUTE, READNEXT, READNEXTTUPLE UniData SQL For information about UniData SQL commands, see the UniData SQL Commands Reference EXIT EXIT The UniBasic EXIT command terminates a FOR/NEXT or LOOP/REPEAT structure and transfers control to the following statement. As with the CONTINUE statement, EXIT forms well structured programs. Tip: Use EXIT in structured programs instead of GOTO. This makes the code easier to read and maintain. Syntax EXIT Examples In the following example, the program segment exits the FOR/NEXT loop when I is greater than 8: FOR I = 1 TO 10 IF I > 8 THEN EXIT PRINT "I = ":I NEXT I Related commands Language Command UniBasic CONTINUE, FOR/NEXT, LOOP/REPEAT EXP The UniBasic EXP function raises e to the power of expr. e is approximately 2.71828. expr must be numeric. The function ex is its own derivative. If y = ex, then x is the natural logarithm of y. If exp is too large or too small, a warning message is printed and 0 is returned. If exp is an empty string, the empty string is returned. Syntax EXP(expr) Examples In the following example, the program statement raises e to the power of 2, and assigns this value, 7.3891, to the variable ETOX: ETOX = EXP(2) Related commands Language Command UniBasic LN 119 Chapter 1: UniBasic commands and functions EXTRACT The UniBasic EXTRACT function retrieves data from an attribute, value, or subvalue in a dynamic array. The dynamic array itself remains unchanged. You can use either of the preceding syntax forms. Syntax EXTRACT(dyn.array.expr, attrib.expr,[val.expr [,subval.expr]])dyn.array.expr <attrib.expr,[val.expr [,subval.expr]]> Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.expr Specifies a dynamic array from which to retrieve the data. attrib.expr Specifies an attribute of the dynamic array from which to retrieve the data. If the value of attrib.expr is less than 1, UniData uses 1. val.expr Specifies a value of attrib.expr from which to extract the data. If the values of val.expr and subval.expr are 0, or if they do not appear in the EXTRACT function, UniData retrieves an attribute. subval.expr Specifies a subvalue of the value specified by val.expr in the attribute specified by attrib.expr, from which to retrieve data. If the values of val.expr and subval.expr are 0, UniData retrieves an attribute. If the value of subval.expr is 0, or if it does not appear in the EXTRACT function, UniData retrieves a value. Examples The following program segment is taken from the sample program in Developing UniBasic Applications. The variable ENTRY is used to extract the user-requested values from the ORDERS record. DISPLAY_DATA: * Display the current information in the desired record. This is * determined by the number the user entered (ORDER_NUMBER). ... NUM_ENTRIES = DCOUNT(ORDER.REC<4>,@VM) FOR ENTRY = 1 TO NUM_ENTRIES PRODUCT_NUMBER = ORDER.REC<4,ENTRY> COLOR = ORDER.REC<5,ENTRY> QUANTITY = ORDER.REC<6,ENTRY> PRICE = OCONV(ORDER.REC<7,ENTRY>,"MD2$,") In the following example, the program segment assigns the string Joan to the variable MID. Joan is the second attribute in the dynamic array ARR. The value and subvalue expressions are 0, resulting in the extraction of an attribute. ARR = "#543":@AM:"Joan":@AM:"D’Arc" MID = EXTRACT(ARR,2,0,0) In the next example, the program segment assigns the string Dagny, the second value of the third attribute, to the variable MID: ARRAY = "#143":@AM:"Gustav":@AM:"Mahler":@VM:"Dagny":@VM:"Jens" 120 FIELD MID = EXTRACT(ARRAY,3,2) Related commands Language Command UniBasic DEL, INSERT, REMOVE, REPLACE, SUBSTRINGS FIELD The UniBasic FIELD function treats a string as an array, with fields delimited by any specified ASCII character (for example, spaces, commas, or periods), and returns a substring or group of substrings. FIELD supports multibyte languages. Syntax FIELD(string.expr,delim.expr,field.expr [,rep.expr]) Parameters The following table describes each parameter of the syntax. Parameter Description string.expr Specifies the string expression to search. delim.expr Specifies the field delimiter. field.expr Specifies the field at which to begin the search. ,rep.expr Specifies the number of fields to return. If you do not specify rep.expr, or it is less than 1, UniData returns a default of 1 substring. Examples In the following example, the program segment assigns the third value (“Guy”) in the array ARR to the array NARRAY: ARR = "#999":@VM:"Charlemagne":@VM:"Guy":@VM:"Pierre" NARRAY = FIELD(ARR,@VM,2,1) In the next example, the program segment assigns the two fields following the third occurrence of the delimiter “,” in the variable ARR to NARRAY. UniData stores the value 5,8 in NARRAY. ARR = "10,10,5,8,7,12,15,8" NARRAY = FIELD(ARR,",",3,2) In the next example, the program segment assigns the second group of characters in a string delimited by spaces in the variable NAME to LNAME. UniData stores the value Smith in LNAME. NAME = "Harry Smith" LNAME = FIELD(NAME," ",2) 121 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic COL1, COL2, INDEX FIELDSTORE The UniBasic FIELDSTORE function inserts an expression and an appropriate delimiter into a string. Syntax FIELDSTORE(str.expr,delimiter,b.pos,option,new.expr) Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies the target string. delimiter Specifies the character that delimits fields in str.expr. b.pos Specifies the occurrence of the delimiter at which to insert. If the number of delimiters is less than b.pos, UniData inserts the appropriate number of spaces and delimiters. option Specifies whether FIELDSTORE will insert before, insert after, or replace the field at b.pos. Refer to the following FIELDSTORE Options table for further details. new.expr Specifies the expression (with its associated delimiter) to insert before or after the specified delimiter. Options The value of option determines the operation to be executed. The following table describes these options and their results. Value Description If option > 0 UniData replaces the number of substrings specified in option. If option = 0 UniData inserts new.expr at the position indicated by b.pos. If option < 0 UniData deletes the number of substrings specified in option, and inserts new.expr at the location indicated by b.pos. Examples In the following example, the program segment inserts AR in the string ASTATES. After execution, ASTATES contains the string “AL:AK:AR:AZ”. ASTATES = 'AL:AK:AZ' ASTATES = FIELDSTORE(ASTATES,':',3,0,'AR') The following program segment compiles and runs only when null value handling is on. The program segment inserts AR, and then inserts the null value into ASTATES. It calls the externally cataloged 122 FILEINFO subroutine PRINT.SETUP to convert the null value to a printing character, and then prints the converted ASTATES. (PRINT.SETUP is shown under CHANGE.) PRT.STR = '' ASTATES = 'AL:AK:AZ' ASTATES = FIELDSTORE(ASTATES,':',3,0,'AR') PRINT "ASTATES = ":ASTATES ASTATES = FIELDSTORE(ASTATES,':',3,0,@NULL) STR = ASTATES CALL PRINT.SETUP(STR,PRT.STR) PRINT "ASTATES = ":PRT.STR This program prints the following: ASTATES = AL:AK:AR:AZ ASTATES = AL:AK:@NULL:AR:AZ In the next example, the program segment specifies that processing begins at the fifth value (ugly), that this value is deleted (the -1 option), and that the new.expr (orange,black) is to be inserted in the same position. After processing, COLORS contains the string “yellow,blue,red,green,orange, black,white”. COLORS = 'yellow,blue,red,green,ugly,white' COLORS = FIELDSTORE(COLORS,',',5,-1,'orange,black') Related commands Language Command UniBasic INS, INSERT FILEINFO The FILEINFO function returns information about the configuration of a file. Syntax FILEINFO(file.var, code) Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file to be analyzed. file.var is the file variable previously used in an OPEN or OPENSEQ statement. code Specifies the type of information to return. FILEINFO codes code indicates the information requested. The following table describes the codes and the return values of the function. 123 Chapter 1: UniBasic commands and functions code Information Requested File Type Return value 0 File open status ALL 1= Open 1 VOC name 2 Full path name of file ALL Path name of file 3 File type HASHED 2 DYNAMIC 3 DIRECTORY 4 SEQUENTIAL 5 NFA 7 OS 8 EDA 13 HASH & DYNAMIC (KEYONLY) Hash type (0, 1, or 3) 0= Not open 4 Hashing file type This parameter is not implemented. DYNAMIC (KEYDATA) DYNAMIC (WHOLEFILE) Hash type (32 , 33, or 35) Hash type (48, 49, or 51) OTHERS 5 Modulo of file HASH Modulo DIRECTORY 0 DYNAMIC Current modulo OTHERS Not applicable 6 Minimum modulo of file DYNAMIC Minimum modulo 7 Group size of file HASH & DYNAMIC (Block size/1024)-1 OTHERS Not applicable HASH & DYNAMIC Block size OTHERS Not applicable 8 Block size of file Returns the same value as option 18 9 10 11 Merge factor percentage Split factor percentage Current load percentage DYNAMIC Merge factor OTHERS Not applicable DYNAMIC Split factor OTHERS Not applicable DYNAMIC Percent result of the formula: OTHERS (keyspace(grp) *100)/blksize Not applicable 12 124 Node name This parameter is not implemented. FILEINFO code Information Requested File Type Return value 13 Does file contain alternate key indexes? HASH & DYNAMIC 1= yes; 2 = no OTHERS Not applicable 14 Next line number to read or write SEQUENTIAL OTHERS Next line number Not applicable 15 Part number This parameter is not implemented. 16 Status This parameter is not implemented. 17 Filename 18 Block size of file HASH & DIR & DYNAMIC VOC entry name OTHERS Not applicable HASH & DYNAMIC Block size OTHERS Not applicable Returns the same value as option 8 19 Access permissions ALL Permissions the person running the program has expressed as total UNIX values (r=4,w=2,x=1, so rw= 6) 20 Index to which the last SETINDEX ALL statement was applied VOC entry name 21 Index record read by last browsing statement, such as READFWD and READBCK. ALL Key value 22 File type: recoverable or nonrecoverable ALL 1 – Recoverable 23 0 – Nonrecoverable Numeric keys For sequentially hashed files. 1 – Numeric keys 0 – Non-numeric keys 24 Type of U2 Data Replication file ALL 0 - The file is not a replication object 1 – The file is being published 2 – The file is being subscribed 3 - The file is subwriteable 25 BEFORE-UPDATE-TRIGGER ALL catalog program name of the file <xx>. BEFORE-UPDATE-TRIGGER catalog program name of the file. If no such trigger exists, returns and empty string. 125 Chapter 1: UniBasic commands and functions code Information Requested File Type 26 BEFORE-DELETE-TRIGGER ALL catalog program name of the file <xx>. BEFORE-DELETE-TRIGGER catalog program name of the file. If no such trigger exists, returns and empty string. 27 Is the file encrypted? 0 – File is not encrypted ALL Return value 1 – File is encrypted 28 Type of file encryption ALL Returns a dynamic array containing the following information: For a file encrypted with the WHOLERECORD option: -1@SM<keyid>@SM<algorithm> For a file encrypted at the field level: <location>@SM<keyid>@SM<algorithm> @SM<field_name> Returns an empty string if the file is not encrypted. 29 AFTER-UPDATE-TRIGGER catalog ALL program name of the file <xx>. AFTER-UPDATE-TRIGGER catalog program name of the file. If no such trigger exists, returns an empty string. 30 AFTER-DELETE-TRIGGER catalog ALL program name of the file <xx>. AFTER-DELETE-TRIGGER catalog program name of the file. If no such trigger exists, returns an empty string. 31 Defines the bit type 0 – 32–bit file HASH & DYNAMIC 1 – 64–bit file FILELOCK The UniBasic FILELOCK command locks the dictionary or data portion of a file against access by READL, READU, READVU, MATREADL, MATREADU, MATWRITEU, WRITEU, and WRITEVU statements. Other file input/output commands ignore FILELOCK. Note: UniBasic locks are advisory only. For more information, see Developing UniBasic Applications. Syntax FILELOCK [file.var] [ON ERROR statements] LOCKED statements 126 FILEUNLOCK Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file to lock. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. A default file is one for which no file variable is assigned in the OPEN statement. ON ERROR statements Specifies statements to perform if the FILELOCK statement fails with a fatal error condition because the file is not open. If you do not specify the ON ERROR clause, the program terminates abnormally. LOCKED statements Specifies statements to execute if the file is already locked. STATUS function return values After you execute of the FILELOCK command, the UniBasic STATUS function returns 0 if the file was locked successfully. If the file was already locked, and if the LOCKED clause was included in the FILELOCK statement, STATUS returns the user number of the process that locked the file. Examples In the following example, the FILELOCK statement locks the file STAT, preventing lock-checking commands from accessing this file: FILELOCK STAT LOCKED STOP Related commands Language Command UniBasic FILEUNLOCK, RECORDLOCKED, RELEASE FILEUNLOCK The UniBasic FILEUNLOCK command unlocks a file previously locked with a FILELOCK command. Syntax FILEUNLOCK [file.var] [ON ERROR statements] Parameters The following table describes each parameter of the syntax. 127 Chapter 1: UniBasic commands and functions Parameter Description file.var Specifies the file to unlock. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. A default file is one for which no file variable is assigned in the OPEN statement. ON ERROR statements Specifies statements to perform if the FILEUNLOCK statement fails with a fatal error condition because the file is not open. If you do not specify the ON ERROR clause, the program terminates. Examples In the following example, the FILEUNLOCK statement unlocks the file referred to by the file variable INVENTORY.FILE: FILEUNLOCK INVENTORY.FILE Related commands Language Command UniBasic FILELOCK, RECORDLOCKED, RELEASE FIND The UniBasic FIND command determines the position of the given expression in a dynamic array. FIND returns the attribute, value, and subvalue position of the found string. The expression must match the entire array element to make a match. Syntax FIND expr IN dyn.array[,occur] SETTING f [,v[,s]] {THEN statements | ELSE statements} Parameters The following table describes each parameter of the syntax. 128 Parameter Description expr Specifies the expression to find. expr must be either a numeric value or a string value. dyn.array Specifies the dynamic array in which to find expr. ,occur Specifies the occurrence of expr to find. The default is 1 (the first occurrence). FINDSTR Parameter Description f,v,s Specifies variables in which to place the position of expr f – Attribute v – Value s – Subvalue If the attribute found has neither multivalues nor subvalues, then v and s, if specified, are set to 0. If only multivalues are present, s is set to 0. If only subvalues exist, v is also set to 0. Specifies statements to execute if the expr is found in the array. END is required when statements extend over more than one line. Either a THEN statement or an ELSE statement is required. THEN statements ELSE statements Specifies statements to execute if the expr is not found in the array. END is required when statements are multiline. Either a THEN statement or an ELSE statement is required. For more information about writing THEN...ELSE parameters, see Developing UniBasic Applications. The UniBasic FIND and LOCATE commands are compared in this manual. Examples In the following example, the program segment searches for an occurrence of 31 in the string DA. This results in F=3, V=1, and S=0 because 31 is found in the third attribute as the first multivalue, and this attribute has no subvalues. 001: 002: 003: 004: 005: 006: DA = 1:@AM:2:@AM:31:@VM:32:@VM:41:@VM:41:@VM:42:@VM:43 FIND 31 IN DA SETTING F,V,S THEN PRINT "F=":F:" V=":V:" S=":S END ELSE PRINT "NOT FOUND" END In the next example, the program segment searches for the second occurrence of 41 in the string DA. This results in F=3, V=4, and S=0 because the second occurrence of 41 is found in the third attribute as the fourth multivalue, and this attribute has no subvalues. DA = 1:@AM:2:@AM:31:@VM:32:@VM:41:@VM:41:@VM:42:@VM:43 FIND 41 IN DA,2 SETTING F,V,S ELSE PRINT "NOT FOUND" Related commands Language Command UniBasic [], FINDSTR, LOCATE FINDSTR The UniBasic FINDSTR command determines the position of a given substring in a dynamic array. FINDSTR supports multibyte languages. 129 Chapter 1: UniBasic commands and functions Syntax FINDSTR substr IN dyn.array[,occur] SETTING f[,v[,s]] {THEN statements | ELSE statements} Parameters The following table describes each parameter of the syntax. Parameter Description substr Specifies the substring to find. substr must be either a numeric value or a string value. dyn.array Specifies the dynamic array in which to find substr. ,occur Specifies which occurrence of substr you want to find in the array. The default for occur is 1 (the first occurrence). f,v,s Specifies variables in which to place the position of substr f – Attribute v – Value s – Subvalue If the attribute found has neither multivalues nor subvalues, then v and s, if specified, are set to 0. If only multivalues are present, s is set to 0. If only subvalues exist, v is also set to 0. THEN statements Specifies statements to execute if the substr is found in the array. Either a THEN statement or an ELSE statement is required. ELSE statements Specifies statements to execute if the substr is not found in the array. Either a THEN statement or an ELSE statement is required. Examples In the following example, the program segment searches for 3 in the string DA. This results in F=3, V=1, and S=0 because 3 is found in the third attribute as the first multivalue, and this attribute has no subvalues. DA = 1:@AM:2:@AM:31:@VM:32:@VM:41:@VM:41:@VM:42:@VM:43 FINDSTR 3 IN DA SETTING F,V,S ELSE PRINT "NOT FOUND" In the next example, the program segment searches for the second occurrence of 4 in the string DA. This results in F=3, V=4, and S=0 because the second occurrence of 4 is found in the third attribute as the 4 multivalue, and this attribute has no subvalues. DA = 1:@AM:2:@AM:31:@VM:32:@VM:41:@VM:41:@VM:42:@VM:43 FINDSTR 4 IN DA,2 SETTING F,V,S ELSE PRINT "NOT FOUND" Related commands Language Command UniBasic FIND, LOCATE FLUSH The FLUSH command flushes output to the terminal when UDT.OPTIONS 46 is on. 130 FMT Note: For more information about UDT.OPTIONS 46, see the UDT.OPTIONS Commands Reference. Syntax FLUSH FMT The UniBasic FMT function formats data in expr for display purposes. FMT can format a dynamic array that contains multivalues. The statement can be no longer than 2,046 characters. In the first form of the syntax, L, R, C, or T and len are required. The second form is the same as the first form with the elements in a different order. The third form does not include the keyword FMT, but the elements are in the same order as in the second form. In the fourth form, you provide the pattern format in a variable, pattern.var. Note: The FMT function can produce different results based on the BASICTYPE setting. The parameter descriptions that follow represent BASICTYPE U. Syntax FMT(expr, "len [f.char] {L | R | T | C} [n] [$] [,] [Z] [mask]") FMT(expr, "{L | R | T | C} # len [f.char] [n] [$] [,] [Z] [mask]") expr "[L | R | T | C] # len [f.char] [n] [$] [,] [Z] [mask]" FMT(expr, pattern.var) Parameters The following table describes each parameter of the syntax. Parameter Description len Specifies the total number of single-byte characters to appear in the output string. f.char Specifies a single-byte fill character to be used if the formatted string is not long enough to fill len; the default is a space. Cannot be a multibyte character. Prefix a numeric f.char with \ to indicate it is the fill character. L Specifies left-justification in a string of len spaces. If the text is longer than len, the text is broken in len intervals. Has no effect in multibyte languages. R Specifies right-justification in a string of len spaces. Has no effect in multibyte languages. C Specifies centered text in the column of width len. Has no effect in multibyte languages. T Specifies text justification. If data must be broken to fit in a column, it is justified on a word basis (from space to space). Has no effect in multibyte languages. 131 Chapter 1: UniBasic commands and functions Parameter Description n Specifies the maximum number of decimal places allowed, rounding as necessary. If n = 0, the number is rounded to an integer. $ Prints a dollar sign before the formatted string. Valid for numeric data only. , Prints numbers with commas separating each level of thousands. Valid for numeric data only. Z Specifies the suppression of leading zeros. mask Specifies a pattern mask composed of numbers and other characters. Numeric data is placed sequentially in the mask before justification. # Truncates the output. STATUS function return values After you execute FMT, the STATUS function returns one of the values described in the following table. Value Description 0 Successful completion. 1 String expression is invalid or exceeds the allowable string size. 2 Conversion code is invalid. Examples In the following example, the program segment prints the variable SS.NUM as a formatted string using a pattern mask. The result printed is a string with 11 characters, left-justified:“543-70-4128”. SS.NUM=543704128 PRINT FMT(SS.NUM,"11L###-##-####") In the next example, the program segment prints the variable NUM as a 12-character, right-justified number with two decimal places, preceded by a dollar sign and composed with commas. The segment prints the value “$16,526.00”. NUM = 16526 PRINT FMT(NUM, "12R2$,") In the next example, the program segment formats the string OUT.STRING with 0 as the fill character, right-justified, and in a column of four spaces. The segment prints 0044. OUT.STRING = 44 OUT.STRING = FMT(OUT.STRING,"4\0R") PRINT OUT.STRING In the next example, the program statement saves the variable STR as a right-justified, eight column string: STR = STR "R#8" In the next example, the program segment uses a variable to specify the pattern format. UniData formats STR according to the variable PATTERN: PATTERN = "12R2$," STR = STR PATTERN 132 FOOTING FOOTING The UniBasic FOOTING command causes the specified string to print or display at the bottom of each page of a report. You can specify a footer of any length. The ECL LIMIT command has no effect on this command. Note: Turn on UDT.OPTION 64 to force the footing to appear on the last page or screen. With this option turned off, the footing does not appear on the last page or screen. For more information about UDT.OPTION 64, see the UDT.OPTIONS Commands Reference. The PRINTER command directs the output of a FOOTING command not sent to a print file as follows: ▪ ▪ PRINTER OFF causes a report, together with its footings, to appear on the user’s terminal screen. PRINTER ON causes all subsequent footings, headings, and PRINT output to be sent to the destination specified by the current SETPTR setting. Syntax FOOTING [ON num.expr] str.expr ['option']... Parameters The following table describes each parameter of the syntax. Parameter Description ON num.expr Specifies a print file to which you want to send the footing: 0-254. str.expr Specifies the string to display at the bottom of each page. option... option must be enclosed in single quotation marks. You can place option(s) anywhere in the footing expression. option can be any of the following: ASCII code – Passes to the printer or file code controlling paging characteristics. P or S – Prints current page number. N – Suppresses the pagination prompt after each page. L – Advances one line. Used for multiline footings. D – Prints date in MM-DD-YY format. T – Prints time/date in MM-DD-YY HH:MM:SS format. C – Centers the footing text. G – Forces the line to fill the width of the page. Examples In the following example, the program statement produces a footing using a character string: FOOTING "Copyright 1999, Genius, Inc." In the next example, the program statement prints Page and the current page number. It advances one line and then prints Paul’s Produce. Notice the two single quotation marks in the middle of the strings. They are necessary to print a single apostrophe in the footer. The ON 2 clause sends the footing to print file 2. 133 Chapter 1: UniBasic commands and functions FOOTING ON 2 "Page 'PL'Paul''s Produce" Related commands Language Command UniBasic GETPTR, HEADING, PRINTER UniData SETPTR For information, see the UniData Commands Reference. FORMLIST The UniBasic FORMLIST command creates an active select list from a dynamic array. FORMLIST uses the attribute marks in dynamic.array.var to create a select list that you can use with READNEXT statements or other list processing commands such as external LIST statements. Syntax FORMLIST dynamic.array.var [TO list.num.expr] Parameters The following table describes each parameter of the syntax. Parameter Description dynamic.array.var Specifies a dynamic array from which to create a select list. TO list.num.expr Specifies which list, 0 through 9, you want the list sent to. 0 is the default list. Examples In the following example, the program segment creates a select list and then uses that list to print four records in the CLIENTS file: ARRAY.LIST = 9999:@AM:10034:@AM:9980:@AM:10015 FORMLIST ARRAY.LIST TO 0 PRINT "PROCESSING THE FOLLOWING ITEMS:" PERFORM "LIST CLIENTS NAME COMPANY" END This program segment produces the following results: LIST CLIENTS NAME COMPANY 17:33:03 Apr 27 1999 1 CLIENTS... Name.......................... Company Name.................. 9999 Paul Castiglione Chez Paul 10034 Fredrick Anderson Otis Concrete 9980 Beverly Ostrovich Riley Architects 10015 Cal di Grigorio Regina Flooring 4 records listed 134 FOR/NEXT Related commands Language Command UniBasic DELETELIST, READLIST, SELECT, SELECTINDEX, SELECTINFO, WRITELIST UniData SQL SELECT For information, see the UniData Commands Reference. UniQuery DELETELIST, GETLIST, SELECT, SSELECT, SAVE.LIST For information, see the UniQuery Commands Reference FOR/NEXT The UniBasic FOR/NEXT command executes statements repeatedly while incrementing a variable over a range until it reaches the end of the range, or until the condition in the WHILE or UNTIL clause is achieved. You can nest FOR/NEXT constructions. Each FOR statement must end with a NEXT statement. FOR/NEXT should be constructed so termination occurs based on the WHILE or UNTIL condition. Use the CONTINUE statement to transfer control to the next iteration of the command. The valid range of values for the size of the integer in the FOR/NEXT counter is -2 gigabytes up to 2 gigabytes -1. Syntax FOR var = val1 TO val2 [STEP val3] statements] [UNTIL | WHILE expr] statements NEXT [var] Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the variable to increment. val1 Specifies the beginning of the range for incrementing var. val2 Specifies the end of the range for incrementing var. STEP val3 Specifies the change to use in incrementing var. The increment can be negative or positive, making the variable decrease or increase. statements Specifies the statements to carry out for each loop. UNTIL | WHILE expr statements Specifies a condition, expr, to test after each loop. If the UNTIL keyword is used, the loop continues until expr is true. If the WHILE keyword is used, the loop continues until expr is not true. In either case, when the loop stops, the statements are executed before the program continues. NEXT var The NEXT statement defines the end of the block of statements to be repeated. The optional var is the same variable as in the beginning of the FOR/NEXT statement. 135 Chapter 1: UniBasic commands and functions Examples The following program segment is taken from the sample program in Developing UniBasic Applications. This segment prints multivalues from the ORDERS file when a client has ordered multiple items. DISPLAY_DATA: * Display the current information in the desired record. This is * determined by the number the user entered (ORDER_NUMBER). . . . FOR ENTRY = 1 TO NUM_ENTRIES PRODUCT_NUMBER = ORDER.REC<4,ENTRY> COLOR = ORDER.REC<5,ENTRY> QUANTITY = ORDER.REC<6,ENTRY> PRICE = OCONV(ORDER.REC<7,ENTRY>,"MD2$,") IF PRODUCT_LINE = '' THEN PRODUCT_LINE = PRODUCT_NUMBER "R#10" COLOR_LINE = COLOR "R#10" QUANTITY_LINE = QUANTITY "R#10" PRICE_LINE = PRICE "R#10" END ELSE PRODUCT_LINE := " ":PRODUCT_NUMBER "R#10" COLOR_LINE := " ":COLOR "R#10" QUANTITY_LINE := " ":QUANTITY "R#10" PRICE_LINE := " ":PRICE "R#10" END NEXT ENTRY In the following example, the program segment prints the string 10,8,6,4,2,. The loop terminates before printing 0 because the FOR/NEXT statement specifies that when the variable I falls below 1, the loop terminates. FOR I = 10 TO 1 STEP -2 PRINT I:",": NEXT I In the next example, the optional WHILE expression clause creates a secondary condition for the termination of the FOR/NEXT structure. While a normal FOR/NEXT loop repeats the contained statements 10 times, the WHILE clause results in this example stopping after only three repetitions. This occurs because the value read from the DATA statement by the INPUT command exceeds the value of I on the third iteration. The WHILE clause with the same statements results in the loop terminating after one iteration. After the iteration, I is less than K, satisfying the condition and causing the loop to stop. K=50 DATA 3,4,2,51,8,10,15,3,2,8 FOR I = 1 TO 10 WHILE I < K INPUT K PRINT I,K NEXT I Related commands 136 Language Command UniBasic CASE, LOOP/REPEAT FUNCTION FUNCTION The UniBasic FUNCTION command begins the definition of a user-written function. The FUNCTION command must be the first noncomment line in the file, which must be cataloged locally or globally. The cataloged file name must be included in the DEFFUN statement in the calling program. The calling program must specify the same number and type of arguments in the calling statement as are included in the FUNCTION statement. Note: UniData triggers are UniBasic subroutines or functions that are called when a user attempts to update or delete a record. For more information about coding a UniBasic function that is called by a trigger, see Developing UniBasic Applications. Syntax FUNCTION function.name [([MAT] arg.1[, [MAT] arg.2]...)] RETURN var Parameters The following table describes each parameter of the syntax. Parameter Description function.name Specifies the name of the function (for documentation purposes only). It need not be the same as the name used to call the function. You must include this function’s cataloged file name in the DEFFUN statement in the calling program. (MAT arg.1 ,MAT arg.2...) Specifies the arguments to be passed from the calling program. Arguments must be enclosed in parentheses and separated by commas. Precede an argument with MAT to indicate that the argument is an array. Up to 254 arguments can be passed. RETURN var Returns control to the calling program. Can pass back an argument. Examples The following function performs calculations on a dimensioned array, returning values in the function arguments and return value, r. The name of the cataloged file that contains this function definition is yourfunc. This name must be used in the DEFFUN statement in the calling program. Notice that the function definition uses yet a different name (anotherfunc). The name anotherfunc is not referenced anywhere. FUNCTION anotherfunc(a, MAT b, c) ;* definition. DIM b(-1) r = 0 c = 1 back. FOR i = 1 TO a in: r += b(i) c *= b(i) NEXT i RETURN r Start function ;* Declare array. ;* Initialize return value. ;* Initialize value passed ;* To the upper bound passed ;* Sum array members. ;* Multiply array members. ;* Return value. 137 Chapter 1: UniBasic commands and functions The following program calls the preceding function. Because the function is called myfunc within this program, the CALLING clause is included in the DEFFUN statement to identify the cataloged program file yourfunc. Note that values in arguments a and b are passed back, although they are not used by the program. DEFFUN myfunc(a, MAT b, c) CALLING "yourfunc" DIM b(10) a = 2 FOR i = 1 TO a b(i) = i NEXT i PRINT "r from FUNCTION: ":myfunc(a, MAT b, c) PRINT "c from FUNCTION: ":c ;* ;* ;* ;* Declare function. Define array. Set upper bound. Initialize array. The program runs and prints out the following text: :RUN BP FUNCTION.CALL r from FUNCTION: 3 c from FUNCTION: 2 Related commands Language Command UniBasic DEFFUN GARBAGECOLLECT The UniBasic GARBAGECOLLECT command releases all reserved but nonactive memory allocated for UniBasic variables. Syntax GARBAGECOLLECT GE The UniBasic >= relational operator tests whether expression expr1 is greater than or equal to expr2. expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Relational operators make the comparisons that direct program flow in conditional statements like the following: IF VAR1 GE VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 >= VAR2 Syntax expr1 GE expr2 Synonyms #<, =>, >= 138 generateKey Examples In the following example, the program segment tests whether A is greater than or equal to B. Because A is greater than B, the message “Greater Than or Equal To” prints. A = 24 B = 22 IF A GE B THEN PRINT "Greater Than or Equal To" END ELSE PRINT "Less Than" END Related commands Language Command UniBasic GES generateKey The generateKey() function generates a public key cryptography key pair and encrypts the private key. You should then put it into an external key file protected by the provided pass phrase. UniData SSL sessions can use the protected private key later to secure communication. The public key will not be encrypted. The generated private key will be in PKCS #8 form and is encoded in either PEM or DER format specified by format. The generated public key is in traditional form. If keyLoc is 1, the resulted key is put into a dynamic array in privKey and pubKey. Otherwise, they are put into OS level files specified by privKey and pubKey. To make sure the private key is protected, you must provide a pass phrase. UniData uses a one-way hash function to derive a symmetric key from the pass phrase to encrypt the generated key. When installing the private key into a security context with the setPrivateKey() function, or generating a certificate request with the generateCertRequest() function, you must provide this pass phrase to gain access to the private key. For detailed information about the generateKey function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax generateKey(priveKey, pubKey, format, keyLoc, algorithm, keyLength, passPhrase, paramFile) Parameters The following table describes each parameter of the syntax. Parameter Description privKey A string storing the generated private key or name of the file storing the generated private key. pubKey A string storing the generated public key or name of the file storing the generated public key. 139 Chapter 1: UniBasic commands and functions Parameter Description format 1 - PEM 2 - DER keyLoc 1 - Put the key into string privKey/pubKey. 2 - Put the key into a file. algorithm 1 - RSA 2 - DSA keyLength Number of bits for the generated key. Between 512 and 2048. passPhrase A string storing the pass phrase to protect the private key. paramFile A parameter file needed by DSA key generation. The following table describes the status of each return code. Return codes Status 0 Success. 1 Key pair cannot be generated. 2 Unrecognized key file format. 3 Unrecognized encryption algorithm. 4 Unrecognized key type or invalid key length (must be between 512 and 2048). 5 Empty pass phrase. 6 Invalid DSA parameter file. 7 Random number generator cannot be seeded properly. 8 Private key cannot be written. GES The UniBasic GES function compares each value in array1 to its corresponding value in array2. UniData returns an array with 1 in each position where the value in array1 is greater than or equal to the value in the corresponding position in array2. UniData returns 0 in each position for values that are less than array2. Syntax GES(array1,array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY2 and returns ARRAY3. ARRAY3 then contains 1}1}1}0}0. ARRAY1 = 10:@VM:20:@VM:30@VM:40:@VM:50 ARRAY2 = 9:@VM:10:@VM:30:@VM:50:@VM:60 ARRAY3 = GES(ARRAY1,ARRAY2) 140 GET GET The UniBasic GET command receives unprompted input from an attached line. UniData accepts all control characters, including the carriage return and line feed as input characters. All data read from the attached line is placed in var. GET supports multibyte languages. Performance of the GET statement varies according to the termination conditions specified, and whether the THEN or ELSE clauses are specified. Input from the attached line is terminated in four ways: ▪ UniData has read the number of characters specified in length. ▪ After a single character is read (when length and UNTIL are not coded). ▪ When any character you specify in term.exp is encountered in input. ▪ When UniData reads the record mark character, @RM, and the number of seconds has elapsed. Note: UniData never executes the ELSE clause if you include UNTIL without WAITING or length. If you code the WAITING clause, UniData executes the ELSE clause only after the number of seconds specified for timeout. If the input is terminated for any other reason, UniData executes the THEN clause. In special cases, UniData executes the ELSE clause if the line has not been attached before executing the GET statement. Syntax GET[X] var[,length] [SETTING count.var] FROM line.expr [UNTIL term.expr] [RETURNING term.var] [WAITING seconds] [THEN statements | ELSE statements] Parameters The following table describes each parameter of the syntax. Parameter Description X Specifies that GET return var as hexadecimal. This feature allows binary data to contain a 255 value (hexadecimal FF). For instance, if a user enters HELLO, the input data variable contains 48454C4C4F. var Specifies a variable to receive input. ,length Specifies the number of characters to accept as input from the attached line. The default is one character unless you use UNTIL in the statement. SETTING count.var count.var is the number of characters received from the attached line. FROM line.expr line.expr is the attached line receiving input. UNTIL term.expr term.expr is a string of characters, any of which terminate input. The terminating character does not appear in the returned text variable. If you use UNTIL and do not specify term.expr, any number of characters is accepted. Characters often used for the UNTIL clause are carriage return and line feed. 141 Chapter 1: UniBasic commands and functions Parameter Description RETURNING term.var Assigns the character that terminates the input to term.var. Input terminates due to: Reaching the maximum number of characters. Timeout. Record mark encountered in input. In this case, term.var contains an empty string. WAITING seconds Specifies the number of seconds to wait before UniData times out. THEN statements | ELSE statements If the line is not attached, UniData performs the ELSE clause. If the line is not attached and there is not an ELSE clause, a runtime error displays and the user enters the UniBasic debugger. Examples In the following example, the program segment waits 15 seconds for 10 characters of input from line 0. If time expires before 10 characters are received from the attached line, UniData stops receiving, returns the data received, and performs the ELSE clause. GET TMP,10 FROM 0 WAITING 15 ELSE PRINT "Input time has expired" Related commands Language Command UniBasic SEND UniData PROTOCOL For information, see the UniData Commands Reference. getCipherSuite The getCipherSuite() function obtains information about supported cipher suites, their version, usage, strength and type for the security context you specify. The result is put into the dynamic array ciphers, with one line for each cipher suite, separated by a field mark (@FM). The format of the string for one cipher suite is as follows. Suite, version, key-exchange, authentication, encryption, digest, export Refer to the cipher tables in UniBasic Extensions for definitions of all suites. The following is an example of a typical Suite. EXP-DES-CBC-SHA SSLv3 Kx=RSA(512) Au=RSA Enc=DES(40) Mac=SHA1 export The suite is broken down as follows. The suite name is EXP-DES-CBC-SHA. It is specified by SSLv3. The Key-exchange algorithm is RSA with 512-bit key. The authentication is also done by RSA algorithm. The Data encryption uses DES (Data Encryption Standard, an NIST standard) with CBC mode. MAC (Message Authentication Code, a hash method to calculate message digest) will be done with SHA-1 (Secure Hash Algorithm 1, also an NIST standard) algorithm. The suite is exportable. UniData only retrieves those methods that are active for the protocol. 142 GETENV Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getCipherSuite(context,ciphers) Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. ciphers A Dynamic array containing the cipher strings delimited by @FM. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid Security Context handle. 2 Unable to obtain information. GETENV The UniBasic GETENV function returns the contents of the UNIX, or Windows platform environment variable. If you include the environment variable explicitly (as opposed to including it in a variable), you must enclose it in quotation marks. Syntax GETENV(var | "envir.var") Examples In the following example, the program statement retrieves the value of UDTBIN in X: X = GETENV("UDTBIN") In the next example, the program retrieves the value of UDTBIN in X, but uses a variable to define UDTBIN: VAR = "UDTBIN" X = GETENV(VAR) getHTTPDefault The getHTTPDefault function returns the default values of the HTTP settings. See the section under setHTTPDefault, on page 347 for additional information. 143 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getHTTPDefault(option, value) Parameters The following table describes each parameter of the syntax. Parameter Description option Currently, the following options are defined: PROXY_NAME PROXY_PORT VERSION BUFSIZE AUTHENTICATE HEADERS value A string containing the appropriate option value. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid option. getIpv The getIpv function, without an option, returns the current IPv setting. If a network choice is entered as an option, it returns only that network’s IPv setting. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getIpv(option[, sockettype]) Parameters The following table describes each parameter of the syntax. Parameter Description option A string containing an option name. See the table below for the options currently defined. The following table describes the available socket types for getIpv. 144 GETLIST Socket Type Description “SOCKET” Specifies the socket network type. “NFA” Specifies the NFA network type. GETLIST The UniBasic GETLIST command restores a select list from a saved list. Tip: Use GETLIST to access a list without having to issue multiple SELECT or SSELECT commands. Syntax GETLIST list.name [,acct.name] [TO list.num] [SETTING count.var] {THEN | ELSE} statements [END] Parameters The following table describes each parameter of the syntax. Parameter Description list.name Specifies the saved list. acct.name Specifies a full path of a directory where the list resides if list.name is not in the current account. TO list.num Specifies the number of the active list. list.num can be 0 through 9. The default list is 0. SETTING count.var Specifies a variable to contain the number of elements the GETLIST command generates. THEN | ELSE statements Specifies statements to execute if the command succeeds (THEN) or fails (ELSE). Either a THEN or an ELSE statement is required. END is required to terminate multiline statements. Examples In the following example, the program segment retrieves the previously saved list CS_STAFF and assigns it to active list 2. If the list is not found, the program aborts and displays an error message. GETLIST "CS_STAFF" TO 2 ELSE ABORT "NO CS_STAFF saved list found." In the next example, the program segment creates a select list and saves it. GETLIST then retrieves the saved list to active list 0 (the default). The program then uses the IDs in list 0 to retrieve the first 22 Canadian clients. EXECUTE 'SELECT CLIENTS WITH COUNTRY = "Canada"' EXECUTE "SAVE.LIST 'canadians'" OPEN 'CLIENTS' TO CLIENT.FILE ELSE ABORT GETLIST 'canadians' ELSE PRINT "SELECT LIST CANNOT BE FOUND";STOP PRINT @(-1) FOR I = 1 TO 22 READNEXT ID ELSE EXIT READ REC FROM CLIENT.FILE, ID THEN 145 Chapter 1: UniBasic commands and functions PRINT @(5,I):REC<1>:@(20,I):REC<2> END ELSE PRINT "CANNOT FIND RECORD":ID END NEXT I CLEARSELECT END Related commands Language Command UniBasic DELETELIST, FORMLIST, READLIST, READNEXT, SELECT, SELECTINDEX, SELECTINFO, WRITELIST UniData SQL SELECT For information, see the UniData Commands Reference. UniQuery DELETELIST, GETLIST, SELECT, SSELECT, SAVE.LIST For information, see the UniQuery Commands Reference GETPTR The UniBasic GETPTR function returns a string variable containing the values of the current printer settings for the unit.no specified. Tip: GETPTR can store the values associated with a print unit so those values can be reset to their initial values at the end of a process. Syntax GETPTR(unit.no) GETPTR function return values The GETPTR function returns a string containing the same set of values as specified in the ECL SETPTR function, including the print unit and the options. The following table describes these values. 146 Return Description unit The number assigned to a given printer through UniData, from 0 through 255. (The default is 0.) width The number of characters per line, from 0 to 256 characters. length The number of lines per page, from 1 to 32,767 lines. topmargin The number of lines to leave blank at the top of each page, from 0 to 25. bottommargin The number of lines to leave blank at the bottom of each page, from 0 to 25. mode Destination of output. For mode values, see SETPTR in the UniData Commands Reference. options Print options such as BANNER, COPIES, NHEAD, and FORM. For option values, see SETPTR in the UniData Commands Reference. GETPU STATUS function return values After you execute GETPTR, the STATUS function returns one of the values described in the following table. Value Description 0 If success. 1 If there are no more rows. 2 Other error. Examples In the following example, the program segment assigns the printer settings to the variable PRINTER.STRING: PRINTER.STRING = GETPTR(1) Related commands Language Command UniData SETPTR For information, see the UniData Commands Reference. GETPU The UniBasic GETPU function returns the full path of the current print or hold file ID created by the current user process. unit.number is the number of the logical printer unit. Tip: Use the ECL SETPTR command to determine the current printer unit of your system. Syntax GETPU(unit.number) Related commands Language Command UniBasic GETPTR UniData SETPTR For information, see the UniData Commands Reference. GETQUEUE The UniBasic GETQUEUE function returns a dynamic array containing information about all records currently locked and waiting to be released. UniBasic commands that check for locks, such as READU and READV, cause processes to wait for locks to be released before proceeding. 147 Chapter 1: UniBasic commands and functions This command delivers the same information as the ECL command LIST.QUEUE, but in a different format. A value mark separates these pieces of information. An attribute mark separates the information about different locks. If GETQUEUE is successful, UniData sets @SYSTEM.RETURN.CODE to the number of locks waiting to be released. If unsuccessful, UniData sets @SYSTEM.RETURN.CODE to -1. Note: UniBasic locks are advisory only. For more information, see Developing UniBasic Applications. Syntax GETQUEUE() GETQUEUE function return values The GETQUEUE function returns the values described in the following table. Value Description UDTNO The number of the UniData process that locked the file. USERNBR The ID of the process that ran the UniData application that locked the file. UID The user ID of the user who ran the UniData application that locked the file. USERNAME The user name of the user who ran the UniData application that locked the file. TTY The terminal ID of the user who ran the UniData application that locked the file. FILE NAME The name of the locked file. INBR The i-node number used by the locked file. For Windows platforms, this value consists of the high integer and low integer of the i-node used by the locked file. The high integer and the low integer are separated by a space. DNBR The device number used by the locked file. RECORD ID The ID of the record in the file that is being updated. MODE The mode of the command that locked the file. GETREADU The UniBasic GETREADU function returns a dynamic array containing information about all records that have been locked by any UniBasic or ECL command that updates any record. This command delivers the same information as the ECL command LIST.READU, but in a different format. A value mark separates these pieces of information. An attribute mark separates the information about different locks. If GETREADU is successful, UniData sets @SYSTEM.RETURN.CODE to the number of locks set. If unsuccessful, UniData sets @SYSTEM.RETURN.CODE to -1. Note: UniBasic locks are advisory only. For more information, see the Developing UniBasic Applications. 148 getResponseHeader Syntax GETREADU() GETREADU function return values The GETREADU function returns the values described in the following table. Value Description UDTNO The number of the UniData process that locked the file. USERNBR The ID of the process that ran the UniData application that locked the file. UID The user ID of the user who ran the UniData application that locked the file. USERNAME The user name of the user who ran the UniData application that locked the file. TTY The terminal ID of the user who ran the UniData application that locked the file. FILE NAME The name of the locked file. INBR The i-node number used by the locked file. For Windows platforms, this value consists of the high integer and low integer of the inode used by the locked file. The high integer and the low integer are separated by a space. DNBR The device number used by the locked file. RECORD ID The ID of the record in the file that is being updated. MODE The mode of the command that locked the file. TIME The time the lock was set. DATE The date the lock was set. getResponseHeader This function gets a specific response header value from response headers returned by submitRequest(). It can be used to query if a specific header, for example, Content-encoding, is present in the response. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getResponseHeader(request_handle, header_name, header_value) Parameters The following table describes each parameter of the syntax. Parameter Description request_handle The handle to the request. header_name A string containing a response header name. header_value The value of the header, if present. Otherwise, an empty string. 149 Chapter 1: UniBasic commands and functions The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid request handle. 2 Header not found. getSocketInformation Use the getSocketInformation function to obtain information about a socket connection. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getSocketInformation(socket_handle, self_ or_ peer, socket_info) Parameters The following table describes each parameter of the syntax. Parameter Description socket_handle The handle to the open socket. self_ or_ peer Get information on the self end or the peer end of the socket. Specify 0 to return information from the peer end and non-zero for information from the self end. socket_info Dynamic Array containing information about the socket connection. For information about the elements of this dynamic array, see the following table. The following table describes each element of the socket_info dynamic array. Element Description 1 Open or closed 2 Name or IP 3 Port number 4 Secure or Non-secure 5 Blocking mode The following table describes the status of each return code. 150 Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. getSocketOptions getSocketOptions The getSocketOptions function gets the current value for a socket option associated with a socket of any type. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax getSocketOptions(socket_handle, Options) Parameters The following table describes each parameter of the syntax. Parameter Description socket_handle The socket handle from openSocket(), acceptSocket(), or initServerSocket(). options A Dynamic Array containing information about the socket options and their current settings. When querying for options, the dynamic array is configured as: optName1<FM> optName2<FM> optName... When the options are returned, the dynamic array is configured as: optName1<VM>optValue1a[<VM>optValue1b]<FM> optName2<VM>optValue2a[<VM>optValue2b]<FM> optName3... Where optName contains an option name string listed below. The first optValue describes if the option is ON or Off and must be one of two possible values: “1” for ON or “2” for OFF. The second optValue is optional and may hold additional data for a specific option. Currently, for option “LINGER”, it contains the delayed time (in milliseconds) before closing the socket. The following table describes the available options (case-sensitive) for getSocketOptions(). Option Description DEBUG Enable/disable recording of debug information. REUSEADDR Enable/disable the reuse of a location address (default). KEEPALIVE Enable/disable keeping connections alive. DONTROUTE Enable/disable routing bypass for outgoing messages. LINGER Linger on close if data is present. BROADCAST Enable/disable permission to transmit broadcast messages. OOBINLINE Enable/disable reception of out-of-band data in band. SNDBUF Get buffer size for output (default 4KB). 151 Chapter 1: UniBasic commands and functions Option Description RCVBUF Get buffer size for input (default 4KB). TYPE Get the type of the socket. ERROR Get and clear error on the socket. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. GETUSERGROUP For UNIX, the UniBasic GETUSERGROUP function returns the group number for the user ID you specify by uid. For Windows platforms, it returns 0. Syntax GETUSERGROUP(uid) Examples In the following example, the program statement assigns the user group to variable X: X = GETUSERGROUP(@UID) In the next example, the program statement assigns the user group for 1023 to variable X: X = GETUSERGROUP(1023) Related commands Language Command UniBasic GETUSERID, GETUSERNAME GETUSERID The UniBasic GETUSERID function returns the user ID for a user name. For UNIX, this is the systemrecognized user ID. For Windows platforms, the returned user ID is meaningful in UniData only. Syntax GETUSERID(user.name) Examples In the following example, the program statement assigns the user ID for “John” to variable X: X = GETUSERID("John") 152 GETUSERNAME Related commands Language Command UniBasic GETUSERGROUP, GETUSERNAME GETUSERNAME The UniBasic GETUSERNAME function returns the user name for a user ID. To obtain the ID of the current user, use the UniBasic @UID variable (or, for UNIX, enter “id” at the UNIX prompt). After you obtain the user ID, you can specify it explicitly in the GETUSERNAME function. Syntax GETUSERNAME(uid) Examples In the following example, the program statement assigns the user name to variable X: X = GETUSERNAME(@UID) In the next example, the program statement assigns the user name for 1023 to variable X: X = GETUSERNAME(1023) Related commands Language Command UniBasic GETUSERGROUP, GETUSERID GOSUB The UniBasic GOSUB command transfers program control to an internal subroutine. UniData requires a valid statement label. Control returns to the main program when the RETURN statement is encountered in the subroutine. Syntax GOSUB label[:] Examples The following program segment is taken from the sample program in Developing UniBasic Applications. This is an example of subroutines used in structured programming style. *-------------- Main Logic ----------------------------GOSUB INITIALIZE LOOP GOSUB DISPLAY_SCREEN GOSUB GET_ORDER_NUMBER UNTIL ORDER_NUMBER[1,1] = 'Q' GOSUB DISPLAY_DATA IF RECORD_FOUND THEN GOSUB GET_RECORD_COMMAND RELEASE REPEAT 153 Chapter 1: UniBasic commands and functions GOSUB EXIT In the next example, the program segment prints: ▪ “Now we go to the subroutine.” ▪ “Now in subroutine BRANCHOUT.” ▪ “Back from subroutine BRANCHOUT.” PRINT "Now we go to the subroutine." GOSUB BRANCHOUT PRINT "Back from subroutine BRANCHOUT." STOP BRANCHOUT: PRINT "Now in subroutine BRANCHOUT." RETURN END Related commands Language Command UniBasic GOTO, ON/GOSUB, RETURN GOTO The UniBasic GOTO command branches unconditionally to a statement label within a program or subroutine. A statement label must exist in the program or subroutine. If the label you specify does not exist, the compiler generates an error message and the program aborts. After a program executes a GOTO, it does not keep track of the point of departure, but simply moves to the new statement and begins executing there. You cannot use the UniBasic RETURN command in conjunction with a GOTO statement. Tip: Use GOSUB instead of GOTO to make your programs easier to follow and maintain. Syntax GOTO label [:] Synonyms GO Examples In the following example, the program statement transfers program control to the statement label 2510: GOTO 2510 In the next example, the program statement transfers control to the statement label START if the variable RETRY is true: IF RETRY GOTO START 154 GROUP Related commands Language Command UniBasic GOSUB, ON/GOTO GROUP The UniBasic GROUP function extracts the number of continuous groups you specify from the given string. GROUP functions similar to option G of the OCONV Group (G) function (group extraction conversion), but allows any single character, including a system delimiter, null value, number, or minus sign (-) as a delimiter. Another difference is that the start parameter of the GROUP function specifies the starting group to return, while OCONV specifies the number of leading groups to skip. Syntax GROUP(str, delim, start, rtn.num) Parameters The following table describes each parameter of the syntax. Parameter Description str Specifies the string from which to extract groups. delim Specifies any ASCII character that delimits groups in the string. start Specifies the first of the groups to return. rtn.num Specifies the number of continuous groups included in the result. If the rtn.num is greater than the number of groups remaining in the string, the function finishes after the entire remaining string is exhausted. Examples In the following example, the program statement assigns 1231 to the variable A: A = GROUP("123124125126","2",1,2) In the next example, the program segment prints “Boulder” because it is the second group separated by ‘:’, and only one group is returned: ST = "Denver:Boulder:Aurora:Littleton" PRINT GROUP(ST,':',2,1) Related commands Language Command UniBasic FIELD, OCONV Group (G) 155 Chapter 1: UniBasic commands and functions GROUPSTORE The UniBasic GROUPSTORE command inserts a given substring or portion of a substring into a string, and replaces all, part, or none of the string. The string can be delimited by the single character delimiter. The unit of replacement is called an element in this section. Syntax GROUPSTORE substr IN str USING start.num,replace.num [,delimiter] Parameters The following table describes each parameter of the syntax. Parameter Description substr Specifies the substring you want to insert into the string. substr can contain any combination of numeric, alphabetic, or special characters. str Specifies the target string into which substr is inserted. start.num Specifies the position from which to begin replacing elements of the string. start.num must be at least 1. If you specify a value of less than 1, start.num defaults to 1. If start.num is negative and replace.num is not negative, UniBasic uses the absolute value of start.num. If start.num is greater than the number of elements in the target string, UniBasic appends the substr to the end of the string with the appropriate number of delimiters in between. replace.num Specifies the number of elements in the string to replace with elements of substr. Refer to the next table for values for replace.num. ,delimiter Specifies a single ASCII character to use as a delimiter. The default delimiter is @AM. If you specify more than one character for delimiter, UniBasic uses the first character. The replace.num option controls whether GROUPSTORE replaces all, part, or none of the substring. The following table describes these options. replace.num value Description >0 The first replace.num elements of the substr replaces elements of the string starting from the position specified by start.num. If the string contains fewer than replace.num elements starting from start.num, the replacement stops after the string is exhausted. 0 The entire substr is inserted before the start.num position in the string. <0 The number of elements specified in replace.num are deleted starting at start.num, and substr replaces them. If both start.num and replace.num are less than 0, replacement does not take place. Only the number of elements specified in replace.num are deleted, starting at start.num. 156 GROUPSTORE Examples In the following example, the program segment assigns the value stored in string SUB in string A. Because the starting number is 2, and no delimiter is specified, UniData uses the attribute mark (@AM) as the delimiter. A = "123":@AM:"ABC":@AM:"456":@VM:"DEF":@AM:"012":@VM:"GHI" SUB = "***" GROUPSTORE SUB IN A USING 2,1 This results in: A = "123":@AM:"***":@AM:"456":@VM:"DEF":@AM:"012":@VM:"GHI" In the next example, the program segment replaces both values in the third attribute in A with SUB. Though the replacement number is 2, UniData replaces only one attribute because SUB has only one element. A = "123":@AM:"ABC":@AM:"456":@VM:"DEF":@AM:"012":@VM:"GHI" SUB = "###" GROUPSTORE SUB IN A USING 3,2 This results in: A = "123":@AM:"ABC":@AM:"###":@AM:"012":@VM:"GHI" In the next example, the program segment inserts SUB before position 1 in A: A = "123":@AM:"ABC":@AM:"456":@VM:"DEF":@AM:"012":@VM:"GHI" SUB = "begin" GROUPSTORE SUB IN A USING 1,0 This results in: A = "begin":@AM:"123":@AM:"ABC":@AM:"456": @VM:"DEF":@AM:"012":@VM:"GHI" In the next example, the program segment replaces the first two attributes and their associated subvalues with SUB using @VM as the delimiter: A = "123":@AM:"ABC":@AM:"456":@VM:"DEF":@AM:"012":@VM:"GHI" SUB = "mv1":@VM:"sub1":@SM:"sub2":@VM:"mv2" GROUPSTORE SUB IN A USING 1,2,@VM This results in: A = "mv1":@AM:"sub1":@AM:"sub2":@VM:"GHI" This next example compiles and runs only with null value handling turned on. The program segment replaces the third element with three asterisks. This program segment calls the externally cataloged subroutine PRINT.SETUP, which converts the null value and UniData delimiters to printable characters, and then prints the converted string. PRT.STR = '' A ="123":@AM:"ABC":@AM:"456":@VM:"DEF":@VM:@NULL:@AM:"012":@VM:@NULL :@VM:"GHI" SUB = "***" 157 Chapter 1: UniBasic commands and functions GROUPSTORE SUB IN A USING 3,1,@VM STR = A CALL PRINT.SETUP(STR,PRT.STR) PRINT "A = ":PRT.STR This program segment prints: A = 123@AMABC@AM456@VMDEF@VM***@VM@NULL@VMGHI GT The UniBasic relational operator GT tests whether expression expr1 is greater than expr2. expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Relational operators make the comparisons that direct program flow in conditional statements such as the following: IF VAR1 GT VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 > VAR2 Syntax expr1 GT expr2 Synonyms > Examples In the following example, the program segment tests whether A is greater than B. Because A is greater than B, the message “Greater Than” prints. A = 24 B = 22 IF A GT B THEN PRINT "Greater Than" END ELSE PRINT "Less Than" END Related commands Language Command UniBasic GTS GTS The UniBasic GTS function compares each value in array1 to its corresponding value in array2. UniData returns an array with 1 in each position where the value in array1 is greater than the value in the corresponding position in array2, and 0 in each position for values that are less than array2. 158 HASH Syntax GTS(array1,array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY2 and returns ARRAY3. ARRAY3 then contains 1}1}0}0}0. ARRAY1 = 10:@VM:20:@VM:30@VM:40:@VM:50 ARRAY2 = 9:@VM:10:@VM:30:@VM:50:@VM:60 ARRAY3 = GTS(ARRAY1,ARRAY2) HASH The UniBasic HASH function determines to which group a particular record key is hashed, depending on the modulo and the file type. HASH returns the group number in which a record with a key of rec.key is stored. HASH includes a file type parameter. When rec.key, modulo, and type are passed to the function, HASH returns the group number to which the record key will hash. Note: Hash Type 3 and WHOLEFILE Split style were added at UniData 8.1.0. The type values used in the HASH function are also shown in the fileview output. However, in fileview, the hash type is shown in hex. Syntax HASH(rec.key,modulo,type) Parameters The following table describes each parameter of the syntax. Parameter Description rec.key Specifies the record key to hash. modulo Specifies the file modulo, the number of groups specified when the file was created. type For the file being tested, specifies static or dynamic and hash type, as determined when the file was created. You can use the following 159 Chapter 1: UniBasic commands and functions Parameter Description Type # File Type Split Style Hash Type 0 Static N/A 0 1 Static N/A 1 3 Static N/A 3 64 Dynamic KEYONLY 0 65 Dynamic KEYONLY 1 67 Dynamic KEYONLY 3 96 Dynamic KEYDATA 0 97 Dynamic KEYDATA 1 99 Dynamic KEYDATA 3 112 Dynamic WHOLEFILE 0 113 Dynamic WHOLEFILE 1 115 Dynamic WHOLEFILE 3 HEADING The UniBasic HEADING command prints a string you specify at the top of each report page on the current print device. Note: The HEADING command clears the screen before displaying a report. Syntax HEADING [ON expr] str.expr ['option']... Parameters The following table describes each parameter of the syntax. 160 Parameter Description ON expr Directs UniData to send output to print file expr. As many as 31 print files can be active at a time. The print files can have identifiers of 0-254. str.expr Specifies a string to print at the top of each report page. You can use special characters, such as unmatched single and double quotation marks, in str.expr. HUSH Parameter Description 'option' option must be enclosed in single quotation marks. You can place option(s) anywhere in the heading expression. option can be any of the following: ASCII code – Passes code controlling paging characteristics. P or S – Prints current page number. N – Suppresses the pagination prompt after each page. L – Advances one line. Used for multiline headings. D – Prints date in MM-DD-YY format. T – Prints time/date in MM-DD-YY HH:MM:SS format. C – Centers the heading text. G – Forces the line to fill the width of the page. W – Causes a page to fill completely before breaking and printing the heading when the HEADING statement is first encountered. If you do not specify W, UniData creates a new page break when it first encounters the HEADING statement. Examples In the following example, the HEADING statement sends a heading to print file 3: “current page number Shareholders Report current date”. HEADING ON 3 "'P' Shareholders Report 'D'" In the next example, the HEADING statement prints the current page number, and the current date and time, on the top of the default print device. The N code causes the report to print continuously, not requiring a carriage return after each page. HEADING "'PTN'" This results in the following heading: 1207-21-91 12:13:00. Related commands Language Command UniBasic FOOTING, GETPTR, PRINTER UniData SETPTR For information, see the UniData Commands Reference. HUSH The UniBasic HUSH command enables or disables terminal output. Syntax HUSH {ON | OFF | expr} [SETTING pre.status.var] Parameters The following table describes each parameter of the syntax. 161 Chapter 1: UniBasic commands and functions Parameter Description ON Disables the terminal output. OFF Enables the terminal output. expr Disables the terminal output if expr is not 0. Enables terminal output if expr is 0. expr must be a numeric value. SETTING pre.status.var The SETTING clause sets the previous terminal status (1 for ON and 0 for OFF) to pre.status.var. Examples In the following example, the program segment prints 1 and -1 on the terminal screen because the HUSH command enables the terminal (A + B evaluates to 0). The second PRINT statement produces nothing on the screen because HUSH ON is set. The third PRINT command prints C = 1 on the screen because terminal output is enabled. A = 1; B = -1 HUSH A + B PRINT A,B HUSH ON PRINT A + B HUSH OFF SETTING C PRINT "C = ":C ICONV The UniBasic ICONV function converts string or numeric data to internal representation format based on conversion codes. ICONV supports multibyte languages. If the input value or conversion code is invalid, UniData returns the input value. With null value handling turned on, the presence of the null value in data produces a result of the null value, and the STATUS function return value is set to 5. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(expr,conv.code.expr, “MM [H] [S[M]]”) Parameters The following table describes each parameter of the syntax. 162 Parameter Description expr Specifies the expression (a string or numeric data) to convert. conv.code.expr Specifies an internal representation format to use when converting expr. H Indicates that 'num.expr' is formatted in 12-hour format with a.m. or p.m. suffixes. S Indicates that seconds are included in the input value. M Indicates that milliseconds are included in the input value. If this parameter is used the S parameter must also be used. ICONV The following table summarizes the valid conversion codes. A detailed discussion of each follows under separate topics. Code Format D System date. G Extracts one or more strings separated by a delimiter. L Length. MB Binary. MC Masked character. MD Masked decimal. ME Masked extended. ML Left justify. MP Packed decimal. MP1 Convert to packed decimal without truncating at the first CHAR(0) or altering this character. MO Octal. MR Right justify. MT System time. MX Hexadecimal. P Pattern match. R Range. S SOUNDEX. T Text extraction. Tfile File translation. STATUS function return values After you execute ICONV, the STATUS function returns one of the values described in the following table. Value Description 0 Successful conversion. 1 Invalid input data. 2 Invalid conversion specification. 3 Invalid date for “D” conversion code only. 5 Null value if null value handling is turned on. Examples The following program segment demonstrates the date and time conversions: ORDER.REC<1> = ICONV(ORDER_DATE,"D") ORDER.REC<2> = ICONV(ORDER_TIME,"MT") The following program segment is taken from the sample program in Developing UniBasic Applications. It demonstrates the alternate syntax that does not use the ICONV function name. This code rightjustifies a string of 10 characters so that the data lines up on the right. PRODUCT_LINE := " ":PRODUCT_NUMBER "R#10" COLOR_LINE := " ":COLOR "R#10" 163 Chapter 1: UniBasic commands and functions QUANTITY_LINE := " ":QUANTITY "R#10" PRICE_LINE := " ":PRICE "R#10" The next example illustrates the ICONV command using milliseconds: CRT '**** Using only "MM" ICONV Code ****' CRT 'ICONV("16:18","MM"): ':ICONV("16:18","MM") CRT 'ICONV("04:18PM","MM"): ':ICONV("04:18PM","MM") CRT 'ICONV("04:18:05PM","MM"): ':ICONV("04:18:05PM","MM") CRT 'ICONV("16:18:05","MM"): ':ICONV("16:18:05","MM") CRT 'ICONV("04:18:05.456PM","MM"): ':ICONV("04:18:05.456PM","MM") CRT 'ICONV("16:18:05.456","MM"): ':ICONV("16:18:05.456","MM") CRT '' CRT '**** Using optional codes ****' CRT 'ICONV("04:18PM","MMH"): ':ICONV("04:18PM","MMH") CRT 'ICONV("04:18:05PM","MMHS"): ':ICONV("04:18:05PM","MMHS") CRT 'ICONV("16:18:05","MMS"): ':ICONV("16:18:05","MMS") CRT 'ICONV("04:18:05.456PM","MMHSM"): ':ICONV("04:18:05.456PM","MMHSM") CRT 'ICONV("16:18:05.456","MMSM"): ':ICONV("16:18:05.456","MMSM") Result: **** Using only "MM" ICONV Code **** ICONV("16:18","MM"): 58680000 ICONV("04:18PM","MM"): 58680000 ICONV("04:18:05PM","MM"): 58685000 ICONV("16:18:05","MM"): 58685000 ICONV("04:18:05.456PM","MM"): 58685456 ICONV("16:18:05.456","MM"): 58685456 **** Using optional Codes **** ICONV("04:18PM","MMH"): 58680000 ICONV("04:18:05PM","MMHS"): 58685000 ICONV("16:18:05","MMS"): 58685000 ICONV("04:18:05.456PM","MMHSM"): 58685456 ICONV("16:18:05.456","MMSM"):58685456 Related commands Language Command UniBasic OCONV ICONV Date (D) The ICONV date (D) function converts display representations of dates into simple integer internal format. Internal date format is the number of days before or since December 31, 1967. If the input value or conversion code is invalid, UniData returns the input value. UniData ignores leading and trailing spaces around the input date. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(ext.date, "D [y] [c]") 164 ICONV Date (D) Parameters The following table describes each parameter of the syntax. Parameter Description ext.date Specifies the date, in display format, to convert to internal format. Valid delimiters include the slash, comma, hyphen, and period. D Indicates a date conversion. yc The ICONV function does not use y and c, but they are accepted to maintain consistency with the OCONV Date (D) function. Points to remember when entering dates To avoid unexpected results when you convert dates into internal date format by using ICONV, be aware of the following: ▪ If you do not enter a year, UniData defaults to the current year. For example, if you enter 12/1 and the year is 1996, UniData stores 10563 (12/1/96). ▪ If you enter a number between 1 and 12 for month, UniData defaults to the first day of the month in the current year. For example, if you enter just 12 during 1996, UniData stores 10563 (12/1/96). ▪ Any two-digit year entered in the range 00-29 defaults to the twenty-first century. For example, UniData interprets 12/31/29 as December 31, 2029. Any two-digit year entered in the range 30-99 is considered to be 1930-1999. Converting more than once Depending on the date range, if an application performs ICONV on an already converted date, UniData could produce unexpected results. Dates that convert into four- or five-digit internal formats and meet the following conditions fall into this category: ▪ The first two digits are 10, 11, or 12. ▪ The second two digits are 01 through 31. ▪ The fifth digit is any number from 0 through 9. Where there is no fifth digit, UniData assigns the current year. For example, assuming 5/28/95 is the input, the code segment shown on the left results in the displays on the right: INPUT VAR VAR=ICONV(VAR,'D') PRINT VAR PRINT OCONV(VAR,'D') VAR=ICONV(VAR,'D') PRINT VAR PRINT OCONV(VAR,'D') 10010 28 MAY 1995 11963 01 OCT 2000 The first ICONV returns a value of 10010. OCONV correctly returns the external format. The date matches the initial entry. However, the second ICONV accepts the internal format, 10010, as input; UniData translates this as October 1, 2000, and ICONV returns an internal format of 11963. The final OCONV returns 01 OCT 2000. Note: To prevent the preceding scenario, you can make all numeric input of fewer than six characters invalid by turning UDT.OPTIONS 82 on. However, your applications will no longer be able to process the abbreviated input dates. 165 Chapter 1: UniBasic commands and functions STATUS function return values After you execute ICONV D, the STATUS function returns one of the values described in the following table. Value Description 0 Successful conversion of a valid date. 1 Invalid input date. 2 Invalid conversion specification. 3 Date was converted correctly, but month and day were inverted in input value. Note: After you execute the ICONV D function, the STATUS function returns a code indicating the execution status of the conversion of the last array element only. Examples The following table describes common date conversions and their results. Value Code Result 09/15/85 D 6468 12/31/67 D 0 December 31, 1967 D 0 01/29/1988 D 7334 In the following example, the program segment prints the date in internal and display format: INPUT IN_DATE INTERNAL = ICONV(IN_DATE,"D") OUTPUT = OCONV(INTERNAL, "D4/") PRINT IN_DATE,INTERNAL,OUTPUT The following table describes various dates you can input in the previous program and their conversions. 166 In_Date Internal Output 1 8402 01/01/1991 11 8706 11/01/1991 011 8402 01/01/1991 12 8736 12/01/1991 121 8736 12/01/1991 110389 8709 11/03/1989 1/1 8402 01/01/1991 1/1/89 8402 01/01/1989 1/1/02 12420 01/01/2002 ICONV Group (G) Related commands Language Command UniBasic DATE, OCONV Date (D), TIMEDATE ICONV Group (G) The ICONV Group (G) function extracts one or more strings separated by a delimiter. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(str.expr, "G[m]*n") Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Indicates a string separated by a delimiter. G Group extraction code. m Indicates the number of strings to skip. If m is omitted, no strings are skipped. * Specifies any single nonnumeric character that is the delimiter. A minus sign (-) is not valid. UniData system delimiters are valid also. n The number of strings to be extracted. Examples In the following example, the program segment prints (303): X = "(303)+555+0988" PRINT ICONV(X,"G0+1") Related commands Language Command UniBasic OCONV Group (G) ICONV Length (L) The ICONV Length (L) function extracts a string of a specified length or that falls within a range of acceptable lengths. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 167 Chapter 1: UniBasic commands and functions Syntax ICONV(str.expr, "Ln[,m]") Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Indicates a string to be searched. L Length conversion code. n Specifies the number of characters the string must match to be extracted. When m is present, n is the shortest string to be extracted. m Specifies the longest string to be extracted. Examples In the following example, the program segment prints “123” and an empty string because the value of X has fewer than five characters and more than three: X = 123; Y = 456789 PRINT ICONV(X,"L3,5") PRINT ICONV(Y,"L3,5") Related commands Language Command UniBasic OCONV Length (L) ICONV Masked Character (MC) The ICONV Masked Character (MC) function provides many conversion functions that retrieve and/or convert values in strings and arrays. This function performs the same conversions and extractions as OCONV Masked Character (MC). UniData returns the input value if either the value to be converted or the conversion code is invalid. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(expr, "MC [A | /A | B | /B | C | U | L | T | N | /N | P| X[D] | D | D[X] | X]") Parameters The following table describes each parameter of the syntax. 168 Parameter Description expr The expression to be searched or converted. A Extracts all alphabetic characters. /A Extracts all nonalphabetic characters. ICONV Masked Decimal (MD) Parameter Description B Extracts all alphabetic and numeric characters. /B Extracts all special characters (not alphabetic nor numeric). C;x;y Converts all occurrences of substring x to substring y. U Converts data to uppercase. L Converts characters to lowercase. T Converts to initial cap style. The first letter of each word is uppercase, and all other letters are lowercase. Space and tab are word separators. N Extracts all numeric characters (0–9). /N Extracts all nonnumeric characters. P Converts all nonprinting characters to tildes (~). X[D] or D Assumes input is in decimal; converts to hexadecimal. D[X] or X Assumes input is in hexadecimal; converts to decimal. Examples You can use ICONV to remove special characters in a formatted price. For example, the following program segment extracts 1234 from $12.34: NEW.PRICE = ICONV("$12.34","MCN") PRINT NEW.PRICE Related commands Language Command UniBasic ALPHA, CONVERT, DOWNCASE, NUM, OCONV Masked Character (MC), UPCASE ICONV Masked Decimal (MD) The ICONV Masked Decimal (MD) function converts a decimal number to internal format after rounding, as specified by f. If the input value or conversion code is invalid, UniData returns the input value. Syntax ICONV(num.expr, "MDn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [-| < | E | C | D] [P] [Z] [T] [xc]") Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. The ICONV MD, ML, and MR functions have the same result. They exist separately to maintain consistency with the OCONV MD, ML, and MR functions, which produce different results. Parameters The following table describes each parameter of the syntax. 169 Chapter 1: UniBasic commands and functions Parameter Description num.expr The decimal number to be converted. num.expr can be any numeric value with or without a decimal. n The ICONV function ignores n (for example, if you specify MD32, UniData ignores the 3), but it is included in the syntax to maintain consistency with the OCONV Masked Decimal (MD) function. f Scales the input value num.expr by moving the decimal point f places to the right. If omitted, f defaults to the value assigned to n (for example, if you specify MD2, UniData reads it as MD22, and then ignores the first 2). dec_symbl You can specify a symbol to represent the decimal point in the input number by including dec_symbl. An example is provided in the following section. [prefix], [thsnd_mark], [suffix]] ] [,] [$] [-| < | E | C | D] [P] [Z] [T] [(xc)] The ICONV function ignores these options, but they are included in the syntax to maintain consistency with the OCONV Masked Decimal (MD) function. Examples In the following example, UniData converts the value 12.339 to 1234 by rounding to two decimal places and converting to internal format: INTERNAL.VAL = ICONV("12.339","MD2") The following example demonstrates how to specify that an alternate symbol is used to represent the decimal point in the input number. This example prints 12350. PRINT ICONV("123@499","MD2[,,@]") END Related commands Language Command UniBasic OCONV Masked Decimal (MD) ICONV Left Justify (ML) The ICONV Left Justify (ML) function converts a decimal number to internal format after rounding, as specified by f. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. The ICONV MD, ML, and MR functions have the same result. They exist separately to maintain consistency with the OCONV MD, ML, and MR functions, which produce different results. Syntax ICONV(num.expr, "MLn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [C] [Z] [(mask)]") 170 ICONV Packed Decimal (MP) Parameters The following table describes each parameter of the syntax. Parameter Description num.expr The decimal number to be converted. num.expr can be any numeric value with or without a decimal. n The ICONV function ignores n (for example, if you specify ML32, UniData ignores the 3), but it is included in the syntax to maintain consistency with the OCONV Left Justify (ML) function. f Scales the input value expr by moving the decimal point f places to the right. If omitted, f defaults to the value assigned to n (for example, if you specify ML2, UniData reads it as ML22, and then ignores the first 2). dec_symbl You can specify a symbol to represent the decimal point in the input number by including dec_symbl. An example is provided in the following section. [prefix], [thsnd_mark], [suffix]] ] [,] [$] [C] [Z] [(mask)] The ICONV function ignores these options, but they are included in the syntax to maintain consistency with the OCONV Left Justify (ML) function. Examples In the following example, UniData converts the value 12.339 to 12339 based on the ML3 conversion code: INTERNAL.VAL = ICONV("12.339","ML3") The following example demonstrates how specify an alternate symbol to represent the decimal point in the input number. This example prints 12350. PRINT ICONV("123@499","ML2[,,@]") END Related commands Language Command UniBasic OCONV Left Justify (ML) ICONV Packed Decimal (MP) The ICONV Packed Decimal (MP) function converts an integer expr into packed decimal representation by compressing two digits of the integer into one byte. UniData returns the input value if either the value to be converted or the conversion code is invalid. Use this function to conserve disk space. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(expr, "MP") 171 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic OCONV Packed Decimal (MP) ICONV Packed Decimal (MP1) The ICONV Packed Decimal (MP1) function converts an integer expr in packed decimal representation into its display format without truncating at the first CHAR(0) character or altering CHAR(0). If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(expr, "MP1") Related commands Language Command UniBasic OCONV Packed Decimal (MP1) ICONV Right Justify (MR) The ICONV Right Justify (MR) function converts a decimal number to internal format after rounding, as specified by f. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. The ICONV MD, ML, and MR functions have the same result. They exist separately to maintain consistency with the OCONV MD, ML, and MR functions, which produce different results. Syntax ICONV(num.expr, "MRn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [C] [Z] [(mask)]") Parameters The following table describes each parameter of the syntax. 172 Parameter Description num.expr The decimal number to be converted. num.expr can be any numeric value with or without a decimal. n The ICONV function ignores n (for example, if you specify MR32, UniData ignores the 3), but it is included in the syntax to maintain consistency with the OCONV Right Justify (MR) function. ICONV Time (MT) Parameter Description f Scales the input value expr by moving the decimal point f places to the right. If omitted, f defaults to the value assigned to n (for example, if you specify MR2, UniData reads it as MR22, and then ignores the first 2). dec_symbl You can specify a symbol to represent the decimal point in the input number by including dec_symbl. An example is provided in the following section. [prefix], [thsnd_mark], [suffix]] ] [,] [$] [C] [Z] [(mask)] The ICONV function ignores these options, but they are included in the syntax to maintain consistency with the OCONV Right Justify (MR) function. Examples In the following example, UniData converts the value 12.339 to 1234 based on the MR2 conversion code: INTERNAL.NUM = ICONV("12.339","MR2") The following example demonstrates how to specify that an alternate symbol is used to represent the decimal point in the input number. This example prints 12350. PRINT ICONV("123@499","MR2[,,@]") END Related commands Language Command UniBasic OCONV Right Justify (MR) ICONV Time (MT) The ICONV Time (MT) function converts the time of day from display format into internal format. The value of the internal format is the number of seconds since midnight (00:00:01 as 1, and 24 as 86400). Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(str.expr, "MT [H] [S] [c]") Parameters The following table describes each parameter of the syntax. 173 Chapter 1: UniBasic commands and functions Parameter Description str.expr Time input must be in the form HH:MM:SS. MM and SS are not required and, if you do not specify them, UniData assumes the values to be zero. You must use a separating character (any nonnumeric character, such as a colon or comma) between units (for example, HH, MM, SS). The suffixes AM, PM, A, and P also are accepted at the end of the string. UniData hours are the same as standard hours, with 12PM as noon (12:00:00) and 12AM as midnight (00:00:00). A value greater than 24:00:00 (for example, 24:00:01) results in an invalid conversion. HSc The remaining options are ignored but are allowed to maintain consistency with the OCONV Time (MT) function. Examples The following table describes the time conversion code and the resulting value. Value Code Specification Result 12:30 MT 45000 12AM MT 0 12PM MT 43200 Related commands Language Command UniBasic DATE, OCONV Time (MT), TIME, TIMEDATE ICONV Hex (MX | HEX), Octal (MO), Binary (MB) The ICONV hex (MX), octal (MO), and binary (MB) functions convert a number from one of three numbering systems to decimal value. UniData returns the input value if either the value to be converted or the conversion code is invalid. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(num.expr, ["HEX | MX [0C] | MO [0C] | MB [0C]"]) Parameters The following table describes each parameter of the syntax. 174 Parameter Description num.expr Specifies the decimal value, in display format, to convert to an alternate numbering system. ICONV Hex (MX | HEX), Octal (MO), Binary (MB) Parameter Description HEX | Indicates conversion from hexadecimal (base 16). The optional 0C specifier converts into ASCII character rather than decimal value. HEX is equivalent to MX0C. MX [0C] MO [0C] Indicates conversion from octal (base 8). The optional 0C converts to ASCII character rather than decimal value. MB [0C] Indicates conversion from binary (base 2). The optional 0C converts to ASCII character rather than decimal value. The following table lists conversion codes to be used with ICONV to convert from other numbering systems to decimal value or ASCII character. From To Function Binary Decimal value Binary ASCII character ICONV MB Octal Decimal value Octal ASCII character Hexadecimal Decimal value Hexadecimal ASCII character ICONV MB0C ICONV MO ICONV MO0C ICONV MX ICONV MX0C ICONV HEX ICONV conversions into other numbering systems produce multiple characters in the target numbering system: ▪ Hexadecimal – One ASCII character produces two hexadecimal characters. For example, ASCII character “0” is equal to hexadecimal “30”. ▪ Octal – One ASCII character produces three octal characters. For example, ASCII character “0” is equal to octal “060”. ▪ Binary – One ASCII character produces eight binary characters. For example, ASCII character “0” is equal to octal “00110000”. Examples The following table demonstrates some ICONV MO, MX, and MB conversion codes and their results. Input Code Result 123123 MO 42579 (decimal) 123123 (octal) MO0C SS (ASCII characters) 100 (hexadecimal) MX 256 (decimal) 101010101010 (binary) MB 170 (decimal) 4B (hexadecimal) MX 75 (ASCII characters) Related commands Language Command UniBasic CHAR, OCONV Hex (MX | HEX), Octal (MO), Binary (MB), SEQ 175 Chapter 1: UniBasic commands and functions ICONV Pattern Match (P) ICONV Pattern Match (P) function performs the same function as the OCONV pattern match (P) function. For information, see OCONV Pattern Match (P), on page 250. Syntax ICONV(str.expr, "P(op)[;(op).....]") ICONV Range (R) The ICONV Range (R)function returns only those data values that fall within a specified range of decimal values. When including a negative range, you must specify the highest negative number first. If range specifications are not met, UniData returns an empty string. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(num.expr, "Rndm[;ndm.....]" Parameters The following table describes each parameter of the syntax. Parameter Description num.expr Indicates a string to be searched. n Specifies the smallest number to be extracted. d Specifies a delimiter separating numbers in a range. Any character except system delimiters can be used to separate the numbers in a range. However, the minus sign (-) should not be used as a delimiter because it refers to a negative number in the range. m Specifies the longest string to be extracted. ; Separates multiple ranges. Examples In the following example, the program segment prints “123” and a blank line because X is within the range and Y is not: X = 123; Y = 456789 PRINT ICONV(X,"R100,200") PRINT ICONV(Y,"R100,200") 176 ICONV SOUNDEX (S) Related commands Language Command UniBasic OCONV Range (R) ICONV SOUNDEX (S) The ICONV SOUNDEX (S) function converts string or numeric data specified by str.expr to phonetic format based on SOUNDEX conversion codes. The S conversion code can be used in an ICONV virtual attribute formula. If the input value or conversion code is invalid, UniData returns the input value. For more information about SOUNDEX conversion codes, see the SOUNDEX command. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(str.expr, "S") Examples The following example is virtual attribute, SDX_LNAME, that converts the value of the variable LNAME to its SOUNDEX expression: ICONV(LNAME,"S") Related commands Language Command UniBasic OCONV SOUNDEX (S), SOUNDEX ICONV Text Extraction (T) The ICONV Text Extraction (T) function extracts a substring from a string. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONV(str.expr, "T[m,]n") Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Indicates a string to be searched. m Extracts a contiguous string of characters starting from character m. 177 Chapter 1: UniBasic commands and functions Parameter Description n Extracts a contiguous string of characters of length n. Examples The following table describes some ICONV text extraction codes and their results. Input Code Result QRSTUV “T3” TUV DAMN THE TORPEDOES “T3,5” MN TH CONVERSION IS THE KEY “T1,9” CONVERSIO 457 COLORADO BLVD “T4,7” [space]COLORA Related commands Language Command UniBasic [], FIND, FINDSTR, OCONV Text Extraction (T) ICONV File Translation (Tfile) The ICONV File Translation (Tfile) function performs the same action as OCONV File Translation (Tfile). For information, see OCONV File Translation (Tfile) . Syntax ICONV(rec.id, "T[DICT] [filename;cn;I-Attribute;O-Attribute]") ICONVS The UniBasic ICONVS function converts string or numeric data from display format to internal format, based on a conversion code, for each element of a dynamic array. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, ICONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax ICONVS(dyn.array.expr, conv.code.expr) Null value handling With null value handling turned on, the presence of the null value in data produces a result of the null value, and the STATUS function return value is set to 5. Note: ICONVS conversion codes are the same as ICONV conversion codes. For information about conversion codes, refer to ICONV. 178 IF/THEN/ELSE Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.expr Specifies a dynamic array, each element of which to convert. conv.code.expr Specifies a code to use in converting each element of the dynamic array. STATUS function return values After you execute ICONVS, the STATUS function returns one of the values described in the following table. Value Description 0 Successful conversion. 1 Invalid input data. 2 Invalid conversion specification. 3 Invalid date for “D” conversion code only. 5 Null value if null value handling is turned on. Examples In the following example, the program segment converts each element of ARR1 to internal format: ARR1 = "$12.34":@VM:5678:@VM:9876 ARR2 = ICONVS(ARR1,"MR2") PRINT ARR2 END This program segment prints the following converted array elements: 1234 567800 987600 Note: The blanks in the number are value marks, which are nonprinting characters. The value marks could display as some other character on your terminal screen. Related commands Language Command UniBasic ICONV, OCONVS IF/THEN/ELSE The UniBasic IF/THEN/ELSE command executes one of two blocks of statements based on a conditional expression. If expr is true, UniData executes the first group of statements. If expr is false, UniData executes the second group of statements. Syntax IF expr THEN statements [ELSE statements] IF expr THEN 179 Chapter 1: UniBasic commands and functions statements... END [ELSE END] statements... IF expr ELSE statements IF expr ELSE statements END Points to Remember when Writing IF/THEN/ELSE Statements The ELSE clause is optional. An IF/THEN/ELSE structure can occupy either a single line or several lines. When coding single- line and multiline statements: ▪ ▪ ▪ The single-line form does not require an END before the ELSE. In the multiline form, each clause must contain at least one statement. If you do not want to take any action, use the NULL command. THEN and ELSE clauses must be delimited by END. A single-line statement that includes the INPUT command as a part of the THEN clause might not produce the results you expect. For example, the following statements produce no output: IF X = 1 THEN INPUT TEST ELSE PRINT "X NE 1" To correct this problem, enter each clause of the statement on a separate line, or use the IN() function to obtain input from the terminal or input queue. With null value handling turned on, a test on expr that is the null value returns false. For an overview of how the null value affects UniBasic, see Developing UniBasic Applications. Tip: You can nest IF/THEN/ELSE statements, but a CASE statement might be more efficient. Examples In the following example, the program statement tests if the variable SUPPLY is less than the variable DEMAND. If the comparison is true, program control is transferred to the statement labeled REORDER. IF SUPPLY < DEMAND THEN GOSUB REORDER In the next example, the program segment compares INCOME to TARGET. UniData executes the first branch if the comparison is true, or executes the second group of statements if the comparison is false. IF INCOME < TARGET THEN PRINT "Income less than target figure." END ELSE PRINT "Income equal to or greater than target!" END Related commands 180 Language Command UniBasic CASE, LOOP/REPEAT, NULL IN IN The UniBasic IN function captures raw data from an input queue or from a terminal. Note: IN can capture function, arrow, and other special keys from the keyboard. Use SYSTEM(14) or -1 with the INPUT statement to check the contents of the input buffer before using the IN() function. Syntax IN( ) Examples In the following example, the program segment assigns the value y to ANSWER: DATA y ANSWER = IN() Related commands Language Command UniBasic DATA, INPUT, INPUT @, INPUTTRAP, SYSTEM INDEX The UniBasic INDEX function returns the starting position of the num.expr occurrence of str.expr2 within str.expr1. INDEX supports multibyte languages. Syntax INDEX(str.expr1,str.expr2,num.expr) Parameters The following table describes each parameter of the syntax. Parameter Description str.expr1 Specifies the string to search. str.expr2 Specifies the string for which to search in str.expr1. num.expr Specifies which occurrence of str.expr2 to return. Examples In the following example, the program segment searches STR.VAR for the second occurrence of the letter t and returns that location in the variable LOC. In this example, it returns a value of 8. STR.VAR = "It was the best of times" LOC = INDEX(STR.VAR,"t",2) 181 Chapter 1: UniBasic commands and functions In the next example, the INDEX function operates like the COL() functions used in conjunction with the FIELD function. It returns the beginning position of the string 212 within the string variable STR. The result stored in the variable NY.STR is 15. STR = "303-433-3199, 212-999-1212" NY.STR = INDEX(STR,"212",1) Related commands Language Command UniBasic COL1, COL2, FIELD INDICES The UniBasic INDICES function returns one of the following: ▪ Names of alternate key indexes. ▪ Information about a particular alternate key index. Syntax INDICES(file.var[, index.name.expr]) Retrieving Names of Alternate Key Indexes If you specify only file.var, the INDICES function returns a dynamic array containing the alternate key index names for all indexes in the file you specify. The index names are not returned in any particular order. Index names are separated by attribute marks. Note: If the index you specify does not exist, the function returns an empty string. Retrieving Information About Indexes If you specify the name of an alternate key index (indexname.expr), the INDICES function returns information about that index in a dynamic array, which consists of six attributes: ▪ 182 Attribute 1 – Four values representing the following information in this order: ▫ Type of key (I or D). ▫ Build required (1 or “ ”). ▫ No meaning. ▫ Automatic update enabled (1 or “ ”). ▪ Attribute 2 – Location of the alternate key in the record. ▪ Attribute 3 – An ASCII string with the time stamp of the last time the index was built (updated by BUILD.INDEX). ▪ Attributes 4 and 5 – Empty. ▪ Attribute 6 – Type of attribute: ▫ S for singlevalued. ▫ M for multivalued. ▫ MS for multi-subvalued. initSecureServerSocket function Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file about which to return index information. , index.name.expr Specifies an alternate key index about which to return information. Related commands Language Command UniBasic SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX For information, see the UniData Commands Reference. initSecureServerSocket function Use the initSecureServerSocket() function to create a secured connection-oriented stream server socket. It does exactly the same as the initServerSocket() function except that the connection will be secure. Once the server socket is opened, any change in the associated security context will not affect the opened socket. Syntax initSecureServerSocket(name_or_IP, port, backlog, svr_socket, context) Parameters The following table describes each parameter of the syntax. Parameter Description name_or_IP DNS name (x.com) or IP address of a server or empty. Empty is equivalent to INADDR_ANY which means the system will choose one for you. Generally, this parameter should be left empty. port Port number. If the port number is specified as a value <= 0, CallHTTP defaults to a port number of 40001. backlog The maximum length of the queue of pending connections (for example, concurrent client-side connections). svr_socket The handle to the server side socket. context The handle to the security context. The following table describes the status of each return code. Return codes Status 0 Success. 1 - 41 See Socket Function Error Return codes. 101 Invalid security context handle. 183 Chapter 1: UniBasic commands and functions initServerSocket Use the initServerSocket function to create a connection-oriented (stream) socket. Associate this socket with an address (name_or_IP) and port number (port), and specify the maximum length the queue of pending connections may grow to. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax initServerSocket(name_or_IP, port, backlog, svr_socket) Parameters The following table describes each parameter of the syntax. Parameter Description name_or_IP DNS name (x.com) or IP address of a server or empty. Empty is equivalent to INADDR_ANY which means the system will choose one for you. Generally, this parameter should be left empty. port Port number. If the port number is specified as a value <= 0, CallHTTP defaults to a port number of 40001. backlog The maximum length of the queue of pending connections (for example, concurrent client-side connections). svr_socket The handle to the server side socket. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. INMAT The UniBasic INMAT function, in the first form, returns the number of elements (rows) in a dimensioned array. The second form returns the current dimension of the dimensioned array array.name. If the dimensioned array has two dimensions, the bounds are separated by value marks. After you open a file, the value of INMAT contains the number of modulos that make up the file. Subsequent file operations using dimensioned array commands also set the value returned by INMAT. Syntax INMAT( ) INMAT(array.name) INMAT function return values INMAT is set by the dimensioned array-oriented commands, as shown in the following table. 184 INMAT Command Meaning DIM 0 – The array was created. 1 – Not enough memory was available to create the array. MATREAD n – The number of attributes loaded into the array. MATREADL 0 – More attributes existed in the record than elements existed in the array. Excess data is stored in the 0,0 element. MATREADU MATPARSE OPEN n – The number of modulos in the file. 0 – The file opened is a directory (DIR type). OSBWRITE n – The number of bytes written to a file or named pipe. WRITE 0 – The WRITE completed successfully 2 – The WRITE completed, but data type enforcement checking failed. If you specify the LOG DTE.OPT, the errors appear in the file_level log. If you specify the IGNORE option, use the SET.DTELOG command to set up your log file 3 – The WRITE completed, but EDA inserted nonconforming data. Examples In the following example, the program segment fills the array MAIN.MAT with values from REC. If a sufficient number of elements are available in the target array, the value of INMAT is set to the number of elements filled. If the number of values exceeds the number of elements in the target array, excess data is lumped in the 0 position, and the value of INMAT is set to 0. MATPARSE MAIN.MAT FROM REC, @VM PRINT INMAT() In the next example, the program segment dimensions two arrays and then prints the dimensions using the PRINT statement and INMAT function: DIM LARGE.ARRAY(23,14) DIM SMALL.ARRAY(9) PRINT INMAT(LARGE.ARRAY) PRINT INMAT(SMALL.ARRAY) This results in the following: 23}14 9 Related commands Language Command UniBasic DIM, MAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATREADU, MATWRITE, MATWRITEU 185 Chapter 1: UniBasic commands and functions INPUT The UniBasic INPUT command requests data from an input queue or from the terminal screen. INPUT supports multibyte languages. If INPUT is successful, UniData sets @SYSTEM.RETURN.CODE to 0. If unsuccessful (the INPUT statement with a FOR or WAITING clause timed out), UniData sets @SYSTEM.RETURN.CODE to -1. One variable is read by each INPUT statement. If you press Enter in response to an INPUT statement, an empty string is assigned to the variable. Tip: Precede INPUT with a PRINT statement to display a prompt. UDT.OPTIONS 83 enables the escape character (usually ASCII code 27) to be accepted by INPUT while screening out or converting other control characters. THEN | ELSE is associated with the WAITING clause except in the case described in the following warning note. Warning: Processing differs when you include INPUT within a single-line IF/THEN/ELSE statement, which is illustrated by the following program segment: RESP = 5 IF RESP = 10 THEN INPUT TEST ELSE PRINT "NO INPUT" END This program produces no output because UniData interprets the ELSE as being a part of the INPUT statement, even though no WAITING clause is included. To avoid this, place the INPUT statement on its own line, as shown in the following example: RESP = 5 IF RESP = 10 THEN INPUT TEST END ELSE PRINT "NO INPUT" END Syntax INPUT var [,length [ _ ]] [:] [{FOR | WAITING} time.expr] [UNFILTERED] [THEN statements | ELSE statements] INPUT var [,-l] [{FOR | WAITING} time.expr] [UNFILTERED] [THEN statements | ELSE statements] Parameters The following table describes each parameter of the syntax. 186 Parameter Description var Specifies a variable to receive the input. In the first form, if data (received by a DATA statement) is present in an input queue, INPUT assigns the next value to the variable var. If a DATA statement was not executed, INPUT prompts the user for input by displaying a question mark on the terminal. ,length Specifies the maximum number of characters accepted. INPUT Parameter Description _ UniData waits for the user to press Enter before processing data input at the keyboard. If the underscore is not included, UniData stops accepting input when the user enters the maximum number of characters. Use the underscore parameter to allow the user to backspace after entering the maximum number of characters. For example, if you specify “INPUT X,5_”, the user can backspace to modify the entry after entering five characters. : Normally, when a user types something and presses Enter in response to an INPUT statement, UniData issues a line feed. The : parameter inhibits this line feed. ,-l UniData checks the type-ahead buffer. The following values are returned in var: 1 – Data is present in the buffer. 0 – No data is present in the type-ahead buffer. Use the -1 parameter to periodically check for input in an application that runs continuously. FOR | WAITING time.expr Specifies the length of time to wait for input. If you do not enter the input before the wait period expires, var does not change, and the ELSE clause executes. If no ELSE nor THEN clause exists, the session terminates at the end of the wait period. UNFILTERED Sets INPUT to capture raw characters (such as backspace, up arrow, down arrow, or ENTER) from the keyboard. THEN statements Specifies statements to execute when input is received within the time specified in the FOR | WAITING clause and input is not an empty string. ELSE statements Specifies statements to execute if no input is received by the time specified in the FOR | WAITING clause or if the input is an empty string. Examples In the following example, the program segment reads the first value established by the DATA statement and assigns it to the variable TEST. In this case, the value 10 is read. DATA 10,20,30,40,50 INPUT TEST In the next example, the program statement prints the prompt “Enter name:”. The INPUT statement then enables the user to enter any number of characters, stopping only when the user presses ENTER. The first 10 characters the user enters are assigned to the variable NAME. PRINT "Enter name: "; INPUT NAME,10_ In the next example, the INPUT statement with the -1 parameter checks the type-ahead buffer. If S.FLAG is 0, the buffer is empty. If it is 1, the buffer contains data. In the latter case, UniData prints the current value of RECS.PROCESSED. INPUT S.FLAG,-1 IF S.FLAG THEN PRINT RECS.PROCESSED In the next example, the user has 30 seconds to input data. Otherwise, the program prints “No input within 30 seconds”. INPUT ANSWER FOR 30 187 Chapter 1: UniBasic commands and functions ELSE PRINT "No input within 30 seconds" Related commands Language Command UniBasic CLEARINPUT, DATA, IN, PROMPT, SYSTEM INPUT @ The UniBasic INPUT @ command places the cursor at a specific location on the terminal screen and prompts the user for input. INPUT @ supports multibyte languages. Tip: The UniBasic @ function also positions the cursor on the terminal screen, but does not accept input as does INPUT @. If INPUT @ is successful, UniData sets @SYSTEM.RETURN.CODE to 0. If unsuccessful (the INPUT @ statement with a FOR or WAITING clause timed out), UniData sets @SYSTEM.RETURN.CODE to -1. Syntax INPUT @(col,row | option) [ , | : ] var [,length] [ _ ] [mask] [{FOR | WAITING} time.expr] [UNFILTERED] [THEN statements | ELSE statements] Parameters The following table describes each parameter of the syntax. Parameter Description col,row Specifies the column and row on the screen at which the cursor is to be placed for input. : Normally, when you type a value and press Enter in response to an INPUT statement, UniData issues a line feed. The : parameter inhibits this line feed. var Specifies a variable to receive the input data. ,length Specifies the maximum number of characters accepted. _ UniData waits for you to press Enter before processing data input at the keyboard. If you do not use the underscore parameter, UniData stops accepting input when you exceed the maximum number of characters. Use the underscore parameter you want the capability of backspacing after entering the maximum number of characters. For example, if you specify “INPUT X,5_”, you can backspace to modify the entry after entering five characters. 188 mask Specifies a format or conversion mask. For format options and instructions about building a conversion mask, see OCONV Masked Decimal (MD). FOR | WAITING time.expr Specifies the amount of time to wait for input. If the input is not entered when this period expires, var does not change, and the ELSE clause executes. If no ELSE nor THEN clause exists, the session terminates at the end of the wait time. INPUT @ Parameter Description UNFILTERED Sets INPUT @ to capture raw characters (such as backspace, up arrow, down arrow, or RETURN) from the keyboard. THEN statements | ELSE statements If the ECL TIMEOUT command has been executed: THEN executes if the input variable contains at least one character. ELSE executes if the input variable contains an empty string. If no ELSE clause is coded, UniData logs you out and displays the ECL prompt. If the ECL TIMEOUT command has not been executed, the program waits indefinitely for input. Examples The following example is taken from the sample program in Developing UniBasic Applications. Notice that the DISPLAY command is combined with the UniBasic @ function to clear the screen and display messages. Then INPUT @ accepts the user’s response (a corrected price). ALTER_RECORD: * Create a new screen, and allow PRICE and ADDRESS to be changed. * Initialize variables and draw the screen NEED.TO.WRITE = 0 DISPLAY @(-1):@(15,5):"Alter ORDER": DISPLAY @(10,8):"(Press RETURN to leave un-changed)" DISPLAY @(8,9):"Old Price":@(42,9):"New Price (Enter 2 decimal places)" * Change the PRICE field (if desired) FOR ENTRY = 1 TO NUM_ENTRIES NEW.PRICE = "" DISPLAY @(10,9+ENTRY):OCONV(ORDER.REC<7,ENTRY>,"MR2$,"): INPUT @(45,9+ENTRY):NEW.PRICE Later in the same sample program, the @ function is again combined with DISPLAY to paint the screen with prompts. After all prompts have been displayed, INPUT @ returns the cursor to the end of the first line, accepting input on that line before moving to the end of the next. In this manner, it accepts input at the end of each line in turn. * Display the current ADDRESS information DISPLAY @(21,12):"Change Address to: ": DISPLAY @(21,13):"Street Line1: ":@(40,13):ADDRESS<2> DISPLAY @(21,14):"Street Line2:" DISPLAY @(40,14):ADDRESS<3>:@(21,15):"City:":@(40,15):CLIENT.REC<6> DISPLAY @(21,16):"State:": DISPLAY @(40,16):CLIENT.REC<7>:@(21,17):"Zip:":@(40,17):CLIENT.REC<8> * Accept INPUT to change values of address INPUT @(40,13):STREET1 IF STREET1 = '' THEN STREET1 = CLIENT.REC<4> INPUT @(40,14):STREET2 IF STREET2 = '' THEN STREET2 = CLIENT.REC<5> INPUT @(40,15):CITY IF CITY = '' THEN CITY = CLIENT.REC<6> INPUT @(40,16):STATE IF STATE = '' THEN STATE = CLIENT.REC<7> INPUT @(40,17):ZIP 189 Chapter 1: UniBasic commands and functions IF ZIP = '' THEN ZIP = CLIENT.REC<8> Related commands Language Command UniBasic CLEARINPUT, DATA, IN, INPUT, INPUTERR, INPUTIF, INPUTNULL, INPUTTRAP, PROMPT, SYSTEM UniData TIMEOUT For information, see the UniData Commands Reference. INPUTCLEAR INPUTCLEAR is a synonym for the CLEARINPUT command. For more information, see CLEARINPUT, on page 67. Synonyms CLEARINPUT INPUTERR The UniBasic INPUTERR command displays an error message at the bottom line of the terminal screen. error.expr can be any valid UniBasic statement, including a literal string enclosed in quotation marks. Tip: Use INPUTERR to prompt for errors when soliciting data with an INPUT statement. The next INPUT command erases previous error messages printed on the bottom line of the screen. The UniBasic program must control the movement of the cursor so it does not enter the bottom line. Note: INPUTERR sends output to the screen regardless of PRINTER on/off status. Syntax INPUTERR error.expr Examples In the following example, the program segment prints an error message at the bottom of the screen if the input does not match the pattern mask: PRINT @(-1) PRINT @(5,5):'Hourly Wage' LOOP PRINT @(16,5) INPUT HOURLY.WAGE UNTIL HOURLY.WAGE MATCHES '1NON.2N' INPUTERR 'Hourly wage must be entered as x.xx' REPEAT PRINT @(5,7):'Accepted.' 190 INPUTIF END Related commands Language Command UniBasic INPUT, INPUT @ INPUTIF The UniBasic INPUTIF command retrieves input from the type-ahead buffer and assigns the input to a variable. Syntax INPUTIF var [THEN statements] [ELSE statements] Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the target variable for input data. THEN statements Executes statements if data is available in the type-ahead buffer. ELSE statements Executes statements if data is not available in the type-ahead buffer. Related commands Language Command UniBasic CLEARINPUT, INPUT, INPUT @, PROMPT, SYSTEM INPUTNULL The UniBasic INPUTNULL command enables you to change the default INPUTNULL character from the default, underscore, to any other single character. When you enter the INPUTNULL character in response to an INPUT or INPUT @ prompt, UniData stores an empty string in place of the character entered. expr specifies the character to serve as the INPUTNULL character for this session. Note: You must enclose expr in quotation marks. Syntax INPUTNULL 'expr' Examples In the following example, the pound sign (#) is set as the new INPUTNULL character: PROMPT "" INPUTNULL "#" PRINT @(-1):@(0,10):"Enter a character: " INPUT @(20,10):inpt 191 Chapter 1: UniBasic commands and functions PRINT "Input is ":inpt PRINT "SEQ = ":SEQ(inpt) PRINT "LEN = ":LEN(inpt) The preceding program segment results in the following output when user input is an underscore character: Enter Input SEQ = LEN = a character: is _ 95 1 _ INPUTTRAP The UniBasic INPUTTRAP command sets a trap for a particular character or characters in a program. INPUTTRAP enables you to specify characters which, if entered at an INPUT or INPUT @ statement, will branch to another statement label. Syntax INPUTTRAP string.expr GOSUB label [:] [,label [:]] INPUTTRAP string.expr GOTO label [:] [,label [:]] Parameters The following table describes each parameter of the syntax. Parameter Description string.expr Specifies the user input upon which to branch to another statement label. To set a trap for both uppercase and lowercase characters, use the following pattern INPUTTRAP ‘Xx’, as in the following: INPUTTRAP ‘Aa’ GOSUB 10,10. GOSUB GOTO These keywords direct program execution to execute or branch to a specified label in the program. GOSUB ensures that program execution returns to the statement below the subroutine call. GOTO is a branch only, and does not return processing to the calling routine. These keywords operate just like the commands of the same names. For more information about the GOTO and GOSUB commands, see their entries in this manual. label Specifies the label to which to branch. Examples In the following example, the program statement performs a GOSUB to label ASUB if the user enters H or to label BSUB if the user enters B: INPUTTRAP 'HB' GOSUB ASUB,BSUB INPUT@ (10,10) VALUE 192 INS Related commands Language Command UniBasic IN, INPUT, INPUT @, INPUTERR INS The UniBasic INS command inserts an expression with the appropriate delimiter before the specified attribute, value, or subvalue mark in a dynamic array. Note: UniData does not insert a delimiter at the end of the array. Syntax INS expr BEFORE dyn.array<attrib.expr[,val.expr [,subval.expr]]> Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to insert. dyn.array<attrib.expr,val.expr,subval.expr> Specifies a dynamic array and attribute, value, and subvalue at which to insert the expression. If any one of these expressions is -1, UniData inserts the expr as the last element in the array position. Examples In the following example, the program segment inserts Zelda, with a new attribute mark, before the second attribute: ARRAY = "H.L. Mencken":@AM:"John":@AM:"Mary" INS "Zelda" BEFORE ARRAY<2> This results in: ARRAY = "H.L. Mencken":@AM:"Zelda":@AM:"John":@AM:"Mary" In the next example, the program segment inserts Stephen at the end of the array because val.expr is -1: ARRAY = "Carmen":@AM:"Sally":@AM:"Billy":@AM:"Mark" INS "Stephen" BEFORE ARRAY<-1> This results in: ARRAY="Carmen":@AM:"Sally":@AM:"Billy":@AM:"Mark":@AM:"Stephen" Related commands Language Command UniBasic FIELDSTORE, INSERT 193 Chapter 1: UniBasic commands and functions INSERT The UniBasic INSERT function inserts an expression (with its delimiter) before or after the specified attribute, value, or subvalue mark in a dynamic array. There is no short form for the INSERT function. However, you can append data by using the short version of the REPLACE function. Syntax INSERT(dyn.array.expr,attrib.expr,[,val.expr[, subval.expr]];insert.expr) INSERT(dyn.array.expr,attrib.expr,[,val.expr[, subval.expr]],insert.expr) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.expr, attrib.expr, val.expr, subval.expr, Specifies a dynamic array and attribute, value, and subvalue of that dynamic array at which to insert the expression. For more information about the type of insertions available, see the following table. insert.expr Specifies the string to insert. Elements in dyn.array.expr,attrib.expr,val.expr, and subval.expr can be any of the following three types. If the element is: then insert expr: a positive number after delimiter, before data. -1 (attrib.expr, val.expr, subval.expr) after the position indicated. 0 (val.expr, subval.expr) at the next higher level. Examples In the following example, the program statement inserts HARRY at the end of the values in attribute 2: STR = INSERT(STR,2,-1,0,'HARRY') In the next example, the program statement inserts HARRY in the first value of attribute 2: STR = INSERT(STR,2,1,0,'HARRY') In the next example, the program statement inserts HARRY in the first subvalue of the first value of attribute 2: STR = INSERT(STR,2,1,1,'HARRY') In the next example, the program segment specifies Alias in the second attribute position: ARRAY = "#111":@AM:"Jones":@AM:"Smith" ARRAY2 = INSERT(ARRAY,2,0,0,"Alias") When you execute this program segment, UniData inserts Alias in the second attribute position: 194 INT ARRAY2 = "#111":@AM:"Alias":@AM:"Jones":@AM:"Smith" Related commands Language Command UniBasic DEL, FIELDSTORE, INS, REMOVE, REPLACE, SUBSTRINGS INT The UniBasic INT function returns the integer value of numeric expression num.expr. Note: This function does not round num.expr, but truncates decimals. Syntax INT(num.expr) Examples In the following example, the program segment prints 1, which is the integer part of the number 1. 734:A = 1.734 PRINT INT(A) ISMB The UniBasic ISMB function returns a code indicating whether the currently installed language is made up of a single-byte or multibyte character set. This function returns 0 to indicate a single-byte character set, or 1 for a multibyte character set. For example, if you execute the ISMB function in a UniData session for which the language is English, the function returns 0. If you execute this function in a UniData session for which the language is Japanese, the function returns 1. Syntax ISMB() Related commands Language Command UniBasic BYTELEN, CHARLEN, DISPLAYWIDTH, LEN, MBLEN ISNV The UniBasic ISNV function tests an expression for the null value. If expr is the null value, this function returns a code of 1. If the expression is not null, or if it contains a null value as well as other characters, this function returns a code of 0. 195 Chapter 1: UniBasic commands and functions Note: The udtconfig parameter NULL_FLAG must be on for a program that contains ISNV to compile. With this flag on, the null value represents an unknown value (represented by @NULL in UniBasic programs), as opposed to an empty string (represented as “”). We recommend that you use @ variables to represent UniData delimiters and the null value because the ASCII value used to represent these characters can vary with language group. Syntax ISNV(expr) Examples The following program example demonstrates testing for the null value in a variable: A=@NULL IF ISNV(A) THEN PRINT "A is the null value." This program results in the following output: A is the null value. The following program uses the function ISNV to determine if a string consists of the null value: PRINT "1.a ISNV(@NULL) = ":ISNV(@NULL) PRINT "2.a NOT(ISNV(@NULL)) = ":NOT(ISNV(@NULL)) A = "abc":@NULL:"def" PRINT "1.b ISNV('abc':@NULL:'def') = ":ISNV(A) PRINT "2.b NOT(ISNV('abc':@NULL:'def')) = ":NOT(ISNV(A)) This program produces the following results. Notice that ISNV executed on a string containing the null value and other characters produces a negative result (0). 1.a 2.a 1.b 2.b ISNV(@NULL) = 1 NOT(ISNV(@NULL)) = 0 ISNV('abc':@NULL:'def') = 0 NOT(ISNV('abc':@NULL:'def')) = 1 Related commands Language Command UniBasic ISNVS ISNVS The UniBasic ISNVS function tests dynamic array elements to see if any of them is the null value. This function is meaningful only when null value handling is on. It returns an array with 0 or 1 in each element. If the array element is the null value, this function returns a code of 1. If the element is not null, or if it contains the null value as well as other characters, this function returns a code of 0. 196 ITYPE Note: The udtconfig parameter NULL_FLAG must be on for a program that contains ISNVS to compile. With this flag on, the null value represents an unknown value (represented BY @NULL in UniBasic programs), as opposed to an empty string (represented as “”). We recommend that you use @ variables to represent UniData delimiters and the null value because the ASCII value used to represent these characters can vary with language group. Syntax ISNVS(dynamic.array) Examples The following program demonstrates the ISNVS function by printing the return values stored in array D: B=@FM:"stereo":@FM:@NULL:@FM:"234":@FM D=ISNVS(B) STG=B GOSUB PRINT.SETUP PRINT "Dynamic array = " PRINT PRT.STG FOR X = 1 TO 4 PRINT "D<":X:"> = ":D<X> NEXT X PRINT.SETUP: PRT.STG = CHANGE(STG, @NULL, "@NULL") PRT.STG = CHANGE(PRT.STG, @FM, "@FM") PRT.STG = CHANGE(PRT.STG, @AM, "@AM") PRT.STG = CHANGE(PRT.STG, @VM, "@VM") RETURN This program results in the following output: Dynamic array = @FMstereo@FM@NULL@FM234@FM D<1> = 0 D<2> = 0 D<3> = 1 D<4> = 0 Related commands Language Command UniBasic ISNV ITYPE The UniBasic ITYPE function enables a UniBasic program to execute a UniData virtual attribute from the dictionary of a UniData file. The value of the function is the same as if it were run using UniQuery or UniData SQL. 197 Chapter 1: UniBasic commands and functions Note: ITYPE generally requires you to open both the dictionary and data portions of the file. Before you use this function, you must compile the dictionary of the file by using the ECL COMPILE.DICT or CD command. In most cases, you also must assign the @ID and @RECORD variables. These variables resolve the value of the ITYPE function. However, if neither the ID of the file nor the data from the record is used in the ITYPE, you do not need to assign these variables. Note: Conversion or formatting codes in the dictionary record of the virtual attribute does not affect the value ITYPE returns. Syntax ITYPE(itype.expr) Examples The following virtual attribute exists in the dictionary file of the demonstration database file ORDERS: YV PRICE*QTY; SUM(SUM(@1)) MD2,$ Grand Total 14R S The following program segment opens both the ORDERS file and the dictionary of the ORDERS file, then reads the compiled virtual attribute into the program variable GRAND_TOTAL. After prompting for an order number and reading the record, the virtual attribute is evaluated with the ITYPE function. In this case, it performs a summation on the value of GRAND_TOTAL in @RECORD. ITYPE does not invoke the conversion and format functions in the dictionary item. OPEN 'ORDERS' TO ORDERS.FILE ELSE STOP OPEN 'DICT','ORDERS' TO DICT.ORDER ELSE STOP READ GRAND_TOTAL FROM DICT.ORDER,'GRAND_TOTAL' ELSE PRINT 'DICTIONARY ITEM GRAND_TOTAL NOT FOUND' STOP END LOOP PRINT 'Enter order number ': INPUT ORDER.ID WHILE ORDER.ID DO @ID = ORDER.ID READ @RECORD FROM ORDERS.FILE,ORDER.ID ELSE PRINT 'ORDER NOT FOUND' @RECORD = '' END IF @RECORD THEN TOT.AMT = ITYPE(GRAND_TOTAL) TOT.AMT = OCONV(TOT.AMT,'MD2,$') PRINT "Total accounts receivable is ":TOT.AMT END REPEAT 198 LE Related commands Language Command UniBasic CALCULATE UniData COMPILE.DICT For information, see the UniData Commands Reference. Virtual attributes For information, see Using UniData. LE The UniBasic LE relational operator tests whether expression expr1 is less than or equal to expr2. expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Relational operators make the comparisons that direct program flow in conditional statements like the following: IF VAR1 LE VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 <= VAR2 Syntax expr1 LE expr2 Synonyms #<, >=, => Examples In the following example, the program segment tests whether A is less than or equal to B. Because A is less than B, the message “Less than or equal to” prints. A = 21 B = 22 IF A LE B THEN PRINT "Less than or equal to" END ELSE PRINT "Greater than" END Related commands Language Command UniBasic LES LEN The UniBasic LEN function returns the length of character expression str.expr. LEN supports multibyte languages. With null value handling on, the null value has a length of one byte. 199 Chapter 1: UniBasic commands and functions Syntax LEN(str.expr) Examples In the following example, the program segment displays 14, the length of the string NAME: NAME = "Arthur Fiedler" PRINT LEN(NAME) The following figure illustrates a string that indicates below each “character” the number of bytes required to store that character. The string contains eight bytes. Therefore, LEN would return 8 for this string. Related commands Language Command UniBasic BYTELEN, CHARLEN, DISPLAYWIDTH, ISMB, LENS, MBLEN LENS The UniBasic LENS function returns the length of the values within each element of a dynamic array. LENS supports multibyte languages. With null value handling on, the null value has a length of one byte. Syntax LENS(dyn.array) Examples In the following example, the program segment creates a new array ARRAY1, which contains the length of each element of ARRAY: ARRAY = '1':@VM:'22':@VM:'333':@VM:'4444':@VM:'55555' ARRAY1 = LENS(ARRAY) ARRAY1 now contains 1}2}3}4}5. Related commands 200 Language Command UniBasic BYTELEN, CHARLEN, DISPLAYWIDTH, ISMB, LEN, MBLEN LES LES The UniBasic LES function compares each value in array1 to its corresponding value in array2. UniData returns an array with 1 in each position where the value in array1 is less than or equal to the value in the corresponding value in array2, and 0 in each position when the value in array1 is greater than that in array2. Syntax LES(array1,array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY2 and returns ARRAY3. ARRAY3 then contains 1}1}1}0}0. ARRAY1 = 9:@VM:10:@VM:30:@VM:50:@VM:60 ARRAY2 = 10:@VM:20:@VM:30@VM:40:@VM:50 ARRAY3 = LES(ARRAY1,ARRAY2) LISTUSER The LISTUSER function returns information about UniData processes currently running in a dynamic array. In the event a UniData user session aborts through a power failure or other abnormal circumstance, UniData registers the aborted process as an active user, and it appears as such in the LISTUSER array. Eventually, the cleanupd daemon will detect these processes and remove the aborted process from the user list. Syntax LISTUSER() LISTUSER Dynamic Array (UNIX) The following table describes the information in the LISTUSER array, by position. Parameter Description UDTNO Sequential number UniData assigns to each user. USRNBR System-level process ID (pid) assigned to a UniData session. UID System-level ID assigned to a user. USRNAME Login name of the user. USRTYPE Type of process the user is running. TTY Device ID. TIME Time the user process started. DATE Date the user process started. Examples The following example displays the output from the LISTUSER function on UNIX: 201 Chapter 1: UniBasic commands and functions 1}5131}0}root}udt}pts/1}10:20:03}Oct 16 2002 LISTUSER Dynamic Array (Windows Platforms) The following table lists the LISTUSER command display attributes. Parameter Description UDTNO Sequential number UniData assigns to each user. USRNBR Process ID of the UniData session. UID Windows ID of the user. USRNAME Login name of the user. USRTYPE Type of process the user is running. TTY Session identifier, formed by concatenating the string “pts/” and the UDTNO. IP-ADDRESS Location where the session is logged in; either “Console” or a valid IP address. TIME The time at which the user process started. DATE The date on which the user process started. LN The UniBasic LN function returns the natural base logarithm of numeric expression num.expr. This function is the inverse of the EXP function. Syntax LN(num.expr) Examples In the following example, the program statement assigns the natural logarithm of 12 to the variable VAL. The result is 2.4849. VAL = LN(12) Related commands Language Command UniBasic EXP loadSecurityContext The loadSecurityContext() function loads a saved security context record into the current session. The name and passPhrase parameters are needed to retrieve and decrypt the saved context. UniData creates an internal data structure and returns its handle in the context parameter. 202 LOCATE Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax loadSecurityContext(context, name, passPhrase) Parameters The following table describes each parameter of the syntax. Parameter Description context The handle to be returned. name String containing the name of the file storing the security contents. PassPhrase String containing the passPhrase needed to decrypt the saved data. The following table describes the status of each return code. Return codes Status 0 Success. 1 Context record does not exist. 2 Context record could not be accessed (e.g. wrong password). 3 Invalid content (file was not saved by the saveSecurityContext() function). 4 Other problems that caused context load failure. Refer to the log file for more information. LOCATE The UniBasic LOCATE command locates an element within a dynamic array. For LOCATE to be successful, the search string, element, must match the entire array element (including any associated lower-level elements). LOCATE does not modify the data in the array. Note: UDT.OPTIONS 85 changes the sort order for an array of mixed negative and positive numbers. With UDT.OPTIONS 85 on, negative and positive numbers are sorted in numeric order regardless of sign. This is effective for the first form of the syntax only. Syntax LOCATEelement INdyn.array<[attribute.expr[,val.expr[,subval.expr]]]>[,var] [BYsearch.type] SETTINGlocation [THENstatementsEND] ELSEstatementsEND For backward compatibility, UniData supports the following alternate syntax: LOCATE(element,dyn.array [,attrib.expr[,val.expr[,subval.expr]]];location [;search.type]) [THEN statements] [END] ELSE statements Parameters The following table describes each parameter of the syntax. 203 Chapter 1: UniBasic commands and functions Parameter Description element Specifies the string to search for. element can be a variable, array element, function, or literal. dyn.array <attrib.expr ,val.expr, subval.expr> Specifies a dynamic array and level (attribute, value, or subvalue) to search. The search operates as follows: The search begins at the lowest level specified. Only the specified level is searched. Returns the position of the located string relative to the beginning of the search. 1 in attrib.expr causes a search starting with the first attribute in the file. 0 in any expression is treated as 1. If the arguments cause the search to begin beyond the end of the dynamic array, the ELSE clause executes. ,var BY search.type See also the LOCATE in BASICTYPEs U, P, and M table. Specifies the attribute, value, or subvalue in the array at which to begin the search. Selects a type of search appropriate for the physical arrangement of a sorted array. AL – Ascending, contents left-justified. AR – Ascending, contents right-justified. DL – Descending, contents left-justified. DR – Descending, contents right-justified. When UniData first retrieves the data, it sorts the data in the requested order. Do not use a BY clause in a LOCATE statement on an unsorted array. The search could terminate before checking all elements. UDT.OPTIONS 85 modifies the sort to place negative numbers first rather than sort them in ASCII order. SETTING location Returns the location of the string. If the search is not successful, execution depends on the presence of the BY clause: If the BY clause is included, the array is assumed to be sorted, and a location is returned indicating where the element should be inserted to maintain the array in sorted order. If the BY clause is not included, the array is assumed to be unsorted, and the location returned is of the last element plus one. THEN statements END ELSE statements END 204 THEN (optional) is executed when the search is successful. Multiple line THEN or ELSE statements require an END keyword. ELSE (required) is executed if the search is unsuccessful. Multiple line THEN or ELSE statements require an END keyword. LOCATE Note: The syntax for BASICTYPEs P and M differs in the number of array elements you can include and the search driven by those elements. Syntax variants for P and M are as follows: LOCATE element IN dyn.array<attribute.expr [,val.expr]> [BY search.type] SETTING location [THEN statements END] ELSE statements END and LOCATE(element,dyn.array [,attrib.expr[,val.expr]];location [;search.type]) [THEN statements] [END] ELSE statements LOCATE in BASICTYPEs U, P, and M The following table compares the searches performed in BASICTYPEs U, P, and M. LOCATE Parameter in BASICTYPE U in BASICTYPEs P and M no expr Performs no search; invalid syntax. Searches all attributes; match must include associated values and subvalues. attrib.expr Searches the attribute specified; match must include associated values and subvalues. Searches values associated with the specified attribute; match must include associated subvalues. val.expr Searches the value specified; match must include associated subvalues. Searches subvalues associated with the specified value. subval.expr Searches subvalues associated with the specified value; begins with the specified subvalue. Performs no search; invalid syntax. Examples The following program segment is taken from the sample program in Developing UniBasic Applications. LOCATE returns the position of the order number to be deleted. DELETE_RECORD: * (Assuming the order #'s are on line 12) READVU ORDER_LINE FROM CLIENT_FILE,CLIENT_NUMBER,12 THEN LOCATE ORDER_NUMBER IN ORDER_LINE<1> SETTING POSITION THEN DEL ORDER_LINE<1,POSITION> END WRITEV ORDER_LINE ON CLIENT_FILE, CLIENT_NUMBER, 12 END In the following example, the program statement searches the entire array, FILMS, element by element, for the literal string “BATMAN.” If the search is successful, UniData assigns the location of the element to the variable NDX. If UniData does not find the string, it sets NDX to the location of the last value plus 1, and it executes the STOP command. The LOCATE command performs the search on the attribute level. LOCATE "BATMAN" IN FILMS<1> SETTING NDX ELSE STOP Because the LOCATE statement compares the entire element (including associated lower-level elements), a match will not be successful on either of the following arrays: "CARMEN":@AM:"BATMANII":@AM:"JAWS" or "CARMEN":@AM:"BATMAN":@VM:"KEATON":@VM:"DEVITO"@VM:"CARREY":@AM:"JAWS" 205 Chapter 1: UniBasic commands and functions In the next example, the program segment prints “BATMAN IS IN POSITION 2 IN THE ARRAY”: FILMS = "CARMEN":@AM:"BATMAN":@AM:"JAWS" LOCATE "BATMAN" IN FILMS<1> SETTING NDX ELSE PRINT "NOT FOUND" STOP END PRINT "BATMAN IS IN POSITION ":NDX:" IN THE ARRAY" In the next example, the program segment searches the array FILMS, starting at attribute 2, value 2, for the contents of the variable DEVITO. UniData assumes the array elements are in ascending order and left-justified. LOCATE DEVITO IN FILMS<2,2> BY "AL" SETTING NDX THEN PRINT "THIS TITLE IS IN THE LIBRARY" END ELSE PRINT "TITLE NOT FOUND, TRY AGAIN." END When executed on the following array, DEVITO is located in position 3 in the array at the value level, and UniData executes the first PRINT statement: "CARMEN":@AM:"BATMAN":@VM:"KEATON":@VM:"DEVITO"@VM:"CARREY ":@AM:"JAWS" However, in the following array, the LOCATE command does not find DEVITO, and UniData executes the second PRINT statement: "CARMEN":@AM:"BATMAN":@VM:"KEATON"@VM:"CARREY":@AM:"BATMANIII": @VM:"KILMER":@VM:"DEVITO"@AM:"JAWS" Related commands Language Command UniBasic FIND, FINDSTR LOCK The UniBasic LOCK command reserves a computer resource (such as a device or file) for the current user process. The lock is associated with resource.num, not the resource itself. Therefore, a command that does not check for locks against the resource number will access the resource even if it is locked. For example, an installation might assign locks 1 through 4 to four system printers. When an application needs to reserve printer 1, the application executes LOCK 1. For lock effectiveness, all other applications must check for locks before accessing the resource. Resources are not automatically unlocked by the termination of the locking program. The UniBasic UNLOCK or ECL QUIT commands must release them. Otherwise, you can release resources by executing the ECL CLEAR.LOCKS command at UniData level. For more information about UniData locks, see Developing UniBasic Applications. Syntax LOCKresource.num{THEN statements[END] |ELSE statements [END]} 206 LOOP/REPEAT Parameters The following table describes each parameter of the syntax. Parameter Description resource.num Specifies a number associated with a resource. resource.num can be any number from 0 through 63. For assistance in assigning resource numbers, see your system administrator. THEN statements END Specifies statements to execute if the LOCK statement executes successfully. ELSE statements END Specifies statements to execute if another user has reserved the resource (using the same resource number) so that the LOCK statement fails to lock it. If you do not specify an ELSE clause and the requested resource has already been locked, the current program waits until that resource is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to release the lock. Examples In the following example, the program statement reserves resource 12 if another program is not using it. If resource 12 is already in use, the current program suspends execution and waits until UniData unlocks resource 12. LOCK 12 In the next example, the program segment locks resource 44 if it is available. If it has already been locked, the program attempts to lock resource 45. If both resources are unavailable, the program stops. T1 = 44; T2 = 45 LOCK T1 ELSE LOCK T2 ELSE STOP Related commands Language Command UniBasic UNLOCK UniData CLEAR.LOCKS, LIST.LOCKS, SUPERCLEAR.LOCKS, DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. LOOP/REPEAT The UniBasic LOOP/REPEAT command repeats any contained statements while or until a specified condition is met, depending on whether you use the WHILE or UNTIL clause. statements can precede and/or follow the test condition. If space permits, you can write the structure on one line. Otherwise, you can extend the structure on as many lines as necessary. REPEAT is required and finishes the LOOP operation. 207 Chapter 1: UniBasic commands and functions UniData executes the first set of statements on the first entry into the loop, and then evaluates the WHILE or UNTIL clause. If expr is true (using the WHILE keyword) or false (using the UNTIL keyword), UniData executes the second set of statements. If you have statements after a WHILE or UNTIL clause, the DO clause is required. Otherwise, it is optional. When the program execution reaches REPEAT, it returns to the first set of statements. Tip: We recommend that you construct loops that terminate based on the WHILE or UNTIL condition. The LOOP statement is flexible enough to incorporate almost any logical progression. Use the CONTINUE keyword to transfer control to the beginning of the next loop. Syntax LOOP [statements] [UNTIL expr [DO] statements] [WHILE expr [DO] statements] REPEAT LOOP {WHILE | UNTIL} expr DO statements REPEAT LOOP statements {WHILE | UNTIL} expr DO REPEAT Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to check to for the UNTIL or WHILE clause. statements expr can be any valid statement that includes a READNEXT statement or LOCATE statement. Specifies statements to execute each time the loop statement repeats. WHILE statements Specifies statements to execute if the expression in the WHILE clause is true. UNTIL statements Specifies statements to execute if the expression in the UNTIL clause is false. Examples The following example is taken from the sample program in in Developing UniBasic Applications. This subroutine loops until the user enters a valid order number, or Q (the prompt for order number is already displayed on the screen). GET_ORDER_NUMBER: * Have the user enter a valid key to a record in the ORDERS file. LOOP DISPLAY @(15,6): INPUT ORDER_NUMBER ORDER_NUMBER = OCONV(ORDER_NUMBER,"MCU") IF NUM(ORDER_NUMBER) OR ORDER_NUMBER[1,1] = "Q" THEN VALID_ORDER_NUMBER = 1 208 LOWER END ELSE VALID_ORDER_NUMBER = 0 MESSAGE = "Order # must be a Number, or the letter 'Q'" CALL DISPLAY_MESSAGE(MESSAGE) END UNTIL VALID_ORDER_NUMBER REPEAT In the next example, the program segment prints and increments POS until it reaches the value of 10: POS=0 LOOP WHILE POS < 10 DO PRINT POS POS +=1 REPEAT In the next example, the program segment prints “Counting” and then increments C. It then evaluates C to see if it is less than eight, and if so, executes the second statement. On the eighth iteration, the program executes the top statement and the loop stops because the condition (C > 8) is met. The program continues execution at the statement following REPEAT. The program does not execute the second statement on the final iteration. C = 0 PRINT "Counting:" LOOP C = C+1 UNTIL C > 8 DO PRINT "C = ":C REPEAT The result of this program: Counting: C = 1 C = 2 C = 3 C = 4 C = 5 C = 6 C = 7 C = 8 Related commands Language Command UniBasic CASE, CONTINUE, FOR/NEXT LOWER The UniBasic LOWER function converts all attribute marks to value marks, and, in a dynamic array, it converts all value marks to subvalue marks. Syntax LOWER(dyn.array.expr) 209 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment lowers the dynamic array D.STR: D.STR = "A":@AM:"B":@AM:"C":@VM:"D" D.STR = LOWER(D.STR) The dynamic array D.STR now contains the string: D.STR = "A":@VM:"B":@VM:"C":@SM:"D" Related commands Language Command UniBasic RAISE LT The UniBasic LT relational operator tests whether expression expr1 is less than expr2. expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Relational operators make the comparisons that direct program flow in conditional statements such as the following: IF VAR1 LT VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 < VAR2 Syntax expr1 LT expr2 Synonyms < Examples In the following example, the program segment tests whether A is less than B. Because A is less than B, the message “Less than” prints. A = 21 B = 22 IF A LT B THEN PRINT "Less than" END ELSE PRINT "Greater than" END Related commands 210 Language Command UniBasic LTS LTS LTS The UniBasic LTS function compares each element in array1 to its corresponding value in array2. UniData returns an array with 1 in each position where the value in array1 is less than the value in the corresponding position in array2, and 0 in each position for values in array1 that are greater than those in array2. Syntax LTS(array1,array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY2 and returns ARRAY3. ARRAY3 then contains 1}1}0}0}0. ARRAY1 = 9:@VM:10:@VM:30:@VM:50:@VM:60 ARRAY2 = 10:@VM:20:@VM:30@VM:40:@VM:50 ARRAY3 = LTS(ARRAY1,ARRAY2) MAT The first form of the UniBasic MAT command assigns new values to all elements of a dimensioned array based on an expression. The second form assigns the contents of a dimensioned array to another dimensioned array. If you assign a dimensioned array the values of a second dimensioned array, the assignment proceeds from element to element in consecutive order. The program assigns the first element of the first array to the first element of the second array, then assigns the second element to the second element of the second array, and so on. The two arrays do not have to match in configuration of dimensions, but must contain the same number of elements. UniData does not alter the second dimensioned array in the assignment process. Use the DIM command to dimension all arrays before you assign new values to the elements. You can place MAT in any looping structure and assign the elements with a variable or function. Syntax MAT dim.array = expr MAT dim.array = MAT dim.array2 Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies a dimensioned array to receive new values. expr Specifies the value to assign to the array elements. expr can be any UniBasic expression. expr can be an empty string, a formula, a single value, a literal string, or a function. dim.array2 Specifies a dimensioned array from which to assign values. 211 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment assigns 1.5 to all elements of the array FEES: DIM FEES(100,100) MAT FEES = 1.5 In the next example, the program segment assigns the values in dimensioned array FEE2 to the dimensioned array FEE1. Note the differing dimensions but the same number of elements in the two matrices. DIM FEE1(2,4),FEE2(4,2) MAT FEE1 = MAT FEE2 If the arrays contain the following values before the assignment: the values assigned to FEE1 would be: Notice how the elements are assigned: from left to right, top to bottom, element by element. UniData maintains all values in dimensioned array FEE2. The positions are shifted to fit the dimensions of dimensioned array FEE1. Related commands Language Command UniBasic DIM, INMAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATREADU, MATWRITE, MATWRITEU MATBUILD The UniBasic MATBUILD command generates a dynamic array from a dimensioned array based on specified starting and ending positions and the delimiter given. The dimensioned array can be multidimensional. The statement retrieves elements from the multidimensional array according to the order in which its elements are stored. 212 MATBUILD Syntax MATBUILD dyn.array FROM dim.array [,start.num [,end.num [USING delim]]] Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array Specifies the dynamic array to be created. FROM dim.array Specifies the dimensioned array from which to build the dynamic array. ,start.num Specifies the starting position in the dimensioned array. If start.num is less than or equal to 0, UniData defaults to 1. The dynamic array is not generated if start.num is greater than end.num. ,end.num Specifies the ending position in the dimensioned array. If end.num is less than or equal to 0, or if it is beyond the end of the dimensioned array, UniData retrieves data to the end of the dimensioned array. The USING clause specifies the delimiter delim in the dyn.array generation. If you do not specify delim, or if you specify an empty string, delim defaults to @AM (attribute mark). If you specify more than one character, only the first character is used. UniData inserts delim between the elements if dyn.array. USING delim Examples In the following example, A is a dimensioned array with five elements: A(1)=11, A(2)=22, A(3)=33, A(4)=44, and A(5)=55 The following program statement: MATBUILD NEW.ARRAY FROM A ,2,4 generates the following dynamic array: NEW.ARRAY = "22":@AM:"33":@AM:"44" The next program statement: MATBUILD ARRAY FROM A ,1 USING ',' generates the following dynamic array: ARRAY = "11,22,33,44,55" Related commands Language Command UniBasic DIM, INMAT, MAT, MATPARSE, MATREAD, MATREADL, MATREADU, MATWRITE, MATWRITEU 213 Chapter 1: UniBasic commands and functions MATCH The UniBasic MATCH or MATCHES function determines if a variable matches a specific pattern of characters, numbers, or a literal string. If var matches the pattern, MATCH or MATCHES returns 1. If var does not match the pattern, MATCH or MATCHES returns 0. Tip: You can mix codes and literal strings. To differentiate between the two, enclose the literal in single quotation marks within the larger pattern, which is enclosed in double quotation marks. Syntax var MATCH "[~] len [X, A, N] [text]" Synonyms MATCHES Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the variable to compare with the MATCH expression. ~ Reverses the pattern. To match 4N, a string must contain four numeric characters. To match ~4N, a string must contain four characters that are not all numeric. len Specifies the number of characters to match. X Specifies that characters can be of any type. A Specifies that only alphabetic characters match the pattern. N Specifies that only numbers match the pattern. text Specifies a literal string to search for. Enclose this literal text within single quotation marks if combined with a pattern (made up of X, A, and N). Examples In the following example, the program segment determines if the variable SSN is a valid social security number: SSN = "522-13-5124" SSNTEST = SSN MATCH "3N'-'2N'-'4N" The following program accepts as input a pattern to match and a string to search: PRINT "This program tests the MATCH function" PRINT "Enter pattern ": INPUT pattern PRINT "Enter string to match": INPUT string1 answer = string1 MATCH pattern PRINT \"\ : answer : \"\ 214 MATCHFIELD In the following test executions of the preceding program, the user tests for a string that consists of three alphabetic characters followed by the literal “3A”. The literal (3A) is enclosed in quotation marks to differentiate it from the pattern 3A. :RUN BP match.test This program tests the MATCH function Enter pattern ?3A'3A' Enter string to match?AAA3A "1" :RUN BP match.test This program tests the MATCH function Enter pattern ?3A'3A' Enter string to match?3AAAA "0" MATCHFIELD The UniBasic MATCHFIELD function returns a substring that matches a pattern or literal. If no match is made, UniData returns an empty string. MATCHFIELD supports multibyte languages. Syntax MATCHFIELD(str.expr,"[~] {len [X | ,A | ,N]} [text]", field.expr) You can mix the codes and a text string to search for specific patterns separated by characters. With null value handling on, if a function encounters the null value in a parameter when a number is expected (field.expr),a warning message displays and UniBasic uses 0. Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies the variable to compare with the MATCH expression. ~ Inverses the pattern. To match 4N, a string must contain four numeric characters. To match ~4N, a string must contain four characters that are not numeric. len Specifies the number of characters to match. X Specifies that characters can be of any data type. A Specifies that only alphabetic characters match the pattern. N Specifies that only numbers match the pattern. text Specifies a literal string to search for. field.expr Specifies a portion of the str.expr to return. Each code segment is considered to be a field for the purposes of field.expr. Examples In the following example, the program segment returns the value 56 because the entire string matches the specified criteria, and the third field contains the number 56: SSN = "534-56-5565" MID = MATCHFIELD(SSN,"3N'-'2N'-'4N",3) 215 Chapter 1: UniBasic commands and functions In the next example, the program segment searches the string and returns the second and fourth fields and prints “99922”: STRING = "ALL999WERE22ABSENT" NUM1 = MATCHFIELD(STRING,'3A3N4A2N6A',2) NUM2 = MATCHFIELD(STRING,'3A3N4A2N6A',4) PRINT NUM1:NUM2 MATPARSE The UniBasic MATPARSE command distributes elements of a delimited string or dynamic array to consecutive elements of a dimensioned array. Delimiters can be the standard UniData delimiters or any other ASCII character. Syntax MATPARSE dim.array FROM str.expr, delim.expr When you specify an alternate delimiter, UniData returns a two-dimensional array. The delimited string is placed in the first dimensioned array element, and the delimiter is placed in the second element. When UniData encounters two delimiters in a row, both are placed in the first element. Note: BASICTYPEs P and R do not support the 0,0 element in dimensioned arrays. If more elements are delimited in the string than can be placed in the dimensioned array, a runtime error results and data is lost. Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies the target dimensioned array. str.expr Specifies a delimited string to place in the dimensioned array. delim.expr Specifies the delimiter to use for parsing str.expr. You can use any ASCII character including commas or spaces. INMAT function return values After you execute MATPARSE, the INMAT function returns one of the values described in the following table. Value Description n The number of elements loaded into the array. 0 The array was too small to contain all elements in the string. All excess data (including delimiters) is placed in the 0,0 element. Examples In the following example, the program segment fills the dimensioned array ALPHA with consecutive characters from a literal string. An empty string is the delimiter, causing one character to be assigned to each dimensioned array cell. In this case, the value returned by the INMAT function would be 7. DIM ALPHA(7) 216 MATREAD MATPARSE ALPHA FROM "ABCDEFG","" The preceding program segment produces the following dimensioned array: ALPHA(1) = "A" ... ALPHA(7) = "G" In the next example, the program segment dimensions the dimensioned array T and then fills it with data from a dynamic array. The delimiter specified is the attribute mark, so each attribute is assigned to consecutive elements of the array. Note that the string “ITEM” has five elements, but the array is dimensioned with four elements. After the MATPARSE command, the INMAT function is 0 and the value of the zero element T(0) is 443. DIM T(4) ITEM = "123:@AM:33:@AM:199:@AM:821:@AM:443" MATPARSE T FROM ITEM, CHAR(254) The preceding program segment produces the following dimensioned array: T(0) T(1) T(2) T(3) T(4) = = = = = 443 123 33 199 821 Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATREAD, MATREADL, MATREADU, MATWRITE, MATWRITEU MATREAD The UniBasic MATREAD command assigns the values found in successive attributes of a record to corresponding elements of a dimensioned array — regardless of lock status. You must use the DIM command to create a dimensioned array before you execute MATREAD. Note: This command does not check for locks. If you are operating in a multiuser environment, you must use record locks to prevent users from overlaying data updated by others. For more information about the UniBasic record locking, see Developing UniBasic Applications. Syntax MATREAD dim.array [FROM [file.var,]record.ID.expr [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies the dimensioned array into which the values are read. 217 Chapter 1: UniBasic commands and functions Parameter Description FROM file.var, Specifies the file from which to read. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. A default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies the record from which to read. ON ERROR statements Specifies statements to execute if the MATREAD statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. INMAT function return values After you execute MATREAD, the INMAT function returns one of the values described in the following table. Value Meaning n The number of attributes loaded into the array. 0 The array was too small to contain all attributes in the record. The excess data (including delimiters) is placed in the 0,0 element. Note: BASICTYPEs P and R do not support the 0,0 element. If more attributes are read from the file than can be placed in the dimensioned array, a runtime error results and data is lost. Examples In the following example, the program segment reads the record with ID NAMES from the CUSTFILE, and assigns the elements to the dimensioned array TEST. If the program does not find the record, it assigns the value 0 to the variable FOUND. DIM TEST(10,10) MATREAD TEST FROM CUSTFILE,"NAMES" ELSE FOUND = 0 In the next example, the program segment reads the record with ID NAMES and assigns the data from the record to the dimensioned array TEST: OPEN "CUSTFILE" TO CF ELSE STOP "NO CUSTFILE" MATREAD TEST FROM CF,"NAMES" ELSE FOUND = 0 In the next example, the MATREAD statement includes multiline THEN and ELSE clauses: FILE.ERR = 0 DIM CUST.ITEM(22) MATREAD CUST.ITEM FROM CUST.FILE,CUST.ID THEN GOSUB PROCESS.CUSTOMER: END ELSE MAT CUST.ITEM = " 218 MATREADL FILE.ERR = 1 END Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATPARSE, MATREADL, MATREADU, MATWRITE, MATWRITEU MATREADL The UniBasic MATREADL command assigns the values found in successive attributes of a record to corresponding elements of a dimensioned array. MATREADL checks for locks and will not read a record locked with an exclusive (U) lock. If the record is available, MATREADL reads and sets a shared (L) lock on it. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax MATREADL dim.array FROM [file.var,]record.ID.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} MATREADL dim.array FROM [file.var,]record.ID.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies the dimensioned array into which the values are read. FROM file.var, Specifies the file from which to read. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. A default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies the record from which to read the attributes. ON ERROR statements Specifies statements to execute if the MATREADL statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until UniData releases the lock on the record. You can place the LOCKED clause after the FROM clause. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. 219 Chapter 1: UniBasic commands and functions Parameter Description THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END INMAT function return values After you execute MATREADL, the INMAT function returns one of the values described in the following table. Value Description n The number of attributes loaded into the array. 0 The array was too small to contain all attributes in the record. The excess data (including delimiters) is placed in the zero element. Note: BASICTYPEs P and R do not support the 0,0 element. If UniData reads more attributes from the file than it can place in the dimensioned array, a runtime error results and data is lost. Examples In the following example, the program segment reads a tape record with the ID specified in TAPE.ID from the TAPES.FILE. If the program finds the record, it transfers control to the subroutine TAPE.PROCESS. Otherwise, the program displays a message and aborts. If the record is locked with an exclusive lock, the program does not execute the subroutine. Instead, it displays the message “RECORD LOCKED” and waits for the lock to be released. MATREADL TAPE.REC FROM TAPES.FILE,TAPE.ID THEN GOSUB TAPE.PROCESS: PRINT "TAPE PROCESSED:":TAPE.ID END LOCKED PRINT "RECORD LOCKED" ELSE PRINT "RECORD NOT FOUND:":TAPE.ID; ABORT Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATPARSE, MATREAD, MATREADU, MATWRITE, MATWRITEU UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. MATREADU The UniBasic MATREADU command assigns the values found in successive attributes of a record to corresponding elements of a dimensioned array. MATREADU checks for locks and will not read a locked record. If the record is available, MATREADU reads and sets an exclusive (U) lock on it. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. 220 MATREADU BASICTYPEs P and R do not support the 0,0 element. If UniData reads more attributes from the file than it can place in the dimensioned array, a runtime error results and data is lost. Syntax MATREADU dim.array FROM [file.var,] record.ID.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} MATREADU dim.array FROM [file.var,] record.ID.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies the dimensioned array into which the values are read. FROM file.var, Specifies the file from which to read. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. A default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies the record from which to read the attributes. ON ERROR statements Specifies statements to execute if the MATREADL statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until UniData releases the lock on the record. You can place the LOCKED clause after the FROM clause. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. INMAT function return values After you execute MATREADU, the INMAT function returns one of the values described in the following table. Value Description n The number of attributes loaded into the array. 0 The array was too small to contain all attributes in the record. All excess data (including delimiters) is placed in the zero element. 221 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment reads the record with ID “NAMES” from the CUST file. Because no LOCKED clause is provided, the program waits for access if the record is locked by another user. DIM TEST(10,10) MATREADU TEST FROM CUST,"NAMES" ELSE GOSUB 105 In the next example, the program segment reads the record with the ID CUST.ID and assigns each attribute to successive elements in the dimensioned array CUST.REC. If the record is found, UniData executes the THEN clause. If the record is locked, UniData displays RECORD LOCKED and waits for the lock to be released. If the record is not found, UniData displays RECORD NOT FOUND FOR CUSTOMER and the customer ID. MATREADU CUST.REC FROM CUSTFILE,CUST.ID THEN PRINT "PROCESSING CUSTOMER: ":CUST.ID GOSUB PROCESS.CUSTOMER: END LOCKED PRINT 'RECORD LOCKED ' END ELSE PRINT 'RECORD NOT FOUND FOR CUSTOMER ':CUST.ID END Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATWRITE, MATWRITEU UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. MATWRITE The UniBasic MATWRITE command writes successive elements of a dimensioned array to the corresponding attributes of a record. If the dimensioned array size exceeds the number of attributes in the target record, the MATWRITE command does not write the trailing spaces. If the 0 element is not empty, the command writes the contents of the element after the final element in the record (as element N+1). Note: This command must be preceded by MATREADU or another locking command to prevent the type of inconsistency that results when multiple users access files at the same time. For more information, see Developing UniBasic Applications. Syntax MATWRITE dim.array {ON | TO file.var,} record.ID.expr [ON ERROR statements] Parameters The following table describes each parameter of the syntax. 222 MATWRITE Parameter Description dim.array Specifies the dimensioned array from which to assign the values read to the successive attributes of the record record.ID.expr. You must name and dimension an array before you can use it in the MATWRITE statement. Specifies the file on which to write the record. You must specify an ON or TO clause. ON | TO file.var, Specifies the record on which to write the attributes. record.ID.expr ON ERROR statements Specifies statements to execute if MATWRITE fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. STATUS function return values After you execute MATWRITE, the STATUS function returns one of the values described in the following table. Value Description 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). Non-RFS files – WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. 10 RFS files – WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. Examples In the following example, the program segment writes the dimensioned array RECEIPTS to the file REC87 as a record with ID “RENTALS”: COMMON RECEIPTS(12) MATWRITE RECEIPTS ON REC87,"RENTALS" Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATWRITE, MATWRITEU 223 Chapter 1: UniBasic commands and functions MATWRITEU The UniBasic MATWRITEU command writes successive elements of a dimensioned array to the corresponding attributes of a specified record. MATWRITEU does not release locks set by READU, READVU, or MATREADU statements. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax MATWRITEU dim.array {ON | TO} [file.var,] record.ID.expr [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description dim.array Specifies the dimensioned array from which to assign the values read to the successive attributes of the record record.ID.expr. ON | TO file.var, record.ID.exp ON ERROR statements You must name and dimension an array before you can use it in the MATWRITE statement. Specifies the target file. You must specify an ON or TO clause. Specifies the target record. Specifies statements to execute if MATWRITEU fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. STATUS function return values After you execute MATWRITEU, the STATUS function returns one of the values described in the following table. Value Description 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 224 Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). MAXIMUM Value Description 10 Non-RFS files – WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files – WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. Examples In the following example, the program statement writes the dimensioned array NEW.CLIENTS to the file CLIENTS as a record with an ID of ‘050887’. If the record is locked, UniData maintains the lock. MATWRITEU NEW.CLIENTS TO CLIENTS,'050887' Related commands Language Command UniBasic DIM, INMAT, MAT, MATBUILD, MATPARSE, MATREAD, MATREADL, MATREADU, MATWRITEU MAXIMUM The UniBasic MAXIMUMfunction returns the largest numeric value found in a dynamic array. This function ignores nonnumeric elements. If the array you specify contains only nonnumeric elements, MAXIMUM returns an empty string. If an element is empty, UniData treats it as 0. UniData treats all system marks (attribute, value, and subvalue marks) indiscriminately. That is, any value between two marks of any kind is taken as an element with respect to this function. Syntax MAXIMUM(dyn.array.var) Examples In the following example, the program segment prints 22: X = "12":@VM:"2":@FM:"dd":@FM:"9":@FM:"22" PRINT MAXIMUM(X) In the next example, the program segment prints 0 because W contains an empty element and no other numeric elements exist: W = "A":@FM:"B":@VM:"":@SM:"C" PRINT MAXIMUM(W) Related commands Language Command UniBasic MINIMUM 225 Chapter 1: UniBasic commands and functions MBLEN The UniBasic MBLEN function returns the number of bytes in the first character of a string. Syntax MBLEN (str.expr) Examples The following figure illustrations a string that indicates below each “character” the number of bytes required to display that character. MBLEN returns 2 for this string, which indicates that the first character is made up of two bytes. Related commands Language Command UniBasic CHARLEN, DISPLAYWIDTH, ISMB, LEN MDPERFORM The UniBasic MDPERFORM command executes various UniData commands, sentences, or paragraphs within a UniBasic program while transferring lists to and from the executed commands. You can nest MDPERFORM. For example, in program A an MDPERFORM statement, which has a “CAPTURING var1” clause, invokes program B. Program B contains a second MDPERFORM statement that also has a “CAPTURING var2” clause. The output of programs A and B is sent to var1 and var2 respectively. You can nest only two MDPERFORM statements. To increase the number of nested levels: ▪ For the entire system – Enter a higher number for the udtconfig file variable MAX_CAPT_LEVEL. ▪ For this process only – Enter a higher number for the environment variable MAX_CAPT_LEVEL. Note: MDPERFORM does not pass select lists unless you explicitly specify them. In this way, you maintain full control and protection over them. STACKCOMMON The ECL STACKCOMMON command makes use of common areas more flexible, although it requires additional memory. STACKCOMMON settings have the following effects: 226 MDPERFORM ▪ If STACKCOMMON is off when one program executes another, the unnamed common is passed to the executed program and back to the executing program. ▪ If STACKCOMMON is on when one program executes another program, unnamed common is not passed to the program you execute. Instead, unnamed common is saved, and the unnamed common of the called program is initialized to 0. When control is passed back to the calling program, unnamed common is restored to its value before the program call. Unnamed common is never passed to a phantom program. Note: STACKCOMMON is always on in BASICTYPEs P and M. The default setting for STACKCOMMON is off in BASICTYPEs R and U. Syntax MDPERFORM str.expr [CAPTURING, dyn.array.var] [RETURNING, dyn.array.var] [RTNLIST int.expr] [PASSLIST int.expr] [PASSCOM] MDPERFORM str.expr [RETURNING, dyn.array.var] [CAPTURING, dyn.array.var] [RTNLIST int.expr] [PASSLIST int.expr] [PASSCOM] Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a UniData command with appropriate parameters. If you pass a file name to MDPERFORM, you must use the actual file name, not a file variable (which is assigned in the OPEN statement). CAPTURING, dyn.array.var The CAPTURING clause stores the output in a dynamic array instead of on the display terminal. Each line of the text becomes an attribute in the array. Output sent to the printer is not affected by this clause. RETURNING, dyn.array.var The RETURNING clause captures error messages resulting from the command executed with MDPERFORM. This variable contains a string of error message numbers separated by spaces. If the executed command creates a spooler hold file, UniData also returns the hold file number in the same variable. RTNLIST int.expr The RTNLIST clause must evaluate to an integer 0–9, designating the list to return to the calling program. You can use the resulting list with subsequent READNEXT statements or in the PASSLIST clause of a MDPERFORM statement. If you do not include an expression after RTNLIST, the generated list replaces the contents of list 0. If you do not specify RTNLIST, the MDPERFORM command does not return a list. PASSLIST int.expr The PASSLIST clause must evaluate to an integer 0, 1, or 2, designating the select list to be sent to the called program. If you do not specify int.expr, UniData assumes list 0. PASSCOM The passed list can be the result of previous SELECT or GETLIST commands, or the RTNLIST clause of an MDPERFORM statement. This parameter is provided for backward compatibility for releases before 3.1. 227 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment lists all the items in the VOC file and returns the result in select list 2: list_var = 2 MDPERFORM "list dict VOC all" RTNLIST list_var In the next example, the program segment performs a selection on the CUSTOMER file, passes the result back in select list 1, and then sorts the result: list_var = 1 cmd1 = "select CUSTOMER with @ID = '200'" cmd2 = "sort CUSTOMER by DATE_OUT" MDPERFORM cmd1 RTNLIST list_var MDPERFORM cmd2 PASSLIST list_var In the next example, the program segment builds different commands based on conditions generated by MDPERFORM. According to the value of input_var, one of three UniQuery commands is executed. list_var = 1 frg1 = "select CUSTOMER with " frg2 = " NAME like '...Jones...' frg3 = " DATE_DUE > '04/22/87' " frg4 = " AMT_DUE < 30" frg5 = " by NAME" BEGIN CASE CASE input_var = 1 MDPERFORM frg1:frg2:frg5 RTNLIST CASE input_var = 2 MDPERFORM frg1:frg3:frg5 RTNLIST CASE input_var = 3 MDPERFORM frg1:frg4:frg5 RTNLIST END CASE " list_var list_var list_var In the next example, the program segment performs the command stored in cmd3, passing the list specified by list_var, and sends output to a dynamic array cpt_var: MDPERFORM cmd3 PASSLIST list_var CAPTURING cpt_var Related commands Language Command UniBasic COMMON, EXECUTE, EXECUTESQL, PCPERFORM, UDTEXECUTE UniData STACKCOMMON For information, see the UniData Commands Reference. MINIMUM The UniBasic MINIMUM function returns the smallest numeric element found in a dynamic array. UniData ignores nonnumeric elements with this function. If dyn.array.var contains only nonnumeric elements, the function returns an empty string. If an array element is empty, it is treated as 0. All system marks (attribute, value, and subvalue marks) are treated indiscriminately. That is, any value between two marks is taken as an element. 228 MOD Syntax MINIMUM(dyn.array.var) Examples In the following example, the program segment prints 2: X = "12":@VM:"2":@AM:"dd":@AM:"9":@AM:"22" PRINT MINIMUM(X) In the next example, the program segment assigns U an empty string because V contains only nonnumeric elements: V = "":@AM:"assignment":@AM:"test" U = MINIMUM(V) Related commands Language Command UniBasic MAXIMUM MOD The UniBasic MOD and REM functions return the remainder of the division of num.expr2 into num.expr1. These functions divide integers and decimals. The sign of the result is the same as that of num.expr1. The formula used by MOD and REM is: REM(x,y) = x - (INT(x/y) * y) where x and y are numeric expressions. The first expression, x, is divided by y, and INT truncates the result. UniData multiplies the resulting integer by y, and subtracts the result from the value of x. Note: The value of num.expr2 cannot be 0. Syntax MOD(num.expr1, num.expr2) Synonyms REM Examples In the following example, the program segment assigns to Z the remainder of the division of Y into X. In this case, the remainder is 2. X = 12 ; Y = 5 Z = MOD(X,Y) 229 Chapter 1: UniBasic commands and functions NE The UniBasic NE relational operator tests whether expression expr1 is not equal to expr2.expr1 and expr2 can be any valid UniBasic expressions, variables, strings, or literals. Tip: You can also use the # symbol to negate other relational operators. For example, the following statement uses the # symbol to negate the > symbol. In this case, if X is not greater than Y, the program branches to label 1000. IF X #> Y THEN GOSUB 1000 Syntax expr1 NE expr2 Synonyms #, <>, >< Examples The following program segment is taken from the sample program in Developing UniBasic Applications. In the first statement, if the variable NEW.PRICE is not equal to an empty string, the variable is written to the seventh element in array ORDER.REC. IF NEW.PRICE NE '' AND NUM(NEW.PRICE) THEN ORDER.REC<7,ENTRY> = NEW.PRICE NEED.TO.WRITE = 1 END Related commands Language Command UniBasic NES NEG The UniBasic NEG function changes the value of expr to its opposite sign. If the value of expr is positive, NEG returns a negative value. If the value of expr is negative, NEG returns a positive value. Syntax NEG(expr) Examples In the following example, the program segment changes the value of variable A to a negative number and prints -1: A = 1 A = NEG(A) PRINT A 230 NES Related commands Language Command UniBasic ABS NES The UniBasic NES function compares each value in array1 to its corresponding value in array2. UniData returns an array with a one in each position where the value in array1 is not equal to the value in the corresponding position in array2, and a zero in each position for values that are equal to array2. Syntax NES(array1, array2) Examples In the following example, the program segment compares ARRAY1 to ARRAY2 and returns ARRAY3. ARRAY3 now contains 0}0}0}1}1. ARRAY1 = 10:@VM:20:@VM:30@VM:40:@VM:50 ARRAY2 = 10:@VM:20:@VM:30:@VM:50:@VM:60 ARRAY3 = NES(ARRAY1,ARRAY2) NFAUSER Beginning at UniData 5.0, a Network File Access (NFA) connection from an NFA client requires a valid user name and password. If the client connection is made through udtelnet, this information is available and passed to the NFA server for connecting. If the session is a console session, the system prompts for the user name and password when a connection is requested, such as when you OPEN the first NFA file on a database. UniBasic now provides the NFAUSER function which enables you to set the user name and password in a UniBasic program. Syntax NFAUSER(“username”, “password”) Parameters The following table describes each parameter of the syntax. Parameter Description username A valid user name on the NFA server to which you are connecting. password The password corresponding to username. After running this function and providing a valid user name and password combination, an NFA connection no longer prompts for this information, regardless if it is from the console or via udtelnet. NFAUSER does not validate the user name/password combination, but registers them in an internal variable for later use. 231 Chapter 1: UniBasic commands and functions NOCONVERT The UniBasic NOCONVERT command controls the conversion of the special character CHAR(0). The following UniBasic commands read and write non-UniData files or tapes and convert CHAR(0) to CHAR(128) on input. They also convert CHAR(128) to CHAR(0) on output. This can cause problems under some circumstances, especially if you use the character CHAR(128) in an application or in stored data. NOCONVERT provides a way of switching the conversion OFF or ON. The default is OFF. Syntax NOCONVERT {OFF | ON} The following UniBasic commands convert CHAR(0) and CHAR(128) when NOCONVERT is turned on: ▪ OSBREAD ▪ OSBWRITE ▪ OSREAD ▪ OSWRITE ▪ READT ▪ WRITET Note: The and CRT functions do not work with strings that contain CHAR(0). Warning: Do not use UniBasic READ and WRITE commands to open or modify binary data in DIRtype files (for example, BP). Doing so can corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. The following functions work with strings containing CHAR(0), regardless of the setting of the NOCONVERT command: ▪ ▪ ▪ ▪ Assignment (X = Y) Bracket function ([]) Substring assignment (A[1,3] = B) String concatenation (A:B) ▪ CHAR ▪ CONVERT ▪ COUNT ▪ DCOUNT ▪ INDEX ▪ LEN ▪ SEQ ▪ SWAP NOT The UniBasic NOT Boolean operator inverts the logical result of the argument expr. If the expression is true, the function returns 0 (false). If the expression is not true, the function returns 1 (true). 232 NOTS Syntax NOT(expr) Examples In the following example, the program segment compares X to Y (false because X is not greater than Y) and inverts the result, evaluating to true instead. Next, the THEN statement executes, sending program control to the label specified by RETRY. X = 1 ; Y = 2 IF NOT(X > Y) THEN GOSUB RETRY: Related commands Language Command UniBasic #, NOTS NOTS The UniBasic NOTS Boolean operator inverts the logical result of each element of a dynamic array. If the element is true, the operator returns 0 (false) in the corresponding position of the new array. If the expression is not true, the operator returns 1 (true) in the corresponding position of the new array. Syntax NOTS(dyn.array) Examples In the following example, the program segment evaluates the dynamic array A, inverts each result of the evaluation, and returns the results in a corresponding array. B now contains 0}1}0}0. A = 1:@FM:0:@FM:1:@FM:30 B = NOTS(A) NULL The UniBasic NULL command acts as a dummy statement. You can use the NULL statement anywhere a statement is required. Tip: Use NULL when a statement or command clause is mandatory, but you do not want to initiate any action. Syntax NULL Examples In the following example, if the length of the variable NAME$ is zero, the program prints nothing: PRINT "NAME: ": ; INPUT NAME$ 233 Chapter 1: UniBasic commands and functions BEGIN CASE CASE LEN(NAME$) = 0 NULL CASE LEN(NAME$) > 0 PRINT "HI, ":NAME$ END CASE NUM The UniBasic NUM function determines if an expression is numeric. If expr is numeric, NUM returns 1. Otherwise, it returns 0. expr can be any valid UniBasic expression. The NUM function returns 0 for any multibyte character. Syntax NUM(expr) With null value handling on, this function returns 1 for the null value. The nonnumeric characters in the following table produce a result of 1. Character Description + Plus sign - Negative sign . Decimal point Nonprinting Null value Examples In the following example, the program segment prints 0 because VAR contains alphabetic characters: VAR = 'ABC' PRINT NUM(VAR) In the next example, the program segment prints 1 because VAR contains an integer: VAR = -123 PRINT NUM(VAR) Related commands Language Command UniBasic ALPHA, ICONV Masked Character (MC), NUMS, OCONV Masked Character (MC) NUMS The UniBasic NUMS function determines, for each element of an array, if that element is numeric. If the element is numeric, NUM returns 1 in the corresponding position of the new array. For nonnumeric and multibyte characters, it returns 0. 234 OCONV Syntax NUMS(dyn.array) With null value handling on, this function returns 1 for the null value. The nonnumeric characters in the following table produce a result of 1. Character Description + Plus sign - Negative sign . Decimal point Nonprinting Null value Examples In the following example, the program segment determines whether each element of array CHARACTERS is numeric. The resulting array B contains 1}1}1}0}0. CHARACTERS = 123:@FM:456:@FM:-789:@FM:"ABC":@FM:"CDE" B = NUMS(CHARACTERS) Related commands Language Command UniBasic ICONV Masked Character (MC), OCONV Masked Character (MC) OCONV The UniBasic OCONV function converts string or numeric data from internal format to display format based on conversion codes. If the input value or conversion code is invalid, UniData returns the input value. OCONV supports multibyte languages. Syntax OCONV(expr, conv.code.expr, "MM [H] [S[M]]") Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies the expression, a string or numeric data, to convert. Time input must be in the form 'SSSSSmmm', where SSSSS are seconds and mmm are milliseconds. If a value is not given then zero is assumed. conv.code.expr Specifies an internal representation format to use when converting expr. 235 Chapter 1: UniBasic commands and functions Parameter Description H Indicates that hours are to be formatted in 12-hour format with a.m. or p.m. suffixes. S Indicates that seconds are to be included in the output. M Indicates that milliseconds are to be included in the output. If this parameter is used the S parameter must also be used. The following table summarizes the valid conversion codes. A detailed discussion of each follows under separate topics. Code Format CB Handles data at the byte level when running in multibyte character mode. D System date. G Extracts one or more strings separated by a delimiter. L Length. MB Binary. MC Masked character. MD Masked decimal. ML Left-justify. MP Packed decimal. MP1 Convert to packed decimal without truncating at the first CHAR(0) or altering this character. MO Octal. MR Right-justify. MT System time. MX Hexadecimal. P Pattern match. R Range. S SOUNDEX. T Text extraction. Tfile File translation. Examples The following example illustrates using the OCONV command using milliseconds: CRT 'OCONV("58685456","MM"): ':OCONV("58685456","MM") CRT 'OCONV("58685456","MMH"): ':OCONV("58685456","MMH") CRT 'OCONV("58685456","MMHS"): ':OCONV("58685456","MMHS") CRT 'OCONV("58685456","MMS"): ':OCONV("58685456","MMS") CRT 'OCONV("58685456","MMHSM"): ':OCONV("58685456","MMHSM") CRT 'OCONV("58685456","MMSM"): ':OCONV("58685456","MMSM") Result: OCONV("58685456","MM"): 16:18 OCONV("58685456","MMH"): 04:18PM OCONV("58685456","MMHS"): 04:18:05PM OCONV("58685456","MMS"): 16:18:05 OCONV("58685456","MMHSM"): 04:18:05.456PM OCONV("58685456","MMSM"): 16:18:05.456 236 OCONV byte level (CB) Related commands Language Command UniBasic ICONV OCONV byte level (CB) The CB option handles data at the byte level substring when running in multibyte character mode. Syntax OCONV(string, "CB;start;length”) Parameters The following table describes each parameter of the syntax. Parameter Description string Indicates a string to be searched start The byte position in the string to start extracting data. length The number of bytes to extract. For more information, see SUBSTRINGS, on page 426. OCONV Date (D) The OCONV Date (D) function converts an integer in internal date format to date display format. If the input value or conversion code is invalid, UniData returns the input value. UniData ignores leading zeros in the input date. The internal format of the date is the number of days before or after December 31, 1967. Days before are represented as negative numbers. With UDT.OPTIONS 4 on, this command converts the text of dates to uppercase. For example, May 13 is converted to MAY 13. With UDT.OPTIONS 29 on, this command converts Sunday to 7 instead of 0. For information about UDT.OPTIONS, see the UDT.OPTIONS Commands Reference. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(integer.exp, "D [y] [c] [fmt]") Parameters The following table describes each parameter of the syntax. Parameter Description integer.exp Indicates a date in internal format. y Number of digits to represent the year in the formatted date. 237 Chapter 1: UniBasic commands and functions Parameter Description c Delimiter separating day, month, and year. Can be a space, slash, period, comma, hyphen, or asterisk. fmt Format for date display. The following formats are available: mm dd yy[yy] day month year yy[yy] mm dd Combine the output format codes in the following table to format the date. The syntax for format codes is the following: [D | W | WA] [ [M] [Y] | Q | QA]] [J] [[,] {An | Zn} [[,] {An | Zn}...] Format codes The following table describes the valid output format codes. Code Description D Includes day in the output date. M Includes month in the output date. Y Includes year in the output date. Q Converts to quarter numeric format. QA Converts to quarter alphabetic format. W Valid for day only. Specifies numeric format. WA Valid for day only. Specifies alphabetic format. An Valid for day, quarter, and month only (WAn, QAn, and MAn respectively). A specifies alphabetic format, and n indicates number of characters. Zn Valid for month and day only. Z specifies numeric format; and n indicates number of digits. Z without a digit and Z0 suppress zeros. J Displays the Julian date (the number of days since January 1). Note: Following SMA standards, Monday is the first day of the week (1). If UDT.OPTIONS 29 is on, Sunday converts to 7 instead of 0. STATUS function return values After you execute OCONV D, the STATUS function returns one of the values described in the following table. Value Description 0 Successful conversion of a valid date. 1 The input date was invalid. 2 The conversion code was invalid. Examples The following statements are taken from the sample program in Developing UniBasic Applications. It converts the date stored in internal format in the ORDERS file. The formatted date is in MM/DD/YYYY format. 238 OCONV Group (G) ORDER_DATE = OCONV(ORDER.REC<1>,"D4/") In the following example, the program statement prints a three-character month name, a numeric day, and a four-digit year (suppressing zeros if necessary): PRINT OCONV(ORDER.REC<1>, "DMDYA3,Z,Z4") In the following example, the program statement prints J 1970 4: PRINT OCONV(732,"dmywa1z3") Some sample format codes are applied in the following table. Input value Conversion code Output 744 DDMY 13 Jan 1970 744 DMDY 01 13 1970 1006 D 02 Oct 1970 1006 DDMY 02 10 1970 1006 DDMYZ0,Z,Z 2 10 1970 0 D4/ 12/31/1967 7334 D 29 Jan 1988 7334 DDMY,A,Z4 29 January 1988 7334 DDMY,A3 29 Jan 1988 7334 DDMY 29 01 1988 7334 DD 29 7334 DM 01 7334 DW 5 7334 DWA Friday 7334 DQ 1 7334 DQA Winter 7334 DJY 029 1988 Related commands Language Command UniBasic DATE, ICONV Date (D), TIMEDATE UniData DATE, DATE.FORMAT, SET.TIME For information, see the UniData Commands Reference. OCONV Group (G) The OCONV Group (G) function extracts one or more strings separated by a delimiter. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 239 Chapter 1: UniBasic commands and functions Syntax OCONV(str.expr, "G[m]x n") Parameters The following table describes each parameter of the syntax. Parameter Description str.exp Indicates a string separated by a delimiter. m Indicates the number of strings to skip. If m is omitted, no strings are skipped. x Specifies any single nonnumeric character to be the delimiter. UniData system delimiters are valid. Hyphen or minus sign is not valid. n The number of strings to be extracted. Examples In the following example, the program segment prints (303): X = "(303)+555+0988" PRINT OCONV(X,"G0+1") Related commands Language Command UniBasic ICONV Group (G) OCONV Length (L) The OCONV Length (L) function extracts a string of a specified length or that falls within a range of acceptable lengths. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "Ln[,m]") Parameters The following table describes each parameter of the syntax. 240 Parameter Description str.exp Indicates a string to be searched. n Specifies the number of characters the string must match to be extracted. When m is present, n is the shortest string to be extracted. m Specifies the longest string to be extracted. OCONV Masked Character (MC) Examples In the following example, the program segment prints “123” and an empty string because X has fewer than five characters and more than three: X = 123; Y = 456789 PRINT OCONV(X,"L3,5") PRINT OCONV(Y,"L3,5") Related commands Language Command UniBasic ICONV Length (L) OCONV Masked Character (MC) The OCONV Masked Character (MC) function converts alphabetic characters to uppercase or lowercase, or extracts alphabetic or numeric characters from strings. This function performs the same conversions and extractions as ICONV MC. If the input value or conversion code is invalid, UniData returns the input value. Syntax OCONV(str.expr, "MC [A | /A | B | /B | C;x;y | U | L | T | N | /N | P | X[D] | D | D[X] | X]") Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Parameters The following table describes each parameter of the syntax. Parameter Description str.expr The expression to be searched or converted. A Extracts all alphabetic characters. /A Extracts all nonalphabetic characters. B Extracts all alphabetic and numeric characters. /B Extracts all special characters (not alphabetic nor numeric). C;x;y Converts all occurrences of substring x to substring y. U Converts data to uppercase. L Converts characters to lowercase. T Converts to initial cap style. First letter of each word is uppercase, and all other letters are lowercase. Space and tab are considered word separators. N Extracts all numeric characters (0-9). /N Extracts all nonnumeric characters. P Converts all nonprinting characters to tildes (~). X[D] or D Assumes input is in hexadecimal; converts to decimal. 241 Chapter 1: UniBasic commands and functions Parameter Description D[X] or X Converts input to hexadecimal. Examples The following subroutine is taken from the sample program in Developing UniBasic Applications. The subroutine converts user input to uppercase, then compares that input with Q to determine if the user is ready to quit the application. The user can enter any string starting with Q or q, or an order number. GET_ORDER_NUMBER: * Have the user enter a valid key to a record in the ORDERS file. LOOP DISPLAY @(15,6): INPUT ORDER_NUMBER ORDER_NUMBER = OCONV(ORDER_NUMBER,"MCU") IF NUM(ORDER_NUMBER) OR ORDER_NUMBER[1,1] = "Q" THEN VALID_ORDER_NUMBER = 1 END ELSE VALID_ORDER_NUMBER = 0 MESSAGE = "Order # must be a Number, or the letter 'Q'" CALL DISPLAY_MESSAGE(MESSAGE) END UNTIL VALID_ORDER_NUMBER REPEAT The following statement, taken from the same sample program, extracts the numbers from user input. This use of OCONV removes the special characters the user might have entered in a formatted date. For example, the statement extracts 1234 from $12.34. NEW.PRICE = OCONV(NEW.PRICE,"MCN") Related commands Language Command UniBasic ALPHA, CONVERT, DOWNCASE, ICONV Masked Character (MC), NUM, @UPCASE OCONV Masked Decimal (MD) The OCONV Masked Decimal (MD) function scales, rounds, and formats a number for display with up to nine decimal places. num.expr can be any numeric value. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(num.expr, "MDn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [- | < | E | C | D] [P] [Z] [T] [xc]") Parameters The following table describes each parameter of the syntax. Some parameters set the same values. Results are unpredictable if you make conflicting assignments. 242 OCONV Masked Decimal (MD) Parameter Description num.expr Indicates a number to be formatted. n Sets precision (the number of decimal places represented). It can be a number between 0 and 9. If n is less than the number of decimal points in the input data, the resulting value is rounded. f Scales the input value num.expr by moving the decimal point f places to the left. If omitted, f defaults to the value assigned to n (for example, if you specify MD2, UniData reads it as MD22). prefix], [thsnd_mark], [dec_symbl], [suffix] The square brackets enclosing these parameters are required. prefix – Nonnumeric character(s) to precede the formatted number. For example, MD2[**] produces "**nnn...". thsnd_mark – Nonnumeric character(s) to delimit thousands. To specify a comma, enclose it in single quotation marks, and then use double quotation marks to enclose the conversion code. For example, MD2[,',' ] produces "...,nnn,nnn". dec_symbl – Alternate symbol to represent the decimal point. suffix – Nonnumeric character(s) to follow the formatted number. For example, MD2[, , ,**] produces "...nnn**". , Inserts commas to separate thousands, millions, and so forth. $ Precedes the output with a dollar sign ($). - Specifies the negative sign (for negative data) to precede negative numbers. < or E Specifies that negative data is surrounded by brackets. C Specifies that negative data is followed by CR, indicating a credit. D Specifies that negative data is followed by DB, indicating a debit. P Specifies that no scaling is performed if a decimal is present in the input value. Z Specifies that zeros are to be suppressed. T Specifies that the number is to be truncated, not rounded to the number of decimal places specified in n. xc Specifies that the character c is used to fill spaces left to the left of the number after output data is formatted. x indicates the size of the mask. Examples The following table describes some OCONV masked decimal conversion codes and their results. Input Code Result 12.339 MD3 0.012 MD2,$ $12.34 MD2$,D $9,123.91DB MD24P 123.46 12.339 1234 -1234 912391 456789 123.456 11111112339 MD32 0.123 MD2$,- <12.34> MD2$,11* $**4,567.89 MD12[@,*,,%] @111*111*123.4% 243 Chapter 1: UniBasic commands and functions The following statement is taken from the sample program in Developing UniBasic Applications. It converts the price stored in internal format in the ORDERS file for display, including two decimal places, commas separating thousands of dollars, preceded by a dollar sign. PRICE = OCONV(ORDER.REC<7,ENTRY>,"MD2$,") Related commands Language Command UniBasic ICONV Masked Decimal (MD) OCONV Left Justify (ML) The OCONV Left Justify (ML) function scales, rounds, and formats a number, or left-justifies it in a mask. str.expr can be any valid text or a numeric value with or without a decimal. If the input value or conversion code is invalid, UniData returns the input value. Note: The OCONV ML and MR functions produce the same output. However, formatting differs slightly in the following way: if a mask is specified that is larger than the formatted number, UniData left- or right-justifies the number within a “column” the width of the mask. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "MLn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [C] [Z] [(mask)]") Parameters The following table describes each parameter of the syntax. Note: Some parameters set the same values. Results are unpredictable if you make conflicting assignments. 244 Parameter Description str.expr Indicates a text string or number to be left-justified and formatted. n Sets precision (the number of decimal places represented). It can be a number between 0 and 9. If n is less than the number of decimal points in the input data, the resulting value is rounded. f Scales the input value num.expr by moving the decimal point f places to the left. If omitted, f defaults to the value assigned to n (for example, if you specify ML2, UniData reads it as ML22). OCONV Packed Decimal (MP) Parameter Description prefix], [thsnd_mark], [dec_symbl], [suffix] The square brackets enclosing these parameters are required. prefix – Nonnumeric character(s) to precede the formatted number. For example, ML2[**] produces "**nnn...". thsnd_mark – Nonnumeric character(s) to delimit thousands. To specify a comma, enclose it in single quotation marks, and then use double quotation marks to enclose the conversion code. For example, ML2[,',' ] produces "...,nnn,nnn". dec_symbl – Alternate symbol to represent the decimal point. suffix – Nonnumeric character(s) to follow the formatted number. For example, ML2[, , ,**] produces "...nnn**". , Inserts commas to separate thousands, millions, and so forth. $ Precedes the output with a dollar sign ($). C Specifies that negative data is followed by CR, indicating a credit. Z Specifies that zeros are to be suppressed. mask Specifies a mask to be used for formatting. Use # to represent number placement. Include special characters as desired. Results are adversely affected if the mask contradicts other parameters. For example, placement of the decimal in the mask overrides n. Examples In the following statement, UniData moves the decimal three places to the left (0.012339), rounds to three decimal places, and then prints 0.012: PRINT OCONV("12.339","ML3") In the following statement, UniData moves the decimal two places to the left (0.12339), rounds to three decimal places, and then prints 0.123: PRINT OCONV("12.339","ML32") In the following example, UniData converts the value 123456789 to 1234-56-789 because it left-justifies it in the mask “####-##-####”: OUTPUT.VAL = OCONV("123456789","ML(####-##-####)") In the following example, UniData converts the value 12.339 to 0.012 based on the ML3 external conversion: INTERNAL.VAL = OCONV("12.339","ML3") Related commands Language Command UniBasic ICONV Left Justify (ML) OCONV Packed Decimal (MP) The OCONV Packed Decimal (MP) function converts an integer from packed decimal representation into display format. If the input value or conversion code is invalid, UniData returns the input value. 245 Chapter 1: UniBasic commands and functions Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(expr, "MP") Related commands Language Command UniBasic ICONV Packed Decimal (MP) OCONV Packed Decimal (MP1) The OCONV packed decimal (MP1) function converts an integer from packed decimal representation into its display format without truncating at the first CHAR(0) character or altering CHAR(0). If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(expr, MP1) Related commands Language Command UniBasic ICONV Packed Decimal (MP1) OCONV Right Justify (MR) The OCONV right justify (MR) function scales, rounds, and formats a number, or right-justifies it in a mask. str.expr can be any valid text or a numeric value with or without a decimal. If the input value or conversion code is invalid, UniData returns the input value. The OCONV ML and MR functions produce the same output. However, formatting differs slightly in the following way: if you specify a mask that is larger than the formatted number, UniData left- or rightjustifies the number within a “column” the width of the mask. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "MRn [f] [ [ [prefix], [thsnd_mark], [dec_symbl], [suffix] ] ] [,] [$] [C] [Z] [(mask)]") 246 OCONV Right Justify (MR) Parameters The following table describes each parameter of the syntax. Some parameters set the same values. Results are unpredictable if you make conflicting assignments. Parameter Description str.exp Indicates a text string or number to be right-justified and formatted. n Sets precision (the number of decimal places represented). It can be a number between 0 and 9. If n is less than the number of decimal points in the input data, the resulting value is rounded. f Scales the input value num.expr by moving the decimal point f places to the left. If omitted, f defaults to the value assigned to n (for example, if you specify MR2, UniData reads it as MR22). prefix], [thsnd_mark], [dec_symbl], [suffix] The square brackets enclosing these parameters are required. prefix – Nonnumeric character(s) to precede the formatted number. For example, MR2[**] produces "**nnn...". thsnd_mark – Nonnumeric character(s) to delimit thousands. To specify a comma, enclose it in single quotation marks, and then use double quotation marks to enclose the conversion code. For example, MR2[,',' ] produces "...,nnn,nnn". dec_symbl – Alternate symbol to represent the decimal point. , suffix – Nonnumeric character(s) to follow the formatted number. For example, MR2[, , ,**] produces "...nnn**". Inserts commas to separate thousands, millions, and so forth. $ Precedes the output with a dollar sign ($). C Specifies that negative data is followed by CR, indicating a credit. Z Specifies that zeros are to be suppressed. mask Specifies a mask to be used for formatting. Use # to represent number placement. Include special characters as desired. Results are adversely affected if the mask contradicts other parameters. For example, placement of the decimal in the mask overrides n. If the conversion to display format is unsuccessful, UniData returns the original value. Examples In the following statement, UniData moves the decimal three places to the left (0.012339), rounds to three decimal places, and then prints 0.012: PRINT OCONV("12.339","MR3") In the following statement, UniData moves the decimal two places to the left (0.12339), rounds to three decimal places, and then prints 0.123: PRINT OCONV("12.339","MR32") In the following example, UniData converts the value 123456789 to 123-45-6789 because it rightjustifies it into the mask “####-##-####”: OUTPUT.VAL = OCONV("123456789","MR(####-##-####)") 247 Chapter 1: UniBasic commands and functions The following example is taken from the sample program in Developing UniBasic Applications. It converts a price stored in internal format in the ORDERS file to display format, including two decimal places, commas separating thousands of dollars, and a preceding $. DISPLAY @(10,9+ENTRY):OCONV(ORDER.REC<7,ENTRY>,"MR2$,"): The following statement is taken from the same sample program. This statement displays the price right-justified and formatted with commas separating thousands of dollars and a preceding $ as in $12,386.34. The right justification aligns data on the right. DISPLAY @(10,9+ENTRY):OCONV(ORDER.REC<7,ENTRY>,"MR2$,"): In the following example, UniData converts the value 123456 to 1,234.56: OUTPUT.VAL = OCONV("123456","MR2$,") Related commands Language Command UniBasic ICONV Right Justify (MR) OCONV Time (MT) The OCONV time (MT) function converts the internal time of day from an integer between 0 and 86400 (the number of seconds in a day) to display format. Syntax OCONV(num.expr, "MT [H] [S] [c]") Time is output in the following form: HH MM [SS] If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Parameters The following table describes each parameter of the syntax. Parameter Description num.expr Indicates a number to be converted. H Indicates that hours are to be formatted in 12-hour format with a.m. or p.m. suffixes. S Indicates that seconds are to be included in the output. c Specifies a delimiter to be placed between hours, seconds, and fractions of seconds. Note: A program that you can use to try out ICONV and OCONV conversion codes is provided in Developing UniBasic Applications. 248 OCONV Hex (MX | HEX), Octal (MO), Binary (MB) Related commands Language Command UniBasic DATE, ICONV Time (MT), TIME, TIMEDATE OCONV Hex (MX | HEX), Octal (MO), Binary (MB) The OCONV hex (MX), octal (MO), and binary (MB) functions convert from decimal or ASCII characters into other numbering systems. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, ["HEX | MX [0C] | MO [0C] | MB [0C]"]) Parameters The following table describes each parameter of the syntax. Parameter Description str.exp Specifies the number to convert to an alternate numbering system. HEX | Indicates conversion to hexadecimal (base 16). The optional 0C converts from ASCII character rather than decimal value. HEX is equivalent to MX0C. MX [0C] MO [0C] Indicates conversion to octal (base 8). The optional 0C converts from ASCII character rather than decimal value. MB [0C] Indicates conversion to binary (base 2). The optional 0C converts from ASCII character rather than decimal value. The following table indicates which parameters to use with OCONV to convert from decimal value or ASCII character to other numbering systems. From To Function Decimal value Binary OCONV MB Decimal value Octal OCONV MO Decimal value Hexadecimal OCONV MX ASCII character Binary OCONV MB0C ASCII character Octal OCONV MO0C ASCII character Hexadecimal OCONV MX0C OCONV HEX Examples The following table demonstrates some OCONV MX, MO, and MB conversion codes and their results. 249 Chapter 1: UniBasic commands and functions Input Code Result SS (ASCII character) MO0C 123123 (octal) 256 (decimal) MX 100 (hexadecimal) 0 (ASCII character) MX 4F (hexadecimal) 5 (decimal) MB 00000101 (binary) 33288 (decimal) MO 101010 (octal) Qat (ASCII character) MX0C 516174 (hexadecimal) U (ASCII character) MB0C 01010101 (binary) Related commands Language Command UniBasic CHAR, ICONV Hex (MX | HEX), Octal (MO), Binary (MB), SEQ OCONV Pattern Match (P) The OCONV pattern match (P) function checks a string for a match with one of the patterns or strings specified in op. If the entire string does not match one of the patterns or strings, UniData returns an empty string. If the input value or conversion code is invalid, UniData returns the input value. OCONV pattern match performs the same function as the ICONV pattern match function. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "P(op)[;(op).....]") Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Indicates a string to be searched. op Specifies the pattern to search for in str.expr. nN – Integer followed by N tests for that number of numeric characters. nA – Integer followed by A tests for that number of alpha characters. nX – Integer followed by X tests for that number of alphanumeric characters. lit.str – Indicates a literal string to be searched for in str.expr. ; Separates multiple patterns. Examples The following statement prints an empty string because the entire input string does not match a pattern or string specified in op: 250 OCONV Range (R) PRINT OCONV("abc123","P(3N);(abc)") The following statement prints “abc” because the input string matches the string provided in op: PRINT OCONV("abc","P(3N);(abc)") OCONV Range (R) The OCONV range (R) function returns only those data values that fall into a specified range of decimal values. When including a negative range, you must specify the highest negative number first. If range specifications are not met, UniData returns an empty string. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(num.expr, "Rndm[;ndm.....]") Parameters The following table describes each parameter of the syntax. Parameter Description num.expr Indicates a string to be searched. n Specifies the smallest number to be extracted. d Specifies a delimiter separating numbers in a range. Any character except system delimiters can be used to separate the numbers in a range. Do not use the minus sign (-) as a delimiter because it refers to a negative number in the range. m Specifies the longest string to be extracted. ; Separates multiple ranges. Examples In the following example, the program segment prints “123” and a blank line because X is within the range and Y is not: X = 123; Y = 456789 PRINT OCONV(X,"R100,200") PRINT OCONV(Y,"R100,200") Related commands Language Command UniBasic ICONV Range (R) 251 Chapter 1: UniBasic commands and functions OCONV SOUNDEX (S) The OCONV SOUNDEX (S) function converts string or numeric data to phonetic format based on SOUNDEX conversion codes. You can use the S conversion code in a virtual attribute formula. If the input value or conversion code is invalid, UniData returns the input value. For more information on SOUNDEX conversion codes, see the SOUNDEX command. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "S") Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Indicates a string to be converted. Examples The following example is a virtual attribute (SDX_LNAME) that converts the value of the variable LNAME to its SOUNDEX expression: OCONV(LNAME,"S") Related commands Language Command UniBasic ICONV SOUNDEX (S), SOUNDEX OCONV Text Extraction (T) The OCONV text extraction (T) function extracts a substring from a string. If you omit m, extraction begins from the rightmost character, and n characters to the left are extracted. If you include m, extraction begins with the position specified, and n characters to the right are extracted. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Syntax OCONV(str.expr, "T[m,]n") Parameters The following table describes each parameter of the syntax. 252 OCONV File Translation (Tfile) Parameter Description str.expr Indicates a string to be searched. m Extracts a contiguous string of characters starting from character m. n Extracts a contiguous string of characters of length n. Examples The following table describes some OCONV text extraction codes and their results. Input Code Result 1234567890 “T3” 890 Three characters are extracted, counting to the left from 0. 1234567890 "T1,3" 123 Three characters are extracted, counting to the right from 1. DAMN THE TORPEDOES “T3,5” MN TH CONVERSION IS THE KEY “T1,9” CONVERSIO 457 COLORADO BLVD “T4,7” [space]COLORA Related commands Language Command UniBasic [], FIND, FINDSTR, ICONV Text Extraction (T) OCONV File Translation (Tfile) The OCONV file translation (Tfile) function retrieves attributes from a file without the file being explicitly opened first. This function performs the same conversion as the ICONV file translation function. If the input value or conversion code is invalid, UniData returns the input value. Syntax OCONV(rec.id, "T[DICT] [filename;cn;I-Attribute;O-Attribute]") Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. Parameters The following table describes each parameter of the syntax. Parameter Description rec.id Specifies the ID of the record to be accessed. Can be a literal or a variable. DICT Include to access the dictionary file. 253 Chapter 1: UniBasic commands and functions Parameter Description filename Specifies the name of the file to be accessed (any valid UniData file in your VOC file containing the required attribute or data). c One of the following translate subcodes: V – If the record does not exist, or if the attribute is an empty string, return an empty string and print an error message. C – If the record does not exist, or if the attribute is an empty string, substitute id.expr for the value of the function. X – If the record does not exist, or if the attribute is an empty string, return an empty string. n Indicates the number of the value of a multivalued attribute to retrieve. If n is not included, UniData retrieves all values of the attribute. I-Attribute Specifies the number of the attribute to be retrieved during input conversion. If I-Attribute is omitted, UniData retrieves the record ID. O-Attribute Number of the attribute to be retrieved during output conversion (OCONV). If the O-Attribute is omitted, UniData retrieves the record ID. Examples The first line of the following program segment reads the demo database file ORDERS, accessing the record with @ID 912, and retrieving the second attribute. OCONV T also converts the internal date to display format. The second line prints the value in that attribute. record.ret = OCONV("912","TORDERS;V;;2") PRINT "Record retrieved: ":record.ret END The following output is obtained by running the preceding program: Record retrieved: 12:30PM In the next example, the program statement translates the TAPE_ID to the TAPES file and returns the name of the tape: TAPE_ID = CUSTOMER.REC<7,X> TAPE_NAME = OCONV("TAPE_ID","TTAPES;X;;1") Related commands Language Command UniBasic ICONV Text Extraction (T) OCONVS The UniBasic OCONVS function converts string or numeric data from internal format to output format, based on a conversion code, for each element of a dynamic array. If the input value or conversion code is invalid, UniData returns the input value. Note: In BASICTYPE P, OCONV returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 254 ON/GOSUB OCONVS conversion codes are the same as OCONV conversion codes. For information about conversion codes, see OCONV. Syntax OCONVS(dyn.array.expr, conv.code.expr) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.expr Specifies a dynamic array, each element of which to convert. conv.code.expr Specifies a code to use in converting each element of the dynamic array. Examples In the following example, the program segment converts each element of ARR1 to output format: ARR1 = 1234:@VM:5678:@VM:9876 ARR2 = OCONVS(ARR1,"MR2$") PRINT ARR2 END The preceding program segment prints the following output: $12.34 $56.78 $98.76 Related commands Language Command UniBasic OCONV, ICONVS ON/GOSUB The UniBasic ON/GOSUB command transfers program control to a subroutine label based on the value of expr. ON GOSUB can appear on one line, or it can be spread over as many successive lines as necessary. Labels must be separated by commas. When the program encounters a RETURN statement in the called subroutine, UniData transfers control to the statement immediately following ON GOSUB. If the subroutine contains a RETURN TO label statement, control resumes at the label specified in the RETURN statement. Note: In BASICTYPE M or P, if expr is nonnumeric or less than 1, UniData bypasses the GOSUB clause and the next program statement executes. Syntax ON expr GOSUB label[:][, label[:]...] 255 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies a numeric expression. UniData evaluates the expression, and then truncates it to an integer. Control passes to a subroutine based on the following rules. If expr is less than or equal to 1, UniData transfers program control to the subroutine starting at the first label in the list. If the number is 2, UniData transfers control to the subroutine starting at the second label, and so forth. If expr is higher than the number of labels, UniData transfers control to the last label in the list. If expr is nonnumeric, control transfers to the first label. label Specifies a subroutine label or multiple subroutine labels. : Optional. A colon is required to identify a nonnumeric label in the statement label itself only, not in the reference to it in the ON/GOSUB statement. Examples In the following example, the program segment divides the variable BALANCE by 100. If the result is less than or equal to 1, the program transfers control to subroutine U100. If the value is 2 or 3, it transfers control to U200 or U300 respectively. If the value is greater than or equal to 4, UniData transfers control to subroutine U400. ON BALANCE/100 GOSUB U100,U200,U300,U400 In the next example, the program segment transfers control to a subroutine after prompting the user for a screen item to modify. In this case, depending on the number the user enters, UniData transfers control to one of the five subroutines in the GOSUB clause. If the user response is nonnumeric or less than 1, UniData transfers control to the first subroutine. If the user enters a value greater than 5, UniData transfers control to the last subroutine (500). GOSUB DISPLAY.SCREEN: PRINT "Enter Item number to modify (1-5): ": INPUT ACTION ON ACTION GOSUB 100,200,300,400,500 Related commands Language Command UniBasic GOSUB, GOTO, ON/GOTO, RETURN ON/GOTO The UniBasic ON/GOTO command transfers program control to a statement label based on a numeric expression. The ON GOTO statement, like the GOTO statement, is one-way branch. If you use an ON GOTO statement to transfer control to a subroutine with a RETURN statement, the subroutine’s RETURN 256 OPEN statement works if a previous GOSUB statement is still waiting for a RETURN statement in the subroutine. Otherwise, the program aborts with a runtime error. Tip: Use ON/GOSUB instead of ON/GOTO to make your programs easier to follow and maintain. Syntax ON expr GOTO label1[:] [, label2[:] ...] Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies a numeric expression. UniData evaluates the expression, and then truncates it to an integer. Control passes to a subroutine based on the following rules. If expr is less than or equal to 1, UniData transfers program control to the subroutine starting at the first label in the list. If the number is 2, UniData transfers control to the subroutine starting at the second label, and so forth. If expr is higher than the number of labels, UniData transfers control to the last label in the list. If expr is nonnumeric, control transfers to the first label. label Specifies a subroutine label or multiple subroutine labels. : Optional. A colon is required to identify a nonnumeric label in the statement label itself only, not in the reference to it in the ON/GOTO statement. Note: In BASICTYPE M or P, if expr is nonnumeric or less than 1, UniData bypasses the GOTO clause and the next program statement executes. Examples In the following example, the program statement transfers program control to the statement label TEST if the variable X is less than or equal to 1. If X is 2, UniData transfers control to statement label 2500. If X is greater than or equal to 3, UniData transfers control to statement label YESNO. ON X GOTO TEST,2500, YESNO Related commands Language Command UniBasic GOSUB, GOTO, GOSUB OPEN The UniBasic OPEN command opens a UniData hashed data or dictionary file, so you can read, write, or delete records from it. The number of files you can open is determined by operating system and UniData configuration parameters. For information about file performance, see Administering UniData on UNIX or Administering UniData on Windows Platforms. 257 Chapter 1: UniBasic commands and functions Warning: Do not use UniBasic READ commands to open or modify binary data in DIR-type files (for example, BP). Doing so could corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Syntax OPEN ["expr",] "filename" [READONLY] [TO file.var] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies the portion of file type to open: “” – UniData opens a data file. DICT – UniData open a dictionary file. filename Specifies the name of the file to open. READONLY Directs UniData to open the file for reading only. If the program attempts to write to a file opened in READONLY mode, UniData displays a runtime error message and does not update the file. For information about security procedures, see Administering UniData on UNIX or Administering UniData on Windows Platforms. TO file.var Specifies a file variable in which to place a pointer to the opened file. If you do not specify file.var, the file you open becomes the default file. UniData performs all default file operations on this file. (Default file statements include all types of read, write, or delete when no file variable specified). A single default file can be declared in each UniBasic program or subroutine, and the default file is specific to the program or subroutine in which it is defined. If a main program opens a default file, and then calls an display subroutine that also opens a default file, UniData restores the original default file when returning to the main program. ON ERROR statements The ON ERROR clause enables the program to continue to perform when a fatal error occurs such as when the file is not open, an I/O error occurs, or UniData cannot find the file. If a VOC entry exists for a file that does not exist, the ON ERROR clause executes. However, if no VOC entry exists, the ELSE statement executes. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END 258 THEN executes if the open is successful. END is required to terminate multiline THEN statements. openSecureSocket function Parameter Description ELSE statements END ELSE executes if the OPEN is not successful or the record does not exist. If the file exists, but some other error occurs, the ELSE statement executes. However, if a file does not exist and no VOC entry exists, the ELSE statement executes. END is required to terminate multiline ELSE statements. INMAT function return values After you execute OPEN, the INMAT function returns one of the values described in the following table. Value Description n The number of modulos for the file. 0 The file opened is a directory. Examples In the following example, the program statement opens the data file ACCREC in read-only mode. Because no file variable is specified, ACCREC becomes the default file. OPEN 'ACCREC' READONLY ELSE STOP 'Cannot open ACCREC' In the next example, the program statement opens the dictionary file ACCPAY, assigning it to the file variable AP. If UniData does not find the file, “File not found” displays. OPEN 'DICT', 'ACCPAY' TO AP ELSE PRINT 'File not found' In the next example, the program segment opens the CLIENTS file to the file variable CLIENT. If it is not found, UniData executes the ELSE statements, printing an error and setting a flag to 1. OPEN 'CLIENTS' TO CLIENT ELSE PRINT 'NO CLIENT' OPEN.ABORT = 1 END IF OPEN.ABORT THEN PRINT 'Aborting on open error';STOP Related commands Language Command UniBasic CLOSE, DELETE, OPENSEQ, OSOPEN, READ, WRITE openSecureSocket function Use the openSecureSocket() function to open a secure socket connection in a specified mode and return the status. This function behaves exactly the same as the openSocket () function, except that it returns the handle to a socket that transfers data in a secured mode (SSL/TLS).All parameters (with the exception of context) have the exact meaning as the openSocket() parameters. Context must be a valid security context handle. Once the socket is opened, any change in the associated security context will not affect the established connection. 259 Chapter 1: UniBasic commands and functions Syntax openSecureSocket(name_or_IP, port, mode, timeout, socket_handle, context) Parameters The following table describes each parameter of the syntax. Parameter Description name_or_IP DNS name (x.com) or IP address of a server. port Port number. If the port number is specified as a value <= 0, CallHTTP defaults to a port number of 40001. mode 0: default (blocking mode) 1: blocking mode 2: non-blocking mode timeout The timeout value, expressed in milliseconds. If you specify mode as 0, timeout will be ignored. socket_handle A handle to the open socket. context A handle to the security context The following table describes the return status of each mode. Return codes Description 0 Success. 1-41 See Socket Function Error Return codes. 101 Invalid security context handle. 102 SSL/TLS handshake failure (unspecified, peer is not SSL aware). 103 Requires client authentication but does not have a certificate in the security context. 104 Unable to authenticate server. OPENSEQ The UniBasic OPENSEQ command opens a sequential file for access, starting at the specified record. UniData limits to 150 the number of sequential files you can open in a UniBasic program. Tip: Use OPENSEQ to open files that use CHAR(10) as a delimiter. You can then use READSEQ to read the next line delimited by CHAR(10), or WRITESEQ to write a line delimited by CHAR(10). You also can use OSBREAD to read a block of data from the file, or OSBWRITE to write a block of data to the file. For UniData for Windows Platforms only: When you use OPENSEQ, UniData uses the fopen function to open files in Text mode and converts NEWLINE [CHAR (10)] line delimiters to CARRIAGE RETURN– NEWLINE pairs [CHAR(13) and CHAR(10)]. 260 OPENSEQ Syntax OPENSEQ [absolutepath | seq.filename,record.id] [READONLY] TO seq.file.var [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} OPENSEQ [absolutepath | seq.filename,record.id] [READONLY] TO seq.file.var [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description absolutepath The operating system path and sequential file name. seq.filename Specifies a UniData directory type file name. record.id Specifies a record in the sequential file at which to start accessing. READONLY Opens the file for reading only. If the program attempts to write to a file opened in READONLY mode, UniData displays a runtime error message and does not update the file. For information about security procedures, see Administering UniData on UNIX or Administering UniData on Windows Platforms. TO seq.file.var Specifies a file variable to contain a pointer to the opened file. ON ERROR statements Specifies statements to execute if the OPENSEQ statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. You can place the LOCKED clause after the FROM clause. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute OPENSEQ, the STATUS function returns one of the values described in the following table. Value Description 0 The record does not exist. 1 The file you specify is not a sequential-access file. 2 The file does not exist. 3 The READONLY clause was included in the command statement and the record does not exist. 261 Chapter 1: UniBasic commands and functions Value Description 4 An unknown error occurred (such as having too many files open or permission problems). Examples In the following example, the program statement opens the sequential file INV.SOURCES in the directory PRINTERS, and assigns the file variable PRNT: OPENSEQ 'PRINTERS','INV.SOURCES' TO PRNT ELSE GOSUB CLOSED: Related commands Language Command UniBasic CLOSESEQ, OPEN, OSBREAD, OSBWRITE, OSCLOSE, OSDELETE, OSOPEN, OSREAD, OSWRITE, READSEQ, WEOFSEQ, WRITESEQ, WRITESEQF UniData DEFAULT.LOCKED.ACTION The following table describes each parameter of the syntax. openSocket Use the openSocket function to open a socket connection in a specified mode and return the status. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax openSocket(name_or_IP, port, mode, timeout, socket_handle) Parameters The following table describes each parameter of the syntax. Parameter Description name_or_IP DNS name (x.com) or IP address of a server. port Port number. If the port number is specified as a value <= 0, CallHTTP defaults to a port number of 40001. mode 0: default (blocking mode) 1: blocking mode 2: non-blocking mode timeout The timeout value expressed in milliseconds. If you specify mode as 0, timeout will be ignored. socket_handle A handle to the open socket. The following table describes the return status of each mode. 262 OPENXMLDATA Mode Return Status 0 - Non-blocking The function will return immediately regardless of whether or not the socket is successfully opened. The return code indicates if the operation is successful. The timeout value is ignored. 1 - Blocking If a positive timeout is specified, the function will either return with a valid socket handle or will time out after the specified timeout period. If the timeout value is 0, the function will block until either the socket is successfully opened, the underlying TCP/IP connection times out or some other error prevents the socket from opening. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. OPENXMLDATA Use the OPENXMLDATA function to open an XML document after preparing it using the PREPAREXML function. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax OPENXMLDATA(xml_handle,xml_data_extraction_rule, xml_data_handle) Parameters The following table describes each parameter of the syntax. Parameter Description xml_handle The XML handle generated by the PREPAREXML() function. xml_data_extraction_ rule xml_data_handle The path to the XML extraction rule file. The XML data file handle. The following are the possible return values: XML.SUCCESS: Success. XML.ERROR: Failed XML.INVALID.HANDLE: Invalid XML handle Examples The following example illustrates use of the OPENXMLDATA function: status = OPENXMLDATA(“STUDENT_XML”, “_XML_/MYSTUDENT.ext”,STUDENT_XML_DATA) If status = XML.ERROR THEN STOP “Error when opening the XML document. “ END IF status = XML.INVALID.HANDLE THEN STOP “Error: Invalid parameter passed.” 263 Chapter 1: UniBasic commands and functions END OR The OR Boolean operator combines a set of expressions. If expr1 or expr2 is true, the combined expression is true. Either expression must be true for a true condition. Syntax expr1 OR expr2 Synonyms ! Examples In the following example, the program segment combines expressions (X < Y) and (Y < Z). If either expression is true, the program calls subroutine RETRY. X = 1 ; Y = 2 ; z = 3 IF (X < Y) OR (Y < Z) THEN GOSUB RETRY: Related commands Language Command UniBasic AND, NOTS, OR OSBREAD The UniBasic OSBREAD command reads data from a file starting at a specified byte location for a certain length of bytes, and assigns the data to a variable. OSBREAD performs an operating system block read on a UNIX, or Windows platform file. Note: Before you use OSBREAD, you must open the file by using the OSOPEN or OPENSEQ command. UniData uses the ASCII 0 character [CHAR(0)] as a string-end delimiter. Therefore, ASCII 0 cannot be used in any string variable within UniBasic. OSBREAD converts CHAR(0) to CHAR(128) when reading a block of data. Syntax OSBREAD var FROM file.var [AT byte.expr] LENGTH length.expr [NODELAY] [ON ERROR statements] Reading from a named pipe Keep these points in mind when you write programs that read from named pipes: ▪ 264 Unlike a typical read, reading a named pipe removes the data. OSBREAD ▪ Your application should check the length of var after reading a pipe. The value returned could be shorter than length.expr. ▪ UniData truncates the data if it is longer than length.expr. Reading other types of files Processing of files that are not named pipes is determined by the presence or absence of the AT clause: ▪ If the AT clause is included, UniBasic begins reading from the file at the offset specified by byte.expr. ▪ If the AT clause is not included, UniBasic begins reading from the current location of the file pointer. ▪ Because named pipes must be read from the beginning, the AT clause is not appropriate for accessing them. If the AT clause is specified, the ON ERROR executes, and the UniBasic STATUS function is set to 2. If the ON ERROR clause is not included, the program aborts. ▪ After successful execution of OSBREAD against a file that is not a named pipe, the file pointer remains at the next byte after the data read. Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies a variable to which to assign the data read. FROM file.var Specifies a file from which to read the data. AT byte.expr Specifies a location in the file from which to begin reading data. If byte.expr is 0, the read begins at the beginning of the file. When reading a named pipe, do not specify an AT clause. Pipes are always read with no offset. LENGTH length.expr AT byte.expr cannot exceed 2,147,483,648 bytes. Specifies a length of data to read from the file, starting at byte.expr. length.expr cannot be longer than the maximum string length determined by your system configuration. NODELAY ON ERROR statements Forces an immediate read of a named pipe regardless of whether the pipe contains data. If you do not specify NODELAY, the process attempting to read waits until the pipe is opened for writing and data is written to it. If filename is not a named pipe, NODELAY has no effect. Specifies statements to execute if a fatal error occurs (if the file is not open, or if the file is a read-only file). If you do not specify the ON ERROR clause, the program terminates under such fatal error conditions. STATUS function return values After you execute OSBREAD, the STATUS function returns one of the values described in the following table. 265 Chapter 1: UniBasic commands and functions Value Description 0 The read was successful. 1 The file name is invalid. 2 Access is denied by the operating system. 3 The file does not exist. 4 An unknown error occurred. Examples In the following example, the program statement reads 10,000 bytes of the file RFILE starting from the beginning of the file. The program assigns the data it reads to the variable TEST. OSBREAD TEST FROM 'RFILE' AT 0 LENGTH 10000 In the next example, the program segment reads 15,000 bytes from an NTFS or UNIX file, starting at the first byte. It then converts ASCII value 10 (a line feed) to a value mark and processes each line sequentially. OSBREAD BLOCK FROM INPUT.DIR AT 0 LENGTH 15000 CONVERT CHAR(10) TO @FM IN BLOCK LOOP REMOVE REC FROM BLOCK SETTING MORE.RECS GOSUB PROCESS.REC: WHILE MORE.RECS REPEAT Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSBWRITE, OSCLOSE, OSDELETE, OSOPEN, READSEQ, WRITESEQ, WRITESEQF OSBWRITE The UniBasic OSBWRITE command writes an expression to a sequential file starting at a specified byte location. OSBWRITE immediately writes a file segment out to the UNIX, or Windows platform file. You do not have to specify a length expression because the number of bytes in expr is written to the file. Note: Before you use OSBWRITE, you must open the file by using the OSOPEN or OPENSEQ command. UniData uses the ASCII 0 character [CHAR(0)] as a string-end delimiter. Therefore, ASCII 0 cannot be used in any string variable within UniBasic. If UniBasic reads a string that contains CHAR(0) characters by using OSBREAD, those characters are converted to CHAR(128). OSBWRITE converts CHAR(128) back to CHAR(0) when writing a block of characters. Syntax OSBWRITE expr {ON | TO} file.var [AT byte.expr] [NODELAY] [ON ERROR statements] 266 OSBWRITE Writing to named pipes The combination of the following conditions and command options determine the action taken by UniBasic when OSBWRITE is executed against a named pipe: ▪ Presence and length of data in the pipe ▪ Open/closed status of the pipe ▪ Presence or absence of the AT and NODELAY command options For information about writing applications that access named pipes, see the Developing UniBasic Applications manual. Writing to other types of files For files that are not named pipes, processing is determined by the presence or absence of the AT clause: ▪ AT clause specified – UniBasic begins writing to the file at the offset specified by byte.expr. ▪ AT clause not specified – UniBasic begins writing to the current location of the file pointer. ▪ After successful execution of OSBWRITE against a file that is not a named pipe, the file pointer remains at the next byte after the data is written. Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies the expression to write to the file. ON | TO file.var Specifies the file on which to write the expression. AT byte.expr If byte.expr is 0, the write begins at the beginning of the file. NODELAY AT byte.expr cannot exceed 2,147,483,648 bytes. Forces an immediate write. Include NODELAY to write to a named pipe immediately regardless of whether the pipe contains data. If you do not specify NODELAY, the process attempting to write waits until the pipe is opened for reading. ON ERROR statements Specifies statements to execute if the OSBWRITE statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. STATUS function return values After you execute OSBWRITE, the STATUS function returns one of the values described in the following table. Value Description 0 The write was successful. 1 The file name is invalid. 2 You do not have permission to access the file. 4 The file does not exist. 267 Chapter 1: UniBasic commands and functions Examples In the following example, the program statement writes the data in TEST to the RFILE starting from the beginning of the file: OSBWRITE TEST ON RFILE AT 0 In the next example, the program segment reads REC.ID from a select list, reads the associated record from the CLIENT file, and appends the record onto a variable (BLOCK), terminating each record with an ASCII 10 (line feed). When it is complete, the code writes the block to the NTFS or UNIX file name opened to the variable CLIENT.SEQ. DONE = 0 LOOP READNEXT REC.ID ELSE DONE = 1 UNTIL DONE DO READ REC FROM CLIENT,REC.ID ELSE REC = ' ' IF REC THEN REC = REC.ID:@FM:REC BLOCK := REC:CHAR(10) END REPEAT OSBWRITE BLOCK ON CLIENT.SEQ AT 0 Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSBREAD, OSCLOSE, OSDELETE, OSOPEN, READSEQ, WRITESEQ, WRITESEQF OSCLOSE The UniBasic OSCLOSE command closes a sequential file that you opened with the OSOPEN or OPENSEQ command. Syntax OSCLOSE file.var [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file to close. ON ERROR statements Specifies statements to execute if the OSCLOSE statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. STATUS function return values After you execute OSCLOSE, the STATUS function returns one of the values described in the following table. 268 OSDELETE Value Description 0 The file is closed successfully. 5 The file did not close. Examples In the following example, the program statement closes the file UNDEF: OSCLOSE UNDEF Related commands Language Command UniBasic CLOSE, CLOSESEQ, OPENSEQ, OSOPEN OSDELETE The UniBasic OSDELETE command deletes an NTFS or UNIX sequential file. Warning: The UniBasic OSDELETE command is intended for use on OS-type files (not UniData hashed files). If you execute the command against a recoverable hashed file, UniData could crash immediately or at the next Recoverable File System (RFS) checkpoint. If you execute the command against a nonrecoverable hashed file, UniData will not crash, but other unpredictable problems could occur. Syntax OSDELETE filename [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description filename Specifies the file to delete. filename must include the file path. If you do not specify a path, UniData searches the current directory. ON ERROR statements Specifies statements to execute if the OSDELETE statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. STATUS function return values After you execute OSDELETE, the STATUS function returns one of the values described in the following table. Value Description 0 The file was deleted. 1 The directory name is invalid. 269 Chapter 1: UniBasic commands and functions Value Description 2 UniData cannot access the file (such as user does not have permission). 4 The file does not exist. Examples In the following example, the program statement deletes the file NAMES in the current directory: OSDELETE "NAMES" In the next example, the program statement deletes the file client.rec in the UNIX subdirectory /u/ trans: OSDELETE '/u/trans/client.rec' Related commands Language Command UniBasic CLOSESEQ, DELETE, OPENSEQ, OSOPEN, OSCLOSE OSOPEN The UniBasic OSOPEN command opens a sequential file that does not use CHAR(10) as the line delimiter. Read/write access mode is the default. Specify this access mode by omitting READONLY and WRITEONLY. Tip: After opening a sequential file with OSOPEN, use OSBREAD to read a block of data from the file, or OSBWRITE to write a block of data to the file. You also can use READSEQ to read a record from the file, or WRITESEQ or WRITESEQF to write a record to the file, if the file is not a named pipe. (READSEQ, WRITESEQ, and WRITESEQF are line-oriented commands that use CHAR(10) as the line delimiter.) On UniData for Windows Platforms only: When you use OSOPEN, UniData uses the open function to open files in binary mode, but does not convert NEWLINE [CHAR(10)] delimiters to CARRIAGE RETURN– NEWLINE pairs [CHAR(13) and CHAR(10)] as the OPENSEQ command does. Syntax OSOPEN filename [READONLY | WRITEONLY] TO file.var [NODELAY] [ON ERROR statements] {THEN | ELSE} statements [END] Parameters The following table describes each parameter of the syntax. 270 Parameter Description filename Specifies the file to open. filename must include the entire path name unless the file resides in the current directory. The maximum length of the path is 254 characters. OSREAD Parameter Description READONLY Directs UniData to open the file for reading only. If the program attempts to write to a file opened in READONLY mode, UniData displays a runtime error message and does not update the file. For information about security procedures, see Administering UniData on UNIX or Administering UniData on Windows Platforms. WRITEONLY Specifies that the pipe or file is open for write access only. TO file.var Specifies a variable to contain a pointer to the file. NODELAY Forces a pipe to be opened immediately. This enables a process to continue even when the pipe is not open in the opposite access mode. The application must then manage access to the pipe to ensure that it is opened for the opposite process before reading from or writing to it. ON ERROR statements If filename is not a named pipe, NODELAY has no effect. Specifies statements to execute if the OSOPEN statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program statement opens the file INVENTORY as INVENT unless UniData cannot access the file. OSOPEN 'INVENTORY' TO INVENT ELSE STOP "Can't open INVENTORY" Related commands Language Command UniBasic CLOSESEQ, OPEN, OPENSEQ, OSBREAD, OSBWRITE, OSCLOSE, OSDELETE, READSEQ, WRITESEQ, WRITESEQF UniData REUSE.ROW For information, see the UniData Commands Reference. OSREAD The UniBasic OSREAD command reads an entire sequential file and assigns the contents of the file to a variable. Warning: Do not use OSREAD on large files. If the file is too large for the program memory, the program aborts and a runtime error message is generated. On large files, use OSBREAD or READSEQ. UniData uses the ASCII 0 character [CHAR(0)] as a string-end delimiter. ASCII 0 cannot be used in any string variable within UniBasic. OSREAD converts CHAR(0) to CHAR(128) when reading a block of data. 271 Chapter 1: UniBasic commands and functions Syntax OSREAD var FROM filename [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the variable to which to assign the data from the file. FROM filename The filename must include the entire path to the file unless filename exists in the current directory. ON ERROR statements Specifies statements to execute if the OSREAD statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program segment reads the data stored in the UNIX file ‘BILLING’ in the subdirectory ‘disk1’ and assigns it to the variable BILL.REC: OSREAD BILL.REC FROM "disk1/BILLING" ELSE PRINT "NO BILLING RECORD FOUND" END Related commands Language Command UniBasic OSWRITE OSWRITE The UniBasic OSWRITE command writes the contents of an expression to a sequential file. UniData uses the ASCII 0 character [CHAR(0)] as a string-end delimiter. For this reason, you cannot use ASCII 0 in any string variable in UniBasic. If UniBasic reads a string with a CHAR(0) character, and then the character is converted to CHAR(128), OSWRITE converts CHAR(128) to CHAR(0) when writing a block of characters. Syntax OSWRITE expr {ON | TO} filename [ON ERROR statements] Parameters The following table describes each parameter of the syntax. 272 PAGE Parameter Description expr Specifies the expression to write to filename. ON | TO filename Specifies the name of a sequential file to which to write. ON ERROR statements Specifies statements to execute if the OSWRITE statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. Examples In the following example, the program segment writes the contents of MAIL.LIST to the file called “mergefile” in the UNIX subdirectory /u/maildir: OSWRITE MAIL.LIST ON "/u/maildir/mergefile" Related commands Language Command UniBasic OSREAD PAGE The UniBasic PAGE command prints the current output page. UniData prints the page with any specified header or footer. If you do not specify any parameters, the result depends on the last PRINTER command executed: ▪ ▪ PRINTER OFF – The new page is generated on the user’s terminal. PRINTER ON – The new page is generated on the system printer. Syntax PAGE [ON num.expr] [expr] Parameters The following table describes each parameter of the syntax. Parameter Description ON num.expr Specifies the page number of the next output page. Each subsequent page is incremented by one. expr Specifies a target print file for the completed page where num.expr is the number assigned to the file. When you specify a num.expr, the PRINTER command setting is disregarded. For assistance assigning print files, see your system administrator. Examples In the following example, the program statement completes the current page with footings, then advances to a new page. The PRINTER command setting determines where the page is printed. PAGE 273 Chapter 1: UniBasic commands and functions In the next example, the program statement sends the completed page to the file assigned to print unit 5. If UniData cannot find the print unit specified, the program prints nothing. PAGE ON 5 Related commands Language Command UniBasic PRINTER UniData SETPTR For information, see the UniData Commands Reference. PAUSE The UniBasic PAUSE command suspends the UniData process that issues the command for the amount of time you specify with wait_time, or until a UniBasic WAKE command is executed for this process. Keep in mind the following points when executing PAUSE: ▪ ▪ ▪ PAUSE has no effect if wait_time is a negative number, or if another UniData process has previously issued a WAKE command for this process. To pause a process indefinitely, omit wait_time, or specify a wait_time of 2. PAUSE must be executed by the process to be paused. Syntax PAUSE [wait_time] Examples The following sample program executes the UniBasic PAUSE command to pause the current session: PAUSE_WAKE PRINT "How long do you want to pause this session": INPUT pause_time PAUSE pause_time END The following example executes the preceding program. In this execution, the user does not enter an amount of time to pause the session, so it is paused indefinitely. (The cursor rests on the line following the prompt.) :RUN BP PAUSE_WAKE How long do you want to pause this session? From another UniData session, the user executes the LIST.PAUSED command to obtain the process ID for the paused process, and then wakes it up by specifying WAKE 1052: :LIST.PAUSED Number of Paused Users ~~~~~~~~~~~~~~~~~~~~~~ 1 UDTNO USRNBR UID USRNAME USRTYPE TTY LEFTTIME TOT_TIME 1 1052 1283 carolw udt pts/0 274 PCPERFORM :WAKE 1052 : Related commands Language Command UniBasic WAKE UniData LIST.PAUSED, PAUSE, SLEEP, WAKE For information, see the UniData Commands Reference. PCPERFORM The UniBasic PCPERFORM command executes an operating system command from within a UniBasic program. PCPERFORM is similar to the EXECUTE and PERFORM commands except that PCPERFORM executes an operating system command. If PCPERFORM is successful, UniData sets @SYSTEM.RETURN.CODE to 0. If unsuccessful, UniData sets @SYSTEM.RETURN.CODE to -1. Note: The settings of UDT.OPTIONS affect the way ECL commands execute. For information about these options, see the UDT.OPTIONS Commands Reference. For information about UDT.OPTIONS that could affect that command, see the appropriate ECL command in UniData Commands Reference. Syntax PCPERFORM str.expr [CAPTURING, dyn.array.var] Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a string to execute as a host operating system command. CAPTURING, dyn.array.var Specifies a target dynamic array to capture the output of the host operating system command. Examples In the following example, the program statement executes the operating system date command: PCPERFORM "date" CAPTURING DATE.TIME Related commands Language Command UniBasic EXECUTE, EXECUTESQL, MDPERFORM, UDTEXECUTE 275 Chapter 1: UniBasic commands and functions PERFORM PERFORM is a synonym for the EXECUTE command. For more information, see EXECUTE, on page 114. Synonyms EXECUTE PRECISION The UniBasic PRECISION command rounds numbers to the number of decimal places indicated in num.expr. num.expr can be a number from 0 to 14. If the number is not within this range, UniData does not change the setting. The default is four decimal places. Tip: UniData converts the operands in numeric operations from string to numeric data type, performs the operations, and then converts the results back to string data type. When making calculations for which you require a high degree of precision, use the PRECISION command to force UniData to represent a particular level of decimal representation. Set the UniData FLOAT.PRECISION to 4 to truncate rather than round at the PRECISION setting. Syntax PRECISION num.expr Examples In the following example, the program statement results in all numeric variables being truncated to eight decimal places: PRECISION 8 In the next example, the program statement truncates all digits to the right of the decimal point: PRECISION 0 In the next example, the program statement sets precision based on the variable DEC: PRECISION DEC Related commands Language Command UniData FLOAT.PRECISION The following table describes each parameter of the syntax. PREPAREXML Use the PREPAREXML function to prepare the XML document in the UniBASIC program. This step allocates memory for the XML document, opens the document, determines the file structure of the document, and returns the file structure. 276 PRINT Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax PREPAREXML(xml_file,xml_handle) Parameters The following table describes each parameter of the syntax. Parameter Description xml_file The path to the file where the XML document resides. xml_handle The return value. The return value is the UniBASIC variable for xml_handle. Status is one of the following return values: XML.SUCCESS: Success XML.ERROR: Error Examples The following example illustrates use of the PREPAREXML function: STATUS = PREPAREXML(“_XML_/MYSTUDENT.XML”,STUDENT_XML) IF STATUS=XML.ERROR THEN STATUS = XMLError(errmsg) PRINT “error message “:errmsg STOP “Error when preparing XML document “ END PRINT The UniBasic PRINT command prints data on the display terminal or the system printer, or sends data to a print file. Separate multiple items in a single PRINT statement with commas or colons. A comma directs the printer to execute a tab. Tab stops are set to 10 spaces. If you use a colon to separate statements, UniData concatenates the items. Unless a PRINT expression ends with a colon, UniData executes a carriage return after printing the line. If the output from the PRINT statement exceeds the current page width, it wraps to the next line. Tip: You can use the UniBasic @ function with the PRINT command to place the cursor and/or direct the terminal to take some action. Execute the ECL REUSE.ROW command to determines whether a line feed is executed when the UniBasic PRINT @ function references column only. For example, PRINT @(10) rather than PRINT @(3,10). The PRINT statement interprets two consecutive nonprinting ASCII characters (such as CHAR(192):CHAR(192)) as one character when displaying data. To suppress the line feed at the end of displayed text, place a colon at the end of the PRINT or DISPLAY statement. 277 Chapter 1: UniBasic commands and functions Syntax PRINT [ON num.expr] [print.expr] Parameters The following table describes each parameter of the syntax. Parameter Description ON num.expr Specifies a target print file. If you do not use the ON clause, the data is printed based on the last PRINTER command executed: PRINTER OFF – The data prints on the display terminal. print.expr PRINTER ON – The data prints on the system printer. Specifies an expression to print. It can be any valid UniBasic expression. If you do not specify a print.expr, a PRINT statement sends a line feed character to the printer or file. Examples In the following example, the program segment prints HI THERE on the system printer: PRINTER ON PRINT "HI THERE" In the next example, the program statement sends the value of variable X concatenated to "X = " to the file specified by unit 10: PRINT ON 10 "X = ":X In the next example, the @ function is included with a terminal option. -1 clears the screen before printing. PRINT @(-1):"Enter true or false: " INPUT answer,5_ In the next example, the comma separation character prints X, Y, a string separated by tabs, X+Y, tabs twice, then prints another string, and finally print the average of X and Y using the INT function: X = 5 ; Y = 7 PRINT X,Y,"Total = ":X+Y,,"Average = ":INT((X+Y)/2) The result is: 5 7 Total = 12 Average = 6 Each item is separated by tabs as the result of the comma separation character. A colon causes all data items to be concatenated. The following program demonstrates the use of the colon at the end of the PRINT statement to suppress the line feed issued by UniBasic at the end of displayed text. The first PRINT statement does not end in a colon. Therefore, UniBasic issues a carriage return and prints a question mark (the default prompt character). The second PRINT statement ends in a colon. In this case, UniBasic displays the default prompt character and waits on the same line with the PRINT statement. PRINT INPUT PRINT PRINT 278 "Enter character to display" X "The character you entered was(1): ":X "Enter character to display": PRINTER INPUT X PRINT "The character you entered was(2): ":X This program produces the following output (with input from the user): Enter character to display ?* The character you entered was(1): * Enter character to display?# The character you entered was(2): # Related commands Language Command UniBasic @, CRT, GETPTR, INPUTERR, PRINTER, PRINTER CLOSE UniData SETPTR For information, see the UniData Commands Reference. PRINTER The UniBasic PRINTER command directs output of PRINT, FOOTING, HEADING, and PAGE statements not sent to a file (those executed without the ON clause). If you specify ON, UniData directs all output to the system printer. If you specify OFF, UniData directs all output to the terminal screen. PRINTER ON causes runtime error messages to print on the system printer. Note: If the printer and your computer are not communicating properly when you execute a print command (for example, a PRINT statement after a PRINTER ON command), UniData generates an error. Syntax PRINTER {ON | OFF} Examples In the following example, the program statement sends all future report output (data from PRINT, FOOTING, HEADING, and PAGE commands) to the printer: PRINTER ON PRINTER CLOSE The UniBasic PRINTER CLOSE command sends data stored in either a print file or a print buffer to the print queue. The ON clause does not physically close the print file. Instead, it sends its contents to a print buffer, leaving the file empty. Then you can send additional data to the same print file to begin a new set of data to be printed. As many as 31 print files can be open at the same time. The PRINTER CLOSE statement does not generate a new line at the end of a page. UniBasic is in control of page feeds or generating new line equivalents. Note: Data in a print file is automatically sent to the print queue if the program ends or issues a PRINTER CLOSE statement. 279 Chapter 1: UniBasic commands and functions Syntax PRINTER CLOSE [ON num] Examples In the following example, the program statement sends the current contents of print file 5 to the print queue: PRINTER CLOSE ON 5 Related commands Language Command UniData SETPTR For information, see the UniData Commands Reference. PRINTERR The UniBasic PRINTERR command prints error messages stored in the UniData system message file or in a user-defined file. To obtain a message from a user-defined error message file, you must open the file first. The UniBasic commands ABORT and PRINTERR return the system message you specify by ID in the command. You can also retrieve system messages using a UniBasic program by opening the system message file and reading a message record by ID. Note: ENGLISH.MSG is the default system message file that is activated when you install UniData. If you execute udtlang.config to select a language group, a different system message file could be activated. To find out which language is installed on your system, execute the ECL command SET.LANG CURRENT. For more information, see UniData International. Syntax PRINTERR expr [FROM file.var] Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies a dynamic array that consists of two elements. The first element is the key for a record in the error message file. The second element is a parameter that some of the format codes use. For format codes, see the following table. Attribute marks (@AM or @FM) delimit elements. FROM file.var Specifies a file from which to extract a user-defined error message. The default is the UniData error message file. Creating a user-defined error message Error messages in the UniData error message file consist of format codes and literal strings. The following table describes the codes you can include in error messages. 280 PRINTERR Code Description A Extracts the next element in expr. A(n) Extracts the next element in expr, left-justified in a string of length n. C Clears the screen. D Enters the date in internal format. E literal Enters the message ID at the beginning of the message enclosed in brackets, followed by an optional literal string. H literal Prints literal. L Prints a carriage return/line feed. You must specify L (carriage return/ line feed) explicitly. L(n) Prints n carriage returns/line feeds. R(n) Extracts the next element in expr, right-justified in an attribute of n blanks. S(n) Prints n spaces. T Enters the time in internal format. W(n) Pauses for n seconds before continuing to display the message. X Skips the next parameter passed to the UniData message printing routine. Examples In the following example, the UniData udtlang.MSG file contains error message 4432 and a userdefined file (S_ERR) contains error message E009. These messages contain the following: Message 4432 in udtlang.MSG L E FILE A(10) H DOES NOT EXIST L H CAN’T PROCEED! L D L T L Message E009 in S_ERR E A L(2) H => ERR S(6) L H IS NOT PROPERLY SPECIFIED L The following code segment produces an error message if the file you enter for FNAME cannot be found or you enter 12 for VAR1: OPEN "S_ERR" TO E_FILE ELSE STOP "S_ERR NOT FOUND" INPUT FNAME INPUT VAR1 ER1 = "4432":@FM:FNAME ER2 = "E009":@FM:"VAR1" OPEN FNAME TO TFILE ELSE PRINTERR ER1 STOP END IF VAR1 > 10 THEN PRINTERR ER2 FROM E_FILE 281 Chapter 1: UniBasic commands and functions If you enter file_test for FNAME and file_test cannot be found, the program segment produces the following error message: [4432] FILE test_file DOES NOT EXIST CAN'T PROCEED! 19 Jan 1996 10:34:19 If you enter 12 for VAR1, the program segment produces the following error message: =>ERR [E009] VAR1 IS NOT PROPERLY SPECIFIED PROCREAD The UniBasic PROCREAD command assigns the string value of the primary input buffer of the calling Proc to a variable. PROCREAD can be used to access the primary input buffer of a calling proc. Note: A proc is a PQ-type VOC record. Syntax PROCREAD var {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies variable to which to assign the string value of the primary input buffer of the calling proc. THEN statements END THEN executes if this program was called by a proc. END is required to terminate multiline THEN statements. ELSE statements END ELSE executes if this program was not called by a proc. END is required to terminate multiline ELSE statements. Examples In the following example, the program segment assigns the string value in the primary input buffer to ARGUMENTS. If the program had been called by something other than a proc, the program prints a two-line error message. PROCREAD ARGUMENTS ELSE PRINT "ERROR!" PRINT "DIALOUT MUST BE CALLED FROM A PROC" ABORT END The following sample Proc loads the UniBasic program name proc.test into the data stack (Hproc.test), turns on that stack (STON), and loads “ONE” into the primary output buffer (HONE). The next command (P) executes the data stack entry, which runs proc.basic. Finally, D0 displays 282 PROCREAD the contents of the active input buffer. The program proc.test prints after the proc, and a sample execution of the proc follows the program: PQ C C name: proc.one C test the interface of basic and PROC. C Hproc.test STON HONE P D0 The following globally cataloged program, proc.test, is executed by the preceding proc. The INPUT statement reads from the currently active output buffer, which the proc loaded with “ONE”. *------------------------------------------------------------------------* subdirectory: interface * program name: proc.test * version : 1.6 or later * compile mode: any * catalog : y * catalog flag: local * test for : accepting passed arguments from a proc and writing * data to PROC data buffer (PROCWRITE). * called by : any proc or executed at the ECL prompt *-------------------------------------------------------------------------* * PROGRAM proc.basic $BASICTYPE 'R' PRINT '*******************' PRINT 'TEST --> PROCREAD ' PRINT '*******************' PROCREAD pname THEN len = LEN(pname) PRINT "The last command executed is stored in the primary input buffer." PRINT "The last 10 characters of the 1st buffer are :":pname[0,len] PRINT "The length of the primary input buffer is :":LEN(pname) END ELSE PRINT "Not run from PROC." END PRINT '*******************' PRINT 'TEST --> PROCWRITE' PRINT '*******************' INPUT procname IF procname = 'ONE' THEN letters = "abcdefg,1234567,ABCDEFG,tuvwxyz," string = '' limit = 512 FOR I = 1 TO limit STEP 32 string := letters NEXT I PRINT "String length = ":LEN(string) END ELSE string = "ONE TWO THREE FOUR FIVE" 283 Chapter 1: UniBasic commands and functions END PROCWRITE string END The preceding proc and program produce the following output: :wproctest ******************* TEST --> PROCREAD ******************* The last command executed is stored in the primary input buffer. The last 10 characters of the 1st buffer are :wproctest The length of the primary input buffer is :9 ******************* TEST --> PROCWRITE ******************* ?ONE String length = 512 abcdefg,1234567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,ab cdefg,1234567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcd efg,1234567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcdef g,1234567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcdefg, 1234567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcdefg,12 34567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcdefg,1234 567,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz,abcdefg,123456 7,ABCDEFG,tuvwxyz,abcdefg,1234567,ABCDEFG,tuvwxyz, Related commands Language Command UniBasic PROCWRITE PROCWRITE The UniBasic PROCWRITE command writes data to the primary input buffer of the calling Proc. PROCWRITE overlays any data in the primary input buffer with the new data in PROCWRITE. Syntax PROCWRITE expr Examples In the following example, the program segment writes the contents of ANSWER to the primary input buffer: PRINT "SEND RESULTS TO THE PRINTER? (Y OR N)" INPUT ANSWER, Y IF ANSWER = "Y" THEN PRINTER ON ... END PROCWRITE ANSWER Note: Another example is provided with PROCREAD. 284 PROGRAM Related commands Language Command UniBasic PROCREAD PROGRAM The UniBasic PROGRAM command defines the name of the current main program. This statement is optional. It is used for documentation purposes only. The PROGRAM statement must be the first noncomment statement in the program. Syntax PROGRAM prog.name Examples In the following example, the program segment declares the program name as BOOKS: REM This is a program to bill customers PROGRAM BILLS Related commands Language Command UniBasic SUBROUTINE UniData BASIC, CATALOG For information, see the UniData Commands Reference. PROMPT The UniBasic PROMPT command sets the prompt displayed by the INPUT command to a specified single-byte character. If str.expr is longer than one character, UniData uses the first character as the prompt. You cannot set the prompt to a multibyte character. Data received from a DATA statement displays after the prompt. If you want to suppress the default prompt character, set the prompt to an empty string. The default prompt character is the question mark. Tip: Setting the prompt to an empty string also suppresses display of input from a DATA statement on the terminal screen. For example: PROMPT "" DATA "mypassword" INPUT PASSWD will not echo “mypassword” to the terminal screen. The PROMPT statement must precede the DATA statement. Data input from the keyboard will still echo on the display terminal. When you want to display text on the screen and have the cursor remain at the end of the displayed text awaiting user input, place a colon at the end of the PRINT or DISPLAY statement. 285 Chapter 1: UniBasic commands and functions Syntax PROMPT str.expr Examples In the following example, the contents of variable PSTRING (in this case, an asterisk) become the new prompt. When an INPUT command is used in the program, an asterisk appears at the current cursor position on the display terminal. PSTRING = "*" PROMPT PSTRING Related commands Language Command UniBasic IN, INPUT, INPUT @, INPUTIF, INPUTTRAP protocolLogging This function will start or stop logging. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax protocolLogging(log_file, log_action, log_level) Parameters The following table describes each parameter of the syntax. Parameter Description log_file The name of the file to which the logs will be recorded. The default log file name is httplog which is created under the current directory. log_action log_level Either “ON” or “OFF.” The default is “OFF”. The detail level of logging from 0 - 10. See table below. The following table describes each log level and detail. Parameter Description 0 No logging. 1 Socket open/read/write/close action (no real data) HTTP request: host inform) 2 Level 1 logging plus socket data statistics (size, and so forth). 3 Level 2 logging plus all data actually transferred. 4-10 More detailed status data to assist debugging. The following table describes the status of each return code. 286 PWR Return codes Status 0 Success. 1 Failed to start logging. PWR The UniBasic PWR function raises expr1 to the power of expr2. Note: PWR is synonymous with two asterisks (**) or ^. Syntax PWR(num.expr1, num.expr2) Examples In the following example, the program segment raises variable X to the power of 3, first using exponentiation operator **, then using the PWR function, and finally using the exponentiation operator ^. The results are identical. X = 2 PRINT X**3 PRINT PWR(X,3) PRINT X^3 Related commands Language Command UniBasic ^ QUOTE The UniBasic QUOTE function encloses a string expression in double quotation marks. Syntax QUOTE(str.expr) Synonyms DQUOTE Examples In the following example, the program segment encloses the string stored in VAR2 with double quotation marks, and then stores that string (“STRING2”) in VAR3: VAR2 = "STRING2" VAR3 = QUOTE(VAR2) In the following example, the program statement uses DQUOTE to print “This is a test”: 287 Chapter 1: UniBasic commands and functions PRINT DQUOTE ('This is a test') In the next example, the program segment prints “‘This is another test’”: X = "This is another test" PRINT DQUOTE(X) Related commands Language Command UniBasic SQUOTE RAISE The UniBasic RAISE function raises all UniData delimiters to the next level. UniData raises attribute marks to record marks, value marks to attribute marks, and subvalue marks to value marks. Syntax RAISE(str.expr) Examples In the following example, the program segment raises all delimiters to the next level: ARRAY = 'Harry Sims':@VM:'114 W. Smith':@SVM:'Suite 220' ARRAY = RAISE(ARRAY) This results in the following array: ARRAY = 'Harry Sims':@FM:'114 W. Smith':@VM:'Suite 220' Related commands Language Command UniBasic LOWER READ The UniBasic READ command reads a record from a file and assigns its contents to a dynamic array. UniData assigns the first attribute of the record to the first position of the array, the second attribute to the second position, and so on. If UniData cannot find the record you specify, it executes the ELSE clause and returns dyn.array.var empty. Note: This command does not check for locks. If you are operating in a multiuser environment, you must use record locks to prevent more than one user from accessing the same record at the same time. For more information about UniBasic record locking, see Developing UniBasic Applications. 288 READ Warning: Do not use UniBasic READ commands to open or modify binary data in DIR-type files (for example, BP). Doing so could corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Syntax READ dyn.array.var FROM [file.var,] record.ID.expr [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. The default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies a record to read. ON ERROR statements Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READ, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 2 A read error occurred. 5 An encryption error occurred during the READ operation. Examples In the following example, the program segment reads a record from the CLIENTS file with ID CLIENT.ID. If the record ID is found, UniData executes the subroutine PROCESS.CLIENT. Otherwise, UniData prints a message and the program performs the subroutine REPROMPT. READ CLIENT.REC FROM CLIENT, CLIENT.ID THEN GOSUB PROCESS.CLIENT END ELSE 289 Chapter 1: UniBasic commands and functions PRINT 'NO CLIENT REC FOR 'CLIENT.ID END Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READL, READU, READV, READVL, READVU, WRITE READBCK The first READBCK command retrieves the alternate key set by SETINDEX, then each subsequent READBCK retrieves the previous alternate key value in the index. The corresponding record is read into a dynamic array, and the record ID is assigned to the @ID variable. Note: This command does not check for locks. If you are operating in a multiuser environment, you must use record locks to prevent more than one user from accessing the same record at the same time. For more information about UniBasic record locking, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in descending order based on an indexed attribute. Before executing READBCK, , you must set the alternate key value with the SETINDEX command. The SETINDEX parameters BUFFER.KEYS and VALIDATE.KEY determine, respectively, whether the buffering mechanism is used and whether keys are validated when READBCK executes. For details, see SETINDEX.READBCK sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READBCK dyn.array.var [FROM file.var] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. 290 READBCKL Parameter Description THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END STATUS function return values After you execute READBCK, the STATUS function returns one of the values described in the following table. Parameter Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. Examples In the following example, the program segment sets the index to the first record that contains Smith, and then reads that record and the previous four: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp FOR X = 1 TO 5 READBCK rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP NEXT X END The preceding program produces the following results: Marge, Smith Smith Widgets Pearl, Sloane Harvard Assoc. Reginald, Sklar Culver Excavating Alexandria, Singleton Vintech Inc. Larry, Singh Smith Widgets Note: This program reads the records even if the records are locked by another user. Related commands Language Command UniBasic READBCKL, READBCKU, READFWD, READFWDL, READFWDU, READXBCK, READXFWD, SELECTINDEX, SELECTINFO UniData BUILD.INDEX, CREATE.INDEX, DUP.STATUS For information, see the UniData Commands Reference. READBCKL The first READBCKL command retrieves the alternate key set by SETINDEX, and then each subsequent READBCKL retrieves the previous alternate key in the index. The corresponding record 291 Chapter 1: UniBasic commands and functions is read into a dynamic array, and the record ID is assigned to the @ID variable. READBCKL checks for locks. If the record is available, it sets a shared (L) lock before reading the record. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in descending order based on an indexed attribute. Before executing READBCKL, , you must set the alternate key value with the SETINDEX command. The SETINDEX parameters BUFFER.KEYS and VALIDATE.KEY determine, respectively, whether the buffering mechanism is used and whether keys are validated when READBCKL executes. For details, see SETINDEX.READBCKL sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READBCKL dyn.array.var [FROM file.var] [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READBCKL dyn.array.var [FROM file.var] [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is already locked. If you do not specify the LOCKED clause, and if the record is locked, UniData waits until the record is available. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END 292 THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful, the current alternate key value is not set by the SETINDEX command, or UniData cannot locate the current alternate key value (for example, when UniData reaches the end of the alternate index). END is required to terminate multiline ELSE statements. READBCKU STATUS function return values After you execute READBCKL, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. Examples This example uses the following program to lock the CLIENT file for two minutes: OPEN "CLIENTS" TO CLIENT.FILE ELSE STOP FILELOCK CLIENT.FILE LOCKED PRINT "CLIENTS FILE already locked." SLEEP 120 FILEUNLOCK CLIENT.FILE If you execute the following program: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp FOR X = 1 TO 5 READBCKL rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP NEXT X END Notice that execution halts on the second program until the first program unlocks the CLIENTS file. This is because commands that set shared locks cannot access files locked with exclusive locks (FILELOCK sets an exclusive lock). Note: If the first program had set a shared lock, the second program would have been able to read the records. Related commands Language Command UniBasic READBCK, READBCKU, READFWD, READFWDL, READFWDU, READXBCK, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX, DEFAULT.LOCKED.ACTION, DUP.STATUS For information, see the UniData Commands Reference. READBCKU The first READBCKU command retrieves the alternate key set by SETINDEX, and then each subsequent READBCKU retrieves the previous alternate key value in the index. The corresponding record is read into a dynamic array, and the record ID is assigned to the @ID variable. READBCKU checks for locks. If the record is available, it sets an exclusive (U) lock before reading the record. 293 Chapter 1: UniBasic commands and functions Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in descending order based on an indexed attribute. Before executing READBCKU, you must set the alternate key value with the SETINDEX command. The SETINDEX parameters BUFFER.KEYS and VALIDATE.KEY determine, respectively, whether the buffering mechanism is used and whether keys are validated when READBCKU executes. For details, see SETINDEX.READBCKU sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READBCKU dyn.array.var [FROM file.var] [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READBCKU dyn.array.var [FROM file.var] [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is already locked. If you do not specify the LOCKED clause, and if the record is locked, UniData waits until the record is available. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END 294 THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful, the current alternate key value is not set by the SETINDEX command, or UniData cannot locate the current alternate key value (for example, when UniData reaches the end of the alternate index). END is required to terminate multiline ELSE statements. READFWD STATUS function return values After you execute READBCKU, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. Examples This example uses the following program to lock the CLIENT file for two minutes: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp READBCKU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP SLEEP 60 END If you execute the following program: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp FOR X = 1 TO 5 READBCKU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP NEXT X END Notice that execution halts on the second program until the first program unlocks the record associated with “Smith.” This is because commands that set exclusive locks cannot access records lock with any kind of lock. Related commands Language Command UniBasic READBCK, READBCKL, READFWD, READFWDL, READFWDU, READXBCK, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX, DEFAULT.LOCKED.ACTION, DUP.STATUS For information, see the UniData Commands Reference. READFWD The first READFWD command retrieves the alternate key set by SETINDEX, and then each subsequent READFWD retrieves the next alternate key value in the index. UniData reads the corresponding record into a dynamic array, and then assigns the record ID to the @ID variable. 295 Chapter 1: UniBasic commands and functions Note: This command does not check for locks. If you are operating in a multiuser environment, you must use record locks to prevent more than one user from accessing the same record at the same time. For more information about UniBasic record locking, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in ascending order based on an indexed attribute. Before executing READFWD, you must set the alternate key value with the SETINDEX command. The SETINDEX parameters BUFFER.KEYS and VALIDATE.KEY determine, respectively, whether the buffering mechanism is used and whether keys are validated when READFWD executes. For details, see SETINDEX.READFWD sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READFWD dyn.array.var [FROM file.var] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READFWD, the STATUS function returns one of the values described in the following table. 296 Value Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READFWDL Examples In the following example, the program segment sets the index to the first record that contains Smith, and then reads that record and the next four: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Singh' ON tmp FOR X = 1 TO 5 READFWD rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP NEXT X This program produces the following results: Charles, Singh Goddard Fabrics Larry, Singh Smith Widgets Alexandria, Singleton Vintech Inc. Reginald, Sklar Culver Excavating Pearl, Sloane Harvard Assoc. Note: This program reads the records even if the records are locked by other users. Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWDL, READFWDU, READXBCK, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX, DUP.STATUS For information, see the UniData Commands Reference. READFWDL The first READFWDL command retrieves the alternate key set by SETINDEX, and then each subsequent READFWDL retrieves the next alternate key value in the index. UniData reads the corresponding record into a dynamic array, and then assigns the record ID to the @ID variable. READFWDL checks for locks. If the record is available, it sets a shared (L) lock. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in ascending order based on an indexed attribute. Before executing READFWDL, you must set the alternate key value with the SETINDEX command. The SETINDEX parameters BUFFER.KEYS and VALIDATE.KEY determine, respectively, whether the buffering mechanism is used and whether keys are validated when READFWDL executes. For details, see SETINDEX.READFWDL sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READFWDL dyn.array.var [FROM file.var] [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} 297 Chapter 1: UniBasic commands and functions READFWDL dyn.array.var [FROM file.var] [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is already locked. If you do not specify the LOCKED clause, and if the record is locked, UniData waits until the record is available. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READFWDL, the STATUSfunction returns one of the values described in the following table. Value Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. Examples This example uses the following program to lock the CLIENT file for two minutes: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp READFWDU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP SLEEP 120 END 298 READFWDU If you execute the following program: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp FOR X = 1 TO 5 READFWDU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP NEXT X END Notice that execution halts on the second program until the first program unlocks the CLIENTS file. This is because commands that set shared locks cannot access files locked with exclusive locks (FILELOCK sets an exclusive lock). Note: If the first program had set a shared lock, the second program would have been able to read the records. Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWD, READFWDU, READXBCK, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX, DEFAULT.LOCKED.ACTION, DUP.STATUS For information, see the UniData Commands Reference. READFWDU The first READFWDU command retrieves the alternate key set by SETINDEX, and then each subsequent READFWDU retrieves the next alternate key value in the index. UniData reads the corresponding record into a dynamic array, and then assigns the record ID to the @ID variable. READFWDU checks for locks. If the record is available, READFWDU sets an exclusive (U) lock before reading the record. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Using this command in a loop, a UniBasic program retrieves records in ascending order based on an indexed attribute. Before executing READFWDU, you must set a pointer to the alternate key value with the SETINDEX command. READFWDU sets the STATUS function return value to 10 if UniBasic detects a duplicate alternate index key value and you have executed the ECL command DUP.STATUS ON during the current session. Syntax READFWDU dyn.array.var [FROM file.var] [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READFWDU dyn.array.var [FROM file.var] [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} 299 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is already locked. If you do not specify the LOCKED clause, and if the record is locked, UniData waits until the record is available. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READFWDU, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 10 UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. Examples This example uses the following program to lock the CLIENT file for two minutes: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp READFWDU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> ELSE STOP SLEEP 120 END If you execute the following program: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'Smith' ON tmp FOR X = 1 TO 5 READFWDU rec FROM tmp THEN PRINT rec<1>:", ":rec<2>:" ":rec<3> 300 READL ELSE STOP NEXT X END Notice that execution halts on the second program until the first program unlocks the record associated with “Smith.” This is because commands that set exclusive locks cannot access records lock with any kind of lock. Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWD, READFWDL, READXBCK, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX, DEFAULT.LOCKED.ACTION, DUP.STATUS For information, see the UniData Commands Reference. READL The UniBasic READL command reads the specified record from a file and assigns its contents to a dynamic array. UniData assigns the first attribute of the record to the first position of the array, the second attribute to the second position, and so on. READL checks for locks. If the record is available, it sets a read-only lock on the record, preventing other lock-checking commands from updating it. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Warning: Do not use UniBasic READ and WRITE commands to open or modify binary data in DIR-type files (for example, BP). Doing so could corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Syntax READL dyn.array.var FROM [file.var,] record.ID.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READL dyn.array.var FROM [file.var,] record.ID.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a target dynamic array for the data being read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. The default file is one for which no file variable is assigned in the OPEN statement. 301 Chapter 1: UniBasic commands and functions Parameter Description ON ERROR statements Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is already locked. If you do not specify the LOCKED clause, and if the record is locked, UniData waits until the record is available. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END STATUS function return values After you execute READL, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 1 UniData was unable to read the record. n The record is locked. The user number of the user who locked the record. Examples This example uses the following program to lock the ORDERS file for two minutes: OPEN "ORDERS" TO ORDER.FILE ELSE STOP FILELOCK ORDER.FILE LOCKED PRINT "ORDERS FILE already locked." SLEEP 120 FILEUNLOCK ORDER.FILE If you immediately execute the following program: OPEN "ORDERS" TO tmp ELSE STOP READL rec FROM tmp,'941' THEN PRINT rec LOCKED PRINT "Record locked, try again later" END the second program prints “Record locked, try again later.” Related commands 302 Language Command UniBasic CLOSE, DELETE, OPEN, READBCKREAD, READU, READV, READVL, READVU, WRITE READLIST Language Command UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. READLIST The UniBasic READLIST command assigns the values in an active select list to a dynamic array. Each select list element becomes an attribute in the dynamic array. Syntax READLIST dyn.array.var [FROM list.num] {THEN statements [END] | ELSE statements [END]} Note: Use the following syntax in BASICTYPE M: READLIST dyn.array.var FROM list.num [, acct.name] [SETTING count.var] {THEN statements [END] | ELSE statements [END]} If you create a list under an account other than the current one, you can specify the account with acct.name. The SETTING clause sets the number of elements in the list to count.var. In BASICTYPE P, use the READSELECT command with the following syntax: READSELECT dyn.array.var [FROM list.name] {THEN statements [END] | ELSE statements [END]} Synonyms READSELECT (BASICTYPE P only) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a dynamic array to contain the values removed from the select list. FROM list.num Specifies which select list (0-9) you want to use. If you do not specify a list.num, UniData reads the default list (0). If no items are available in the list, UniData executes the ELSE clause. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the list does not exist. END is required to terminate multiline ELSE statements. Examples In the following example, the program segment selects the IDs in the INVENTORY file to select list 0, and then builds a dynamic array of the items for which quantity in stock is greater than 10. The last program statement prints the select list to show its contents. OPEN 'INVENTORY' TO INV.FILE ELSE STOP SELECT INV.FILE DONE = 0 LOOP 303 Chapter 1: UniBasic commands and functions READNEXT INV.ID ELSE DONE = 1 WHILE NOT(DONE) DO READ INV.REC FROM INV.FILE,INV.ID ELSE PRINT "No INVENTORY RECORD: ":INV.ID END IF INV.REC<6> > 9 THEN READLIST LIST.ITEM ELSE LIST.ITEM = " " END REPEAT PRINT LIST.ITEM Related commands Language Command UniBasic DELETELIST, FORMLIST, GETLIST, READNEXT, SELECT, SELECTINDEX, SELECTINFO, WRITELIST UniData SQL SELECT For information, see the UniData SQL Commands Reference UniQuery DELETELIST, GETLIST, SELECT, SAVE.LIST, SSELECT For information, see the UniQuery Commands Reference READNEXT The UniBasic READNEXT command assigns the next record ID from an active select list to a variable. Note: READNEXT does not actually read the record, but assigns it to a variable. After the variable is assigned, you can use it within a READ statement to access it. As an example, a customer transaction might require that data be read in a particular sequence. The sequence is determined by using a sorted SELECT statement to select IDs in the appropriate order and then using the READNEXT statement to assign an ID to a variable. Note: READNEXT performs differently with BASICTYPEs M and P as shown in the following syntax: READNEXT var FROM list.name {, acct.name} [SETTING count.var] {THEN statements [END] | ELSE statements [END]} The SETTING clause assigns the number of elements in the list to the variable count.var. Syntax READNEXT id.var [, val.var[, subval.var]] [FROM list.num.expr] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} READNEXT and multivalued attributes Select lists used by READNEXT can contain an optional value and subvalue positions (if you create the list using the BY.EXP keyword). The select list created by using this keyword is sorted based on a multivalued or subvalued attribute. The select list contains, in each of two attributes, the record ID and position of the sorted value or subvalue. The READNEXT command passes the value or subvalue positions to val.var and subval.var. A subsequent READ statement might access the appropriate value using val.var (and subval.var). 304 READNEXT Note: When you create a select list using the BY.EXP keyword against a multivalued or multisubvalued attribute, the resulting select list contains the multivalue position in the second value of the attribute and the multi-subvalue position in the third value of the attribute. If a BY.EXP select statement is executed against an attribute with a value code specifier of MV, the third value in each attribute in the resulting select list is -5 as the following shows: 001: 785}1}-5 002: 796}1}-5 003: 812}1}-5 ... READNEXT assigns the values and subvalues of each record ID to val.var and subval.var. The val.var and subval.var each can contain more than one data value (separated by value or subvalue marks) if you use more than one BY.EXP keyword when you create the select list. In this case, the first subvalue in val.var and in subval.var corresponds to the value and subvalue position of the attribute in the first BY.EXP expression. The second subvalue in val.var and in subval.var corresponds to the value and subvalue position of the attribute in the second BY.EXP clause, and so forth for each successive BY.EXP clause. Parameters The following table describes each parameter of the syntax. Parameter Description id.var Specifies a variable to contain the value of the next record ID. ,val.var,subval.var Specifies a value and subvalue to read. FROM list.num.expr Specifies which select list (0-9) you want to use. If you do not specify list.num, the default (0) list is used. If no items are available in the list, UniData executes the ELSE clause. ON ERROR statements Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. Examples In the following example, the program segment reads 10 IDs from select list 1, and then reads the records associated with those IDs. If a record ID is not found in the default system file, the program displays the message NOT FOUND. FOR I = 1 TO 10 READNEXT ID FROM 1 ELSE SHORT.LIST = 1 THEN READU REC FROM CUST,ID ELSE PRINT "NOT FOUND" END NEXT I 305 Chapter 1: UniBasic commands and functions In the next example, the program selects all Canadian clients, and then executes READNEXT to read and display the records for the first 22: EXECUTE 'SELECT CLIENTS WITH COUNTRY = "Canada"' EXECUTE "SAVE.LIST 'canadians'" OPEN 'CLIENTS' TO CLIENT.FILE ELSE ABORT GETLIST 'canadians' SETTING LIST.CNT ELSE PRINT CLIENT:" SAVELISTS ID ‘canadians’ CANNOT BE FOUND";STOP PRINT @(-1) FOR I = 1 TO 22 READNEXT ID ELSE EXIT READ REC FROM CLIENT.FILE, ID THEN PRINT @(5,I):REC<1>:@(20,I):REC<2> END ELSE PRINT "CANNOT FIND RECORD":ID END NEXT I CLEARSELECT END Related commands Language Command UniBasic DELETELIST, FORMLIST, GETLIST, READLIST, SELECT, SELECTINDEX, SELECTINFO, WRITELIST UniData SQL SELECT For information, see the UniData SQL Commands Reference UniQuery DELETELIST, GETLIST, SELECT, SAVE.LIST, SSELECT, For information, see the UniQuery Commands Reference READNEXTTUPLE The UniBasic READNEXTTUPLE command assigns the next entire record to a variable. The record ID is obtained from an active select list that was created by a UniData SQL SELECT statement during the current work session. READNEXTTUPLE creates a dynamic array delimited by attribute marks (@AM). The attribute marks are entered by the UniData SQL SELECT statement. Tip: Do not use the UniData SQL UNNEST command in the SQL statement that creates the ID list. UniData might not return the entire record with attribute marks, value marks, and/or subvalue marks if you use UNNEST. Syntax READNEXTTUPLE dyn.array.var FROM file.name.expr {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. 306 READSELECT Parameter Description dyn.array.var Specifies the dynamic array to contain the record. FROM file.name.expr Specifies the file from which to read the next record ID. file.name.expr must have been created during the current session by: An EXECUTESQL statement with a TO clause in the UniBasic program. A UniData SQL statement executed at the ECL prompt before the program was run. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program segment executes a UniData SQL statement and stores the output in an internal result file called SQL_INPUT. The READNEXTTUPLE statement then reads the records stored in SQL_INPUT until the last record item is read. The process converts the attribute marks to spaces and prints each record read. OUT.COMMAND = "SELECT NAME, ADDRESS, CITY" OUT.COMMAND := " FROM CLIENTS TO SQL_INPUT; " EXECUTESQL OUT.COMMAND DONE = 0 BPIOCP LOOP READNEXTTUPLE CLIENT.REC FROM "SQL_INPUT" ELSE DONE = 1 END UNTIL DONE DO CONVERT @AM TO " " IN CLIENT.REC CONVERT @VM TO","IN CLIENT.REC PRINT CLIENT.REC REPEAT END Related commands Language Command UniBasic EXECUTE, EXECUTESQL, @variables UniData SQLSELECT For information, see the Using UniData SQL READSELECT READSELECT is a synonym for the READLIST command. For more information, see READLIST, on page 303. 307 Chapter 1: UniBasic commands and functions Synonyms READLIST READSEQ The UniBasic READSEQ command reads the next record from a sequential file and assigns the data read to a variable. Note: Before you use READSEQ, you must open the file by using the OSOPEN or OPENSEQ command. If the file is a named pipe, you cannot use READSEQ to read it. You must use the OSBREAD command. Each read from the sequential file searches for a line feed character [CHAR(10)] to determine the end of the record. READSEQ maintains a pointer to the current position in the file (where the last record terminated). Syntax READSEQ var FROM seq.file.var {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies a variable to which to assign the record. FROM seq.file.var Specifies a sequential file from which to read the record. THEN statements END seq.file.var must be a sequential file opened by using an OPENSEQ or OSOPEN statement. THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program statement reads the next record in the file PORT.FILE and assigns it to the variable TAX.REC: READSEQ TAX.REC FROM PORT.FILE ELSE STOP "Can’t READSEQ TAX.REC" Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSBREAD, OSBWRITE, OSCLOSE, OSDELETE, OSOPEN, WRITESEQ, WRITESEQF readSocket Use the readSocket function to read data in the socket buffer up to max_read_size characters. 308 READT Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax readSocket(socket_handle, socket_data, max_read_size, time_out, blocking_mode, actual_read_size) Parameters The following table describes each parameter of the syntax. Parameter Description socket_handle The handle to the open socket. socket_data The data to be read from the socket. max_read_size The maximum number of characters to return. If this is 0, then the entire buffer should be returned. time_out The time (in milliseconds) before a return in blocking mode. This is ignored for non-blocking read. blocking_mode 0: using current mode 1: blocking 2: non-blocking actual_read_size The number of characters actually read. -1 if error. The following table describes the return status of each mode. Mode Return Status 0 - Non-Blocking The function will return immediately if there is no data in the socket. If the max_read_size parameter is greater than the socket buffer then just the socket buffer will be returned. 1 - Blocking If there is no data in the socket, the function will block until data is put into the socket on the other end. It will return up to the max_read_size character setting. The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. READT The UniBasic READT command reads the next record from a tape and assigns it to a variable. 309 Chapter 1: UniBasic commands and functions Note: Before you use the READT command, you must attach a tape drive with the T.ATT command. For information about tape commands, see the UniData Commands Reference. You must use the TAPELEN option for the T.ATT command and specify the length of the tape in megabytes. This command is intended for use with UniData tapes only. UniData uses the ASCII 0 character (CHAR(0)) as an end-of-record mark. Therefore, you cannot use ASCII 0 in any string variable in UniBasic. READT converts (CHAR(0)) to CHAR(128). Syntax READT [UNIT (mu.expr)] var {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description UNIT (mu.expr) Specifies the conversion code (first digit), and the unit number (second digit). UniData allows unit numbers from 0 through 9. mu.expr is optional. The default value is 00, indicating tape unit 0 and no conversion: 0 – No conversion (ASCII assumed) 1 – EBCDIC conversion 2 – Invert high bit 3 – Swap bytes var Specifies a variable to contain the record. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE statements END ELSE executes if the read is not successful or the record does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READT, the STATUS function returns one of the values described in the following table. 310 Value Description 0 Successful read. 1 End of file encountered. 2 End of tape encountered. 3 Tape not assigned. 4 Parity error. 5 Unknown hardware error. 6 Other unspecified error. READU Examples In the following example, the program segment first uses the ECL T.ATT command to reserve tape unit 0 and perform no conversion. Then the program segment reads all the records on the tape (until the end of the file or tape) and calls an internal subroutine that processes the record. PERFORM "T.ATT" DONE = 0 LOOP READT UNIT (00) TAX.RECORD ELSE DONE = 1 UNTIL DONE DO GOSUB PROCESS.RECORD REPEAT Related commands Language Command UniBasic RESIZET, REWIND, WEOF, WRITET UniData SETTAPE, T.ATT, T.DET For information, see the UniData Commands Reference. READU The UniBasic READU command reads a record from a file and assigns its contents to a dynamic array. READU checks for locks. If the record is available, it sets an exclusive lock and reads the record. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Warning: Do not use UniBasic READ and WRITE commands to open or modify binary data in DIR-type files (for example, BP). Doing so could corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Syntax READU dyn.array.var FROM [file.var,] record.ID.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READU dyn.array.var FROM [file.var,] record.ID.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a dynamic array to contain the record. 311 Chapter 1: UniBasic commands and functions Parameter Description FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. record.ID.expr ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies the record ID to use to retrieve the record. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute READU, the STATUS function returns one of the values described in the following table. Value Description 0 Successful read. 1 UniData was unable to read the record. n The record is locked. The user number of the user who locked the file is returned in n. Examples The following program segment is taken from the sample program in Developing UniBasic Applications. READU checks for locks. If the record is available, it sets an exclusive lock and reads the record into ORDER.REC. DISPLAY_DATA: * Display the current information in the desired record. This is * determined by the number the user entered (ORDER_NUMBER). READU ORDER.REC FROM ORDERS_FILE,ORDER_NUMBER THEN * Read with a lock so that no one else can modify it at the same time. RECORD_FOUND = 1 The record remains locked until the following program executes, which releases locks: WRITE ORDER.REC ON ORDERS_FILE,ORDER_NUMBER In the following example, the program segment assigns the record, read from the default file, to the variable INFO, and sets an exclusive lock on that record. UniData prints “Record locked” if the record 312 READV is locked by another program, or prints “File not found” if the record does not exist. If the default file is not found, the program ends. READU INFO FROM "IDENT" LOCKED PRINT "Record locked" ELSE PRINT "Record not found" Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READ, READL, READV, READVL, READVU, WRITE UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. READV The UniBasic READV command assigns the data from an attribute of a record to a variable. Note: READV ignores locks. To update a record, you should use the READVU command, which checks for locks. For an explanation of UniData locks, see Developing UniBasic Applications. Tip: To improve efficiency, use READV when only one or two attributes are needed from a record. If access to more attributes is needed, READ or MATREAD is more efficient. Syntax READV var FROM [file.var,] record.ID.expr, attribute.expr [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies a dynamic array to contain the attribute. FROM file.var, Specifies the file from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. record.ID.expr The default file is one for which no file variable is assigned in the OPEN statement. Specifies the record to read. attribute.expr Specifies the attribute to read. ON ERROR statements Specifies statements to execute if the READV statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. 313 Chapter 1: UniBasic commands and functions Parameter Description ELSE statements END ELSE executes if the read is not successful or the record does not exist. END is required to terminate multiline ELSE statements. Examples In the following example, the program segment reads CLIENT.NAME from the CLIENTS file, record ID 10034, attribute 2. If the record exists, UniData appends the attribute to string NAME.ARRAY1 using the short form of the replace command. Otherwise, UniData executes the ELSE clause. NAME.ARRAY1 = "Smith Jones Brown" OPEN "CLIENTS" TO CLIENT.FILE ELSE STOP READV CLIENT.NAME FROM CLIENT.FILE,"10034",2 THEN NAME.ARRAY1<-1> = CLIENT.NAME PRINT NAME.ARRAY1 END ELSE PRINT 'NO FILE FOR CLIENT ':CLIENT.ID END In the next example, you can use the READV command with an attribute.expr of 0 to verify that a record exists (for example, if you are assigning IDs sequentially in the CLIENTS file). Each time you need to create a new ID, you need to verify that the ID you selected is not in use. The following code accomplishes this task, incrementing the ID until an ID is available. LOOP READV CHECK FROM CLIENT,NEXT.ID,0 ELSE CHECK = 0 UNTIL CHECK NE 0 DO NEXT.ID += 1 REPEAT CLIENT.ID = NEXT.ID Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READ, READL, READU, READVL, READVU, WRITE READVL The UniBasic READVL command assigns the data from an attribute of a record to a variable. READVL checks for locks. If the record is available, it sets a shared lock before it reads the record. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. You generally use the READVL command when only one or two attributes are needed from a record. If access to more attributes is needed, READ or MATREAD is more efficient. Syntax READVL var FROM [file.var,] record.ID.expr, attribute.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} 314 READVL READVL var FROM [file.var,] record.ID.expr, attribute.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the variable to contain the attribute. FROM file.var, Specifies the file from which to read the attribute. If you do not specify a file with file.var, the data is read from the most recently opened default file. Specifies a record from which to read an attribute. record.ID.expr If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. The default file is one for which no file variable is assigned in the OPEN statement. Specifies an attribute from which to read. attribute.expr ON ERROR statements Specifies statements to execute if the READVL statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, READVL checks for locks on the record CARS in the default file. If the record is available, it sets a shared lock and reads the third attribute of the record. If the data is not found, UniData displays the message “NOT FOUND”. READVL MODEL FROM "CARS",3 ELSE PRINT "NOT FOUND" Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READ, READL, READU, READV, READVU, WRITE UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. 315 Chapter 1: UniBasic commands and functions READVU The UniBasic READVU command assigns the data from an attribute of a record to a variable. READVU checks for locks. If the record is available, it sets an exclusive lock before it reads the record. Tip: You can improve efficiency by using the READVU command when you need only one or two attributes from a record. If more attributes are necessary, or if you need to update more attributes, use the READU or MATREADU commands. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax READVU var FROM [file.var,] record.ID.expr, attribute.expr [ON ERROR statements] [LOCKED statements] {THEN statements [END] | ELSE statements [END]} READVU var FROM [file.var,] record.ID.expr, attribute.expr [LOCKED statements] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies a variable to contain the data read from the attribute. FROM file.var, Specifies the file from which to read the attribute. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. record.ID.expr The default file is one for which no file variable is assigned in the OPEN statement. Specifies a record in the file from which to read the data. attribute.expr Specifies an attribute within the file from which to read the data. ON ERROR statements Specifies statements to execute if the READVU statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. THEN statements END ELSE statements END 316 THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. READXBCK Examples The following program segment is taken from Developing UniBasic Applications. READVU checks for locks. If the record is available, it sets an exclusive lock and reads the multivalued attribute containing the order number the user wants to delete. DELETE_RECORD: * (Assuming the order #'s are on line 12) READVU ORDER_LINE FROM CLIENT_FILE,CLIENT_NUMBER,12 THEN LOCATE ORDER_NUMBER IN ORDER_LINE<1> SETTING POSITION THEN DEL ORDER_LINE<1,POSITION> END WRITEV ORDER_LINE ON CLIENT_FILE, CLIENT_NUMBER, 12 END In the next example, the program segment reads the seventh attribute of the record named in the variable ID from the INV file and stores the attribute in the variable SUPPL. If the record is locked, or if the default file cannot be found, UniData displays a read-error message. READVU SUPPL FROM INV,ID,7 LOCKED PRINT "Locked" ELSE GOTO 2010: Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READ, READL, READU, READV, READVL, WRITE UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. READXBCK The UniBasic READXBCK command reads the previous key in an alternate key index in much the same manner as the READBCK command, but does not read the associated record. READXBCK enables a program to read alternate keys without incurring the overhead of retrieving a record every time. Syntax READXBCK dyn.array.var [FROM file.var] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a dynamic array to which to assign the values read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. The default file is one for which no file variable is assigned in the OPEN statement. 317 Chapter 1: UniBasic commands and functions Parameter Description ON ERROR statements Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END THEN executes if the read is successful. END is required to terminate multiline THEN statements. ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWD, READFWDL, READFWDU, READXFWD, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX For information, see the UniData Commands Reference. READXFWD The UniBasic READXFWD command reads the next value in an alternate key index in much the same manner as the READFWD command, but does not read the associated record. READXFWD enables a program to read alternate keys without incurring the overhead of retrieving a record every time. Syntax READXFWD dyn.array.var [FROM file.var] [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a dynamic array to which to assign the values read. FROM file.var, Specifies a file variable from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal READ error occurs. ON ERROR statements The default file is one for which no file variable is assigned in the OPEN statement. Specifies statements to execute if the statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END 318 THEN executes if the read is successful. END is required to terminate multiline THEN statements. READXMLDATA Parameter Description ELSE statements END ELSE executes if the read is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWD, READFWDL, READFWDU, READXBCK, SELECTINDEX, SETINDEX UniData BUILD.INDEX, CREATE.INDEX For information, see the UniData Commands Reference. READXMLDATA After opening the XML document with the OPENXMLDATA function, read the document using the READXMLDATA function. UniBASIC returns the XML data as a dynamic array. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax READXMLDATA(xml_data_handle, rec) Syntax The following table describes each parameter of the syntax. Parameter Description xml_data_handle A variable that holds the XML data handle created by the OPENXMLDATA function. rec A mark-delimited dynamic array containing the extracted data. After you read the XML document, you can execute any UniBASIC statement or function against the data. Status codes The status code can be one of the following: Status code Description XML.SUCCESS Success XML.ERROR Failure XML.INVALID.HANDLE Invalid xml_data_handle XML.EOF End of data Examples The following example illustrates use of the READXMLDATA function: MOREDATA=1 319 Chapter 1: UniBasic commands and functions LOOP WHILE (MOREDATA=1) status = READXMLDATA(STUDENT_XML,rec) IF status = XML.ERROR THEN STOP “Error when preparing the XML document. “ END ELSE IF status = XML.EOF THEN PRINT “No more data” MOREDATA = 0 END ELSE PRINT “rec = “:rec END REPEAT RECORDLOCKED The UniBasic RECORDLOCKED function returns the lock status of the specified record or file. For an explanation of UniData locks, and for a sample program you can use to test this command, see Developing UniBasic Applications. Syntax RECORDLOCKED (file.var, rec.id.expr) Null value handling With null value handling on, the null value in file.var results in a RECORDLOCKED return value of -2 and a STATUS function return value of -12. The null value is a valid record ID and can be passed to the function in rec.id.expr. Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies the file on which to check lock status. The null value in file.var results in a RECORDLOCKED return value of -2. rec.id.expr Specifies the record on which to check lock status. RECORDLOCKED function return values The RECORDLOCKED function returns one of the values described in the following table. 320 Value Lock type Lock owner Locking command 4 exclusive you FILELOCK, SQL LOCK TABLE, implicit SQL TP lock escalation. 3 shared you FILELOCK, SQL LOCK TABLE, implicit SQL TP lock escalation. 2 exclusive you READU, RECORDLOCKU, SQL TP implicit record locking. 1 shared you READL, RECORDLOCKL, SQL TP implicit record locking. 0 The record is not locked. -1 shared another user READL, RECORDLOCKL, SQL TP implicit record locking. RECORDLOCKL Value Lock type Lock owner Locking command -2 exclusive another user READU, RECORDLOCKU, SQL TP implicit record locking. -3 shared another user FILELOCK, SQL LOCK TABLE, implicit SQL TP lock escalation. -4 exclusive another user FILELOCK, SQL LOCK TABLE, implicit SQL TP lock escalation. Note: When UDT.OPTIONS 35 is on, this function returns a value of -2 when another user has a READU lock on the record or file. STATUS function return values After you execute RECORDLOCKED, the STATUS function returns one of the values described in the following table. Value RECORDLOCKED return value Meaning n A number between -1 and -4. The record is locked. The user number of the user who owns the lock is returned in n. 0 0 The record is not locked. -1 -11 The file is NFA. Currently, RECORDLOCKED does not support NFA files. -2 -12 Invalid file type. file.var can contain the null value. -3 -13 System error: unknown user. Related commands Language Command UniBasic FILELOCK, FILEUNLOCK, RECORDLOCKL, RECORDLOCKU, RELEASE RECORDLOCKL The UniBasic RECORDLOCKL command checks for record locks. If the record is available, it sets a shared lock on the record. For an explanation of UniData locks, and for a sample program that you can use to test this command, see Developing UniBasic Applications. Syntax RECORDLOCKL [file.var,] record.ID.expr [ON ERROR statements] [LOCKED statements] Parameters The following table describes each parameter of the syntax. 321 Chapter 1: UniBasic commands and functions Parameter Description file.var, Specifies the file from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. The default file is one for which no file variable is assigned in the OPEN statement. Specifies a record to lock. record.ID.expr ON ERROR statements Specifies statements to execute if the RECORDLOCKL statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if another user has an exclusive lock on the record. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. Examples In the following example, the program statement sets a shared lock on the record HOLLY in the default file. If the record is already locked by another user, the program waits until the record is released. RECORDLOCKL "HOLLY" In the next example, the program segment sets a lock on the record with the ID Smith from file CLIENT.FILE. If the record is locked, UniData displays the message “THE RECORD IS ALREADY LOCKED”. RECORDLOCKL CLIENT.FILE,"Smith" LOCKED PRINT "THE RECORD IS ALREADY LOCKED" Related commands Language Command UniBasic FILELOCK, FILEUNLOCK, RECORDLOCKED, RECORDLOCKU, RELEASE UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. RECORDLOCKU The UniBasic RECORDLOCKU command checks for record locks. If the record is available, it sets an exclusive lock on the record. For an explanation of UniData locks, and for a sample program that you can use to test this command, see Developing UniBasic Applications. Syntax RECORDLOCKU [file.var,] record.ID.expr [ON ERROR statements] [LOCKED statements] 322 RELEASE Parameters The following table describes each parameter of the syntax. Parameter Description file.var, Specifies the file from which to read the record. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. The default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies a record to lock. ON ERROR statements Specifies statements to execute if the RECORDLOCKU statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. LOCKED statements Specifies statements to execute if the record is locked by another user. If you do not specify a LOCKED clause, the program waits until the lock on the record is released. Use the ECL command DEFAULT.LOCKED.ACTION BELL to make the terminal beep while you wait for UniData to unlock the record. Related commands Language Command UniBasic FILELOCK, FILEUNLOCK, RECORDLOCKED, RECORDLOCKL, RELEASE UniData DEFAULT.LOCKED.ACTION For information, see the UniData Commands Reference. RELEASE The UniBasic RELEASE command unlocks records and files locked by the same user process. If no files or records are locked, RELEASE has no effect. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax RELEASE [file.var [, record.ID.expr]] [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies a file to unlock. If you do not specify a file or a record, UniData releases all locks set by the same user process. 323 Chapter 1: UniBasic commands and functions Parameter Description ,record.ID.expr Specifies a record ID to unlock. If you do not specify a record with record.ID.expr, UniData releases all locked records within the file. ON ERROR statements Specifies statements to execute if the RELEASE statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. Examples The following program segment is taken from the sample program in Developing UniBasic Applications. In this program, the WRITE statement unlocks records so that locks are retained only as long as required. However, some error conditions could result in processing returning to the main routine with a record still locked. For this reason, the program segment includes a RELEASE statement. *-------------- Main Logic ----------------------------GOSUB INITIALIZE LOOP GOSUB DISPLAY_SCREEN GOSUB GET_ORDER_NUMBER UNTIL ORDER_NUMBER[1,1] = 'Q' GOSUB DISPLAY_DATA IF RECORD_FOUND THEN GOSUB GET_RECORD_COMMAND RELEASE REPEAT GOSUB EXIT In the next example, the program statement releases the record “COLO” in the file CONTACTS. Other locked records in this file remain locked. RELEASE CONTACTS,"COLO" Related commands Language Command UniBasic FILELOCK, FILEUNLOCK, RECORDLOCKED, RECORDLOCKL, RECORDLOCKU RELEASEXML Release the dynamic array variable using the RELEASEXML function. RELEASEXML destroys the internal DOM tree and releases the associated memory. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax RELEASEXML(XMLhandle) Parameter The following table describes each parameter of the syntax. 324 REM Parameter Description XMLhandle The XML handle created by the PREPAREXML function. REM The UniBasic REM command enables you to enter remarks in a program. You can enter the comment on a line by itself by entering the comment command followed by text. You also can enter a comment on a line that contains another UniBasic command by preceding the comment command with a semicolon. Tip: In structured programming, a single command is entered on each line. This makes programs easier to read and maintain. Syntax REM [comment text] Synonyms !, * Note: REM is also a synonym for the MOD function. For more information, see MOD, on page 229. Examples In the following example, comments describe the subroutine’s functionality. The program uses !, *, and REM. ! Subroutine to test user input validity. SUBROUTINE TEST COMMON N,DATA.IN,VAL,SCORE(10) BEGIN CASE CASE DATA.IN=VAL ** answer correct, then SCORE(N)=1 REM add one to SCORE(N) PRINT "Got it right!" ! print message. CASE IN <> VAL SCORE(N)=0 PRINT "Incorrect, try again." END CASE RETURN REM end of error check subroutine. REMOVE The UniBasic REMOVE command extracts an element from a dynamic array and assigns the removed element to a variable. REMOVE does not change the value of the dynamic array. REMOVE supports multibyte languages. REMOVE searches a dynamic array for system delimiters. When UniData finds a delimiter, it assigns the contents of the array element and the delimiter to the variable. UniData maintains a pointer to the last substring you remove so that successive REMOVE statements move progressively through a dynamic array. 325 Chapter 1: UniBasic commands and functions Tip: Use REMOVE to sequentially process the elements of a dynamic array. Syntax REMOVE var FROM dyn.var [AT col.pos] SETTING delim.var Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies the element to contain the extracted array element. FROM dyn.var Specifies a dynamic array from which to remove elements. AT col.pos Specifies the position in the array at which to start removing elements. This position is the number of characters, including system delimiters, from the beginning of the array. To process the entire array, set col.pos to 1 (0 defaults to 1). The value of col.pos changes as the array is processed, indicating the current position of the pointer. SETTING delim.var Specifies the delimiter code. When the end of the array is encountered, delim.var is set to 0. The SETTING clause assigns the variable delim.var a value based on the type of delimiter encountered. The following table describes the values of the delimiter codes. Delimiter code Description ASCII value* 0 array end 1 record mark 255 2 attribute mark 254 3 value mark 253 4 subvalue mark 252 5 text mark 251 6 not used; nonprinting 250 7 not used; nonprinting 249 *ASCII value is language-dependent and can be reassigned. Examples In the following example, the program segment processes the dynamic array CLIENT: DIM VAR(5,2) CLIENT = "G.Flaubert":@VM:"Guy":@SM:"12":@VM:"Yvette":@SM:"7" FOR I = 1 TO 5 REMOVE VAR(I,1) FROM CLIENT SETTING VAR(I,2) NEXT I CLIENT = CLIENT;*reset REMOVE pointer After the loop terminates, VAR contains the following: VAR(1,1) = "G.Flaubert" VAR(1,2) = 3 VAR(2,1) = "Guy" VAR(2,2) = 4 326 REMOVE VAR(3,1) = "12" VAR(3,2) = 3 VAR(4,1) = "Yvette" VAR(4,2) = 4 VAR(5,1) = "7" VAR(5,2) = 0 Notice that each element in the array VAR contains the extracted array element and the associated delimiter. In the next example, the program segment starts at the beginning of the array AMOUNTS, successively removes each element from the array, calculates a 3.5 percent tax amount, and adds it into the variable TAX.AMT. When MARK = 0 (delim.var is 0), processing terminates. COL = 1 LOOP REMOVE INV.AMT FROM AMOUNTS AT COL SETTING MARK TAX.AMT += INV.AMT*.035 WHILE MARK DO REPEAT In the next example, the program segment demonstrates the difference between UniBasic and other implementations of BASIC: ARRAY = "AB":@AM:"CD":@AM:"EF" COL = 1 LOOP REMOVE LINE FROM ARRAY AT COL SETTING MARK PRINT LINE, COL, MARK WHILE MARK REPEAT In UniBasic, the result is the following: AB 4 2 CD 7 2 EF 9 0 In some implementations, the values are different: AB 3 2 CD 6 2 EF 8 2 In the next example, the program segment compares processing time for the REMOVE statement versus the EXTRACT statement: MAINLINE OPEN ' ', 'VOC' TO VOC ELSE STOP 'CANNOT OPEN VOC FILE!' READ ITEM FROM VOC, 'BIGTEST' THEN LINE.CNT = DCOUNT (ITEM, @AM) PRINT "Bigtest in file VOC: "; LINE.CNT: " lines, ": PRINT LEN(ITEM): "bytes." GOSUB TIME.EXTRACT GOSUM TIME.REMOVE END ELSE PRINT 'COULD NOT READ ITEM BIGTEST' END STOP TIME.EXTRACT: LINE.IDX = 1 START.TIME = TIME() LOOP UNTIL LINE.IDX LINE.CNT DO LINE = ITEM<LINE.IDX> 327 Chapter 1: UniBasic commands and functions LINE.IDX += 1 REPEAT END.TIME = TIME() PRINT "EXTRACT: ": OCONV(END.TIME-START.TIME, 'MTS'): RETURN TIME.REMOVE START.TIME = TIME() LOOP REMOVE LINE FROM ITEM SETTING MORE.LINES WHILE MORE.LINES DO REPEAT END.TIME = TIME() PRINT "REMOVE: ": OCONV(END.TIME-START.TIME, 'MTS'): RETURN This results in the following: Bigtest in file VOC: 6000 lines, 59999 bytes. Processing time: EXTRACT: 00:07:26 REMOVE: 00:00:03 Related commands Language Command UniBasic DEL, EXTRACT, INSERT, REMOVE, REPLACE, SUBSTRINGS REMOVE The UniBasic REMOVE function extracts an element from a dynamic array and assigns the removed element to a variable. REMOVE does not change the value of the dynamic array. REMOVE searches a dynamic array for system delimiters. When UniData finds a delimiter, it assigns the contents of the array element and the delimiter to the variable. UniData maintains a pointer to the last substring you remove so that successive REMOVE statements move progressively through a dynamic array. The REMOVE function performs the same action as the REMOVE command, but you cannot use it to specify a starting position. Tip: Use REMOVE to sequentially process the elements of a dynamic array. Syntax REMOVE(dyn.array.var, delim.var Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.var Specifies a dynamic array from which to remove elements. delim.var Specifies the delimiter code. When the end of the array is encountered, delim.var is set to 0. The variable delim.var is a value based on the type of delimiter encountered. The following table describes the values of the delimiter codes. 328 REPLACE Delimiter code Description ASCII value* 0 array end 1 record mark 255 2 attribute mark 254 3 value mark 253 4 subvalue mark 252 5 text mark 251 6 not used; nonprinting 250 7 not used; nonprinting 249 *ASCII value is language-dependent and can be reassigned. Related commands Language Command UniBasic DEL, EXTRACT, INSERT, REMOVE, REPLACE, SUBSTRINGS REPLACE The UniBasic REPLACE function replaces data in a dynamic array with an expression. If an attribute, value, or subvalue is less than 0, the replacement string is placed after the last attribute, value, or subvalue as appropriate. If the position given does not exist (for example, attribute 6 specified in an array with two attributes), the necessary number of attribute, value, and subvalue marks are added to create the specified position. Syntax REPLACE(dyn.array.expr, attrib.expr, val.expr, subval.expr, replace.expr) dyn.array.expr<attrib.expr, val.expr, subval.expr> = replace.expr Null value handling With null value handling on, when UniBasic encounters the null value in a command parameter when a number is expected (attrib.expr, val.expr, subval.expr), it displays a warning message and uses 0. Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array.expr Specifies the dynamic array to modify. attrib.expr Specifies the attribute to replace. The following rules also apply: If attrib.expr is a negative number, replace.expr is appended to the existing value instead of replacing it. If attrib.expr is 0, the preceding level (attribute, value, subvalue) is replaced by replace.expr. 329 Chapter 1: UniBasic commands and functions Parameter Description val.expr Specifies the value of the attribute to replace. The following rules also apply: If attrib.expr is a negative number, replace.expr is appended to the existing value instead of replacing it. If attrib.expr is 0, the preceding level (attribute, value, subvalue) is replaced by replace.expr. subval.expr Specifies the subvalue of the value of the attribute to replace. The following rules also apply: If attrib.expr is a negative number, replace.expr is appended to the existing value instead of replacing it. If attrib.expr is 0, the preceding level (attribute, value, subvalue) is replaced by replace.expr. replace.expr Specifies the replacement value. Examples In this example, the program statement replaces the first value of attribute 2 with the value ‘220 W. 44TH’: CLIENT.REC = REPLACE(CLIENT.REC,4,1,0,'220 W. 44TH') In the next example, the program segment replaces “Blue” with the null value in STG, prints STG, then replaces the null value with “Blue” in STG, and prints STG again. The subroutine PRINT.SETUP converts attribute marks, value marks, and the null value to characters that can be displayed and printed. STG = "Movies":@AM:"The Sacrifice":@VM:"Blue":@AM:"Rocky IV" STG = REPLACE(STG,2,2,0,@NULL) GOSUB PRINT.SETUP PRINT "STG = ":PRT.STG STG = REPLACE(STG,2,2,0,"Blue") GOSUB PRINT.SETUP PRINT "STG = ":PRT.STG PRINT.SETUP: PRT.STG = CHANGE(STG, @NULL, "@NULL") PRT.STG = CHANGE(PRT.STG, @AM, "@AM") PRT.STG = CHANGE(PRT.STG, @VM, "@VM") RETURN This program prints the following: STG = Movies@AMThe Sacrifice@VM@NULL@AMRocky IV STG = Movies@AMThe Sacrifice@VMBlue@AMRocky IV In the next example, the first REPLACE places Harry Smith in the first attribute position. The second REPLACE places an array with two values in the fifth attribute. CUST.REC ='' CUST.REC = REPLACE(CUST.REC,1,0,01'Harry Smith') CUST.REC = REPLACE(CUST.REC,5,0,0,"V220":@VM:"v230") This results in: CUST.REC = "Harry 330 RESIZET Smith":@AM::@AM::@AM::@AM:"V220":@VM:"V230" In the following example, the program uses the short form of the REPLACE command to append CLIENT.NAME to NAME.ARRAY1: NAME.ARRAY1 = "Smith Jones Brown" OPEN "CLIENTS" TO CLIENT.FILE ELSE STOP READV CLIENT.NAME FROM CLIENT.FILE,"10034",2 THEN NAME.ARRAY1<-1> = CLIENT.NAME PRINT NAME.ARRAY1 END ELSE PRINT 'NO RECORD FOR CLIENT ':CLIENT.ID END Related commands Language Command UniBasic DEL, DELETE, EXTRACT, INSERT, REMOVE, REPLACE RESIZET The UniBasic RESIZET command changes the block size the WRITET command uses. When UniData processes a variable length record, the record length is less than the block length and UniData fills the remaining portion of the block with blanks. Tip: Use this command when the block size in a file is not the same as the block size in T.ATT. Syntax RESIZET [UNIT(mu.expr)] expr {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Paragraph Description UNIT(mu.expr) Specifies the conversion code and unit number. The mu.expr is optional. The default value is UNIT (00) for tape unit 0 with no conversion (ASCII assumed). 0 – No conversion (ASCII assumed). 1 – EBCDIC conversion. 2 – Invert high bit. 3 – Swap bytes. expr Specifies the block size to which to resize. THEN statements END THEN executes if the resize is successful. END is required to terminate multiline THEN statements. ELSE statements END ELSE executes if the resize is not successful. END is required to terminate multiline ELSE statements. 331 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment changes the block size the WRITET statement uses for the length of REC: RESIZET LEN(REC) ELSE PRINT 'RESIZET ERROR' WRITET REC ELSE PRINT 'WRITET ERROR' Related commands Language Command UniBasic READT, REWIND, WRITET UniData SETTAPE, T.ATT, T.DET For information, see the UniData Commands Reference. RETURN The UniBasic RETURN command transfers program control from a subroutine back to the calling program or subroutine. The optional TO clause returns to a statement label. This clause is valid only for internal subroutine returns. If you do not specify a TO clause, control passes to the statement immediately following the GOSUB or CALL statement in the calling program or subroutine. Syntax RETURN [TO label[:]] Examples The following externally cataloged subroutine is called by the sample program in Developing UniBasic Applications. The RETURN statement returns control to UPDATE_ORDERS. SUBROUTINE DISPLAY_MESSAGE(MESSAGE) DISPLAY @(5,20):MESSAGE DISPLAY @(5,21):"Press the (Return) key.": INPUT PAUSE,1_ RETURN Related commands Language Command UniBasic CALL, GOSUB, ON/GOSUB REUSE The UniBasic REUSE function affects the application of arithmetic operations on dynamic arrays. Syntax REUSE(dyn.array.expr) 332 REWIND When REUSE Is Not Used When you execute an arithmetic operation on an array and you do not include the REUSE function, one of the following happens: ▪ ▪ Array and constant – When you apply an arithmetic operation to an array and a constant, the operation is executed against only the first element of the array. If you want the operation to execute on every element in the array, apply REUSE to the constant. Two arrays – When you execute an arithmetic operation on arrays of different lengths, the operation is performed on the number of elements in the shortest array only. The remaining elements are each filled with 1 or 0, depending on the operation performed: ▫ Division – 1. ▫ Addition, subtraction, and multiplication – 0. If you apply REUSE to the shorter array, the last element in this array is used to perform the operation on the remaining elements in the longer array. Examples In the following example, the program segment multiplies the arrays without using the REUSE function: VIEWERS = 100:@VM:200:@VM:300 COST = 40:@VM:1 VCOST = VIEWERS*COST This results in: VCOST = 4000:@VM:200:@VM:0 VCOST takes its length from VIEWERS, the longest of the two arrays, but multiplication is performed on only the first two elements of each array because the other array, COST, has only two elements. The final element in the result array (VCOST) is filled with 0. 0 is used to fill because the arithmetic operation is multiplication. However, if you apply the REUSE function to the shorter array: VCOST = VIEWERS*REUSE(COST) This results in: VCOST = 4000:@VM:200:@VM:300 The final element in COST (1) is used to multiply with the final element of VIEWERS and fill the final element of the result array, VCOST. REWIND The UniBasic REWIND command rewinds a tape. Note: Before you can use the REWIND command, you must reserve a tape drive for use with the T.ATT command. For information about ECL T.ATT, see the UniData Commands Reference. Syntax REWIND [UNIT(mu.expr)] {THEN statements [END] | ELSE statements [END]} 333 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description UNIT(mu.expr) Specifies the conversion code (first digit), and the unit number (second digit). UniData allows unit numbers from 0 through 9. The mu.expr is optional and the default value is UNIT (00) for tape unit 0 with no conversion (ASCII assumed). 0 – No conversion (ASCII assumed). 1 – EBCDIC conversion. 2 – Invert high bit. 3 – Swap bytes. THEN statements END THEN executes if the rewind is successful. END is required to terminate multiline THEN statements. ELSE executes if the rewind is not successful. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program segment first uses the ECL T.ATT command to reserve tape unit 0 and specifies no conversion code. Then a routine reads all the records on the tape (until the end of the file or tape) and calls an internal subroutine that processes the record. After the process is finished, the REWIND command rewinds the tape. PERFORM "T.ATT DO" DONE = 0 LOOP READT UNIT (00) TAX.RECORD ELSE DONE = 1 UNTIL DONE DO GOSUB PROCESS.RECORD REPEAT REWIND UNIT (00) ELSE PRINT 'REWIND UNSUCCESSFUL' Related commands Language Command UniBasic READT, RESIZET, WRITET UniData SETTAPE, T.ATT, T.DET For information, see the UniData Commands Reference. RND The UniBasic RND function returns a random integer from 0 through num.expr minus 1. Syntax RND(num.expr) Examples In the following example, the program statement prints a random number from 0 through 9: 334 RNDSEED PRINT RND(10) Related commands Language Command UniBasic RNDSEED RNDSEED The UniBasic RNDSEED command enables you to “seed” the pseudo random number generator. The RND function gives you a different sequence of numbers each time. RNDSEED generates the same sequence of random numbers each time you run a program with the same seed. expr is a numeric seed point. Each time you use the same expr, RND generates the same sequence of random numbers. Syntax RNDSEED expr Examples In the following program segment, RND produces an array of random numbers to replace the values in VCOST. Because RNDSEEN is a constant, this program always produces the same series of random numbers. Without this statement, the program produces a different set of random numbers each time it is run. RNDSEED 234 VCOST = 100:@VM:200:@VM:0@VM:100:@VM:200:@VM:300 VCOST = RND(VCOST) PRINT VCOST Related commands Language Command UniBasic RND RQM RQM is a synonym for the SLEEP function. For more information, see SLEEP, on page 359. Synonyms SLEEP SADD The UniBasic SADD function adds two string numbers and returns the result as a string number. SADD is the string addition function. Arguments can be any valid numbers or string numbers of any magnitude or precision. If x or y contains nonnumeric data, UniData displays an error message and returns a result of 0. 335 Chapter 1: UniBasic commands and functions The SADD function results in a string number, so you can use the function in any expression in which a string number is valid. Because string numbers can exceed the range of numbers that standard arithmetic operators can accommodate, you might not want to use the SADD function in any expression in which a standard number is valid. Note: The result of the SADD function cannot exceed the maximum allowable number determined by your hardware. Syntax SADD(x, y) Tip: Processing string data type numbers rather than numeric data type numbers degrades processing speed. Numbers specified in quotation marks are string data type. Numbers specified without quotation marks are numeric data type. The data type in a variable is determined by the data first loaded into it. Examples In the following example, the program statement assigns to variable B the sum of the string constant (1.4149) and variable A: B = SADD("1.4149",A) saveSecurityContext The saveSecurityContext() function encrypts and saves a security context to a system security file. UniData maintains this file on a per account basis for. and uses the name as the record ID to access the saved security information. Since the information is encrypted, you should not attempt to directly manipulate the information. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. You may want your application to a security context to be used later. You can create multiple contexts to suit different needs. For example, you may want to use different protocols to talk to different servers. These contexts can be saved and reused. When creating a saved context, you must provide both a name and a passPhrase to use to encrypt the contents of the context. You must provide the name and passPhrase to load the saved context back. To ensure a high level of security, we recommend that the passPhrase be relatively long, yet easy to remember. Syntax saveSecurityContext(context, name, passPhrase) Parameters The following table describes each parameter of the syntax. 336 Parameter Description context The Security context handle. SCMP Parameter Description name String containing the file name of the saved context. passPhrase String containing the password to encrypt the context contents. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid security context handle. 2 Invalid parameters (empty name or passPhrase). 3 Context could not be saved. SCMP The UniBasic SCMP function compares two string numbers and returns a value depending on the result of the comparison. Arguments can be any valid numbers or string numbers of any magnitude or precision. If x or y contains nonnumeric data, UniData displays an error message, and the comparison returns 0. Syntax SCMP(x, y) SCMP function return values The SCMP function returns one of the values described in the following table. Comparison Returning value x<y -1 x=y 0 x>y 1 Tip: Processing string data type numbers rather than numeric data type numbers degrades processing speed. Numbers specified in quotation marks are string data type. Numbers specified without quotation marks are numeric data type. The data type in a variable is determined by the data first loaded into it. Examples In the following example, the program segment compares FA to FB. If the result of the IF statement is true (the SCMP function returns 1), UniData executes the PRINT statement. IF SCMP(FA,FB) GT 0 THEN PRINT FA:" IS GREATER THAN ":FB SDIV The UniBasic SDIV function divides two string numbers and returns the result as a string number. SDIV divides x by y. Arguments can be any valid numbers or string numbers of any magnitude or precision. However, result precision is limited to 14 significant digits. 337 Chapter 1: UniBasic commands and functions If x or y contains nonnumeric data, UniData displays an error message, and the operation results in 0. If y is 0, UniData displays an error message that indicates you cannot divide by 0 and returns a result of 0. The SDIV function results in a string number, so you can use the function in any expression in which a string is required. Because the resulting string numbers can be longer than the arithmetic operator can accommodate, you might not want to use the SDIV function in expressions requiring numeric data type. Syntax SDIV(x, y) Tip: Processing string data type numbers rather than numeric data type numbers degrades processing speed. Numbers specified in quotation marks are string data type. Numbers specified without quotation marks are numeric data type. The data type in a variable is determined by the data first loaded into it. Examples In the following example, the program statement divides the constant (1.4149) by variable A and assigns the result to variable B: B = SDIV("1.4149",A) SELECT The UniBasic SELECT command creates an active select list of all record IDs in a file. Records appear in the list in the order in which they are stored in the file. You can access the select list with a READNEXT statement. The UniBasic SELECT command differs from EXECUTE "SELECT ...", which executes the UniQuery SELECT command. The UniBasic SELECT command immediately makes available to READNEXT one group of IDs at a time. The program does not have to wait for the entire ID list to be constructed. If changes occur in a group that has not been selected yet, those changes are reflected in the select list that is being read by the program. If an ID is deleted before the group is selected by the UniBasic program, that ID does not appear in the list. Record IDs are truncated at 96 characters when they are copied into the select list. When using the UniQuery SELECT command, SYSTEM(11) returns the number of items remaining in the list. With the UniBasic SELECT command, SYSTEM(11) returns the number of items remaining in the group. Note: You can specify named or numbered lists (using list.num.expr or list.var.expr) in BASICTYPEs R and U. Only named lists (list.var.expr) are supported in BASICTYPEs M and P. Syntax SELECT file.var [TO {list.num.expr | list.var.expr}] [ON ERROR statements] SELECT dyn.array [TO {list.num.expr | list.var.expr}] [ON ERROR statements] 338 SELECT Parameters The following table describes each parameter of the syntax. Parameter Description file.var Specifies a file variable from which to read record IDs. If you do not specify a file.var, UniData reads from the default file. If no default file is open, a fatal error occurs. The default file is one for which no file variable is assigned in the OPEN statement. dyn.array Specifies a dynamic array from which to select a list of attributes. TO list.num.expr Supported in BASICTYPEs R and U only. Specifies a numbered select list, 0-9, to contain record IDs. If you do not specify a list, SELECT creates list 0. TO list.var.expr Supported in all BASICTYPEs. Specifies a named select list to contain record IDs. Initialize list.var.expr with a statement like list.name = '' before using it in the SELECT statement to avoid a compiler warning for an uninitialized variable. ON ERROR statements Specifies statements to execute if the SELECT statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. Examples The following program segment places in select list 1 all record IDs in the CLIENTS file, and then prints the ID of the first record: OPEN 'CLIENTS' TO CLIENT ON ERROR PRINT "File open error." THEN PRINT "OPEN" SELECT CLIENT TO 1 READNEXT var FROM 1 ON ERROR PRINT "Error in READNEXT." THEN PRINT var END ELSE PRINT "Record not found." END The following sample program creates a select list that is named rather than numbered. This program is compiled in BASICTYPE P, but compiles and runs in all BASICTYPEs. $BASICTYPE "P" list = '' OPEN 'INVENTORY' TO INV_FILE ELSE PRINT "OPEN error" SELECT INV_FILE TO list FOR X = 1 TO 10 READNEXT ID FROM list ELSE PRINT "No more IDs in list" END READU REC FROM INV_FILE,ID THEN PRINT "Record ":X:" is ":REC<1>:" ":REC<3> END ELSE PRINT "Record not found." 339 Chapter 1: UniBasic commands and functions END NEXT X END Here is the output for this program: Record Record Record Record Record Record Record Record Record Record 1 is 10105 Memory 2 is 10076 Telephone 3 is 10020 Adapter 4 is 10086 Modem 5 is 10092 Adapter 6 is 10073 Monitor 7 is 10041 Computer 8 is 10071 Computer 9 is 10103 Telephone 10 is 10101 Computer In the following example, the program statement creates a list of all record IDs in the INVENTORY file in active select list 0: SELECT INVENTORY In the next example, the program segment first creates a list of all IDs in the ORDERS file and assigns the ID list to list 1. It then uses the READNEXT command to read the IDs from the list sequentially, executing a subroutine, PROCESS.ORDERS, each time. SELECT ORDERS TO 1 LOOP READNEXT ORDER.ID FROM 1 ELSE TAPE.ID = " " WHILE ORDER.ID GOSUB PROCESS.ORDERS REPEAT Related commands Language Command UniBasic DELETELIST, FORMLIST, READLIST, SELECTINDEX, SELECTINFO, WRITELIST UniData SQL SELECT For information, see the UniData SQL Commands Reference UniQuery DELETE.LIST, GET.LIST, SAVE.LIST, SELECT, SSELECT For information, see the UniQuery Commands Reference SELECTINDEX The UniBasic SELECTINDEX command creates a select list based on an alternate key index. Note: SELECTINDEX is not supported with EDA files. Syntax SELECTINDEX index.name.expr[, key.val.expr] FROM file.var [TO list.num.expr] 340 SELECTINDEX Parameters The following table describes each parameter of the syntax. Parameter Description index.name.expr Specifies an alternate key index from which to select all key values if the key.val.expr is not specified. , key.val.expr Specifies a key value expression for SELECTINDEX to create a select list of record IDs (associated with the alternate key value) found in the alternate key index. FROM file.var Specifies a file variable from which to select the list. TO list.num.expr Specifies the list to which to select keys. STATUS function return values After you execute SELECTINDEX, the STATUS function returns one of the values described in the following table. Value Description 0 The select list is loaded with alternate key values or record IDs for the specified file. 1 No alternate index key exists for this attribute using the name specified. The select list is empty. Examples The following program creates a select list based on alternate index LNAME, and then reads the record using the first ID retrieved from that list: OPEN 'CLIENTS' TO CLIENT.FILE ELSE ABORT SELECTINDEX 'LNAME' FROM CLIENT.FILE TO 2 PRINT @(-1) READNEXT ID FROM 2 THEN READ REC FROM CLIENT.FILE, ID THEN PRINT @(5,I):REC<1>:@(20,I):REC<2> END ELSE PRINT "CANNOT FIND RECORD":ID END CLEARSELECT END In the following example, SELECTINDEX uses the alternate key index LNAME and creates a list of all the last names contained in the CLIENTS file: SELECTINDEX "LNAME" FROM CLIENTS In the next example, SELECTINDEX uses the alternate key value “Smith” and creates a list of all occurrences of Smith contained in the CLIENTS file: SELECTINDEX "LNAME","Smith" FROM CLIENTS Related commands Language Command UniBasic DELETELIST, FORMLIST, INDICES, READLIST, SELECT, SELECTINFO, SELECTINDEX, WRITELIST 341 Chapter 1: UniBasic commands and functions Language Command UniData SQL SELECT For information, see the UniData SQL Commands Reference UniQuery DELETE.LIST, GET.LIST, SAVE.LIST, SELECT, SSELECT For information, see the UniQuery Commands Reference SELECTINFO The UniBasic SELECTINFO function returns the state of a select list. list.num.expr is an expression evaluating to the number of the select list (0-9). Syntax SELECTINFO([list.num.expr,] 1) Parameters The following table describes each parameter of the syntax. Parameter Description list.num.expr The select list number (0-9). 1 The only code.expr currently implemented is 1, which returns the values described in the following table. SELECTINFO function return values The SELECTINFO function returns one of the values described in the following table. Value Description 1 The select list you specify is active. 0 The select list you specify is not active. -1 The select list does not exist, or code.expr is not valid, or (in BASICTYPE P) list.num.expr is not a list variable. Related commands Language Command UniBasic DELETELIST, FORMLIST, READLIST, SELECT, SELECTINDEX, WRITELIST UniData SQL SELECT For information, see the UniData SQL Commands Reference UniQuery DELETE.LIST, GET.LIST, SAVE.LIST, SELECT, SSELECT For information, see the UniQuery Commands Reference SEND The UniBasic SEND command sends output data to a specified line. You usually use SEND after a line is attached. 342 SEND Syntax SEND[X] expr[:expr2...] [:] TO line.expr {THEN | ELSE} statements [END] Parameters The following table describes each parameter of the syntax. Parameter Description X Directs UniData to convert expr from an exploded ASCII hexadecimal representation string to its binary equivalent, and then transmit it on the specified line. The conversion process ends when UniData reads the first nonhexadecimal character. expr:expr2... A string that contains data formatting expressions. You can specify more than one string to send. : Suppresses the sending of a terminating carriage return and line feed. TO line.expr Specifies a line number. line.expr must be valid or an error message displays and the user enters the UniBasic debugger. THEN statements END If the line is attached, the process has exclusive use of it. If the line is not attached, UniData performs the ELSE clause. THEN executes if the SEND is successful. END is required to terminate multiline statements. ELSE executes if the SEND is not successful. END is required to terminate multiline statements. ELSE statements END Note: SEND with the X option suppresses the output of return/line feed. However, you cannot include both quotation marks and the colon (‘:’) in the same statement. Examples In the following example, the program statement sends the string to line 0 unless line 0 is not attached. If line 0 is not attached, UniData displays the message “Line not attached”. SEND BEGIN_TRANSMISSION TO 0 ELSE PRINT "Line not attached" In the next example, the program statement converts the string to HELLO WORLD before sending it to line 0: TESTVAR = "48454C404F WORLD" SENDX TESTVAR TO 0 ELSE PRINT "Line not attached" Related commands Language Command UniBasic GET UniData PROTOCOL For information, see the UniData Commands Reference. 343 Chapter 1: UniBasic commands and functions SEQ The UniBasic SEQ function converts a single character to its ASCII code value. The SEQ function is the complement of the CHAR function. SEQ supports multibyte languages. Tip: Use SEQ(@NULL) to determine the ASCII code that represents the null value on your system. Syntax SEQ("char.expr") Examples In the following example, the program statement prints the ASCII code corresponding to the character “#” (in this case, 35): PRINT SEQ("#") Related commands Language Command UniBasic ASCII, CHAR, CHARS, EBCDIC SEQS The UniBasic SEQS function converts the first character in each element of a dynamic array to its ASCII code value. SEQS supports multibyte languages. Syntax SEQS("char.expr") Examples In the following example, the program statement prints the ASCII code corresponding to the value in each element of the dynamic array ARR1. The result is 65}66}67}68. ARR1 = "A":@AM:"B":@AM:"C":@AM:"D" PRINT SEQS(ARR1) Related commands Language Command UniBasic ASCII, CHAR, CHARS, EBCDIC, SEQ setAuthenticationDepth The setAuthenticationDepth() function sets how deeply UniData should verify before deciding that a certificate is not valid. 344 setCipherSuite Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. You can use this function to set both server authentication and client certification, determined by the value in serverOrClient parameter. The default depth for both is 1. The depth is the maximum number of intermediate issuer certificate, or CA certificates which must be examined while verifying an incoming certificate. Specifically, a depth of 0 means that the certificate must be self-signed. A default depth of 1 means that the incoming certificate can be either self-signed, or signed by a CA which is known to the context. Syntax setAuthenticationDepth(context, depth, serverOrClient) Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. depth Numeric value for verification depth. serverOrClient 1 - Server 2 - Client The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid Security Context handle. 2 Invalid depth (must be greater than or equal to 0). 3 Invalid value for serverOrClient (must be 1 or 2) setCipherSuite The setCipherSuite() function enables you to identify which cipher suites to support for the specified context. It affects the cipher suites and public key algorithms supported during the SSL/TLS handshake and subsequent data exchanges. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setCipherSuite(context,cipherSpecs) When a context is created, its cipher suites will all be set to SSLv3 suites by default. The CipherSpecs parameter is a string containing cipher-spec separated by colons. An SSL cipher specification in cipher-spec is composed of 4 major attributes as well as several, less significant attributes. These are defined below. 345 Chapter 1: UniBasic commands and functions Some of this information on ciphers is excerpted from the mod_ssl open source package of the Apache web server. ▪ Key Exchange Algorithm - RSA or Diffie-Hellman variants. ▪ Authentication Algorithm - RSA, Diffie-Hellman, DSS or none. ▪ Cipher/Encryption Algorithm - DES, Triple-DES, RC4, RC2, or none. ▪ MAC Digest Algorithm - MD5, SHA or SHA1. An SSL cipher can also be an export cipher and is either an SSLv2 or SSLv3/TLSv1 cipher (here TLSv1 is equivalent to SSLv3). To specify which ciphers to use, one can either specify all the ciphers, one at a time, or use aliases to specify the preference and order for the ciphers. For detailed information about cipher algorithms, see UniBasic Extensions. Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. CipherSpecs String containing cipher suite specification described above. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid Security Context handle. 2 Invalid cipher suite specification. setClientAuthentication The setClientAuthentication() function turns client authentication for a server socket on or off. When option is set to on, during the initial SSL handshake, the server sends a client authentication request to the client. It will also receive the client certificate and perform authentication according to the issuer’s certificate (or certificate chain) set in the security context. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setClientAuthentication(context,option) Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. option 1 - ON 2 - OFF 346 SETENV The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid Security Context handle. SETENV Use the SETENV function to set an environment variable from UniBasic. Syntax SETENV(var_name, value) Parameters The following table describes each parameter of the syntax. Parameter Description var_name The name of the environment variable. value The value of the environment variable. If the var_name is umask and the command is issued while a running udapi_slave process (such as a UniObjects or UniObjects for Java connection) on UNIX, then the return code is the original umask setting of the udapi_slave process. In addition, the command changes the umask of the process. Note: The umask value is interpreted as an octal value, just as a normal umask value is. Although this will work to change the permissions for newly created sequential files, some UniData functions like CREATE.FILE are unaffected by the change. Return codes The following table describes the SETENV return codes. Return codes Description 0 Setting the environment variable was successful. -1 Setting the environment variable was not successful. setHTTPDefault The setHTTPDefault function configures the default HTTP settings, including proxy server and port, buffer size, authentication credential, HTTP version, and request header values. UniBasic uses these settings with every HTTP request that follows. If you require all outgoing network traffic to go through a proxy server, you should call setHTTPDefault() with value containing the proxy server name or IP address as well as the port (if other than the default of 80). Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 347 Chapter 1: UniBasic commands and functions Syntax setHTTPDefault(option, value) Parameters The following table describes each parameter of the syntax. Parameter Description option A string containing an option name. See the table below for the options currently defined. value A string containing the appropriate option value. The following table describes the available options for setHTTPDefault. Option Description PROXY_NAME Name or IP address of the proxy server. PROXY_PORT The port number to be used on the proxy server. This only needs to be specified if the port is other than the default of 80. VERSION The version of HTTP to be used. The default version is 1.0, but it can be set to 1.1 for web servers that understand the newer protocol. The string should be ”1.0” or “1.1”. BUFSIZE The size of the buffer for HTTP data transfer between UniData and the web server. The default is 4096 however, the buffer size can be increased to improve performance. It should be entered as an integer greater than or equal to 4096. AUTHENTICATE The user name and password to gain access. The string should be “user-name:password”. Default BASIC authentication can also be set. If a request is denied (HTTP staus 401/407), UniBasic will search for the default credential to automatically re-submit the request. HEADERS The header to be sent with the HTTP request. If default_headers contains an empty string, then any current user-specified default header will be cleared. Currently, the only default header UniBasic sets automatically is “User-Agent” UniData 6.0.” If you do not want to send out this header you should overwrite it with setHTTPDefault(). Per RFC 2616, for “net politeness,”an HTTP client should always send out this header. UniBasic will also send a date/time stamp with every HTTP request. According to RFC 2616, the stamp will represent time in Universal Time (UT) format. A header should be entered as a dynamic array in the form of <HeaderName>@VM<HeaderValue>@Fm<HeaderName>@VM<HeaderValue>. The following table describes the status of each return code. 348 Return codes Status 0 Success. 1 Invalid option. 2 Invalid Value. setIpv Note: All defaults set by setHTTPDefault() will be in effect until the end of the current UniData session. If you do not want the setting to affect subsequent programs, you will need to clear it before exiting the current program. If the user wishes to set the “Authorization” or “ProxyAuthorization” header as defaults, see the description under setRequestHeader(). To clear the default settings, pass an empty string with PROXY_NAME, AUTHENTICATE and HEADERS, and 0 for PROXY_PORT and BUFSIZE. setIpv The setIpv function configures which IP setting to use; IPv4 or IPv6. If the machine is IPv6 enabled, all server side sockets will use IPv6, which can accept client connections on both IPv4 and IPv6. If the machine is not IPv6 enabled, server and client will remain working on IPv4. This function can accept one or two options. For example, setIpv(IPV6) or setIpv(IPV6,SOCKET). Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setIpv(option[, sockettype]) Parameters The following table describes each parameter of the syntax. Parameter Description option A string containing an option name. See the table below for the options currently defined. The following table describes the available options for setIpv. Option Description IPV4 Specifies using IPv4 only. IPV6 Specifies using IPv6 only. IPVANY Specifies using whichever IPv option is available. IPV4_IPV6 Specifies using IPv4 as the first option and then IPv6. IPV6_IPV4 Specifies using IPv6 as the first option, and then IPv4. The following table describes the socket type options available options for setIpv. Socket type Description SOCKET Specifies the socket network type. NFA Specifies the NFA network type. SETINDEX The UniBasic SETINDEX command sets a pointer to a key in an alternate key index. 349 Chapter 1: UniBasic commands and functions Syntax SETINDEX index.name.expr [, [rop] key.val.expr [, id.expr]] [ON file.var] [BUFFER.KEYS {ON | OFF}] [VALIDATE.KEY {ON | OFF}] Note: The FILEINFO function, specifically FILEINFO(file.var,21), returns the current alternate key value. UniBasic maintains index.name.expr for READBCK or READFWD, and related statements. Normally, you should use the following relational (rop) operators: ▪ ▪ Before READBCK statements: LT, LE, LAST_ALT_KEY Before READFWD statements: GT, GE, EQ, FIRST_ALT_KEY, NULLVAL_ALT_KEY Note: You can point to only one alternate index at a time. Each time you use SETINDEX, the current value is reset and the subsequent READFWD/READBCK statement reads the record associated with the newly selected index. Parameters The following table describes each parameter of the syntax. Parameter Description index.name.expr Specifies the alternate key index to use in subsequent READFWD/READBCK statements. rop , key.val.expr One of several valid operators (see the following table). The default rop operator is EQ. Specifies the key value to initialize. If you do not specify this value, UniData sets the internal pointer to the first key value in the index. If you specify FIRST_ALT_KEY, LAST_ALT_KEY, or NULLVAL_ALT_KEY as rop, you cannot specify key.val.expr. , id.expr Specifies the @ID associated with the key value to position the pointer in the index. When the id.expr entered does not exist, SETINDEX sets the position to the key value following the expected location of id.expr. ON file.var Specifies the file to act on. BUFFER.KEYS ON | OFF Directs READFWD/READBCK to use or not use a buffering mechanism. ON improves performance, but you could miss some newly added key values. OFF (the default) slows performance, but you will not miss any key values added after the one you just read. VALIDATE.KEY ON | OFF Directs READFWD/READBCK to validate or not validate the key value just read against what is in the tuple. Because reading a key value and its tuple is not an atomic action, a tuple could be deleted after it is read. ON prevents this, but could degrade performance. rop operators The following table describes the valid rop operators. 350 SETINDEX Operator Resulting current alternate key value EQ First value equal to the specified value (default). GT First value greater than that specified. GE First value greater than or equal to that specified. LT Last value less than that specified. LE Last value less than or equal to that specified. FIRST_ALT_KEY First non-null alternate key value. Keys that are an empty string are sorted before keys containing values. If you specify FIRST_ALT_KEY as rop, you cannot specify key.val.expr. LAST_ALT_KEY Last alternate key value. If you specify LAST_ALT_KEY as rop, you cannot specify key.val.expr. NULLVAL_ALT_KEY First null alternate key value. Keys that are empty strings are sorted after null value keys, followed by keys containing values. If you specify NULLVAL_ALT_KEY as rop, you cannot specify key.val.expr. STATUS function return values After you execute SETINDEX, the STATUS function returns one of the values described in the following table. Status value Description 0 The alternate key specified exists. 1 Error. 2 The alternate key specified does not exist. Examples In the following example, the program segment sets the pointer at the first occurrence of the data element containing Miller in the alternate index LNAME: OPEN 'CLIENTS' TO tmp ELSE STOP SETINDEX 'LNAME', 'SMITH' ON tmp The following series of examples demonstrates the use of SETINDEX to set the record pointer to the first null key in the PROD_NAME alternate key index: OPEN 'INVENTORY' TO inventory ELSE PRINT "Open error" SETINDEX 'PROD_NAME', NULLVAL_ALT_KEY inventory FOR X = 1 TO 5 READFWD rec FROM inventory THEN PRINT rec<0>:", ":rec<3>:", ":rec<4> END ELSE NULL NEXT X STOP This program produces the following result when no null values exist in the PROD_NAME index: :RUN BP set.idx 10020, Adapter, A/C Adapter for notebook computers 10086, Adapter, Ethernet LC Card 10092, Adapter, Workgroup Hub 10082, CD Player, Portable Model 10104, CD Player, Personal Model, Bass Boost 351 Chapter 1: UniBasic commands and functions After the null value is inserted into the PROD_NAME attribute for records 10008 and 56060, this same program produces the following results: :RUN BP set.idx 10015, , Portable, B/W, 6 ppm 10238, , Super Deluxe Model 10020, Adapter, A/C Adapter for notebook computers 10086, Adapter, Ethernet LC Card 10092, Adapter, Workgroup Hub The following program demonstrates the use of SETINDEX to set the record pointer to the first nonnull key in the PROD_NAME alternate key index by specifying rop operator FIRST_ALT_KEY: OPEN 'INVENTORY' TO inventory ELSE PRINT "Open error" SETINDEX 'PROD_NAME', FIRST_ALT_KEY inventory FOR X = 1 TO 5 READFWD rec FROM inventory THEN PRINT rec<0>:", ":rec<3>:", ":rec<4> END ELSE NULL NEXT X STOP Next, run this program using the INVENTORY file that you modified to contain null values in the PROD_NAME attribute for records 10015 and 10238. The following output results. :RUN BP set.idx 10020, Adapter, A/C Adapter for notebook computers 10086, Adapter, Ethernet LC Card 10092, Adapter, Workgroup Hub 10082, CD Player, Portable Model 10104, CD Player, Personal Model, Bass Boost Tip: You would obtain this same output if the INVENTORY file contained no null values in PROD_NAME and you specified rop NULLVAL_ALT_KEY. Related commands Language Command UniBasic READBCK, READBCKL, READBCKU, READFWD, READFWDL, READFWDU, READXBCK, READXFWD, SELECTINDEX UniData BUILD.INDEX, CREATE.INDEX For information, see the UniData Commands Reference. setPrivateKey The setPrivateKey() function loads the private key into a security context so that it can be used by SSL functions. If the context already had a set private key, it will be replaced. SSL depends on public key crypto algorithms to perform its functions. A pair of keys is needed for each communicating party to transfer data over SSL The public key is usually contained in a certificate, signed by a CA, while the private key is kept secretly by the user. Private key is used to digitally sign a message or encrypt a symmetric secret key to be used for data encryption. 352 setRandomSeed For detailed information about the setPrivateKey function, see UniBasic Extensions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setPrivateKey(key, format, keyLoc, passPhrase, validate, context) Parameters The following table describes each parameter of the syntax. Parameter Description Key A string containing either the key or path for a key file. Format 1 - PEM (Base64 encoded) format 2 - DER (ASN.1 binary) format KeyLoc 1 - key contained in key string 2 - key is in a file specified by key passPhrase String containing the path phrase required for gaining access to the key. It can be empty if the key is not pass phrase protected. This is not recommended. Validate 1 - Validate against matching public key 0 - Will not bother to validate Context The security context handle. The following table describes the status of each return code. Return codes Status 0 Success 1 Invalid Security handle 2 Invalid format 3 Invalid key type 4 Key file cannot be accessed (non-existent or wrong pass phrase) 5 Certificate cannot be accessed 6 Private key does not match public key in certificate 7 Private key cannot be interpreted 99 Other errors that prevent private key from being accepted by UniData or UniVerse. setRandomSeed The setRandomSeed() function generates a random seed file from a series of source files and sets that file as the default seed file for the supplied security context. 353 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setRandomSeed(inFiles, outFile, length, context) The strength of cryptographic functions depends on the true randomness of the keys. This function generates and sets the random seed file used by many of the UniData cryptographic functions. By default, UniData uses the .rnd file in your current account. You can override the default by calling this function. The random seed file is specified by outFile, which is generated based on source files specified in inFiles. For Windows platforms, multiple files must be separated by “;” (a semi-colon). For Unix platforms, multiple files must be separated by “:” (a colon). The length parameter specifies how many bytes of seed data UniData should generate. If you do not specify a source in the inFiles parameter, the outFile parameter must already exist. If you do not specify context, the seed file will be used as a global seed file that applies to all cryptographic functions. However, a seed file setting in a particular security context will always override the global setting. Parameters The following table describes each parameter of the syntax. Parameter Description inFiles A string containing source file names. outFiles A string containing the generated seed file. length The number of bytes that should be generated (the default is 1024 if less that 1024 is specified). context The Security Context handle. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid parameter(s). 2 Random file generation error. 3 Random file set error. setRequestHeader The setRequestHeader function allows the user to set additional headers for a request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 354 setSocketOptions Syntax setRequestHeader(request_handle, header_name, header_value) Parameters The following table describes each parameter of the syntax. Parameter Description request_handle The handle to the request returned by createRequest(). header_name header_value The name of the header. The value of the header. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid request handle. 2 Invalid header (Incompatible with method). 3 Invalid header value. Note: Since a user-defined header or header value can be transferred, it is difficult to check the validity of parameters passed to the function. UniBasic currently will not perform syntax checking on the parameters, although it will reject setting a response header to a request. Refer to RFC 2616 for valid request headers. The header set by this function overwrites settings by setHTTPDefault(). This function supports Base64 encoding for BASIC authentication. If header_name contains either “Authorization” or “Proxy-Authorization”, the header_value should then contain ASCII text user credential information in the format of “userid:password”, as specified by RFC 2617. This function will then encode the text based on Base64 encoding. Only BASIC authentication is supported. Digest authentication may be supported in the future. BASIC authentication is not safe and is not recommended for use with transferring secured data. setSocketOptions The setSocketOptions function sets the current value for a socket option associated with a socket of any type. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax setSocketOptions(socket_handle, options) Parameters The following table describes each parameter of the syntax. 355 Chapter 1: UniBasic commands and functions Parameter Description socket_handle The socket handle from openSocket(), acceptSocket(), or initServerSocket(). options Dynamic Array containing information about the socket options and their current settings. The dynamic array is configured as: optName1<VM>optValue1a[<VM>optValue1b]<FM> optName2<VM>optValue2a[<VM>optValue2b]<FM> optName3... Where optName is specified by the caller and must be an option name string listed below. The first optValue specifies if the option is ON or OFF and must be one of two possible values: “1” for ON or “2” for OFF. The second optValue is optional and may hold additional data for a specific option. Currently, for the “LINGER” option it contains the delayed time (in milliseconds)before closing the socket. For all other options, it should not be specified as it will be ignored. The following table describes the available options (case-sensitive) for setSocketOptions. Option Description DEBUG Enable/disable recording of debug information. REUSEADDR Enable/disable the reuse of a location address (default) KEEPALIVE Enable/disable keeping connections alive. DONTROUTE Enable/disable routing bypass for outgoing messages. LINGER Linger on close if data is present. BROADCAST Enable/disable permission to transmit broadcast messages. OOBINLINE Enable/disable reception of out-of-band data in band. SNDBUF Set buffer size for output (default 4KB). RCVBUF Set buffer size for input (default 4KB). The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. showSecurityContext The showSecurityContext() function dumps the SSL configuration parameters of a security context into a readable format. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. The security context handle must have been returned by a successful execution of createSecurityContext() or loadSecurityContext().The configuration information includes: protocol, version, certificate, cipher suite used by this connection and start time, and so forth. 356 SIGNATURE Note: For security reasons, UniData does not display the privateKey installed into the context. Once installed, there is no way for you to extract it. Syntax showSecurityContext(context,config) Parameters The following table describes each parameter of the syntax. Parameter Description context The Security Context handle. config A dynamic array containing the configuration data. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid Security Context handle. 2 Configuration data could not be obtained. SIGNATURE The SIGNATURE() function generates a digital signature or verifies a signature using the supplied key. Syntax SIGNATURE(algorithm, action, data, dataLoc, key, keyLoc, keyFmt, pass, sigIn, result) The algorithm parameter specifies the digest algorithm used to construct the signature. UniData supports the MD5 and SHA1 algorithms. There are four actions you can be specify: ▪ RSA-Sign ▪ RSA-Verify ▪ DSA-Sign ▪ DSA-Verify If you choose DSA, you can only specify SHA1 in algorithm. The data to be signed or verified against a signature can be supplied either directly in data, or read from a file whose names is in data. For signing action, you should specify a private key. For verification, a public key is usually expected. However, UniData also accepts a private key for verification purposes. Key can be either in PEM or DER format. If a private key is password protected, the password must be supplied with pass. For verification, key can also contain a certificate or name of a certificate file. A signature is expected in sigIn. For signing action, the generated signature is put into result. 357 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description algorithm The digest algorithm used for signing or verification (must be either “MD5” or “SHA1”). action 1 - RSA-Sign 2 - RSA-Verify 3 - DSA-Sign 4 - DSA-Verify data Data or the name of the file containing the data to be signed or verified. dataLoc 1 - Data in a string 2 - Data in a file key The key or the name of the file containing the key to be used to sign or verify. In the case of verification, key can be a certificate string or a file. keyLoc 1 - Key is in a string 2 - Key is in a file 3 - Key is in a certificate for verification keyFmt 1 - PEM 2 - DER pass A string containing the pass phrase for the private key. sigIn A string containing a digital signature. result A generated signature or a file to store the signature. The following table describes the status of each return code. Return codes Status 0 Success. 1 Unsupported digest algorithm. 2 The data cannot be read. 3 Message digest cannot be obtained. 4 Invalid parameters. 5 Key cannot be read or is in the wrong format / algorithm. 6 Incorrect Password. 7 Signature cannot be generated. 8 Signature cannot be verified. SIN The UniBasic SIN function returns the trigonometric sine of the numeric expression num.expr. 358 SLEEP Syntax SIN(num.expr) Examples In the following example, the program segment assigns the sine of the number 25 to the variable SIN. X. The result is 0.4226.X = 25 SIN.X=SIN(X) In the next example, the program statement prints 1.0000, the sine of 90: PRINT SIN(90) Related commands Language Command UniBasic ACOS, ASIN, ATAN, COS, TAN SLEEP The UniBasic SLEEP and RQM commands halt program execution for the time specified in seconds, or until the time specified. Tip: You can use SLEEP or RQM if you want a processing or reporting program to wait until midnight before running to better use system resources. SLEEP is also useful when waiting for the release of locked system resources. Note: The original purpose of RQM was to release remaining execution time reserved for a program, allowing other programs to use the time. If a particular program is very computationintensive, RQM could improve overall system performance. Syntax SLEEP [hh:mm[:ss]] [seconds] Synonyms RQM Parameters The following table describes each parameter of the syntax. Parameter Description hh:mm:ss Specifies the time to end sleep in hours, minutes, and (optional) seconds. You must surround the time in quotation marks. seconds Specifies the number of seconds to sleep. Examples In the following example, the program statement halts program execution for 10 seconds: 359 Chapter 1: UniBasic commands and functions SLEEP 10 In the next example, the program statement suspends program execution until 11:45 PM: SLEEP “23:45” In the next example, the program statement halts program execution for one second: SLEEP SMUL The UniBasic SMUL function multiplies two string numbers and returns the result as a string number. Arguments can be any valid numbers or string numbers of any magnitude or precision. Using string numbers rather than standard numbers degrades processing speed. If x or y contains nonnumeric data, UniData displays an error message and returns a result of 0. The SMUL function results in a string number, so you can use the function in any expression in which a string number is valid. Because string numbers can exceed the range of numbers that standard arithmetic operators can accommodate, you might not want to use the SMUL function in any expression in which a standard number is valid. Syntax SMUL(x, y) Tip: Processing string data type numbers rather than numeric data type numbers degrades processing speed. Numbers specified in quotation marks are string data type. Numbers specified without quotation marks are numeric data type. The data type in a variable is determined by the data first loaded into it. Examples In the following example, the program statement multiplies the constant (1.4149) by variable A and assigns the result to variable B: B = SMUL("1.4149",A) SOAPCreateRequest Creates a SOAP request and returns a handle to the request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPCreateRequest(URL, soapAction, Request) Parameters The following table describes each parameter of the syntax. 360 SOAPCreateSecureRequest Parameter Description URL A string containing the URL where the web service is located. UniData sends the SOAP request to this URL. [IN] soapAction A string UniData uses as the SOAPAction HTTP header for this SOAP request. [IN] Request The returned handle to the SOAP request. This handle can be used in subsequent calls to the SOAP API for UniBasic. [OUT] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function complete successfully. 1 Invalid URL syntax. 2 Invalid HTTP method (indicates the POST method is not supported by the HTTP server). You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPCreateSecureRequest The SOAPCreateSecureRequest function creates a secure SOAP request and returns a handle to the request. Syntax SOAPCreateSecureRequest(URL, soapAction, Request, security_context) Parameters The following table describes each parameter of the syntax. Parameter Description URL A string containing the URL where the web service is located. UniVerse sends the SOAP request to this URL. For information about the format of the URL, see URL Format below. [IN] soapAction A string UniVerse uses as the SOAPAction HTTP header for this SOAP request. [IN] Request The returned handle to the SOAP request. You can use this handle can be used in subsequent calls to the SOAP API for UniVerse BASIC. [OUT] security_context A handle to the security context. URL Format The URL you specify must follow the syntax defined in RFS 1738. The general format is: http://<host>:<port>/path>?<searchpart> The following table describes each parameter of the syntax. 361 Chapter 1: UniBasic commands and functions Parameter Description host Either a name string or an IP address of the host system. port The port number to which you want to connect. If you do not specify port, UniVerse defaults to 80. Omit the preceding colon if you do not specify this parameter. path Defines the file you want to retrieve on the web server. If you do not specify path, UniVerse defaults to the home page. searchpart Use searchpart to send additional information to a web server. Note: If the URL you define contains a searchpart, you must define it in its encoded format. For example, a space is converted to +, and other nonalphanumeric characters are converted to %HH format. You do not need to specify the host and path parameters in their encoded formats. UniVerse BASIC encodes these parameters prior to communicating with the web server. Return code The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function complete successfully. 1 Invalid URL syntax. 2 Invalid HTTP method (indicates the POST method is not supported by the HTTP server). 101 Invalid security context handle. You can also use the UniVerse BASIC STATUS() function to obtain the return status from the function. Examples The following code segment illustrates the SOAPCreateSecureRequest function: * Create the Request Ret = SoapCreateSecureRequest(URL, SoapAction, SoapReq, SecurityContext) IF Ret <> 0 THEN STOP "Error in SoapCreateSecureRequest: " : Ret END . . SOAPGetDefault Gets default SOAP settings, such as the SOAP version. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 362 SOAPGetFault Syntax SOAPGetDefault(option, value) Parameters The following table describes each parameter of the syntax. Parameter Description option A string containing an option name. UniData currently only supports the VERSION option. [IN] value A string returning the option value. [OUT] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid option (currently, UniData only supports the VERSION option). You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPGetFault Parses the response data from SOAPSubmitRequest after receiving a SOAP Fault, into a dynamic array of SOAP Fault components. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPGetFault(respData, soapFault) Parameters The following table describes each parameter of the syntax. Parameter Description respData Response data from SOAPSubmitRequest after receiving a SOAP fault. [IN] 363 Chapter 1: UniBasic commands and functions Parameter Description soapFault Dynamic array consisting of Fault Code, Fault String, and optional Fault Detail, for example: <faultcode>@AM<faultstring>@AM<faultdetail>@AM<faultactor> Fault code values are XML-qualified names, consisting of: ▪ VersionMismatch ▪ MustUnderstand ▪ DTDNotSupported ▪ DataEncoding Unknown ▪ Sender ▪ Receiver Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid response data, possibly not a valid XML document. 2 SOAP Fault not found in response data. You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPGetResponseHeader Gets a specific response header after issuing a SOAP request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPGetResponseHeader(Request, headerName, headerValue) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] headerName headerValue 364 The header name whose value is being queried. [IN] The header value, if present in the response, or empty string if not (in which case the return status of the function is 2). [OUT] SOAPRequestWrite Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle. 2 Header not found in set of response headers. You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPRequestWrite Outputs the SOAP request in XML format to a string or to a file. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPRequestWrite(Request, reqDoc, docTypeFlag) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] reqDoc docTypeFlag Depending on docTypeFlag, either an output string containing the SOAP request content, or a path to a file where the SOAP request content will be written. [OUT] A flag indicating whether reqDoc is an output string that is to hold the request content, or a path to a file where the SOAP request content will be written. ▪ 0 – reqDoc is a file where the request content will be written upon successful completion. ▪ 1 – reqDoc is a string that will hold the request upon successful completion. [IN] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle. 2 Unable to open the file named by reqDoc. 3 Unable to write to the file named by reqDoc. 365 Chapter 1: UniBasic commands and functions You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPSetDefault Setup default SOAP settings, such as SOAP version. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSetDefault(option, value) Parameters The following table describes each parameter of the syntax. Parameter Description option A string containing an option name. UniData currently only supports the “VERSION” option. [IN] value A string containing the appropriate option value. For the VERSION option, the string should be 1.0, 1.1, or 1.2. [IN] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid option (currently, UniData only supports VERSION). 2 Invalid value. 1.1 assumed. You can also use the UniBasic STATUS() function to obtain the return status from the function. Usage notes The default SOAP version is 1.1. The namespace prefixes "env" and "enc" are associated with the SOAP namespace names http://schemas.xmlsoap.org/soap/envelope/ and http://schemas.xmlsoap.org/ soap/encoding/ respectively. The namespace prefixed "xsi" and "xsd" are associated with the namespace names http://www.w3.org/1999/XMLSchema-instance and http://www.w3.org/1999/ XMLSchema respectively. The SOAP version can be set to 1.2 to support the newer SOAP 1.2 protocol. The namespace prefixes "env" and "enc" will be associated with the SOAP namespace names "http://www.w3.org/2001/12/ soap-envelope" and "http://www.w3.org/2001/12/soap-encoding" respectively. The namespace prefixes "xsd" and "xsi" will be associated with the namespace names "http://www.w3.org/2001/ XMLSchema" and "http://www.w3.org/2001/XMLSchema-instance" respectively. All defaults set by SOAPSetDefault will be in effect until the end of the current UniData session. If you do not want the setting to affect subsequent programs, you need to clear it before exiting the current program. 366 SOAPSetParameters Along with SOAPSetDefault, the CallHTTP function setHTTPDefault may be called to set HTTPspecific settings or headers, if the HTTP default settings are not sufficient. SOAPSetParameters Sets up the SOAP request body, specifying a remote method to call along with the method's parameter list. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSetParameters(Request, URI, serviceName, value) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] namespace A string that is used as the namespace URI for the SOAP call. [IN] method The name of the method to be called. [IN] paramArray A dynamic array containing the method parameters for the SOAP call. Each method parameter consists of the following values: ▪ A parameter name ▪ A parameter value ▪ A parameter type (if type is omitted, xsd:string will be used. name, value, and type are separated by @VM. Additional parameters are separated by @AM, as shown in the following example: <param1Name>@VM<param1Value> @VM<param1Type>@AM<param2Name> @VM<param2Value>@VM<param2Type>...[IN] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle was passed to the function. You can also use the UniBasic STATUS() function to obtain the return status from the function. Usage notes As an example, the following inputs: 367 Chapter 1: UniBasic commands and functions Input Description Method “getStockQuote” namespace “http://host/#StockQuoteService” paramArray “symbol”:@VM:”U2”:@VM:”xsd:string” will set the SOAP body as follows: <SOAP-ENV:Body> <ns1:getStockQuote xmlns:ns1="http://host/#StockQuoteService"> <symbol xsi:type="xsd:string">U2</symbol> </ns1:getQuote> <SOAP-ENV:Body> SOAPSetRequestBody Sets up a SOAP request body directly, as opposed to having it be constructed through the SOAPSetParameters function. With this function it also possible to attach multiple body blocks to the SOAP request. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSetRequestBody(Request, value) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] value A dynamic array containing SOAP body blocks, for example: <body block>@AM<body block>... [IN] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle. You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPSetRequestContent Sets the entire SOAP request's content from an input string or from a file. 368 SOAPSetRequestHeader Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSetRequestContent(Request, reqDoc, docTypeFlag) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] reqDoc docTypeFlag The input document to be used as the SOAP request content. [IN] A flag indicating whether reqDoc is a string holding the actual content, or the path to a file holding the content. ▪ 0 – reqDoc is a file holding the request content. ▪ 1 – reqDoc is a string holding the request content. [IN] Return codes The return code indicating success or failure. The following table describes the status of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle. 2 Unable to open the file named by reqDoc. 3 Unable to read the file named by reqDoc. You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPSetRequestHeader Sets up a SOAP request header. By default, there is no SOAP header. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSetRequestHeader(Request, value) Parameters The following table describes each parameter of the syntax. 369 Chapter 1: UniBasic commands and functions Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] value A dynamic array containing SOAP header blocks, for example: <header block>@AM<header block>...[IN] Return codes The return code indicating success or failure. The following table describes the value of each return code. Return codes Description 0 Function completed successfully. 1 Invalid request handle. You can also use the UniBasic STATUS() function to obtain the return status from the function. SOAPSubmitRequest Submits a request and gets the response. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax SOAPSubmitRequest(Request, timeout, respHeaders, respData, soapStatus) Parameters The following table describes each parameter of the syntax. Parameter Description Request Handle to the request created with SOAPCreateRequest. [IN] timeout Timeout, in milliseconds, to wait for a response. [IN] respHeaders Dynamic array of HTTP response headers and their associated values. [OUT] respData The SOAP response message. [OUT] soapStatus Dynamic array containing status code and explanatory text. [OUT] Return codes The return code indicating success or failure. The following table describes the value of each return code. 370 Return codes Description 0 Function completed successfully. 1 Invalid request handle. 2 Request timed out. 3 Network error occurred. 4 Other error occurred. SORT You can also use the UniBasic STATUS() function to obtain the return status from the function. Usage notes Internally, SOAPSubmitRequest utilizes CallHTTP's submitRequest() to send out the SOAP message. The soapStatus variable holds the status from the underlying CallHTTP function. If an error occurs on the SOAP server while processing the request, soapStatus will indicate an HTTP 500 "Internal Server Error", and respData will be a SOAP Fault message indicating the server-side processing error. SORT The SORT function enables you to sort a dynamic array. Syntax SORT(var) The elements in the dynamic array are sorted in ascending order, left-justified. UniBasic sorts the dynamic array by the highest system delimiter in the array. ▪ If the dynamic array contains any attribute marks, the sort is by attribute. Values and subvalues remain with the original attribute. ▪ If the dynamic array contains value marks and no attribute marks, the sort is by value. Subvalues are unaffected and remain with the original value. ▪ If the dynamic array contains subvalue marks and neither attribute marks nor value marks, the sort is by subvalue. Parameter The following table describes the parameter of the syntax. Parameter Description var The name of the dynamic array to sort. SOUNDEX The UniBasic SOUNDEX function converts an expression into a phonetic code. This function can return unpredictable results with multibyte characters. Syntax SOUNDEX(expr) Use SOUNDEX to compare alphabetic strings, such as names, when an alternate spelling or misspelling should not cause a mismatch. expr is an expression evaluating to a string value. SOUNDEX evaluates the expression by: ▪ Returning the first alphabetic letter. ▪ Converting the remainder of the string to uppercase. ▪ Ignoring letters A, E, H, I, O, U, W, Y, and nonalphabetic characters. ▪ Converting each valid letter to a phonetic code. 371 Chapter 1: UniBasic commands and functions ▪ Testing for duplication. If a character is next to another character that has the same phonetic code, it is not included. ▪ Adjusting the length of the code to four characters by truncating codes longer than four characters or padding with zeros any expression less than four characters. SOUNDEX phonetic codes The following table displays the phonetic code for each letter that UniData evaluates. Code Letters 1 BFPV 2 CGJKQSXZ 3 DT 4 L 5 MN 6 R Examples The following table shows SOUNDEX sample output values. Expression SOUNDEX STEPHEN S315 STEVEN S315 TERMINATE T655 RRR R600 Related commands Language Command UniBasic ICONV SOUNDEX (S), OCONV SOUNDEX (S) SPACE The UniBasic SPACE function returns a string containing the specified number of spaces. Note: Functions can be concatenated within a PRINT statement. Syntax SPACE(expr) Examples In the following example, the program statement prints HI and THERE separated by 15 spaces: PRINT "HI":SPACE(15):"THERE" 372 SPACES This results in: HI THERE Related commands Language Command UniBasic SPACES SPACES The UniBasic SPACES function returns the number of spaces specified in each element of the dynamic array dyn.array.expr. Syntax SPACES(dyn.array.expr) Examples In the following example, the program segment prints the number of spaces specified in each element of the dynamic array ARR1: ARR1 = 1:@AM:2:@AM:3:@AM:4:@AM:5 ARR2 = SPACES(ARR1) This results in ARR2 containing one space in the first element, two spaces in the second element, and so forth. Related commands Language Command UniBasic SPACE SPLICE The UniBasic SPLICE function concatenates two strings or arrays and inserts an expression between them. Syntax SPLICE(expr1,"expr", expr2) Parameters The following table describes each parameter of the syntax. Parameter Description expr1 Specifies the first string or array to concatenate. expr Specifies the expression to insert between expr1 and expr2 when concatenating them. 373 Chapter 1: UniBasic commands and functions Parameter Description expr2 Specifies the second string or array to concatenate. Examples In the following example, the program segment concatenates PHONE to NUMBER and inserts a dash (-) between the two strings: PHONE = "555" NUMBER = "1234" PRINT SPLICE (PHONE,"-",NUMBER) This results in: 555-1234 The following program inserts the null value between PHONE and NUMBER. The CALLED subroutine, PRINT.SETUP, converts UniData delimiters and the null value to printable characters (this subroutine is printed in the entry for CHANGE in this manual). PRT.STG='' PHONE = "555" NUMBER = "1234" STG = SPLICE (PHONE,@NULL,NUMBER) CALL PRINT.SETUP(STG,PRT.STG) PRINT PRT.STG END This program prints the following: 555@NULL1234 In the following example, the program segment concatenates each element of array ARR1 to array ARR2 and inserts a plus sign (+) between the two elements: ARR1 = 1:@AM:2:@AM:3 ARR2 = 4:@AM:5:@AM:6 PRINT SPLICE (ARR1,"+",ARR2) This results in the following: 1+4}2+5}3+6 Related commands Language Command UniBasic CAT, CATS SQLAllocConnect SQLAllocConnect allocates and initializes a connection environment in a UniData BCI environment. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 374 SQLAllocEnv Use this function to create a connection environment to connect to a particular data source. One UniData BCI environment can have several connection environments, one for each data source. The function stores the internal representation of the connection environment in the connect.env variable. Note: Use the connection environment variable only in UniData BCI calls that require it. Using it improperly can cause a runtime error and break communication with the data source. Syntax status = SQLAllocConnect (bci.env, connect.env) Parameters The following table describes each parameter of the syntax. Parameter Description bci.env UniData BCI environment variable returned in an SQLAllocEnv call. connect.env Variable that represents the allocated connection environment. Return values The following table describes return values from the SQLAllocConnect function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLAllocEnv SQLAllocEnv creates an environment in which to execute UniData BCI calls. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Use this function to allocate memory for a UniData BCI environment. The function stores the address in the bci.env variable. SQLAllocEnv must be the first UniData BCI call issued in any application. You can allocate more than one UniData BCI environment. Note: Use the environment variable only in UniData BCI calls that require it. Using it in any other context causes a runtime error or breaks communication with the data source. Syntax status = SQLAllocEnv (bci.env) Parameters The following table describes each parameter of the syntax. 375 Chapter 1: UniBasic commands and functions Parameter Description bci.env Variable that represents the allocated UniData BCI environment. Return values The following table describes return values from the SQLAllocEnv function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR SQLAllocStmt SQLAllocStmt creates an SQL statement environment in which to execute SQL statements. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Use this function to allocate memory for an SQL statement environment. Note: Use the SQL statement environment variable only in UniData BCI calls that require it. Using it in any other context causes a runtime error or breaks communication with the data source. Syntax status = SQLAllocStmt (connect.env, statement.env) Parameters The following table describes each parameter of the syntax. Parameter Description connect.env Connection environment used in SQLAllocConnect and SQLConnect calls. If you have not established a connection to the data source using connect.env, an error is returned to the application. statement.env Variable that represents an SQL statement environment. Return values The following table describes return values from the SQLAllocStmt function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLBindCol Use this function to tell UniData BCI where to return the results of an SQLFetch call. SQLBindCol defines the name of the variable (column) to contain column results retrieved by SQLFetch, and 376 SQLBindCol specifies the data conversion (data.type) on the fetched data. SQLBindCol has no effect until SQLFetch is used. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Normally you call SQLBindCol once for each column of data in the result set. When SQLFetch is issued, data is moved from the result set at the data source and put into the variables specified in the SQLBindCol call, overwriting existing variable contents. Data is converted from the SQL data type at the data source to the UniBasic data type requested by the SQLBindCol call, if possible. If data cannot be converted to data.type, an error occurs. Values are returned only for bound columns. Unbound columns are ignored and are not accessible. For example, if a SELECT command returns three columns, but SQLBindCol was called for only two columns, data from the third column is not accessible to your program. If you bind more variables than there are columns in the result set, an error is returned. If you bind no columns and an SQLFetch is issued, the cursor advances to the next row of results. You need not use SQLBindCol with SQL statements that do not produce result sets. Syntax status = SQLBindCol (statement.env, col#, data.type, column) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment of the executed SQL statement. col# Column number of result data, starting at 1. This value must be from 1 to the number of columns returned in an operation. data.type BASIC data type into which to convert the incoming data. Possible values are the following: SQL.B.CHAR – Character string data. SQL.B.BINARY – Bit string (raw) data. SQL.B.NUMBER – Numeric data (integer or double). SQL.B.DEFAULT – SQL data type determines the BASIC data type. SQL.B.INTDATE – UniData date in internal format. SQL.B.INTTIME – UniData time in internal format. column Variable that will contain column results obtained with SQLFetch. Return values The following table describes the return values of the SQLBindCol function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE 377 Chapter 1: UniBasic commands and functions SQLBindParameter SQLBindParameter specifies where to find values for input parameter markers when you issue an SQLExecute or SQLExecDirect call. For output parameter markers, SQLBindParameter specifies where to find the return value of a called procedure. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLBindParameter ( statement.env, mrk#, data.type, sql.type, prec, scale, param [ , param.type ] ) Description Parameter markers are placeholders in SQL statements. Input parameter markers let a program send user-defined values with the SQL statement when an SQLExecute or SQLExecDirect call is executed repeatedly. Output parameter markers receive values returned from a called procedure. The placeholder character is ? (question mark). SQLBindParameter tells the system where to find the variables to substitute for parameter markers in the SQL statement and how to convert the data before sending it to the data source. You need to do only one SQLBindParameter for each parameter marker in the SQL statement, no matter how many times the statement is to be executed. For example, consider the following SQL statement: INSERT INTO T1 VALUES (?,?,?); If you want to load 1000 rows, you need issue only three SQLBindParameter calls, one for each question mark. Normally you specify data.type as SQL.B.BASIC. If you specify sql.type as SQL.DATE, however, you can specify data.type as SQL.B.INTDATE; if you specify sql.type as SQL.TIME, you can specify data.type as SQL.B.INTTIME. If you specify sql.type as SQL.BINARY, SQL.VARBINARY, or SQL.LONGVARBINARY, you can specify data.type as SQL.B.BINARY. If you use SQL.B.INTDATE, the UniData BCI assumes the program variable holds a date in UniData internal date format and uses the DATEFORM conversion string to convert the internal date to an external format as required by the data source. To set or change the DATEFORM conversion string, see the SQLSetConnectOption function. If you specify sql.type as SQL.TIME and data.type as SQL.B.INTTIME, UniData BCI assumes the program variable holds a time in UniData internal time format and does not convert the data. SQLBindParameter uses the value of prec only for the following SQL data types: 378 ▪ SQL.CHAR ▪ SQL.VARCHAR ▪ SQL.LONGVARCHAR ▪ SQL.WCHAR ▪ SQL.WVARCHAR ▪ SQL.WLONGVARCHAR ▪ SQL.BINARY ▪ SQL.VARBINARY SQLBindParameter ▪ SQL.LONGVARBINARY ▪ SQL.NUMERIC ▪ SQL.DECIMAL For all other data types, the extended parameters DBLPREC, FLOATPREC, and INTPREC determine the maximum length for strings representing double-precision numbers, floating-point numbers, and integers. Parameters The following table describes each parameter of the syntax. Input Variable Description statement.env SQL statement environment associated with an SQL statement. mrk# Number of the parameter marker in the SQL statement to which this call refers. Parameter markers in the SQL statement are numbered left to right, starting at 1. data.type UniBasic data type to bind to the parameter. data.type must be one of the following: SQL.B.BASI – Use with any sql.type. SQL.B.BINARY – Use only when sql.type is SQL.BINARY, SQL.VARBINARY, or SQL.LONGVARBINARY. SQL.B.INTDATE – Use only when sql.type is SQL.DATE. SQL.B.INTTIME – Use only when sql.type is SQL.TIME. sql.type SQL data type to which the UniBasic variable is converted. prec Precision of the parameter, representing the width of the parameter. If prec is 0, default values are used. scale Scale of the parameter, used only when sql.type is SQL.DECIMAL or SQL.NUMERIC. param Variable that contains the data to use when SQLExecute or SQLExecDirect is called. param.type Type of parameter. param.type can be one of the following: SQL.PARAM.INPUT – Use for parameters in an SQL statement that does not call a procedure, or for input parameters in a procedure call. SQL.PARAM.OUTPUT – Use for parameters that mark the output parameter in a procedure. SQL.PARAM.INPUT.OUTPUT – Use for an input/output parameter in a procedure. If you do not specify param.type, SQL.PARAM.INPUT is used. Return values The following table describes the return values of the SQLBindParameter function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR 379 Chapter 1: UniBasic commands and functions Return value Description -2 SQL.INVALID.HANDLE SQLCancel This function is equivalent to the SQLFreeStmt call with the SQL.CLOSE option. It closes any open cursor associated with the SQL statement environment and discards pending results at the data source. It is good practice to issue SQLCancel when all results have been read from the data source, even if the SQL statement environment will not be reused immediately for another SQL statement. Issuing SQLCancel frees any locks that may be held at the data source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLCancel (statement.env) Parameters The following table describes each parameter of the syntax. Input Variable Description statement.env SQL statement environment. Return values The following table describes the return values of the SQLCancel function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLColAttributes Use this function to get information about a column. SQLColAttributes returns the specific information requested by the value of col.attribute. Some DBMSs (such as SYBASE) do not make column information available until after the SQL statement is executed. In such cases, issuing an SQLColAttributes call before executing the statement produces an error. The SQL.SUCCESS.WITH.INFO return occurs when you issue the call for a column that contains an unsupported data type or when text.var is truncated. The SQL data type returned is SQL.BINARY (-2). If you are connected to an ODBC database, SQL.COLUMN.NULLABLE always returns SQL.NULLABLE.UNKNOWN. 380 SQLColAttributes When you are connected to an ODBC data source, calling SQLColAttributes with one of the column attributes returns a status of SQL.ERROR with SQLSTATE set to S1091. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLColAttributes (statement.env, col#, col.attribute, text.var, num.var) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment of the executed SQL statement. col# Column number to describe, starting with 1. col.attribute Attribute of the column that needs information. col.attribute values are listed in this section. These values are defined in the ODBC.H file. text.var Contains column information for attributes returning text data. If the return value is numeric, text.var contains invalid information. num.var Contains column information for attributes returning numeric data. If the return value is text, num.var contains invalid information. The following table lists the column attributes you can use with ODBC databases. Column Attribute Output SQL.COLUMN.AUTO.INCREMENT num.var Description 1 – TRUE if the column values are incremented automatically. 0 – FALSE if the column values are not incremented automatically. SQL.COLUMN.CASE.SENSITIVE num.var 1 – TRUE for character data. 0 – FALSE for all other data. SQL.COLUMN.COUNT num.var Number of columns in result set. The col# argument must be a valid column number in the result set. SQL.COLUMN.DISPLAY.SIZE num.var Maximum number of characters required to display data from the column. SQL.COLUMN.LABEL text.var Column heading. SQL.COLUMN.LENGTH num.var SQL.COLUMN.NAME text.var Number of bytes transferred by an SQLFetch call. SQL.COLUMN.NULLABLE num.var Name of specified column. Column can contain null values. Can return one of the following: 0 – SQL.NO.NULLS 1 – SQL.NULLABLE 2 – SQL.NULLABLE.UNKNOWN 381 Chapter 1: UniBasic commands and functions Column Attribute Output Description SQL.COLUMN.PRECISION num.var Column precision. SQL.COLUMN.SCALE num.var Column scale. SQL.COLUMN.SEARCHABLE num.var Always returns 3, SQL.SEARCHABLE. SQL.COLUMN.TABLE.NAME text.var Name of the table to which the column belongs. If the column is an expression, an empty string is returned. SQL.COLUMN.TYPE num.var Number representing the SQL type of this column. SQL.COLUMN.TYPE.NAME text.var Data type name for column, specific to the data source. SQL.COLUMN.UNSIGNED num.var 1 – TRUE for nonnumeric data types. SQL.COLUMN.UPDATABLE num.var 0 – FALSE for all other data types. Any expressions or computed columns return SQL.ATTR.READONLY, and stored data columns return SQL.ATTR.WRITE. Return values The following table describes the return values of the SQLColAttributes function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE ODBC data sources The following table lists the column attributes you can use only with ODBC databases. Column Attribute Output Description SQL.COLUMN.MONEY num.var 1 – TRUE if column is money data type. 0 – FALSE if column is not money data type. SQL.COLUMN.OWNER.NAME text.var SQL.COLUMN.QUALIFIER.NAME text.var Owner of the table containing the column. Qualifier of the table containing the column. SQLColumns This function returns a result set in statement.env as a cursor of 12 columns describing those columns found by the search pattern (see SQLTables). As with SQLTables, the search is done on the SQL catalog. This is a standard result set that can be accessed with SQLFetch. The ability to obtain descriptions of columns does not imply that a user has any privileges on those columns. 382 SQLColumns Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLColumns (statement.env, schema, owner, tablename, columnname ) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. schema Schema name search pattern. owner Table owner number search pattern. tablename Table name search pattern. columnname Column name search pattern. Result set The result set contains 12 columns: Column Name Data Type TABLE.SCHEMA VARCHAR(128) OWNER INTEGER TABLE.NAME VARCHAR(128) COLUMN.NAME VARCHAR(128) DATA.TYPE SMALLINT TYPE.NAME VARCHAR(128) NUMERIC.PRECISION INTEGER CHAR.MAX.LENGTH INTEGER NUMERIC.SCALE SMALLINT NUMERIC.PREC.RADIX SMALLINT NULLABLE SMALLINT REMARKS VARCHAR(254) The application is responsible for binding variables for the output columns and fetching the results using SQLFetch. Return values The following table describes the returns values of the SQLColumns function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO –1 SQL.ERROR 383 Chapter 1: UniBasic commands and functions Return value Description –2 SQL.INVALID.HANDLE SQLSTATE values The following table shows all possible SQLSTATE values returned by SQLColumns. SQLSTATE Description S1000 General error for which no specific SQLSTATE code has been defined. S1001 S1008 S1010 Memory allocation failure. Cancelled. Execution of the statement was stopped by an SQLCancel call. Function sequence error. The statement.env specified is currently executing an SQL statement. S1C00 The table owner field was not numeric. 24000 Invalid cursor state. Results are still pending from the previous SQL statement. Use SQLCancel to clear the results. 42000 Syntax error or access violation. This can be caused by a variety of reasons. The native error code returned by the SQLError call indicates the specific UniData error that occurred. SQLConnect Use this function to connect to the ODBC data source specified by data.source. Use the login1 and login2 parameters to log in to the DBMS specified by the ODBC data.source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. You cannot use SQLConnect within a transaction. An SQLConnect call issued within a transaction returns SQL.ERROR, and sets SQLSTATE to 25000, indicating that the SQLConnect function is illegal within a transaction. A connection is established when the data source validates the user name and authorization. Syntax status = SQLConnect (connect.env, data.source, login1, login2) Parameters The following table describes each parameter of the syntax. Parameter Description connect.env Connection environment assigned in a previous SQLAllocConnect. data.source 384 Data source name. For ODBC data sources, this is the name of a data source specified by the data source management program you are using. SQLDescribeCol Parameter Description login1 For ODBC data sources, this is typically the password for the remote database or operating system. For the specific information required for login1 when connecting to ODBC data sources, see the configuration for the specific driver used. login2 For ODBC data sources, this is typically the password for the remote database or operating system. For the specific information required for login2 when connecting to ODBC data sources, see the configuration for the specific driver used. Return values The following table describes the return values of the SQLConnect function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLDescribeCol Use this function to get information about the column described by col#. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. The SQL.SUCCESS.WITH.INFO return occurs when you issue the call for a column that contains an unsupported data type, or if col.name is truncated. The SQL data type returned is SQL.BINARY (-2). Syntax status = SQLDescribeCol (statement.env, col#, col.name, sql.type, prec, scale, null) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment of the executed SQL statement. col# Column number to describe, starting with 1. col.name Column name. sql.type SQL data type of the column, a numeric code defined in the ODBC.H file. prec Precision of the column, or –1 if precision is unknown. scale Scale of the column, or –1 if scale is unknown. 385 Chapter 1: UniBasic commands and functions Parameter Description null One of the following: 0 – SQL.NO.NULLS: field cannot contain NULL. 1 – SQL.NULLABLE: field can contain NULL. 2 – SQL.NULLABLE.UNKNOWN: not known whether field can contain NULL. Return values The following table describes the return values of the SQLDescribeCol function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLDisconnect SQLDisconnect disconnects a connection environment from a data source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. You cannot use SQLDisconnect within a transaction. An SQLDisconnect call issued within a transaction returns SQL.ERROR, and sets SQLSTATE to 25000. You must commit or abort active transactions before disconnecting, and you must be in autocommit mode. If there is no active transaction, SQLDisconnect frees all SQL statement environments owned by this connection before disconnecting. SQLDisconnect returns SQL.SUCCESS.WITH.INFO if an error occurs but the disconnect succeeds. Syntax status = SQLDisconnect (connect.env) Parameters The following table describes each parameter of the syntax. Parameter Description connect.env Connection environment. Return values The following table describes the return values of the SQLDisconnect function. 386 Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO SQLError Return value Description -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLError SQLError returns error status information about one of the three environments you use. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLError (bci.env, connect.env, statement.env, sqlstate, dbms.code, error) Use SQLError when a function returns a status value other than SQL.SUCCESS or SQL.INVALID.HANDLE. SQLError returns a value in sqlstate when UniData BCI detects an error condition. The dbms.code field contains information from the data source that identifies the error. Each environment type maintains its own error status. SQLError returns errors for the right most nonnull environment. For example, to get errors associated with a connection environment, specify input variables and constants in the following order: bci.env, connect.env, SQL.NULL.HSTMT To get errors associated with a particular SQL statement environment, specify the following: bci.env, connect.env, statement.env If all arguments are null, SQLError returns a status of SQL.NO.DATA.FOUND and sets SQLSTATE to 00000. Since multiple errors can be returned for a variable, you should call SQLError until it returns a status of SQL.NO.DATA.FOUND. This ensures that all errors are reported. ODBC data sources When a program is connected to an ODBC server, errors can be detected by UniData BCI, by the ODBC driver, or by the data source. When the error is returned, the source of the error is indicated by bracketed items in the error output variable, as shown in the following examples. Errors detected by Unidata BCI: [U2][SQL Client] An illegal configuration option was found Errors detected by the ODBC driver: SQLConnect error: Status = -1 SQLState = S1000 Natcode = 9352 [ODBC] [INTERSOLV][ODBC Oracle driver][Oracle]ORA-09352: Windows 32-bit Two-Task driver unable to spawn new ORACLE task For information about errors detected by the ODBC driver manager, see the Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide. Errors detected by the data source: [U2][SQL Client][U2] Database not found or no system permissions. 387 Chapter 1: UniBasic commands and functions For information about errors detected by the data source, see the documentation provided for the DBMS running on the data source. Parameters The following table describes each parameter of the syntax. Parameter Description bci.env UniData BCI environment or the constant SQL.NULL.HENV. connect.env Connection environment or the constant SQL.NULL.HDBC. statement.env SQL statement environment or the constant SQL.NULL.HSTMT. sqlstate SQLSTATE code. This code describes the UniData BCI Client error associated with the environment passed. sqlstate is always a fivecharacter string. dbms.code Error code specific to the data source. dbms.code contains an integer error code from the data source. If dbms.code is 0, the error was detected by UniData BCI. For the meanings of specific error codes, see the documentation provided for the data source. error Text describing the error in more detail. Return values The following table describes the return values of the SQLError function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE 100 SQL.NO.DATA.FOUND SQLExecDirect SQLExecDirect accepts an SQL statement or procedure call and delivers it to the data source for execution. It uses the current values of any SQL statement parameter markers. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLExecDirect (statement.env, statement) SQLExecDirect differs from SQLExecute in that it does not require a call to SQLPrepare. SQLExecDirect prepares the SQL statement or procedure call implicitly. Use SQLExecDirect when you do not need to execute the same SQL statement or procedure repeatedly. You can use parameter markers in the SQL statement or procedure call as long as you have resolved each marker with an SQLBindParameter call. 388 SQLExecDirect After an SQLExecDirect call you can use SQLNumResultCols, SQLDescribeCol, SQLRowCount, or SQLColAttributes to get information about the resulting columns. You can use SQLNumResultCols to determine if the SQL statement or procedure call created a result set. If the executed SQL statement or procedure produces a set of results, you must use an SQLFreeStmt call with the SQL.CLOSE option before you execute another SQL statement or procedure call using the same SQL statement environment. The SQL.CLOSE option cancels any pending results still waiting at the data source. Your application programs should not try to issue transaction control statements directly to the data source (for instance, by issuing a COMMIT statement with SQLExecDirect or SQLPrepare). Programs should use only UniBasic transaction control statements. UniData BCI issues the correct combination of transaction control statements and middleware transaction control function calls that are appropriate for the DBMS you are using. Trying to use SQLExecDirect to execute explicit transaction control statements on ODBC data sources can cause unexpected results and errors. When SQLExecDirect calls a procedure, it does not begin a transaction. If a transaction is active when a procedure is called, the current transaction nesting level is maintained. Note: If you execute a stored procedure or enter a command batch with multiple SELECT statements, the results of only the first SELECT statement are returned. Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment from a previous SQLAllocStmt. statement Either an SQL statement or a call to an SQL procedure, to be executed at the data source. If you are connected to an ODBC data source, it may treat identifiers and keywords in the SQL statement casesensitively. To call an SQL procedure, use one of the following syntaxes: [ { ] CALL procedure [ ( [ parameter [ , parameter ] … ] ) ] or [ } ] procedure parameter If you are connected to an ODBC data source, use the first syntax and enclose the entire call statement in braces. Name of the procedure. If the procedure name contains characters other than alphabetic or numeric, enclose the name in double quotation marks. To embed a single double quotation mark in the procedure name, use two consecutive double quotation marks. Either a literal value or a parameter marker that marks where to insert values to send to or receive from the data source. Programmatic SQL uses a ? (question mark) as a parameter marker. Use parameters only if the procedure is a subroutine. The number and order of parameters must correspond to the number and order of the subroutine arguments. For an ODBC data source, parameters should be of the same data type as the procedure requires. 389 Chapter 1: UniBasic commands and functions Return values The following table describes the return values of the SQLExecDirect function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLExecute Use this function to repeatedly execute an SQL statement, using different values for parameter markers. You must use an SQLPrepare call to prepare the SQL statement before you can use SQLExecute. If the SQL statement specified in the SQLPrepare call contains parameter markers, you must also issue an SQLBindParameter call for each marker in the SQL statement before you use SQLExecute. After you load the parameter marker variables with data to send to the data source, you can issue the SQLExecute call. By setting new values in the parameter marker variables and calling SQLExecute, new data values are sent to the data source and the SQL statement is executed using those values. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLExecute (statement.env) Description If the SQL statement uses parameter markers, SQLExecute performs any data conversions required by the SQLBindParameter call for the parameter markers. If the SQL statement executed produces a set of results, you must use an SQLFreeStmt call with the SQL.CLOSE option before you execute another SQL statement using the same SQL statement environment. The SQL.CLOSE option cancels any pending results still waiting at the data source. Your application programs should not try to issue transaction control statements directly to the data source (for instance, by issuing a TRANSACTION COMMIT statement with SQLExecDirect or SQLPrepare). Programs should use only UniBasic transaction control statements. UniData BCI issues the correct combination of transaction control statements and middleware transaction control function calls that are appropriate for the DBMS you are using. Trying to use SQLExecute to execute explicit transaction control statements on ODBC data sources can cause unexpected results and errors. SQLExecute tells the data source to execute a prepared SQL statement or a called procedure, using the current values of any parameter markers used in the statement. Using SQLExecute with an SQLBindParameter call is the most efficient way to execute a statement repeatedly, since the statement does not have to be parsed by the data source each time it is issued. Parameters The following table describes each parameter of the syntax. 390 SQLFetch Parameter Description statement.env SQL statement environment associated with a prepared SQL statement. Return values The following table describes the return values of the SQLExecute function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLFetch Use this function to retrieve the next row’s column values from the result set at the data source and put them into the variables specified with SQLBindCol. SQLFetch performs any required data conversions. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. SQLFetch returns SQL.SUCCESS.WITH.INFO if numeric data is truncated or rounded when converting SQL values to UniData values. SQLFetch logically advances the cursor to the next row in the result set. Unbound columns are ignored and are not available to the application. When no more rows are available, SQLFetch returns a status of 100 (SQL.NO.DATA.FOUND).Your application must issue an SQLFetch call at the same transaction nesting level (or deeper) as the corresponding SQLExecDirect or SQLExecute call. Also, an SQLFetch call must be executed at the same transaction isolation level as the SELECT statement that generates the data. If it does not, SQLFetch returns SQL.ERROR and sets SQLSTATE to S1000. Use SQLFetch only when a result set is pending at the data source. Syntax status = SQLFetch (statement.env) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment of the executed SQL statement. Return values The following table describes the return values of the SQLFetch function. Return value Description 0 SQL.SUCCESS 391 Chapter 1: UniBasic commands and functions Return value Description -1 SQL.ERROR -2 SQL.INVALID.HANDLE 1 SQL.SUCCESS.WITH.INFO 100 SQL.NO.DATA.FOUND SQLFreeConnect SQLFreeConnect releases a connection environment and its resources. You must use SQLDisconnect to disconnect the connection environment from the data source before you release the connection environment with SQLFreeConnect, otherwise an error is returned. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLFreeConnect (connect.env) Parameters The following table describes each parameter of the syntax. Parameter Description connect.env Connection environment. Return values The following table describes the return values of the SQLFreeConnect function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLFreeEnv SQLFreeEnv releases an SQL Client Interface environment and its resources. You must use SQLFreeConnect to release all connection environments attached to the UniData BCI environment before you release the UniData BCI environment with SQLFreeEnv, otherwise an error is returned. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLFreeEnv (bci.env) 392 SQLFreeStmt Parameters The following table describes each parameter of the syntax. Parameter Description bci.env UniData BCI environment. Return values The following table describes the return values of the SQLFreeEnv function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLFreeStmt SQLFreeStmt frees some or all resources associated with an SQL statement environment. If your program uses the same SQL statement environment to execute different SQL statements, use SQLFreeStmt with the SQL.DROP option, then use SQLAllocStmt to reallocate a new SQL statement environment. This unbinds all bound columns and resets all parameter marker variables. It is good practice to issue SQLFreeStmt with the SQL.CLOSE option when all results have been read from the data source, even if the SQL statement environment will not be reused immediately for another SQL statement. Issuing SQLFreeStmt with the SQL.CLOSE option frees any locks that may be held at the data source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLFreeStmt (statement.env, option) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. 393 Chapter 1: UniBasic commands and functions Parameter Description option option is one of the following: ▪ ▪ ▪ ▪ SQL.CLOSE – Closes any open cursor associated with the SQL statement environment and discards pending results at the data source. Using the SQL.CLOSE option cancels the current query. All parameter markers and columns remain bound to the variables specified in the SQLBindCol and SQLBindParameter calls. SQL.UNBIND – Releases all bound column variables defined in SQLBindCol for this SQL statement environment. SQL.RESET.PARAMS – Releases all parameter marker variables set by SQLBindParameter for this SQL statement environment. SQL.DROP – Releases the SQL statement environment. This option terminates all access to the SQL statement environment. SQL.DROP also closes cursors, discards pending results, unbinds columns, and resets parameter marker variables. Options are defined in the ODBC.H file. Return values The following table describes the return values of the SQLFreeStmt function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLGetInfo SQLGetInfo returns general information about the ODBC driver and the data source. This function supports all of the possible requests for information defined in the ODBC 2.0 specification. The #defines for info.type are contained in the ODBC.H include file. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLGetInfo (connect.env, info.type, info.value) Parameters The following table describes each parameter of the syntax. 394 Parameter Description connect.env Connection environment. info.type The specific information requested. For a list of values, see the info.type tables under “Description.” info.value The information returned by SQLGetInfo. SQLGetInfo ODBC info.type values The following table lists the valid ODBC values for info.type. For more detailed information about information types, see Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide. Driver Information SQL.ACTIVE.CONNECTIONS SQL.DRIVER.VER SQL.ACTIVE.STATEMENTS SQL.FETCH.DIRECTION SQL.DATA.SOURCE.NAME SQL.FILE.USAGE SQL.DRIVER.HDBC SQL.GETDATA.EXTENSIONS SQL.DRIVER.HENV SQL.LOCK.TYPES SQL.DRIVER.HLIB SQL.ODBC.API.CONFORMANCE SQL.DRIVER.HSTMT SQL.ODBC.SAG.CLI.CONFORMANCE SQL.DRIVER.NAME SQL.ODBC.VER SQL.DRIVER.ODBC.VER SQL.POS.OPERATIONS SQL.ROW.UPDATES SQL.SERVER.NAME SQL.SEARCH.PATTERN.ESCAPE DBMS Product Information SQL.DATABASE.NAME SQL.DBMS.VER SQL.DBMS.NAME Data Source Information SQL.ACCESSIBLE.PROCEDURES SQL.OWNER.TERM SQL.ACCESSIBLE.TABLES SQL.PROCEDURE.TERM SQL.BOOKMARK.PERSISTENCE SQL.QUALIFIER.TERM SQL.CONCAT.NULL.BEHAVIOR SQL.SCROLL.CONCURRENCY SQL.CURSOR.COMMIT.BEHAVIOR SQL.SCROLL.OPTIONS SQL.DATA.SOURCE.READ.ONLY SQL.STATIC.SENSITIVITY SQL.DEFAULT.TXN.ISOLATION SQL.TABLE.TERM SQL.MULT.RESULT.SETS SQL.TXN.CAPABLE SQL.MULTIPLE.ACTIVE.TXN SQL.TXN.ISOLATION.OPTION SQL.NEED.LONG.DATA.LEN SQL.USER.NAME SQL.NULL.COLLATION Supported SQL SQL.ALTER.TABLE SQL.ODBC.SQL.OPT.IEF SQL.COLUMN.ALIAS SQL.ORDER.BY.COLUMNS.IN.SELECT SQL.CORRELATION.NAME SQL.OUTER.JOINS SQL.EXPRESSIONS.IN.ORDER.BY SQL.OWNER.USAGE SQL.GROUP.BY SQL.POSITIONED.STATEMENTS SQL.IDENTIFIER.CASE SQL.PROCEDURES SQL.IDENTIFIER.QUOTE.CHAR SQL.QUALIFIER.LOCATION SQL.KEYWORDS SQL.QUALIFIER.NAME.SEPARATOR SQL.LIKE.ESCAPE.CLAUSE SQL.QUALIFIER.USAGE SQL.NON.NULLABLE.COLUMNS SQL.QUOTED.IDENTIFIER.CASE SQL.ODBC.SQL.CONFORMANCE SQL.SPECIAL.CHARACTERS SQL.SUBQUERIES SQL.UNION 395 Chapter 1: UniBasic commands and functions SQL Limits SQL.MAX.BINARY.LITERAL.LEN SQL.MAX.OWNER.NAME.LEN SQL.MAX.CHAR.LITERAL.LEN SQL.MAX.PROCEDURE.NAME.LEN SQL.MAX.COLUMN.NAME.LEN SQL.MAX.QUALIFIER.NAME.LEN SQL.MAX.COLUMNS.IN.GROUP.BY SQL.MAX.ROW.SIZE SQL.MAX.COLUMNS.IN.ORDER.BY SQL.MAX.ROW.SIZE.INCLUDES.LONG SQL.MAX.COLUMNS.IN.INDEX SQL.MAX.STATEMENT.LEN SQL.MAX.COLUMNS.IN.SELECT SQL.MAX.TABLE.NAME.LEN SQL.MAX.COLUMNS.IN.TABLE SQL.MAX.TABLES.IN.SELECT SQL.MAX.CURSOR.NAME.LEN SQL.MAX.USER.NAME.LEN SQL.MAX.INDEX.SIZE Scalar Function Information SQL.CONVERT.FUNCTIONS SQL.TIMEDATE.ADD.INTERVALS SQL.NUMERIC.FUNCTIONS SQL.TIMEDATE.DIFF.INTERVALS SQL.STRING.FUNCTIONS SQL.TIMEDATE.FUNCTIONS SQL.SYSTEM.FUNCTIONS Conversion Information SQL.CONVERT.BIGINT SQL.CONVERT.LONGVARCHAR SQL.CONVERT.BINARY SQL.CONVERT.NUMERIC SQL.CONVERT.BIT SQL.CONVERT.REAL SQL.CONVERT.CHAR SQL.CONVERT.SMALLINT SQL.CONVERT.DATE SQL.CONVERT.TIME SQL.CONVERT.DECIMAL SQL.CONVERT.TIMESTAMP SQL.CONVERT.DOUBLE SQL.CONVERT.TINYINT SQL.CONVERT.FLOAT SQL.CONVERT.VARBINARY SQL.CONVERT.INTEGER SQL.CONVERT.VARCHAR SQL.CONVERT.LONGVARBINARY Return values The following table lists the return values of the SQLGetInfo function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO –1 SQL.ERROR –2 SQL.INVALID.HANDLE SQLGetTypeInfo SQLGetTypeInfo returns information about an SQL on the data source. You can use SQLGetTypeInfo only against ODBC data sources. SQLGetTypeInfo returns a standard result set ordered by DATA.TYPE and TYPE.NAME. 396 SQLGetTypeInfo Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLGetTypeInfo (statement.env, sql.type) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. sql.type A driver-specific SQL data type, or one of the following: ▪ SQL.B.BINARY ▪ SQL.BIGINT ▪ SQL.BINARY ▪ SQL.BIT ▪ SQL.C.BINARY ▪ SQL.CHAR ▪ SQL.DATE ▪ SQL.DECIMAL ▪ SQL.DOUBLE ▪ SQL.FLOAT ▪ SQL.INTEGER ▪ SQL.LONGVARBINARY ▪ SQL.LONGVARCHAR ▪ SQL.NUMERIC ▪ SQL.REAL ▪ SQL.SMALLINT ▪ SQL.TIME ▪ SQL.TIMESTAMP ▪ SQL TINYINT ▪ SQL.VARBINARY ▪ SQL.VARCHAR ▪ SQL.WCHAR ▪ SQL.WLONGVARCHAR ▪ SQL.WVARCHAR Result set The following table lists the columns in the result set. For more detailed information about data type information, see the Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide. 397 Chapter 1: UniBasic commands and functions Column Name Data Type Description TYPE.NAME Varchar Data-source-dependent data type name. DATA.TYPE Smallint Driver-dependent or SQL data type. PRECISION Integer Maximum precision of the data type on the data source. LITERAL.PREFIX Varchar(128) Characters used to prefix a literal. LITERAL.SUFFIX Varchar(128) Characters used to terminate a literal. CREATE.PARAMS Varchar(128) Parameters for a data type definition. NULLABLE Smallint Data type accepts null values. Returns one of the following: SQL.NO.NULLS SQL.NULLABLE SQL.NULLABLE.UNKNOWN CASE.SENSITIVE Smallint Character data type is case-sensitive. Returns one of the following: TRUE if data type is a character data type and is case-sensitive FALSE if data type is not a character data type and is not case-sensitive SEARCHABLE Smallint How the WHERE clause uses the data type. Returns one of the following: SQL.UNSEARCHABLE if data type cannot be used SQL.LIKE.ONLY if data type can be used only with the LIKE predicate SQL.ALL.EXCEPT.LIKE if data type can be used with all comparison operators except LIKE SQL.SEARCHABLE if data type can be used with any comparison operator UNSIGNED.ATTRIBUTE Smallint Data type is unsigned. Returns one of the following: TRUE if data type is unsigned FALSE if data type is signed NULL if attribute is not applicable to the data type or the data type is not numeric MONEY Smallint Data type is a money data type. Returns one of the following: TRUE if data type is a money data type FALSE if it is not 398 SQLNumParams Column Name Data Type Description AUTO.INCREMENT Smallint Data type is autoincrementing. Returns one of the following: TRUE if data type is autoincrementing FALSE if it is not NULL if attribute is not applicable to the data type or the data type is not numeric LOCAL.TYPE.NAME Varchar(128) Localized version of TYPE.NAME. MINIMUM.SCALE Smallint Minimum scale of the data type on the data source. MAXIMUM.SCALE Smallint Maximum scale of the data type on the data source. Return values The following table describes the return values of the SQLGetTypeInfo function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO –1 SQL.ERROR –2 SQL.INVALID.HANDLE SQLNumParams SQLNumParams returns the number of parameters in an SQL statement. Use this function after preparing or executing an SQL statement or procedure call to find the number of parameters in an SQL statement. If the statement associated with statement.env contains no parameters, parameters is set to 0. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLNumParams (statement.env, parameters) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment containing the prepared or executed SQL statement. parameters Number of parameters in the statement. Return values The following table describes the return values of the SQLNumParams function. 399 Chapter 1: UniBasic commands and functions Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLNumResultCols SQLNumResultCols returns the number of columns in a result set. Use this function after executing an SQL statement to find the number of columns in the result set. If the executed statement was not a SELECT statement or a called procedure that produced a result set, the number of result columns returned is 0. Use this function when the number of columns to be bound to application variables is unknown, for example, when your program is processing SQL statements entered by users. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLNumResultCols (statement.env, cols) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment containing the executed SQL statement. cols Number of report columns generated. Return values The following table describes the return values of the SQLNumResultCols function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLParamOptions SQLParamOptions lets applications load an array of parameter markers in a single SQLExecDirect or SQLExecute function call. Use this function only when you are connected to an ODBC data source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. SQLParamOptions works for all parameter types—output and input/output parameters as well as the more usual input parameters. Be careful when you use matrices instead of arrays. For example, in the matrix: dim matrix(10,10) 400 SQLParamOptions the elements 1,1, 1,2, ..., 1,10, 2,1, 2,2, ... occupy consecutive memory locations. Since SQLParamOptions requires each location specified in SQLBind parameter to point to a consecutive series of values in memory, an application using a matrix must load the values of the matrix in the correct order. When the SQL statement is executed, all variables are checked, data is converted when necessary, and all values in the set are verified to be appropriate and within the bounds of the marker definition. Values are then copied to low-level structures associated with each parameter marker. If a failure occurs while the values are being checked, SQLExecDirect or SQLExecute returns SQL.ERROR, and value contains the number of the row where the failure occurred. Syntax status = SQLParamOptions (statement.env, option, value) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. option One of the following, followed by a value: SQL.PARAMOPTIONS.SET – value is an input variable containing the number of rows to process. It can be an integer from 1 through 1024. SQL.PARAMOPTIONS.READ – value is an output variable containing the number of parameter rows processed by SQLExecDirect or SQLExecute. As each set of parameters is processed, value is updated to the current row number. If SQLExecDirect or SQLExecute encounters an error, value contains the number of the row that failed. value If option is SQL.PARAMOPTIONS.SET, value is the number of rows to process. It can be an integer from 1 through 1024. 1 is the default. If option is SQL.PARAMOPTIONS.READ, value contains the number of parameter rows processed by SQLExecDirect or SQLExecute. As each set of parameters is processed, value is updated to the current row number. Return values The following table describes the return values of the SQLParamOptions function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO –1 SQL.ERROR –2 SQL.INVALID.HANDLE Examples This example shows how you might use SQLParamOptions to load a simple table. Table TAB1 has two columns: an integer column and a CHAR(30) column. $include INCLUDE ODBC.H 401 Chapter 1: UniBasic commands and functions arrsize = 20 dim p1(arrsize) dim p2(arrsize) SQLINS1 = "INSERT INTO TAB1 VALUES(?,?)" rowindex = 0 status = SQLAllocEnv(henv) status = SQLAllocConnect(henv, hdbc) status = SQLConnect(hdbc, "odbcds", "dbuid", "dbpwd") status = SQLAllocStmt(hdbc, hstmt) status = SQLPrepare(hstmt, SQLINS1) status = SQLBindParameter(hstmt, 1, SQL.B.BASIC, SQL.INTEGER, 0, 0, p1(1), SQL.PARAM.INPUT) status = SQLBindParameter(hstmt, 2, SQL.B.BASIC, SQL.CHAR, 30, 0, p2(1), SQL.PARAM.INPUT) status = SQLParamOptions(hstmt, SQL.PARAMOPTIONS.SET, arrsize) for index = 1 to arrsize p1(index) = index p2(index) = "This is row ":index next index * now execute, delivering 20 sets of parameters in one network operation stexec = SQLExecute(hstmt) status = SQLParamOptions(hstmt, SQL.PARAMOPTIONS.READ, rowindex) if stexec = SQL.ERROR then print "Error in parameter row number ":rowindex end else print rowindex:" parameter marker sets were processed" end SQLPrepare SQLPrepare passes an SQL statement or procedure call to the data source in order to prepare it for execution by SQLExecute. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLPrepare (statement.env, statement) Use this function to deliver either an SQL statement or a call to an SQL procedure to the data source where it can prepare to execute the passed SQL statement or the procedure. The application subsequently uses SQLExecute to tell the data source to execute the prepared SQL statement or procedure. What happens when the data source executes the SQLPrepare call depends on the data source. In many cases the data source parses the SQL statement and generates an execution plan that allows rapid, efficient execution of the SQL statement. Use SQLPrepare and SQLExecute functions when you are issuing SQL statements or calling a procedure repeatedly. You can supply values to a prepared INSERT or UPDATE statement and issue an SQLExecute call each time you change the values of parameter markers. SQLExecute sends the current values of the parameter markers to the data source and executes the prepared SQL statement or procedure with the current values. 402 SQLRowCount Note: Before you issue an SQLExecute call, all parameter markers in the SQL statement or procedure call must be defined using an SQLBindParameter call, otherwise SQLExecute returns an error. If the parameter type of an SQLBindParameter procedure is SQL.PARAM.OUTPUT or SQL.PARAM.INPUT.OUTPUT, values are returned to the specified program variables. ODBC data sources If you execute a stored procedure or enter a command batch with multiple SELECT statements, the results of only the first SELECT statement are returned. Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment from a previous SQLAllocStmt. statement Either an SQL statement or a call to an SQL procedure, to be executed at the data source. To call an SQL procedure, use the following syntax: procedure parameter [ { ] CALL procedure [ ( [ parameter [ , parameter ] … ] ) ] [ } ] Name of the procedure. If the procedure name contains characters other than alphabetic or numeric, enclose the name in double quotation marks. To embed a single double quotation mark in the procedure name, use two consecutive double quotation marks. Either a literal value or a parameter marker that marks where to insert values to send to or receive from the data source. Programmatic SQL uses a ? (question mark) as a parameter marker. Use parameters only if the procedure is a subroutine. The number and order of parameters must correspond to the subroutine arguments. For an ODBC data source, parameters should be of the same data type as the procedure requires. Return values The following table describes the returns values of the SQLPrepare function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLRowCount SQLRowCount returns the number of rows changed by UPDATE, INSERT, or DELETE statements, or by a called procedure that executes one of these statements. 403 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Statements such as GRANT and CREATE TABLE, which do not update rows in the database, return 0 in rows. For a SELECT statement, a 0 row count is always returned, unless the SELECT statement includes the TO SLIST clause. In that case, SQLRowCount returns the number of rows in the select list. The value of rows returned after executing a stored procedure at the data source may not be accurate. It is accurate for a single UPDATE, INSERT, or DELETE statement. Syntax status = SQLRowCount (statement.env, rows) Parameters The following table describes each parameter of the syntax. Input Variable Description statement.env SQL statement environment containing the executed SQL statement. rows Number of rows affected by the operation. Return values The following table describes the return values of the SQLRowCount function. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE SQLSetConnectOption SQLSetConnectOption controls some aspects of the connection to a data source. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLSetConnectOption (connect.env, option, value) Parameters The following table describes each parameter of the syntax. 404 SQLSetConnectOption Parameter Description connect.env Connection environment returned from a previous SQLAllocConnect. Options The following table describes the options available with SQLSetConnectOption. Option Description SQL.AUTO.COMMIT Determines the commit mode for transactions. When you use this option, the connection must already be established, and the SQL.TX.PRIVATE option must be set to SQL.TX.PRIVATE.ON. Valid settings are: SQL.AUTO.COMMIT.ON – Puts a private connection into autocommit mode. SQL.AUTO.COMMIT.OFF – Puts a private connection into manual commit mode. SQL.TX.PRIVATE Determines if a transaction is controlled by UniBasic or the data source. Valid settings are: SQL.TX.PRIVATE.ON – Transaction processing is controlled directly by the DBMS on the server. SQL.TX.PRIVATE.OFF – Transaction processing is fully managed by UniBasic. SQL.TXN.ISOLATION Determines the isolation level on the server. When you use this option, the connection must already be established, the SQL.TX.PRIVATE option must be set to SQL.TX.PRIVATE.ON, and no transactions may be active. Valid settings are: SQL.TXN.READ.UNCOMMITTED – Sets the isolation level on the server to 1. SQL.TXN.READ.COMMITTED – Sets the isolation level on the server to 2. SQL.TXN.REPEATABLE.READ – Sets the isolation level on the server to 3. SQL.TXN.SERIALIZABLE – Sets the isolation level on the server to 4. Return values The following table describes the return values for the SQLSetConnectOption. Return value Description 0 SQL.SUCCESS -1 SQL.ERROR -2 SQL.INVALID.HANDLE Private transactions SQL.TX.PRIVATE.ON frees the connection from being managed by the UniData transaction manager. When you make a connection private, the application can use the SQL.AUTOCOMMIT option to put the 405 Chapter 1: UniBasic commands and functions connection into either autocommit mode or manual commit mode. By default, private connections are in autocommit mode, in which each SQL statement is treated as a separate transaction, committed after the statement is executed. In manual commit mode the application can do either of the following: ▪ ▪ Use the SQLTransact function to commit or roll back changes to the database. Set the SQL.AUTOCOMMIT option of SQLSetConnectOption to SQL.AUTOCOMMIT.ON. This commits any outstanding transactions and returns the connection to autocommit mode. You must return the connection to autocommit mode before using SQLDisconnect to close the connection. You can do this in two ways: ▪ ▪ Set the SQL.AUTOCOMMIT option of SQLSetConnectOption to SQL.AUTOCOMMIT.ON Set the SQL.TX.PRIVATE option of SQLSetConnectOption to SQL.TX.PRIVATE.OFF When a connection is private, SQL.TXN.ISOLATION lets the application define the default transaction isolation level at which to execute server operations. To determine what isolation levels the data source supports, use the SQL.TXN.ISOLATION.OPTION option of the SQLGetInfo function. This returns a bitmap of the options the data source supports. The application can then use the UniBasic BIT functions to determine whether a particular bit is set in the bitmap. Use SQLSetConnectOption with the SQL.TXN.ISOLATION option only in the following two places: ▪ ▪ Immediately following an SQLConnect function call Immediately following an SQLTransact call to commit or roll back an operation Whenever you execute an SQL statement, a new transaction exists, which makes setting the SQL.TXN.ISOLATION option illegal. If a transaction is active when the SQL.TXN.ISOLATION.OPTION is set, UniData BCI returns SQL.ERROR and sets SQLSTATE to S1C00. SQLSetParam SQLSetParam is a synonym for SQLBindParameter. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. SQLSpecialColumns SQLSpecialColumns gets information about columns in a table. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLSpecialColumns (statement.env, col.type, schema, owner, tablename, IDscope, null) SQLSpecialColumns lets applications scroll forward and backward in a result set to get the most recent data from a set of rows. Columns returned for column type SQL.BEST.ROWID are guaranteed not to change while positioned on that row. Columns of the row ID can remain valid even when the cursor is not positioned on the row. The application can determine this by checking the SCOPE column in the result set. 406 SQLSpecialColumns Once the application gets values for SQL.BEST.ROWID, it can use these values to reselect that row within the defined scope. The SELECT statement is guaranteed to return either no rows or one row. Columns returned for SQL.BEST.ROWID can always be used in an SQL select expression or WHERE clause. However, SQLColumns does not necessarily return these columns. If no columns uniquely identify each row in the table, SQLSpecialColumns returns a row set with no rows; a subsequent call to SQLFetch returns SQL.NO.DATA.FOUND. Columns returned for column type SQL.ROWVER let applications check if any columns in a given row have been updated while the row was reselected using the row ID. If col.type, IDscope, or null specifies characteristics not supported by the data source, SQLSpecialColumns returns a result set with no rows, and a subsequent call to SQLFetch returns SQL.NO.DATA.FOUND.For complete details about the SQLSpecialColumns function, see the Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide. Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. col.type Type of column to return. col.type is one of the following: SQL.BEST.ROWID – Returns the best column or set of columns that uniquely identifies a row in a table. SQL.ROWVER – Returns the column or columns that are automatically updated when any value in the row is updated by a transaction. schema Qualifier name for tablename. If a driver supports qualifiers for some tables but not others, use an empty string for tables that do not have qualifiers. owner Name of the owner of the table. If a driver supports owners for some table but not others, use an empty string for tables that do not have owners. tablename Name of the table. IDscope Minimum required scope of the row ID. IDscope is one of the following: SQL.SCOPE.CURROW – Row ID is guaranteed to be valid only while positioned on that row. SQL.SCOPE.TRANSACTION – Row ID is guaranteed to be valid for the duration of the current transaction. SQL.SCOPE.SESSION – Row ID is guaranteed to be valid for the duration of the session. null Can be one of the following: SQL.NO.NULLS – Excludes special columns that can have null values. SQL.NULLABLE – Returns special columns even if they can have null values. Return values The following table describes the return values of the SQLSpecialColumns function. Return value Description 0 SQL.SUCCESS 407 Chapter 1: UniBasic commands and functions Return value Description 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE Results are returned as a standard result set ordered by SCOPE. The following table lists the columns in the result set. The lengths of VARCHAR columns are maximums; the actual lengths depend on the data source. To get the length of the COLUMN.NAME column, use the SQL.MAX.COLUMN.NAME.LEN option of the SQLGetInfo function. Column Name Data Type Description SCOPE Smallint Actual scope of the row ID. It contains one of the following: SQL.SCOPE.CURROW SQL.SCOPE.TRANSACTION SQL.SCOPE.SESSION The null value is returned when col.type is SQL.ROWVER. COLUMN.NAME Varchar(128) Column identifier. Not null DATA.TYPE Smallint Not null TYPE.NAME Varchar(128) Not null 408 Either an ODBC SQL data type or a driver-specific SQL data type. Data-source-dependent data type name. PRECISION Integer Precision of the column on the data source. The null value is returned for data types where precision does not apply. LENGTH Integer The length in bytes of data transferred on an SQLGetData or SQLFetch if SQL.C.DEFAULT is specified. For numeric data, this size can differ from the size of the data stored on the data source. This value is the same as the PRECISION column for character or binary data. SCALE Smallint The scale of the column on the data source. The null value is returned for data types where scale does not apply. SQLStatistics Column Name Data Type Description PSEUDO.COLUMN Smallint Indicates whether the column is a pseudo-column: SQL.PC.UNKNOWN SQL.PC.PSEUDO SQL.PC.NOT.PSEUDO Pseudo-columns should not be quoted with the identifier quote character returned by SQLGetInfo. SQLStatistics SQLStatistics gets a list of statistics about a single table and its indexes. Use this function only when you are connected to an ODBC data source. SQLStatistics returns information as a standard result set ordered by NON.UNIQUE, TYPE, INDEX.QUALIFIER, INDEX.NAME, and SEQ.IN.INDEX. The result set combines statistics for the table with statistics for each index. Note: SQLStatistics might not return all indexes. For example, a driver might return only the indexes in files in the current directory. Applications can use any valid index regardless of whether it is returned by SQLStatistics. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLStatistics (statement.env, schema, owner, tablename, index.type, accuracy) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. schema Qualifier name for tablename. If a driver supports qualifiers for some tables but not others, use an empty string for tables that do not have qualifiers. owner Name of the owner of the table. If a driver supports owners for some table but not others, use an empty string for tables that do not have owners. tablename Name of the table. index.type One of the following: SQL.INDEX.UNIQUE SQL.INDEX.ALL 409 Chapter 1: UniBasic commands and functions Parameter Description accuracy The importance of the CARDINALITY and PAGES columns in the result set: SQL.ENSURE – The driver unconditionally gets the statistics. SQL.QUICK – The driver gets results only if they are readily available from the server. The driver does not ensure that the values are current. Return values The following table describes the return values of the SQLStatistics function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO -1 SQL.ERROR -2 SQL.INVALID.HANDLE The lengths of VARCHAR columns are maximums; the actual lengths depend on the data source. Use SQLGetInfo to determine the actual lengths of the TABLE.QUALIFIER, TABLE.OWNER, TABLE.NAME, and COLUMN.NAME columns. Column Name Data Type Description TABLE.QUALIFIER Varchar(128) Table qualifier identifier (schema) of the table. The null value is returned if it is not applicable to the data source. If a driver supports qualifiers for some tables but not others, it returns an empty string for tables without qualifiers. TABLE.OWNER Varchar(128) Name of the owner of the table. The null value is returned if it is not applicable to the data source. If a driver supports owners for some tables but not others, it returns an empty string for tables without owners. TABLE.NAME Varchar(128) Name of the table. Not null NON.UNIQUE Smallint The index prohibits duplicate values: TRUE if the index values can be nonunique. FALSE if the index values must be unique. NULL if TYPE is SQL.TABLE.STAT. INDEX.QUALIFIER Varchar(128) Index qualifier identifier used by the DROP INDEX statement. The null value is returned if the data source does not support index qualifiers or if TYPE is SQL.TABLE.STAT. If a nonnull value is returned, it must be used to qualify the index name in a DROP INDEX statement, otherwise the TABLE.OWNER name should be used to qualify the index name. 410 SQLStatistics Column Name Data Type Description INDEX.NAME Varchar(128) Name of the index. The null value is returned if TYPE is SQL.TABLE.STAT. TYPE Smallint Type of information returned: Not null SQL.TABLE.STAT indicates a statistic for the table. SQL.INDEX.CLUSTERED indicates a clustered index. SQL.INDEX.HASHED indicates a hashed index. SQL.INDEX.OTHER indicates another type of index. SEQ.IN.INDEX Smallint Column sequence number in index, starting with 1. The null value is returned if TYPE is SQL.TABLE.STAT. COLUMN.NAME Varchar(128) Name of a column. If the column is based on an expression, the expression is returned. If the expression cannot be determined, an empty string is returned. If the index is filtered, each column in the filter condition is returned (this may require more than one row). The null value is returned if TYPE is SQL.TABLE.STAT. COLLATION Char(1) Sort sequence for the column: A indicates ascending. B indicates descending. The null value is returned if the data source does not support column sort sequence. CARDINALITY Integer Number of rows in the table if TYPE is SQL.TABLE.STAT. Number of unique values in the index if TYPE is not SQL.TABLE.STAT. The null value is returned if the value is not available from the data source or if it is not applicable to the data source. PAGES Integer Number of pages for the table if TYPE is SQL.TABLE.STAT. Number of pages for the index if TYPE is not SQL.TABLE.STAT. The null value is returned if the value is not available from the data source or if it is not applicable to the data source. FILTER.CONDITION Varchar(128) If the index is filtered, the filter condition, or an empty string if the filter condition cannot be determined. The null value is returned if the index is not filtered, or if it cannot be determined that the index is filtered, or TYPE is SQL.TABLE.STAT. If the row in the result set corresponds to a table, the driver sets TYPE to SQL.TABLE.STAT and sets the following columns to NULL: 411 Chapter 1: UniBasic commands and functions ▪ NON.UNIQUE ▪ INDEX.QUALIFIER ▪ INDEX.NAME ▪ SEQ.IN.INDEX ▪ COLUMN.NAME ▪ COLLATION If CARDINALITY or PAGES are not available from the data source, the driver sets them to NULL. For complete details about the SQLStatistics function, see the Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide. SQLTables SQLTables returns a result set listing the tables matching the search patterns. Use this function only when you are connected to an ODBC data source. This function returns statement.env as a standard result set of five columns containing the schemas, owners, names, types, and remarks for all tables found by the search. The search criteria arguments can contain a literal, an SQL LIKE pattern, or be empty. If a literal or LIKE pattern is specified, only values matching the pattern are returned. If a criterion is empty, tables with any value for that attribute are returned. owner cannot specify a LIKE pattern. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax status = SQLTables (statement.env, schema, owner, tablename, type) Parameters The following table describes each parameter of the syntax. Parameter Description statement.env SQL statement environment. schema Schema name search pattern. owner Table owner number search pattern. tablename Table name search pattern. type Table type (one of the following: BASE TABLE, VIEW, ASSOCIATION, or TABLE) search pattern. You can access the result set with SQLFetch. These five columns have the following descriptors: 412 Column Name Data Type TABLE.SCHEMA VARCHAR(128) TABLE.OWNER VARCHAR(128) TABLE.NAME VARCHAR(128) TABLE.TYPE VARCHAR(128) REMARKS VARCHAR(254) SQLTransact Special search criteria Three special search criteria combinations enable an application to enumerate the set of schemas, owners, and tables: Table Qualifier Table Owner Table Name Table Type Return Is ... % empty string empty string ignored Set of distinct schema names empty string ignored Set of distinct table owners empty string % Set of distinct table types empty string empty string empty string The ability to obtain information about tables does not imply that you have any privileges on those tables. Return values The following table describes the return values of the SQLTables function. Return value Description 0 SQL.SUCCESS 1 SQL.SUCCESS.WITH.INFO –1 SQL.ERROR –2 SQL.INVALID.HANDLE SQLSTATE Values The following table describes the SQLSTATE values. SQLSTATE Description S1000 General error for which no specific SQLSTATE code has been defined. S1001 S1008 S1010 Memory allocation failure. Cancelled. Execution of the statement was stopped by an SQLCancel call. Function sequence error. The statement.env specified is currently executing an SQL statement. S1C00 The table owner field was not numeric. 24000 Invalid cursor state. Results are still pending from the previous SQL statement. Use SQLCancel to clear the results. 42000 Syntax error or access violation. This can be caused by a variety of reasons. The native error code returned by the SQLError call indicates the specific error that occurred. SQLTransact SQLTransact requests a COMMIT or ROLLBACK for all SQL statements associated with a connection or all connections associated with an environment. Use this function only when you are connected to an ODBC data source. 413 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. This function provides the same transaction functions as the UniBasic statement TRANSACTION COMMIT. When connect.env is a valid connection environment with SQL.AUTOCOMMIT set to OFF, SQLTransact commits the connection. To use SQLTransact, all of the following conditions must be met: ▪ The SQL.TX.PRIVATE option of SQLSetConnectOption is set to SQL.TX.PRIVATE.ON. ▪ The SQL.AUTOCOMMIT option is set to SQL.AUTOCOMMIT.OFF. ▪ The connection is active. Setting bci.env to a valid environment handle and connect.env to SQL.NULL.HDBC requests the server to try to execute the requested action on all hdbcs that are in a connected state. If any action fails, SQL.ERROR is returned, and the user can determine which connections failed by calling SQLError for each connection environment in turn. If you call SQLTransact with a type of SQL.COMMIT or SQL.ROLLBACK when no transaction is active, SQL.SUCCESS is returned. Syntax status = SQLTransact (bci.env, connect.env, type) Parameters The following table describes each parameter of the syntax. Parameter Description bci.env UniData BCI environment. connect.env Connection environment or SQL.NULL.HDBC. type One of the following: SQL.COMMIT – Writes all modified data to the data source, releases all lock acquired by the current transaction, and terminates the transaction. SQL.ROLLBACK – Discards any changes written during the transaction and terminates it. Return values The following table describes the return values of the SQLTransact function. Return value Description 0 SQL.SUCCESS –1 SQL.ERROR –2 SQL.INVALID.HANDLE SQLSTATE values The following table describes the SQLSTATE values for the SQLTransact function. 414 SQRT SQLSTATE Description S1000 General error for which no specific SQLSTATE code has been defined. S1001 Memory allocation failure. S1012 type did not contain SQL.COMMIT or SQL.ROLLBACK. 08003 No connection is active on connect.env. 08007 The connection associated with the transaction failed during the execution of the function. It cannot be determined if the requested operation completed before the failure. SQRT The UniBasic SQRT function returns the square root of a positive numeric argument. Syntax SQRT(num.expr) Examples In the following example, the program statement prints SQUARE ROOT OF 16 IS 4: PRINT "SQUARE ROOT OF 16 IS ":SQRT(16) SQUOTE The UniBasic SQUOTE function encloses a string with single quotation marks. Syntax SQUOTE(str.expr) Examples In the following example, the program statement prints ‘This is ‘a’ test’ on the screen: PRINT SQUOTE("This is 'a' test") In the next example, the program segment prints ‘This is another test’ on the screen: X = "This is another test" PRINT SQUOTE(X) Related commands Language Command UniBasic QUOTE 415 Chapter 1: UniBasic commands and functions SSUB The UniBasic SSUB function subtracts the second string number from the first string number and returns the result as a string number. Arguments can be any valid numbers or string numbers of any magnitude or precision. Tip: Processing string data type numbers rather than numeric data type numbers degrades processing speed. Numbers specified in quotation marks are string data type. Numbers specified without quotation marks are numeric data type. The data type of a variable is determined by the data first loaded into it. If x or y contains nonnumeric data, UniData displays an error message and returns a result of 0. The SSUB function results in a string number, so you can use the function in any expression in which a string number is valid. Because string numbers can exceed the range of numbers that standard arithmetic operators can accommodate, you might not want to use the SSUB function in any expression in which a standard number is valid. Syntax SSUB(x, y) Examples In the following example, the program statement assigns to B the result of subtracting 1.4149 from A, and then prints the answer 98.5851: A = 100 B = SSUB(A, "1.4149") PRINT B STATUS The UniBasic STATUS function returns a code indicating the condition of the command or function just executed. Several UniBasic commands and functions set STATUS function return values. For information about the return values set by a particular command or function, see Commands that set STATUS() return values, on page 537. Syntax STATUS( ) Examples In the following example, the STATUS function returns a value of 0, indicating a successful conversion of a valid date by OCONV. STATUS would return 1 if 7334 were an invalid input date or 2 if D were an invalid conversion specification. PRINT OCONV(7334,"D") PRINT STATUS() 416 STOP Related commands Language Command UniBasic SYSTEM @variables For information, see UniBasic@variables, on page 520. STOP The UniBasic STOP command halts execution of the current program. If you specify an expression, UniData prints the expression on the display terminal before halting the program. expr can contain variables, functions, and arithmetic or string operators. STOP returns the cursor to the UniData prompt, a calling menu, or a calling paragraph, depending on how the program was executed. Tip: The ABORT command returns the cursor to UniData level regardless of what process initiated the program. Note: The STOP command performs differently with BASICTYPE P. The following syntax is valid in BASICTYPE P: STOP [message-id] STOP [expr,...] message-id must evaluate to a key contained in UniData error message file ERRMSG. expr can contain variables, functions, and arithmetic or string operators. Syntax STOP [expr] Examples In the following example, the program segment attempts to read a record from a file. If the record does not exist, the program aborts and prints the message RECORD IS MISSING at line 10, column 10 on the terminal. CUST.ID = 1234 OPEN 'CLIENTS' READONLY TO CLIENT.FILE ELSE STOP "Cannot Open" READ REC FROM CLIENTR, CLIENT.ID ELSE STOP @(10,10):'RECORD IS MISSING' END In the next example, the segment prints a prompt if an error flag ERR.FLAG has been set, and reads the user’s input into the variable ANS. If ANS equals Y, the program stops. ERR.FLAG = 1 IF ERR.FLAG THEN PRINT "STOP PROGRAM?" INPUT ANS IF ANS = "Y" THEN STOP END In the next example, in BASICTYPE P, the program segment prints an error message from record 10075 in the ERRMSG file if the program aborts: 417 Chapter 1: UniBasic commands and functions If A < 0 THEN ABORT 10075 Related commands Language Command UniBasic ABORT STR The UniBasic STR function returns a string composed of a number of repetitions of a string. Syntax STR(str.expr, num.expr) Null value handling If a function encounters the null value in a parameter when a number is expected (num.expr), a warning message displays, and UniBasic uses 0. Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a string expression to concatenate num.expr times. num.expr Specifies the number of repetitions of the string expression to concatenate. Examples In the following example, the program statement prints a string of 25 hyphens on the terminal screen: PRINT STR("-",25) Related commands Language Command UniBasic STRS STRS The UniBasic STRS function returns each element of dyn.array the number of times specified in expr. Syntax STRS(dyn.array, expr) 418 submitRequest Null value handling If a function encounters the null value in a parameter when a number is expected (expr), a warning message displays, and UniBasic uses 0. Examples In the following example, the program segment prints the each element of the ARR1 dynamic array 10 times: ARR1 = 1:@AM:2:@AM:3:@AM:4:@AM:5 ARR2 = STRS(ARR1,10) PRINT ARR2 This results in the following: 1111111111}2222222222}3333333333}4444444444}5555555555 Related commands Language Command UniBasic STR submitRequest The submitRequest function submits a request and gets a response. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax submitRequest(request_handle, time_out, post_data, response_headers, response_data, http_status) The request is formed on the basis of default HTTP settings and previous setRequestHeader() and addRequestParameter() values. Specifically, for a GET method with parameters added, UniBasic creates a parameter string (properly encoded) and attaches to the URL string after the ‘?’ character. For a POST request with non-empty post_data, the data is attached to the request message as is. No encoding is performed, and any parameters added through addRequestParameter() will be totally ignored. Otherwise the following processing will be performed. For a POST request with default content type, the parameter string will be assembled, a ContentLength header created, and then the string is attached as the last part of the request message. For a POST request with multipart/* content type, a unique boundary string is created and then multiple parts will be generated in the sequence they were added through calling addRequestParameter(). Each will have a unique boundary, followed by optional Content-* headers, and data part. The total length is calculated and a Content-Length header is added to the message header. The request is then sent to the Web server identified by the URL supplied with the request and created through createRequest() (maybe through a proxy server). UniBasic is then waiting for the web server to respond. Once the response message is received, the status contained in the response is analyzed. 419 Chapter 1: UniBasic commands and functions If the response status indicates that redirection is needed (status 301, 302, 305 or 307), it will be performed automatically, up to five consecutive redirections (the limit is set to prevent looping, suggested by RFC 2616).If the response status is 401 or 407 (access denied), the response headers will be examined to see if the server requires (or accepts) BASIC authentication. If no BASIC authentication request is found, the function will return with an error. Otherwise default Authentication (set by setHTTPDefault) will be used to resend the request. If no default authentication is set, and no other cached user authentication is found, the function will return with an error. If the user provides authentication information through “Authorization” or “Proxy-Authorization” header, the encoded information is cached. If later, a BASIC authentication request is raised, no default authentication is found, and only one user/password encoding is cached, then it will be used to resend the request. The response from the HTTP server is disposed into response_header and response_data. It is the user’s responsibility to parse the headers and data. UniBasic only performs transfer encoding (chunked encoding), and nothing else is done on the data. In other words, content-encoding (gzip, compress, deflate, and so forth) are supposed to be handled by the user, as with all MIME types. Also, if a response contains header “Content-type: multipart/*”, all the data (multiple bodies enclosed in “boundary delimiters”, see RFC 2046) will be stored in response_data. It is the user’s responsibility to parse it according to “boundary” parameter. Parameters The following table describes each parameter of the syntax. Parameter Description request_handle The handle to the request. time_out The timeout value (in milliseconds) before the wait response is abandoned. post_data The data sent with the POST request. response_headers A dynamic array to store header/value pairs. response_data The resultant data (may be in binary format). http_status A dynamic array containing the status code and explanatory text. For a list of http_status codes, see the HTTP standard RFC 2616. The following table describes the status of each return code. Return codes Status 0 Success. 1 Invalid request handle. 2 Timed out. 3 Network Error. 4 Other Errors. SUBROUTINE The UniBasic SUBROUTINE command determines the beginning of an external subroutine. The SUBROUTINE statement must be the first noncomment line in a subroutine. 420 SUBROUTINE You can specify arguments to pass data between the main program and the subroutine. If you pass arguments, the number of arguments in the CALL statement and the SUBROUTINE statement must match, although variable names do not need to be the same. Changes made to arguments in the subroutine retain their new values when UniData exits the subroutine and control reverts to the calling program. When calling a subroutine from UniData ODBC, the subroutine name cannot contain any special characters. Note: All subroutines must be cataloged using the ECL CATALOG command before being called. For more information about the CATALOG command, see the UniData Commands Reference. A subroutine name cannot exceed 65 characters. If it does, the program will fail to compile. Syntax SUBROUTINE sub.name[(argument1 [, argument2] ...)] Parameters The following table describes each parameter of the syntax. Parameter Description sub.name Specifies the subroutine name. (argument1 ,argument2 ...) Specifies arguments to pass to the subroutine. The arguments can be simple variables, dynamic arrays, or dimensioned arrays. Examples In the following example, the main program prompts the user for two numbers. These are sent to the subroutine COMP, together with an empty variable C. The subroutine, COMP, renames the passed arguments, calculates their average, and returns the result in the third variable. This is the main program: REM Main program PRINT "Enter A,B:":; INPUT A; INPUT B CALL COMP(A,B,C) PRINT "Average = ":C STOP This is the subroutine: REM Calculates average of two numbers SUBROUTINE COMP(X,Y,Z) Z = (X+Y)/2 RETURN END The sample program in Developing UniBasic Applications includes the following subroutine, which is called by the main program to display messages on the screen: SUBROUTINE DISPLAY_MESSAGE(MESSAGE) DISPLAY @(5,20):MESSAGE DISPLAY @(5,21):"Press the (Return) key.": INPUT PAUSE,1_ RETURN 421 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic CALL, PROGRAM, SUBROUTINE (Update Trigger), SUBROUTINE (Delete Trigger) UniData CATALOG For information, see the UniData Commands Reference. SUBROUTINE (Update Trigger) Triggers enforce user-defined constraints that must be met before data can be updated. The trigger is associated with the data file, so it verifies any access to the data. A UniBasic trigger subroutine or function serves as an UPDATE trigger. The SUBROUTINE or FUNCTION definition must be the first line in the UniBasic trigger. You must include a RETURN statement in the function: RETURN [execstat] Syntax SUBROUTINE trigname(execstat, dictflag, filename, record.ID.expr, new_recordval, old_recordval) FUNCTION trigname(dictflag, filename, record.ID.expr, new_recordval, old_recordval) Points to remember ▪ When you attempt to update a record, UniData calls the trigger, passing the file name, DICT if dictionary file, record ID, and the input value before updating the record. The subroutine returns the execution status and the new record value. ▪ If the update request fails, the subroutine must return an execstat value of 0. If the request passes, the return value must be 1. Tip: You can call a C routine from the UniBasic subroutine or function that is called from a trigger. Note: A subroutine name cannot exceed 65 characters. If it does, the program will fail to compile. Parameters The following table describes each parameter of the syntax. Paragraph Description trigname Name of the globally cataloged subroutine. execstat Execution status returned by the trigger subroutine: 0 – No updates allowed. 1 – Update is allowed. 2 – Update is allowed; uses the return recordval. 422 SUBROUTINE (Update Trigger) Paragraph Description dictflag “DICT” – Indicates that the trigger is operating on the dictionary file. “” – Indicates that the trigger is operating on the data file. The quotation marks are required. filename The name of the file on which the trigger is operating. record.ID.expr The record to be updated. new_recordval The input record value submitted to the UPDATE trigger. recordval is both an input and output parameter. The trigger can change this value (for example, by performing a conversion). Then, if the trigger sets execstat to 2, this value is passed back in recordval and updates the data record. Only strings and numbers are valid. If the value returned in recordval is invalid, the record is not updated, even if the trigger subroutine sets execstat to 2. In this case, the UniBasic STATUS function returns 3 when executed immediately after the command that calls the trigger. Only strings and numbers are valid. Any change to this parameter in the After-Event trigger is not recommended and will be ignored. old_.recordval The original record content before being overwritten by the new value. STATUS function return values After you execute a trigger subroutine, the STATUS function returns one of the values described in the following table. Tip: The UniBasic STATUS function returns the status of the preceding command. You can place it within the trigger subroutine to learn about the status of individual commands executed within the trigger. If you place it immediately after the statement that calls the trigger, it returns the status of the UniBasic command as determined by the trigger. The trigger subroutine also returns a value indicating its status in the parameter execstat. These values returned in execstat are listed in the Parameters section. Return value Description 0 No error. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the update or delete is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). 5 After Trigger program returns 0 indicating an error occurred. 6 After Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 423 Chapter 1: UniBasic commands and functions Examples The following example begins with an UPDATE trigger subroutine called TRIG1. Because the return status is always 0, no record in the file can be updated. SUBROUTINE TRIG1(exec.stat,dict.flag,trig.name,rec.id.expr,rec.val) exec.stat=0 RETURN Next, we create the trigger, associate it with the ORDERS file, and list the triggers associated with the ORDERS file: :CREATE.TRIGGER ORDERS TRIG1 UPDATE :LIST.TRIGGER ORDERS BEFORE UPDATE TRIGGER: TRIG1 BEFORE DELETE TRIGGER: not defined Finally, we attempt to copy record 969 into record 970 in the ORDERS file, and the trigger prevents the copy: :COPY FROM ORDERS TO ORDERS 969,970 Cannot update 970, due to trigger constraint. 0 records copied SUBROUTINE (Delete Trigger) A UniBasic subroutine or function serves as the DELETE trigger that is executed when you attempt to delete a record in the subject file. The SUBROUTINE or FUNCTION definition must be the first line in the UniBasic trigger subroutine. You must include a RETURN statement in the function: RETURN [execstat] Syntax SUBROUTINE trigname(execstat, dictflag, filename, record.ID.expr, old_recordval) FUNCTION trigname(dictflag, filename, record.ID.expr, old_recordval) Points to Remember Remember the following items when writing a subroutine that is triggered by a user attempting to delete a record: ▪ When you attempt to delete a record, UniData calls the trigger, passing the file name, DICT if dictionary file, record ID, and the input value before deleting the record. The subroutine returns the execution status. ▪ If the delete request fails the constraint, the subroutine must return a status of 0. If the request passes, the return must be 1. Tip: You can call a C routine from the UniBasic subroutine or function that is called from a trigger. 424 SUBROUTINE (Delete Trigger) Note: A subroutine name cannot exceed 65 characters. If it does, the program will fail to compile. Parameters The following table describes each parameter of the syntax. Parameter Description trigname Name of the globally cataloged subroutine. execstat Execution status returned by the trigger subroutine. Valid values for this include: 0 – Delete is not allowed. 1 – Delete is allowed. dictflag “DICT” – Indicates that the trigger is operating on the dictionary file. “” – Indicates that the trigger is operating on the data file. The quotation marks are required. filename Name of the file the trigger is operating on. record.ID.expr Record to be deleted. old_recordval The original record content before being overwritten by the new value. STATUS function return values After you execute a trigger subroutine, the STATUS function returns one of the values described in the following table. Tip: The UniBasic STATUS function returns the status of the preceding command. You can place it within the trigger subroutine to learn about the status of individual commands executed within the trigger. If you place it immediately after the statement that calls the trigger, it returns the status of the UniBasic command as determined by the trigger. The trigger subroutine also returns a value indicating its status in the parameter execstat. These values returned in execstat are listed in the “Parameters” section. Return value Description 0 No error. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the update or delete is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). 5 After Trigger program returns 0 indicating an error occurred. 6 After Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 425 Chapter 1: UniBasic commands and functions Examples The following example begins with a DELETE trigger subroutine called DEL_TRIG. This subroutine always returns 1 and always allows records to be deleted: SUBROUTINE DEL_TRIG(exec.stat,dict.flag,trig.name,rec.id.expr,rec.val) exec.stat=1 RETURN Note: After creating and compiling the subroutine, you must catalog it globally. Next, we create the trigger and associate it with the ORDERS file: :CREATE.TRIGGER ORDERS DEL_TRIG DELETE Finally, we delete records in the ORDERS file. The trigger always allows the deletion because the subroutine sets the execution status to 1. :DELETE ORDERS 912 '912' deleted. : SUBSTRINGS The UniBasic SUBSTRINGS function extracts strings from elements within a dynamic array. SUBSTRINGS supports multibyte languages. Syntax SUBSTRINGS(dyn.array, num.expr1, num.expr2) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array Specifies the dynamic array from which to extract the substring. num.expr1 Specifies a starting position for the extraction operation. num.expr2 Specifies the number of characters to return. Examples In the following example, the program segment extracts the first character of each element of the dynamic array LASTNAMES. This results in S}J}J}H. LASTNAMES = "Smith":@AM:"Jones":@AM:"Johnson":@AM:"Howard" LINITIAL = SUBSTRINGS(LASTNAMES,1,1) PRINT LINITIAL 426 SUM Related commands Language Command UniBasic DEL, INSERT, REMOVE, REPLACE SUM The UniBasic SUM function adds the numeric values in the dynamic array dyn.array according to dynamic array delimiters. SUM begins with the lowest level of delimiter and sums all values to the next level. You can input a range, starting position, and level at which to perform the sum. Note: The SUM function can contain a maximum of 1621 characters. Syntax SUM(dyn.array [, <attribute.expr [, value.expr]>] [, start.expr [, stop.expr]]) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array Specifies a dynamic array of numeric values to sum. , <attribute.expr value.expr>, start.expr , stop.expr Specifies a range within the dynamic array to sum. The range is specified as an attribute, a value, a starting point, and a stopping point. Tip: To sum all elements in an array, execute SUM twice. The first execution sums each group of subvalues and returns a string of numeric values; the second SUM returns a single value. Examples In the following example, the program segment begins with an array of two values, each with two subvalues. The SUM function sums the subvalues and returns a string with two numeric values. NUM.ARRAY = 12:@SM:10:@VM:15:@SM:15 VAL1 = SUM(NUM.ARRAY) This results in: VAL1 = 22:@VM:30 In the next example, the program statement sums VAL1 and returns the numeric value 52 with no dynamic array delimiters: VAL1 = SUM(VAL1) SWAP The UniBasic SWAP command replaces all occurrences of one substring with a second substring. The search string does not have to be the same length as the replacement string. SWAP supports mulitbyte languages. 427 Chapter 1: UniBasic commands and functions Tip: CONVERT compares and replaces substrings on a character-by-character basis. CONVERT cannot exchange strings of different lengths. Syntax SWAP str.expr1 WITH str.expr2 IN var Parameters The following table describes each parameter of the syntax. Parameter Description str.expr1 Specifies the string expression to replace with str.expr2. str.expr2 Specifies the string expression with which to replace str.expr1. IN var Specifies the variable in which to replace str.expr1 with str.expr2. Examples In the following example, the program segment replaces all occurrences of the string “AB” with the string “AZ” in the variable VAR. The new string assigned to VAR is “THE TAZ WAS GRAZBED”. VAR = "THE TAB WAS GRABBED" SWAP "AB" WITH "AZ" IN VAR In the next example, SWAP does not replace a character with a character, but it replaces a string with a string. The program segment prints HARRY BELAFONTE. STRING = 'MARION BELAFONTE' SWAP 'MARION' WITH 'HARRY' IN STRING PRINT STRING The following program first creates a string that contains the null value, then calls a subroutine that converts UniData delimiters and the null value to characters that can be displayed or printed. Next, the program swaps the null value for another string (“def”), calls the conversion subroutine again, and prints the string again. A = @AM:"abc":@VM:@NULL:@VM:"ghi":@AM:"jkl" B = A CALL null.swap(B) PRINT B SWAP @NULL WITH "def" IN A B = A CALL null.swap(B) PRINT B The called subroutine is: SUBROUTINE null.swap(B) SWAP @NULL WITH "null" IN B SWAP @AM WITH " " IN B SWAP @VM WITH " " IN B SWAP @SM WITH " " IN B RETURN 428 SYSTEM This program prints: :RUN BP null.swap.test abc null ghi jkl abc def ghi jkl Related commands Language Command UniBasic CONVERT SYSTEM The UniBasic SYSTEM function retrieves certain system-level parameters set by UniBasic statements or by ECL commands such as SETPTR, TERM, and query statements. Note: The SYSTEM function is similar to the STATUS function and several of the @variables featured in UniBasic@variables, on page 520. The SYSTEM and STATUS functions return the same values after execution of UniBasic commands and functions. Syntax SYSTEM(expr) Parameters expr must be a number from 0 through 16. If you specify 0, the value of SYSTEM is determined by a previously executed UniBasic command. If you specify a number from 1 through 16, UniData returns predefined system parameters as described in the following table. UniBasic returns the original value when expr is invalid. Parameter Description 1 1 – PRINTER ON or (P) option is specified. Output is printed on the system printer. 0 – Output is printed to the terminal. 2 Current terminal or page size (width). 3 Current terminal or page length (number of lines on page). 4 Number of lines remaining on current page. 5 Current printer page number. 6 Current number of lines printed on the terminal or printer page. 7 Terminal type. 8 Current tape block size. 9 Current CPU millisecond count from the start of the program. 10 1 – The current stack (STON) condition is enabled. 0 – Current stack is inactive. 11 12 n – A SELECT list is active. n = # of items selected. 0 – No SELECT list is active. Current time in milliseconds (local time). 429 Chapter 1: UniBasic commands and functions Parameter Description 13 Sleeps one second. 14 Number of characters in the type-ahead buffer. If the number of characters in the internal buffer exceeds 511 bytes, this parameter returns 511. 15 Returns command options as a character string. 16 Run level, same as @LEVEL. 17 Indicates where UniData transfers control of a UniBasic program when the next RETURN statement executes. 0 – Program has no called subroutine or internal subroutine GOSUB to return to. 1 – Returning from a CALL. 18-29 30 31 32 2 – Returning from a GOSUB. Not currently used. Shows the level to which the interrupt key is set. If the value is 0, the interrupt key is enabled. For all other values, the interrupt key is disabled. To enable the interrupt key, you must match the number of BREAK OFF statements in a program with an equal number of BREAK ON statements to bring the value of SYSTEM(30) to 0. Returns the value of $UDTHOME. Returns current BASICTYPE. 33 Returns the implementation of UniData that is currently running, such as UNIX or a Windows platform. 34 Not currently used. 35 The language. 36 Shows the current setting for DATE.FORMAT: 0 – Date format is MM/DD/YY. 1 – Date format is DD/MM/YY. 37 The character used to separate thousands. 38 The character used as the decimal point. 39 The character used for the dollar sign. 40 Returns the name of the program being run. 41 Returns the UniData product serial number. 42 Returns the ASCII value of @RM. 43 Returns the ASCII value of the print control character. (Default print control character is 192.) 44 Returns the ASCII value of @NULL. 45 Returns the version, including patch number, of UniData currently running. If it is different from the version number stored in the VOC file, an asterisk is appended to the version number. The operating system-level updatevoc command updates the VOC file from the latest installation or patch. 48 430 Returns the name of the COMO file automatically created by a PHANTOM process. This function is available to the process the PHANTOM process spawned, not to the parent process. SYSTEM Parameter Description 49 Returns the calling stack for the UniBasic program at runtime. The calling stack is stored in a dynamic array with each line represented as a separate field. Each field is separated into three values (the sequence number, the object name, and the line number), and the values are separated by value marks. 50 The UniBasic SYSTEM(50) function returns a list of files open in UniBasic as a dynamic array. The first field is multivalued, and contains the following information: Value 1 – The maximum number of files that can be opened systemwide. Value 2 – The current number of hashed files open in UniBasic. Value 3 – The current number of dynamic hashed files open in UniBasic. Value 4 – The current number of recoverable hashed files open in UniBasic. Value 5 – The current number of sequential and OS-level files open in UniBasic. Value 6 – The current number of index files open in UniBasic. Value 7 – The current number of temporarily closed files in UniBasic. 51 Returns information about device licensing. If you are not using device licensing, SYSTEM(51) returns a null string. 52 Returns the entire command stack for the UniBasic program at runtime. The command stack is stored in a dynamic array. Commands are separated by attribute marks (@FM). 99 Returns the system time in the number of seconds since midnight in Coordinated Universal Time (UTC), January 1, 1970. 512 In a UDTelnet session, returns the IP address. In a console session, returns the word “Console”. (Windows platforms only) 513 Returns the current UniData version and build number. 514 Returns the number of UniData users currently logged in. SYSTEM(514) does not include phantoms. 515 Returns the localized name of the Administrators group. The group name differs based on the localized version of Windows. (Windows NT or Windows 2000 only) 516 (Windows only) Note: SYSTEM(515) lets UniData SQL create privilege table records for items owned by the Administrators group, even if the Windows version is not an English-language version. Returns 1 if the user is a member of the local Administrators group. Otherwise, returns 0. 9010 Returns the type of database. This function returns UD if the database is UniData, or UV if the database is UniVerse. If the database is the UniData Personal Edition, the function returns UD.PE. 9012 Returns the client type. The function returns 1 if the client is InterCall; otherwise, it will return a 0. 431 Chapter 1: UniBasic commands and functions Examples In the following example, the program segment turns on the printer if data is currently being sent to the display terminal: IS.ON = SYSTEM(1) IF IS.ON = 0 THEN PRINT 'TURNING THE PRINTER ON' PRINTER ON END TAN The UniBasic TAN function returns the trigonometric tangent of a numeric expression, num.expr. Syntax TAN(num.expr) Examples In the following example, the program statement prints 0.2679, the tangent of the argument 15: PRINT TAN(15) Related commands Language Command UniBasic ACOS, ASIN, ATAN, COS, SIN TIME The UniBasic TIME function returns the time of day in internal format, expressed as the number of seconds elapsed since midnight. Note: The TIME function has no arguments. Syntax TIME( ) Examples In the following example, the program statement prints the time of day in internal format. If the time is 1:01 A.M., UniData prints the value 3660, the number of seconds since midnight in internal format. PRINT TIME() In the next example, the TIME function is used in conjunction with the OCONV function for conversion to external format: PRINT OCONV(TIME(),"MT") 432 TIMEDATE Related commands Language Command UniBasic DATE, ICONV Date (D), OCONV Date (D), TIMEDATE TIMEDATE The UniBasic TIMEDATE function returns a string representation of the current time and date in the following external format: hh:mm:ss dd mmm yyyy Syntax TIMEDATE( ) Examples In the following example, the program statement assigns the string representation of the current time and date to the variable TSTRING. If the current time and date were November 1, 1999, at 11:45 A.M., TSTRING would be “11:45:00 01 NOV 1999”. TSTRING = TIMEDATE() Related commands Language Command UniBasic DATE, ICONV Date (D), OCONV Date (D), TIME TRANSACTION ABORT The UniBasic TRANSACTION ABORT command cancels the active transaction. UniData discards the pending writes. As a result, other users never know that the transaction was in progress, and none of the updates associated with the transaction take place. A transaction can abort due to any of the following conditions, in addition to the execution of a TRANSACTION ABORT statement: ▪ ▪ A program finishes before a transaction commit is issued (STOP or END). A program chains to another program. ▪ An error terminates the program before a transaction commit is issued. ▪ A user breaks out of the program before a transaction commit is issued. This can be controlled programmatically by disabling the interrupt key during a transaction. ▪ The user is forced to log out or the user process is killed, which terminates a program before a transaction commit is issued. UniData handles the above abort conditions in the same way it does the TRANSACTION ABORT statement, by canceling the transaction. Tip: You should be aware of these various abort conditions and control the resulting action from within the program where possible and appropriate. For example, write statements that fail execute the ON ERROR clause if it exists. Otherwise the program aborts and the transaction also aborts. 433 Chapter 1: UniBasic commands and functions Syntax TRANSACTION ABORT Examples In the following example, the transaction process aborts if var is 0: TRANSACTION START THEN PRINT "Transaction started." ELSE PRINT "Transaction start failed, STATUS = ":STATUS(): STOP READU var FROM file.var, record1 var += 2 IF var = 0 THEN TRANSACTION ABORT; GOTO ERR: WRITE var TO file.var, record1 TRANSACTION COMMIT THEN PRINT "Transaction committed." ELSE PRINT "Transaction Aborted, STATUS = ":STATUS(); STOP Related commands Language Command UniBasic TRANSACTION COMMIT, TRANSACTION START TRANSACTION COMMIT The UniBasic TRANSACTION COMMIT command concludes the active transaction. UniData writes all pending writes to the appropriate files. You must specify a THEN clause or an ELSE clause. You can specify both clauses. UniData performs the following steps during a transaction commit: ▪ Disables the interrupt key. ▪ Writes all updates. ▪ Releases all record locks locked inside the transaction. ▪ Executes the THEN clause if it exists. ▪ Enables the interrupt key. Warning: When including WRITE statements within a transaction, you must code an ON ERROR clause that takes appropriate action to notify the user and stop the transaction. If the transaction is not aborted by the ON ERROR clause, processing continues, and the transaction will commit inappropriately. Syntax TRANSACTION COMMIT {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. 434 Parameter Description THEN statements END THEN executes if the commit is successful. END is required to terminate multiline THEN statements. TRANSACTION START Parameter Description ELSE statements END ELSE executes if the commit is not successful because no transaction is active or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. UniData performs the following steps when a commit fails: Aborts the transaction. Executes the ELSE clause if it exists. Releases all record locks inside the transaction. STATUS function return values After you execute TRANSACTION COMMIT, the STATUS function returns one of the values described in the following table. Value Description 0 The commit completed successfully. 1 Transaction not started. 3 Transaction cannot commit. Examples The program segment below is taken from the sample program in Developing UniBasic Applications. The segment executes the UniBasic function STATUS if the commit is not successful, but does not abort the transaction. However, when an error occurs, the transaction will never be committed and will automatically abort when the program terminates. TRANSACTION COMMIT ELSE IF STATUS() = 1 THEN DISPLAY "The TRANSACTION was not started" END ELSE DISPLAY "The TRANSACTION could not be committed." END END In the following example, the TRANSACTION COMMIT command ends the transaction process and writes the new record to the database. Otherwise, it prints the return value of the UniBasic STATUS function. TRANSACTION COMMIT THEN PRINT "Transaction committed." ELSE PRINT "Transaction aborted, STATUS = ":STATUS(); STOP Related commands Language Command UniBasic TRANSACTION ABORT, TRANSACTION START TRANSACTION START The UniBasic TRANSACTION START command initiates a new transaction, storing all updates until a TRANSACTION COMMIT or TRANSACTION ABORT statement executes. 435 Chapter 1: UniBasic commands and functions Warning: When you include WRITE statements within a transaction, you must code an ON ERROR clause that takes action to notify the user and take appropriate action, such as stopping the transaction. If the transaction is not aborted by the ON ERROR clause, processing continues, and the transaction could commit inappropriately. Syntax TRANSACTION START {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description THEN statements END THEN executes if the TRANSACTION START is successful. END is required to terminate multiline THEN statements. ELSE executes if the TRANSACTION START is not successful, the record or ID does not exist, or a transaction is already active. END is required to terminate multiline ELSE statements. ELSE statements END STATUS function return values After you execute TRANSACTION START, the STATUS function returns one of the values described in the following table. Value Description 0 The transaction was started. 1 The transaction was not started. Examples The following program segment displays a message if a transaction is already started when TRANSACTION START is executed: TRANSACTION START ELSE IF STATUS() = 1 THEN DISPLAY "A Transaction had already been started, NESTED Transactions" DISPLAY "are NOT Allowed. (Contact System Administrator)" INPUT PAUSE,1_ END END Related commands Language Command UniBasic TRANSACTION COMMIT, TRANSACTION COMMIT TRIM The UniBasic TRIM function removes all spaces or every occurrence of a specified character from a string expression. If UniData does not find an occurrence of the specified character, the string remains 436 TRIM unchanged. TRIM removes leading or trailing occurrences of the specified character from a string, and converts embedded spaces or occurrences of the specified characters in a string to one space or a specified character. UniData does not remove single spaces or occurrences of the specified character embedded in the string. Syntax TRIM(str.expr[,char[,type]]) Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a string from which to remove spaces or the specified character. ,char Specifies a character to remove from str.expr. The default is a space. ,type Specifies the type of removal to perform. If char is an empty string, UniData does not perform the operation. L – Removes all leading occurrences of char. T – Removes all trailing occurrences of char. B – Removes leading and trailing occurrences of char. A – Removes all occurrences of char. R – (Default) Removes all leading, trailing, and contiguous occurrences of char. Note: We recommend that you do not use the TRIM function on dynamic arrays. For BASICTYPEs M and P, some leading and trailing spaces or occurrences of a specified character are not removed from elements in a dynamic array. For example, for BASICTYPE M or P, the following program segment: P = “**Fred**Smith**”:@VM:”**Jim**Olsen**” Q = TRIM(P,”*”) produces the following result (notice the asterisks surrounding the delimiter character): Q = Fred*Smith*}*Jim*Olsen For BASICTYPE R or U, the program segment produces the following result: Q = Fred*Smith}Jim Olsen To get this latter result regardless of BASICTYPE, use the TRIMS function. Examples In the following example, the program segment removes the leading, trailing, and extraneous blanks from the variable NAME: NAME = " Zenith, NAME = TRIM(NAME) R. " This results in the following: NAME = "Zenith, R." 437 Chapter 1: UniBasic commands and functions In the next example, the program segment removes the asterisks from the variables X and Y: X = TRIM("***NOT***ICE***","*") Y = TRIM("***NOT***ICE***","*","A") This results in the following: X = "NOT*ICE" Y = "NOTICE" Related commands Language Command UniBasic TRIMB, TRIMF, TRIMS TRIMB The UniBasic TRIMB function removes any trailing spaces from a string expression. If UniData does not find any trailing spaces, the string remains unchanged. Syntax TRIMB(str.expr) Examples In the following example, the program statement removes the trailing spaces from the variable NAME. This results in NAME = " Zenith, R.". NAME = " Zenith, R. NAME = TRIMB(NAME) " Related commands Language Command UniBasic TRIM, TRIMF, TRIMS TRIMF The UniBasic TRIMF function removes any leading spaces from the string expression. If UniData does not find any leading spaces, the string remains unchanged. Syntax TRIMF(str.expr) Examples In the following example, the program segment removes the leading spaces from the variable NAME, storing the resulting string. This results in "Zenith, R. ". NAME= " 438 Zenith, R. " TRIMS NAME = TRIMF(NAME) Related commands Language Command UniBasic TRIM, TRIMB, TRIMS TRIMS The UniBasic TRIMS function removes any spaces from each element of a dynamic array. If UniData does not find any spaces, the element remains unchanged. TRIMS removes any leading or trailing spaces from a string and converts any contiguous spaces in a string to one space. Single blanks between text are not removed. Syntax TRIMS(dyn.array[,char[,type]]) Parameters The following table describes each parameter of the syntax. Parameter Description dyn.array Specifies a dynamic array from which to remove spaces or the specified character. ,char Specifies a character to remove from elements in dyn.array. The default is a space. ,type Specifies the type of removal to perform. If char is an empty string, UniData does not perform the operation. L – Removes all leading occurrences of char. T – Removes all trailing occurrences of char. B – Removes leading and trailing occurrences of char. A – Removes all occurrences of char. R – (Default) Removes all leading, trailing, and contiguous occurrences of char. Examples In the following example, the program segment removes any spaces from each element of the dynamic array ARR1: ARR1 = " Jones ":@AM:" ARR1 = TRIMS(ARR1) Smith ":@AM:" Johnson " This results in the following: ARR1 = Jones}Smith}Johnson 439 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic TRIM, TRIMB, TRIMF UDOArrayAppendItem The UDOArrayAppendItem() function appends the item you specify to the UDO array. If the new array item is of UDO_OBJECT or UDO_ARRAY type, it must be a stand-alone object or array, and it must not be the ancestor of the current UDO object. Note: When using the UDOArrayAppendItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArrayAppendItem(udoHandle, value) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO array. value The value of the array item you are appending. UDOArrayDeleteItem The UDOArrayDeleteItem() function deletes the array item you specify by its index. If the array item is of UDO_ARRAY or UDO_OBJECT type, UDO will make either the UDO object or a UDO array as stand-alone and will remove it from memory if it is not referenced by any UniBasic variable. Note: When using the UDOArrayDeleteItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArrayDeleteItem(udoHandle,index) Parameters The following table describes each parameter of the syntax. 440 Parameter Description udoHandle Must be a UDO array. index The index of the item to be deleted. Must be a positive integer. UDOArrayGetItem UDOArrayGetItem The UDOArrayGetItem() function returns a UDO array item by its index. Note: When using the UDOArrayGetItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArrayGetItem(udoHandle, index, value[out], value_type[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO array. index The name of the UDO array index returned. Must be a positive integer. value[out] The UDO value type of the array item. If the array item is of UDO_OBJECT or UDO_ARRAY type, the output variable “item” holds only a reference to the object or array. Further changes to the object or array through this reference, such as updating a property value or removing an array item, affect the original item as well. If the array item is of UDO_STRING, UDO_NUMBER, UDO_TRUE, UDO_FALSE or UDO_NULL type, the output variable “item” holds the actual value instead of a reference. Further changes to this variable do not affect the original property value. value_type[out] The type of the value returned by value. UDOArrayGetNextItem The UDOArrayGetNextItem() function returns the next UDO array item relative to the current position, which is the position of the array the last time it was accessed by this function. The initial position is 1. Note: When using the UDOArrayGetNextItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. After exhausting the entire array, the UDOArrayGetNextItem() function returns UDO_ERROR and the current position is reset to 1.We recommend that you not modify the array when calling the UDOArrayGetNextItem() function. If you must modify the array, remember that UDOArrayGetNextItem() always returns the item at the current position +1. Syntax UDOArrayGetNextItem(udoHandle, value[out], type[out]) 441 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO array. value[out] The value of the item. type[out] The type of the value returned by value. UDOArrayGetSize The UDOArrayGetSize() function gets the size of a UDO array. Note: When using the UDOArrayGetSize command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArrayGetSize(udoHandle, size[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO array. size The size of the UDO array. UDOArrayInsertItem The UDOArrayInsertItem() function inserts a UDO array element at the position you specify by index. If the index is larger than the size of the array, UDO will pad the array with UDO_NULL values before it inserts the array item into the array.: Note: When using the UDOArrayInsertItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArrayInsertItem(udoHandle, index, value) Parameters The following table describes each parameter of the syntax. 442 Parameter Description udoHandle Must be a UDO array. UDOArraySetItem Parameter Description index The position what you want to insert the item. Must be a positive integer. value The value of the array item you are inserting. UDOArraySetItem The UDOArraySetItem() function sets or inserts a UDO array element at the position you specify. If the index is larger than the size of the array, UDO will pad the array with UDO_NULL values before it inserts the array item into the array. Otherwise, if the old array item is of UDO_OBJECT or UDO_ARRAY type, either an object or an array will be marked as stand-alone and removed from memory if it is not referenced by any UniBasic variable. If the new array item is of UDO_OBJECT or UDO_ARRAY type, it must be a stand-alone object or array and it must not be the ancestor of the current UDO object. Note: When using the UDOArraySetItem command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOArraySetItem(udoHandle, index, value) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO array. index The position what you want to set or insert the element. Must be a positive integer. value The value of the array item you are setting. UDOClone The UDOClone function clones a UDO object or array so that changes to the new object or array will not affect the original object. Note: When using the UDOClone command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOClone(udoHandle, newUdoHandle[out]) Parameters The following table describes each parameter of the syntax. 443 Chapter 1: UniBasic commands and functions Parameter Description udoHandle Must be a UDO type variable. newUdoHandle When the UDOClone function returns successfully, newUDOHandle points to a stand-alone object or array that is the exact replication of the original object. UDOCreate The UDOCreate function creates a UDO item of the type you specify. Syntax UDOCreate(udoType, udoHandle[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoType Must be one of UDO_OBJECT, UDO_ARRAY, UDO_TRUE, UDO_FALSE, or UDO_NULL. udoHandle If udoType is UDO_OBJECT, udoHandle holds an empty object. If udoType is UDO_ARRAY, udoHandle holds an empty array. If udoType is UDO_TRUE, UDO_FALSE, or UDO_NULL, udoHandle holds the specified value. UDODeleteProperty The UDODeleteProperty function deletes a property from the UDO object. Note: When using the UDODeleteProperty command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDODeleteProperty(udoHandle, name) Parameter The following table describes each parameter of the syntax. 444 Parameter Description udoHandle Must be a UDO object. name The name of the property. If the property is of UDO_OBJECT or UDO_ARRAY type, its value (either a UDO object or a UDO array) is marked as stand-alone and will be removed from memory if it is not referenced by any UniBasic variable. UDOFree UDOFree The UDOFree function forcefully removes a UDO object or array from memory. Note: When using the UDOFree command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. UDO will clear all UniBasic variables that reference the object or array and its descendants. Any attempt to access these variables, other than assigning a new value, fails. You should always call this function when a UDO object or array is no longer needed. This avoids a potential memory leak. Syntax UDOFree(udoHandle) Parameter The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a stand-alone UDO object or array. UDOGetLastError If the previous UDO call returned UDO_ERROR, use the UDOGetLastError() function to return the error code and error message. Syntax UDOGetLastError(errorCode[out], errorMessage[out]) Parameters The following table describes each parameter of the syntax. Parameter Description errorCode The UDO error code. errorMessage The UDO error message. UDOGetNextProperty The UDOGetNextProperty function provides a convenient way to walk through all the properties in a UDO object, without needing to know the property names in advance. When all properties on the UDO object are exhausted, the UDOGetNextProperty() function returns UDO_ERROR, then goes back to the first property. We recommend that you avoid modifying the properties on a UDO object when calling the UDOGetNextProperty() to retrieve the properties. 445 Chapter 1: UniBasic commands and functions Note: When using the UDOGetNextProperty command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOGetNextProperty(udoHandle, name[out], value[out], value_type[out]) Parameters The following table describes each parameter of the syntax. Patameter Description udohandle Must be a UDO type object. name[out] The name of the array that holds the names of all the properties in the UDO object. value[out] If the property is a UDO_OBJECT or UDO_ARRAY type (it is either a UDO object or an array), the output value holds only a reference to the object or array. Further changes to the object or array through this reference, such as updating a property value on the object or removing an array item, affects the original object as well. If the property is a UDO_STRING, UDO_NUMBER, UDO_TRUE, UDO_FALSE, or UDO_NULL type, the output variable value holds the actual value instead of a reference. Further changes to this variable do not affect the original property value. value_type[out] The type of the value returned by value. UDOGetOption The UDOGetOption function gets the value of a UDO option. Syntax UDOGetOption(option, value[out]) Parameters The following table describes each parameter of the syntax. Parameter Description option The UDOOPTION_OUTPUTMODE. value[out] A string type option value. . UDOGetProperty The UDOGetProperty function returns the value and type of property on the UDO object. 446 UDOGetPropertyNames Note: When using the UDOGetProperty command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOGetProperty(udoHandle, name, value[out], value_type[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO object. name The name of the property. value[out] If the property is a UDO_OBJECT or UDO_ARRAY type (it is either a UDO object or an array), the output value holds only a reference to the object or array. Further changes to the object or array through this reference, such as updating a property value on the object or removing an array item, affects the original object as well. If the property is a UDO_STRING, UDO_NUMBER, UDO_TRUE, UDO_FALSE, or UDO_NULL type, the output variable value holds the actual value instead of a reference. Further changes to this variable do not affect the original property value. value_type[out] The type of the value returned by value. UDOGetPropertyNames The UDOGetPropertyNames function returns a UDO array that holds the names of all the properties in the UDO object. Note: When using the UDOGetPropertyNames command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR Syntax UDOGetPropertyNames(udoHandle, udoArray[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO object. nameArray[out] The UDO array to hold the names of all the properties in the UDO object. 447 Chapter 1: UniBasic commands and functions UDOGetType The UDOGetType() function gets the UDO value type of a UniBasic variable. Note: When using the UDOGetType command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOGetType(udoHandle, type[out) Parameters The following table describes each parameter of the syntax. Parameters Description udoHandle Can be a UDO handle, or a UniBasic string or number. type[out] The UDO value type. UDOIsTypeOf The UDOIsTypeOf() function tests the UDO value type of a UniBasic variable. Note: When using the UDOIsTypeOf command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOIsTypeOf(udoHandle, type) Parameters The following table describes each parameter of the syntax. Parameters Description udoHandle Can be a UDO handle, or a UniBasic string or number. type[in] The UDO value type. UDORead The UDORead function creates a UDO object from a JSON string. Syntax UDORead(inputString, inputType, udoHandle[out]) 448 UDOSetOption Parameters The following table describes each parameter of the syntax. Parameter Description inputString A JSON string. inputype UDOFORMAT_JSON. udoHandle [out] The UniBasic variable that holds a reference to the UDO object upon successful return of the function. UDOSetOption Sets the options for the UDO API. Syntax UDOSetOption(option, value) Parameters The following table describes each parameter of the syntax. Parameter Description option The UDOOPTION_OUTPUTMODE. value A string type option value. UDOSetProperty The UDOSetProperty function creates or updates a property on a UDO object. Note: When using the UDOSetPropety command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOSetProperty(udoHandle, name, value) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO object. 449 Chapter 1: UniBasic commands and functions Parameter Description name The name of the property. If the property does not exist, UDO creates a new property for the object. If the property exists, the new value replaces the old value. If the old property is of UDO_OBJECT or UDO_ARRAY type, the old value, either a UDO object or an array, is marked as stand-alone and will be removed from memory if it is not referenced by any UniBasic variable. If the new value is of UDO_OBJECT or UDO_ARRAY type, it must be a stand-alone object or array, and it must not be the ancestor of the current UDO object. value The value of the property. UDOWrite Writes a UDO object in JSON format. Note: When using the UDOWrite command, your UniBasic program should check that the return status is not UDT_SUCCESS to determine if the function call succeeds, rather than checking only for UDT_ERROR. Syntax UDOWrite(udoHandle, outputType, outputString[out]) Parameters The following table describes each parameter of the syntax. Parameter Description udoHandle Must be a UDO type variable. outputType UDOFORMAT_JSON. outputString [out] The string that holds the serialized output. UDTEXECUTE The UniBasic UDTEXECUTE command executes a command in ECLTYPE U, regardless of the BASICTYPE used when the program was compiled. When you compile a program in BASICTYPE P, EXECUTE or PERFORM passes the string to execute to a nonstandard UniData parser. This parser looks for a specific sentence structure common to BASICTYPE P systems. Standard UniQuery sentences might not be handled correctly in this circumstance. Therefore, when you want to execute a standard UniQuery statement from within a UniBasic program that has been compiled in BASICTYPE P, use the UDTEXECUTE command instead of EXECUTE or PERFORM. Syntax UDTEXECUTE str.expr [{ASYNC | SYNC} ON connection] 450 UNASSIGNED [CAPTURING dyn.array.var] [RETURNING dyn.array.var] [PASSCOM] STACKCOMMON The ECL STACKCOMMON command makes use of common areas more flexible, although it requires additional memory. STACKCOMMON settings have the following effects: ▪ If STACKCOMMON is off when one program executes another, the contents of unnamed common areas are passed to the executed program and back to the executing program. ▪ If STACKCOMMON is on when one program executes another program, the contents of unnamed common areas are not passed to the program you execute. Instead, they are saved, and the unnamed common areas of the called program are initialized to 0. When control is passed back to the calling program, it is restored to its value before the program call. Unnamed common areas are never passed to a phantom program. Note: STACKCOMMON defaults to OFF in BASICTYPEs R and U, but is always on in BASICTYPEs M and P. Parameters The following table describes each parameter of the syntax. Parameter Description str.expr Specifies a command to execute. ASYNC | SYNC UniData no longer supports this parameter, but it remains for syntax compatibility. ON connection UniData no longer supports this parameter, but it remains for syntax compatibility. CAPTURING, dyn.array.var The CAPTURING clause stores the output in a dynamic array instead of on the display terminal. Each line of the text becomes an attribute in the array. Output sent to the printer is not affected by this clause. RETURNING, dyn.array.var PASSCOM The order of CAPTURING and RETURNING is interchangeable. The RETURNING clause captures error messages resulting from the command executed with UDTEXECUTE. This variable contains a string of error message numbers separated by spaces. If the executed command creates a spooler hold file, UniData also returns the hold file number in the same variable. This parameter is provided for backward compatibility for releases before 3.1. Related commands Language Command UniBasic COMMON, EXECUTE, EXECUTESQL, MDPERFORM, PCPERFORM UniData STACKCOMMON For information, see the UniData Commands Reference. UNASSIGNED The UniBasic UNASSIGNED function checks a variable in a program to see if it is currently assigned a value. If the variable is not assigned a value, the function returns 1. Otherwise, it returns 0. 451 Chapter 1: UniBasic commands and functions Syntax UNASSIGNED(var.name) Examples In the following example, the program statement returns 0 if FILENAME1 is currently assigned a value. It returns 1 if no value is currently assigned. X = UNASSIGNED(FILENAME1) UNLOCK The UniBasic UNLOCK command unlocks predefined computer resources reserved by the LOCK command. Resource numbers range from 0 through 63. If you do not specify a resource number, the system releases all locks you have set. If there are no locked resources at the time of execution, the statement does not have any effect. The lock is associated with num.expr, not the resource. Therefore, a command that does not check for locks against the resource number will access the resource even if it is locked. For example, an installation might assign locks 1 through 4 to four system printers. When an application needs to reserve printer 1, the application executes LOCK 1. All other programs must check for locks before accessing the resource for the lock to be effective. Resources are not automatically unlocked by the termination of the locking program. You must use the UniBasic UNLOCK or ECL QUIT commands to release them. You also can release resources by executing the ECL CLEAR.LOCKS command at the UniData level. Syntax UNLOCK [num.expr] Examples In the following example, the program statement unlocks all computer resources reserved by the current user: UNLOCK Related commands Language Command UniBasic LOCK UniData CLEAR.LOCKS, LIST.LOCKS, SUPERCLEAR.LOCKS For information, see the UniData Commands Reference. UPCASE The UniBasic UPCASE function converts lowercase characters to uppercase. Nonalphabetic values are not changed. Special characters, including the null value, are not converted by this function. UPCASE does not support multibyte languages. 452 WAKE Syntax UPCASE(string.expr) Examples In the following example, the program segment converts “be bold!!” to “BE BOLD!!”: STRING = 'be bold!!' PRINT UPCASE(STRING) Related commands Language Command UniBasic DOWNCASE, ICONV Masked Character (MC), OCONV Masked Character (MC) WAKE The UniBasic WAKE command activates a UniData process (pid) that has been paused with either the ECL PAUSE command or the UniBasic PAUSE command. If the specified process has not already been paused, UniData disregards the next PAUSE issued for the process indicated by pid. Syntax WAKE pid Examples The following program, WAKEUP, lists paused processes, then prompts for the ID of a process to wake up. Next, the program executes the UniBasic WAKE command against that process, and then executes LIST.PAUSED again to verify that the process was reactivated. WAKEUP EXECUTE "LIST.PAUSED" PRINT "Enter ID for process to wake ": INPUT pid WAKE pid EXECUTE "LIST.PAUSED" The following example shows the results of executing the preceding program, waking up process 10811: 1 :RUN BP WAKEUP 2 Number of Paused Users 3 ~~~~~~~~~~~~~~~~~~~~~~ 4 1 5 6 UDTNO USRNBR UID USRNAME USRTYPE TTY LEFTTIME TOT_TIME 7 1 10811 1283 carolw udt pts/0 - 8 9 Enter ID for process to wake ?10811 10 Number of Paused Users 11 ~~~~~~~~~~~~~~~~~~~~~~ 12 0 453 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic PAUSE UniData LIST.PAUSED, PAUSE, WAKE For information, see the UniData Commands Reference. UniData paragraph SLEEP command For more information, see Using UniData WEOF The UniBasic WEOF command writes an EOF (end-of-file) mark to a magnetic tape. Syntax WEOF [UNIT(mu.expr)] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description UNIT(mu.expr) Specifies the conversion code (first digit), and the unit number (second digit). UniData allows unit numbers from 0 through 9. The mu.expr is optional, and the default value for UNIT is (00) for tape unit 0 with no conversion performed (ASCII assumed). Valid options include the following: 0 – No conversion (ASCII assumed). 1 – EBCDIC conversion. 2 – Invert high bit. 3 – Swap bytes. THEN statements END ELSE statements END THEN executes if command execution is successful. END is required to terminate multiline THEN statements. ELSE executes if command execution is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. STATUS function return values After you execute WEOF, the STATUS function returns one of the values described in the following table. 454 Value Description 0 Successful read. 1 End of file encountered. 2 End of tape encountered. 3 Tape not assigned. 4 Parity error. WEOFSEQ Value Description 5 Unknown hardware error. 6 Other unspecified error. Examples In the following example, the program statement writes an end-of-file mark to tape 0. If unable to write the end-of-file mark, UniData executes the ELSE clause. WEOF UNIT(00) ELSE "Unable to write an end-of-file" Related commands Language Command UniBasic READT, RESIZET, REWIND, WRITET UniData SETTAPE, T.ATT, T.DET For information, see the UniData Commands Reference. WEOFSEQ The UniBasic WEOFSEQ command writes an end-of-file mark at the record pointer position in a sequential file, which results in the file being truncated at the current position. Use WEOFSEQ after a series of WRITESEQ operations. Syntax WEOFSEQ seq.file.var [ON ERROR statements] Parameters The following table describes each parameter of the syntax. Parameter Description seq.file.var Specifies a sequential file variable to which to write the end-of-file mark. ON ERROR statements Specifies statements to execute if the WEOFSEQ statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. Examples In the following example, the program statement writes an end-of-file mark to the file TRIAL.RUN at the current pointer position: WEOFSEQ TRIAL.RUN 455 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSCLOSE, OSOPEN, READSEQ, WRITESEQ, WRITESEQF WRITE The UniBasic WRITE command writes an expression to an opened file and releases locks set by the same process. Note: WRITE updates the record and releases UniData locks regardless of lock status. To check for and retain record locks, use the WRITEU command. For more information, see Developing UniBasic Applications. To maintain file integrity, UniData locks records with a nonprogrammable lock during a write. UniData releases this lock immediately after the WRITE command executes. Warning: Do not use UniBasic READ and WRITE commands to open or modify binary data in DIRtype files (for example, BP). Doing so can corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Syntax WRITE expr {ON | TO} [file.var,] record.ID.expr [ON ERROR statements] Updating alternate key indexes Remember the following points about alternate key indexes when you code WRITE statements: ▪ Alternate key indexes that are currently enabled are automatically updated when you write a record. ▪ If you execute the ECL command DUP.STATUS ON, and then write a record that creates a duplicate alternate key, WRITE sets the STATUS return value to 10. ▪ If the NO.DUPS keyword was specified when the alternate key index was created, UniBasic will not write a record that would create a duplicate index key. Instead, the ON ERROR clause executes (or the program aborts if ON ERRORis not coded) and the STATUS function returns a value of 10. RFS does not support NO.DUPS. Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write to the record. ON | TO file.var Specifies a file to which to write the expression. If you do not specify a file.var, UniData writes to the default file. If no default file is open, a fatal error occurs. A default file is one for which no file variable is assigned in the OPEN statement. 456 WRITE Parameter Description record.ID.expr Specifies a record to receive the expression. If the record already exists, the new expression you specify with expr replaces the existing information. If the record you specify does not exist, UniData creates the record. ON ERROR statements Specifies statements to execute in the event of a fatal error condition (such as the file is not open, an I/O error occurs in the write process, or the record contains a duplicate alternate index key). If you do not specify the ON ERROR clause, the program terminates under fatal error conditions. When including WRITE statements within a transaction, you must code an ON ERROR clause that notifies the user and takes appropriate action, such as stopping the transaction. If the transaction is not aborted by the ON ERROR clause, processing continues, and the transaction could commit inappropriately. STATUS function return values After you execute WRITE, the STATUS function returns one of the values described in the following table. Return value Meaning 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 10 Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). Non-RFS files – WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files – WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. Examples The following program segment is taken from the sample program in Developing UniBasic Applications. The statements update records that were previously locked with READU and release locks on the records. WRITE CLIENT.REC ON CLIENT_FILE,CLIENT_NUMBER WRITE ORDER.REC ON ORDERS_FILE,ORDER_NUMBER In the next example, the program statement writes the contents of the variable OVERSTOCK to the file named in variable FNAME as a record with ID OS: WRITE OVERSTOCK TO FNAME,"OS" 457 Chapter 1: UniBasic commands and functions Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READL, READU, READV, READVL, READVU, WRITEU, WRITEV, WRITEVU UniData DUP.STATUS For information, see the UniData Commands Reference. WRITELIST The UniBasic WRITELIST command writes the contents of a variable to a saved list. The values saved can then be used as item IDs to retrieve the data record. WRITELIST saves only the first value of the attribute. UniData saves only the first value in a multivalued or multi-subvalued attribute. Syntax WRITELIST var ON list.name Parameters The following table describes each parameter of the syntax. Parameter Description var Specifies a variable to place in a saved list. ON list.name Specifies a saved list to contain the retrieved list. Related commands Language Command UniBasic DELETELIST, FORMLIST, READLIST, SELECT, SELECTINDEX, SELECTINFO UniData SQL SELECT For information, see the UniData Commands Reference. UniQuery DELETE.LIST, GET.LIST, SELECT, SSELECT, SAVE.LIST For information, see the UniQuery Commands Reference WRITESEQ The UniBasic WRITESEQ command writes an expression as a record on a sequential file at the current record pointer position. Note: Before you use WRITESEQ, you must open the file by using the OSOPEN or OPENSEQ command. Tip: Use the READSEQ command to position the record pointer before using WRITESEQ. If the file is a named pipe, you cannot use WRITESEQ to write to it. You must use the OSBWRITE command. WRITESEQ cannot immediately write a record to disk. UniData stores records in a buffer until the buffer is full. 458 WRITESEQF Syntax WRITESEQ expr [APPEND] {ON | TO} seq.file.var [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write as a record. APPEND Use the APPEND option to start the WRITESEQ process at the endof-file mark. When APPEND is included, and no file exists, UniData creates a new file. ON | TO seq.file.var Specifies a sequential file to receive the expression. ON ERROR statements Specifies statements to execute if the WRITESEQ statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END THEN executes if the WRITESEQ is successful. END is required to terminate multiline THEN statements. ELSE executes if the WRITESEQ is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program segment writes the expression BAD.ACCOUNTS to the file ACCOUNTS. A message displays if the record pointer is not at the end of the file. WRITESEQ BAD.ACCOUNTS TO ACCOUNTS ELSE PRINT "NOT AT END-OF-FILE" Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSBREAD, OSBWRITE, OSCLOSE, OSDELETE, OSOPEN, READSEQ, WEOFSEQ, WRITESEQF WRITESEQF The UniBasic WRITESEQF command writes an expression as a record on a sequential file from a current record pointer position and forces UniData to immediately write the data to the disk. Note: Before you use WRITESEQF, you must open the file by using the OSOPEN or OPENSEQ command. 459 Chapter 1: UniBasic commands and functions Tip: Use the READSEQ command to position the record pointer before using WRITESEQF. If the file is a named pipe, you cannot use WRITESEQF to write to it. You must use the OSBWRITE command. Use the READSEQ command to position the record pointer before using WRITESEQF. Syntax WRITESEQF expr [APPEND] {ON | TO} seq.file.var [ON ERROR statements] {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write as a record. APPEND Use the APPEND option to start the WRITESEQF process at the endof-file mark. If you use the APPEND option in a file that does not contain data, UniData creates a new file. ON | TO seq.file.var Specifies a sequential file variable to receive the expression. ON ERROR statements Specifies statements to execute if the WRITESEQF statement fails with a fatal error because the file is not open, an I/O error occurs, or UniData cannot find the file. If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. THEN statements END If you specify the ON ERROR clause and UniData cannot find the endof-file mark, the ELSE clause executes. THEN executes if the WRITESEQF is successful. END is required to terminate multiline THEN statements. ELSE executes if the WRITESEQF is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. ELSE statements END Examples In the following example, the program statement writes the variable CHK.WRITE to the file PAYROLL. All records currently in the output buffer are written to disk along with this record. WRITESEQF CHK.WRITE ON PAYROLL ELSE GOTO 100: Related commands Language Command UniBasic CLOSESEQ, OPENSEQ, OSBREAD, OSBWRITE, OSCLOSE, OSDELETE, OSOPEN, READSEQ, WEOFSEQ writeSocket Use the writeSocket function to write data to a socket connection. 460 WRITET Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax writeSocket(socket_handle, socket_data, time_out, blocking_mode, actual_write_size) Parameters The following table describes each parameter of the syntax. Parameter Description socket_handle The handle to the open socket. socket_data The data to be written to the socket. time_out The allowable time (in milliseconds) for blocking. This is ignored for a non-blocking write. blocking_mode 0: using current mode 1: blocking 2: non-blocking actual_write_size The number of characters actually written. The following table describes the return status of each mode. Mode Return Status 0 - Blocking The function will return only after all characters in socket_data are written to the socket. 1 - Non-Blocking The function may return with fewer character written than the actual length (in the case that the socket is full). The following table describes the status of each return code. Return codes Status 0 Success. Non-zero See Socket Function Error Return codes. WRITET The UniBasic WRITET command writes the value of an expression as a record onto tape. Note: Before you can use the WRITET command, you must reserve a tape drive with the ECL T.ATT command. For detailed information about tape commands, see the UniData Commands Reference.UniData uses the ASCII 0 character (CHAR(0)) as a string-end delimiter. Therefore, you cannot use ASCII 0 in any string variable in UniBasic. When a string is read in a UniBasic program, CHAR(0) characters are converted to CHAR(128), and WRITET converts CHAR(128) back to CHAR(0). 461 Chapter 1: UniBasic commands and functions Syntax WRITET [UNIT(mu.expr)] expr {THEN statements [END] | ELSE statements [END]} Parameters The following table describes each parameter of the syntax. Parameter Description UNIT(mu.expr) Specifies the conversion code (first digit) and the unit number (second digit). Unit numbers range from 0 through 9. The mu.expr is optional and the default value for UNIT is (00) for tape unit 0 with no conversion performed (ASCII assumed). Valid options include the following: 0 – No conversion (ASCII assumed). 1 – EBCDIC conversion. 2 – Invert high bit. 3 – Swap bytes. expr Specifies an expression to write. THEN statements END THEN executes if command execution is successful. END is required to terminate multiline THEN statements. ELSE statements END ELSE executes if command execution is not successful or the record (or ID) does not exist. END is required to terminate multiline ELSE statements. Multireel tape processing You must use the TAPELEN option for the T.ATT command and specify the tape length. This command is intended for use with UniData tapes only. For information about the ECL T.ATT command, see the UniData Commands Reference. STATUS function return values After you execute WRITET, the STATUS function returns one of the values described in the following table. 462 Value Description 0 Successful read. 1 End of file encountered. 2 End of tape encountered. 3 Tape not assigned. 4 Parity error. 5 Unknown hardware error. 6 Other unspecified error. WRITEU Examples In the following example, the T.ATT command is executed, and then UniData writes the variable TAX.RECORD to tape: PERFORM "T.ATT" WRITET UNIT (00) TAX.RECORD ELSE PRINT 'TAPE PROBLEM' Related commands Language Command UniBasic READT, RESIZET, REWIND, WEOF UniData SETTAPE, T.ATT, T.DET For information, see the UniData Commands Reference. WRITEU The UniBasic WRITEU command writes a record to a file without releasing locks. WRITEU writes regardless of lock status. Syntax WRITEU expr {ON | TO} [file.var,] record.ID.expr [ON ERROR statements] Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Warning: Do not use UniBasic READ and WRITE commands to open or modify binary data in DIRtype files (for example, BP). Doing so can corrupt data in the file. Instead, use OSREAD or OSBREAD after executing the UniBasic NOCONVERT command. Updating alternate key indexes Remember the following points about alternate key indexes when you code WRITEU statements: ▪ Alternate key indexes that are currently enabled are automatically updated when you write a record. ▪ If you execute the ECL command DUP.STATUS ON, and then write a record that creates a duplicate alternate key, WRITEU sets the STATUS return value to 10. ▪ If the NO.DUPS keyword was specified when the alternate key index was created, UniBasic will not write a record that would create a duplicate index key. Instead, the ON ERROR clause executes (or the program aborts if ON ERROR is not coded) and the STATUS function returns a value of 10. RFS does not support NO.DUPS. Parameters The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write to the file. 463 Chapter 1: UniBasic commands and functions Parameter Description ON | TO file.var, Specifies a file to receive the expression. If you do not specify a file.var, UniData writes to the default file. If no default file is open, a fatal WRITEU error occurs. A default file is one for which no file variable is assigned in the OPEN statement. Specifies a record to receive the expression. record.ID.expr ON ERROR statements Specifies statements to execute if the WRITEU statement fails with a fatal error (such as the file is not open, an I/O error occurs in the write process, or the record contains a duplicate alternate index key). If the transaction is not aborted by the ON ERROR clause, processing continues, and the transaction could commit inappropriately. STATUS function return values After you execute WRITEU, the STATUS function returns one of the values described in the following table. Return value Description 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITEU is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 10 Non-RFS files – WRITEU created a duplicate alternate index key and ECL DUP.STATUS is ON; or WRITEU failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files – WRITEU created a duplicate value in the index, and ECL DUP.STATUS is ON. Examples In the following example, the program statement writes the variable IDEA.57 to the file IDEAS as a record with the ID ‘LAST’. The lock remains in place if the record was locked before executing WRITEU. WRITEU IDEA.57 ON IDEAS,'LAST' Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READL, READU, READV, READVL, READVU, WRITE, WRITEV, WRITEVU UniData DUP.STATUS For information, see the UniData Commands Reference. 464 WRITEV WRITEV The UniBasic WRITEV command updates a specified attribute in a file regardless of lock status. The WRITEV command releases locks set by the same process. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax WRITEV expr {ON | TO} [file.var,] record.ID.expr, attrib.expr [ON ERROR statements] Updating alternate key indexes Remember the following points about alternate key indexes when you code WRITEV statements: ▪ Alternate key indexes that are currently enabled are automatically updated when you write a record. ▪ If you execute the ECL command DUP.STATUS ON, and then write a record that creates a duplicate alternate key, WRITEV sets the STATUS return value to 10. ▪ If the NO.DUPS keyword was specified when the alternate key index was created, UniBasic will not write a record that would create a duplicate index key. Instead, the ON ERROR clause executes (or the program aborts if ON ERROR is not coded) and the STATUS function returns a value of 10. RFS does not support NO.DUPS. The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write to an attribute of a record. ON | TO file.var, Specifies a file to receive the expression. If you do not specify a file.var, UniData writes to the default file. If no default file is open, a fatal WRITEV error occurs. A default file is one for which no file variable is assigned in the OPEN statement. record.ID.expr Specifies a record to receive the expression. attrib.expr Specifies an attribute to receive the expression. ON ERROR statements Specifies statements to execute if the WRITEV statement fails with a fatal error (such as the file is not open, an I/O error occurs in the write process, or the record contains a duplicate alternate index key). If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. When including WRITEV statements within a transaction, you must code an ON ERROR clause that notifies the user and takes appropriate action, such as stopping the transaction. If the transaction is not aborted by the ON ERRORclause, processing continues, and the transaction could commit inappropriately. 465 Chapter 1: UniBasic commands and functions STATUS function return values After you execute WRITEV, the STATUS function returns one of the values described in the following table. Value Description 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITEV is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). Non-RFS files – WRITEV created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITEV failed because a duplicate value exists in the index and NO.DUPS was specified when the index was created. 10 RFS files – WRITEV created a duplicate value in the index, and ECL DUP.STATUS is on. Examples In the following example, the program statement writes the variable NAME to the first attribute in the customer record with CLIENT.ID in the file CLIENTS: WRITEV NAME ON CLIENT,CLIENT.ID,1 The following example is taken from the sample program in Developing UniBasic Applications. It demonstrates using WRITEV to write an attribute. Notice that the attribute is read and the record locked. Then LOCATE is used to determine the position (within the attribute) of the value to be deleted. After that value is deleted, the attribute is written back to the record. DELETE_RECORD: * (Assuming the order #'s are on line 12) READVU ORDER_LINE FROM CLIENT_FILE,CLIENT_NUMBER,12 THEN LOCATE ORDER_NUMBER IN ORDER_LINE<1> SETTING POSITION THEN DEL ORDER_LINE<1,POSITION> END WRITEV ORDER_LINE ON CLIENT_FILE, CLIENT_NUMBER, 12 END * DELETE ORDERS_FILE, ORDER_NUMBER RELEASE CLIENT_FILE,CLIENT_NUMBER RETURN Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READL, READU, READV, READVL, READVU, WRITE, WRITEU, WRITEVU UniData DUP.STATUS For information, see the UniData Commands Reference. 466 WRITEVU WRITEVU The UniBasic WRITEVU command writes an expression to an attribute of a record regardless of lock status. This command retains locks. As with the WRITEV statement, the record ID and attribute number are mandatory. Note: UniBasic locks are advisory only. They prevent access by other lock-checking commands only. For more information about UniBasic locks, see Developing UniBasic Applications. Syntax WRITEVU expr {ON | TO} [file.var,] record.ID.expr, attrib.expr [ON ERROR statements] Updating alternate key indexes Remember the following points about alternate key indexes when you code WRITEVU statements: ▪ Alternate key indexes that are currently enabled are automatically updated when you write a record. ▪ If you execute the ECL command DUP.STATUS ON, then write a record that creates a duplicate alternate key, WRITEVU sets the STATUS return value to 10. ▪ If the NO.DUPS keyword was specified when the alternate key index was created, UniBasic will not write a record that would create a duplicate index key. Instead, the ON ERROR clause executes (or the program aborts if ON ERROR is not coded) and the STATUS function returns a value of 10. RFS does not support NO.DUPS. The following table describes each parameter of the syntax. Parameter Description expr Specifies an expression to write to an attribute of a record. ON | TO file.var, Specifies a file to receive the expression. If you do not specify a file.var, UniData writes to the default file. If no default file is open, a fatal error occurs. record.ID.expr The default file is one for which no file variable is assigned in the OPEN statement. Specifies a record to receive the expression. attrib.expr Specifies an attribute to receive the expression. ON ERROR statements Specifies statements to execute if the WRITEVU statement fails with a fatal error (such as the file is not open, an I/O error occurs in the write process, or the record contains a duplicate alternate index key). If you do not specify the ON ERROR clause and a fatal error occurs, the program terminates. When including WRITEVU statements within a transaction, you must code an ON ERROR clause that notifies the user and takes appropriate action, such as stopping the transaction. If the transaction is not aborted by the ON ERROR clause, processing continues, and the transaction could commit inappropriately. 467 Chapter 1: UniBasic commands and functions STATUS function return values After you execute WRITEVU, the STATUS function returns one of the values in the following table. Return value Description 0 Successful write. 1 System error, such as a damaged file. 2 Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITEVU is not allowed. 3 Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). Non-RFS files – WRITEVU created a duplicate alternate index key and ECL DUP.STATUS is ON; or WRITEVU failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. 10 RFS files – WRITEVU created a duplicate value in the index, and ECL DUP.STATUS is ON. Related commands Language Command UniBasic CLOSE, DELETE, OPEN, READL, READU, READV, READVL, READVU, WRITE, WRITEU, WRITEVU UniData DUP.STATUS For information, see the UniData Commands Reference. XDOMAddChild Finds the xpathString in the context xmlHandle in the DOM structure, and inserts a node as the last child of the found node. If the inserted node type is XDOM.ATTR.NODE, this node is inserted as an attribute. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMAddChild(xmlHandle, xpathString, nsMap, nodeHandle, dupFlag,nodeType) Parameters The following table describes each parameter of the syntax. 468 Parameter Description xmlHandle The handle to the context. [IN] XDOMAppend Parameter Description xpathString Relative or absolute xpathString. [IN] nsMap The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] nodeHandle dupFlag The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to a DOM subtree. If nodeHandle points to a DOM document, all of its children are inserted, in the same order. [IN] XDOM.DUP: Clones nodeHandle, and inserts the duplicate node. XDOM.NODUP: Inserts the original node. The subtree is also removed from its original location. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMAppend Finds the xpathString in the context xmlHandle in the DOM structure, and inserts nodeHandle into the DOM structure as next sibling of the found node. If the inserted node type is XDOM.ATTR.NODE, this node is inserted as an attribute Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMAppend(xmlHandle, xpathString, nsMap, nodeHandle, dupFlag) 469 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle The handle to the context. [IN] xpathString Relative or absolute xpathString. [IN] nsMap The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] nodeHandle dupFlag The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to a DOM subtree. If nodeHandle points to a DOM document, all of its children are inserted, in the same order. [IN] XDOM.DUP: Clones nodeHandle, and inserts the duplicate node. XDOM.NODUP: Inserts the original node. The subtree is also removed from its original location. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMClone Duplicates the DOM subtree specified by xmlHandle to a new subtree specified by newXmlHandle. The duplicate node has no parent (parentNode returns null.). Cloning an element copies all attributes and their values, including those generated by the XML processor, to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node. Cloning any other type of node simply returns a copy of this node. 470 XDOMClose Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMClone(xmlHandle, newXmlHandle, depth) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle Handle to the DOM subtree. [IN] newXmlHandle Handle to the new DOM subtree. [IN] depth XDOM.FALSE: Clone only the node itself. XDOM.TRUE: Recursively clone the subtree under the specified node. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMClose XDOMClose frees the DOM structure. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMClose(domHandle) Parameters The following table describes each parameter of the syntax. Parameter Description domHandle Handle to the DOM structure. [IN] 471 Chapter 1: UniBasic commands and functions Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMCreateNode XDOMCreateNode creates a new node in the DOM structure. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMCreateNode(xmlHandle, nodeName, nodeValue, nodeType, nodeHandle) Parameters The following table describes each parameter of the syntax. Parameters Description xmlHandle A handle to the DOM structure. This handle acts as the context when resolving the namespace_uri from the prefix or resolving the prefix from the namespace_uri. [IN] nodeName The name of the node to be created. [IN The name can be in any of the following formats: nodeValue ▪ Local_name ▪ prefix: local_name:namespace_uri ▪ prefix:local_name ▪ local_name:namespace_uri The nodeName parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The string to hold the node value. [IN] The nodeValue parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. 472 XDOMCreateNode Parameters Description nodeType The type of the node to be created. Valid values are: XDOM.ELEMENT.NODE XDOM.ATTR.NODE XDOM.TEXT.NODE XDOM.CDATA.NODE XDOM.ENTITY.REF.NODE XDOM.ENTITY.NODE XDOM.PROC.INST.NODE XDOM.COMMENT.NODE XDOM.DOC.NODE XDOM.DOC.TYPE.NODE XDOM.DOC.FRAG.NODE XDEOM.NOTATION.NODE XDOM.XML.DECL.NODE UniData uses this argument, along with direction and childIndex, to get the right type node. For example, if direction is XDOM.PREV.SIBLING, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node that is the first previous sibling of nodeHandle. If direction is XDOM.CHILD, childIndex is XDOM.FIRST.CHILD, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node that is the first element child of nodeHandle. If the direction is XDOM.CHILD, childIndex is 2, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node that is the second element child of nodeHandle. When the direction is XDOM.NEXT.SIBLING.WITH.SAME.NAME, XDOM.PREV.SIBLING.WITH.SAME.NAME, or XDOM.PARENT, this argument is not used. [IN] nodeHandle Handle to the DOM node. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. 473 Chapter 1: UniBasic commands and functions XDOMCreateRoot XDOMCreateRoot creates a new DOM structure with root only. You can use the result handle in other functions where a DOM handle or node handle is needed. The default declaration for the XML document created by this function is as follows: <?xml version=”1.0” encoding=”UTF-8” standalone=”no” ?> Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMCreateRoot(domHandle[,xmlOptions]) Parameters The following table describes each parameter of the syntax. Parameter Description domHandle Handle to the opened DOM structure. [OUT] xmlOptions A string specifying the key/value pairs for the encoding, standalone, and version options to be declared in the XML document created by this function. [IN] The string can be entered in either of the following formats: "version=1.0 encoding=ISO-8859-1 standalone=yes" or ’version="1.0" encoding="iso-8859-1" standalone="no"’ The encoding, standalone, and version options are the same as those in the xmlconfig file and accept the same values. Keys and values are case-insensitive. Valid encoding settings can be found at http://www.iana.org/ assignments/character-sets Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. 474 Return codes Description XML.SUCCESS The function completed successfully. XDOMEvaluate Return codes Description XML.ERROR An error occurred. If an error is encountered in xmlOptions, XMLGetError() returns one of the following error codes: ▪ 38 Invalid XML config key: ’key_name’ ▪ 39 Invalid XML config value: ’value_string’ ▪ 40 Invalid XML config format: ’name_value_string’ XDOMEvaluate XDOMEvaluate returns the value of the XPathString in the context xmlHandle in the DOM structure. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMEvaluate(xmlHandle, xpathString, nsMap, aValue) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle The handle to the context. [IN] xpathString Relative or absolute xpathString. [IN] nsMap The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] aValue The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The value of xpathString. [OUT] The aValue parameter uses the out-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. 475 Chapter 1: UniBasic commands and functions Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMGetAttribute XDOMGetAttribute gets the node's attribute node, whose attribute name is attrName. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetAttribute(nodeHandle, attrName, nodeHandle) Parameters The following table describes each parameter of the syntax. Parameter Description nodeHandle Handle to the DOM node. [IN] attrName Attribute name. [IN] nodeHandle The attrName parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to the found attribute node. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. 476 Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMGetChildNodes XDOMGetChildNodes The XDOMGetChildNodes function returns all child nodes of xmlHandle. The XDOMGetChildNodes function behaves in the same way as: XDOMLocate(xmlHandle, "*", "", XML.MULTI) Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMChildNodes(xmlHandle, nodeListHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle Handle to the DOM structure. nodeListhandle The handle to the node list. Examples In this example, suppose xmlHandle points to <ENTRY id="id1" name="bookentry">. After the call to XDOMGetChildNodes(xmlHandle, nodehandle), nodeHandle should point to all child nodes, that is, <NAME>, <ADDRESS>, three <PHONENUM>s, and <EMAIL>. ?<xml version="1.0" encoding="utf-8"?> <ADDRBOOK cmt="my address book"> <ENTRY id="id1" name=”bookentry”> <NAME>Name One</NAME> <ADDRESS>101 Some Way</ADDRESS> <PHONENUM DESC="Work">303-111-1111</PHONENUM> <PHONENUM DESC="Fax">303-111-2222</PHONENUM> <PHONENUM DESC="Pager">303-111-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> <ENTRY ID="id2" NAME=”bookentry”> <NAME>Name Two</NAME> <ADDRESS>202 Some Way</ADDRESS> <PHONENUM DESC="Work">303-222-1111</PHONENUM> <PHONENUM DESC="Fax">303-222-2222</PHONENUM> <PHONENUM DESC="Home">303-222-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> </ADDRBOOK> XDOMGetElementById The XDOMGetElementByld function finds the first element with the ID you specify. The XDOMGetElementById function behaves in the same way as: XDOMLocate(xmlHandle,"//*[@ID=’idstr’ or @id=’idstr’]","",XML_MULTI) 477 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetElementById(xmlHandle, idstr,nodeHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle Handle to the DOM structure. idstr The ID of the element you want to return. nodeHandle Handle to the DOM node. [IN] Examples In this example, suppose xmlHandle points to the document root. After the call to XDOMGetElementById(xmlHandle, "id2", nodeHandle), nodeHandle should point to element <ENTRY ID="id2" NAME="bookentry>. ?<xml version="1.0" encoding="utf-8"?> <ADDRBOOK cmt="my address book"> <ENTRY id="id1" name=”bookentry”> <NAME>Name One</NAME> <ADDRESS>101 Some Way</ADDRESS> <PHONENUM DESC="Work">303-111-1111</PHONENUM> <PHONENUM DESC="Fax">303-111-2222</PHONENUM> <PHONENUM DESC="Pager">303-111-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> <ENTRY ID="id2" NAME=”bookentry”> <NAME>Name Two</NAME> <ADDRESS>202 Some Way</ADDRESS> <PHONENUM DESC="Work">303-222-1111</PHONENUM> <PHONENUM DESC="Fax">303-222-2222</PHONENUM> <PHONENUM DESC="Home">303-222-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> </ADDRBOOK> XDOMGetElementsByName The XDOMGetElementsByName function tries to find all elements with the name you specify. The XDOMGetElementsByName function behaves in the same way as: XDOMLocate(xmlHandle,"//*[@NAME=’namestr’ or @name=’namestr’]", ,"",XML_SINGLE) Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 478 XDOMGetElementsByTag Syntax XDOMGetElementsByName(xmlHandle, namestrnodeListHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle Handle to the DOM structure. namestr The name of the element you want to return. nodeListhandle The handle to the node list. Examples In this example, suppose xmlHandle points to the document root. After the call to XDOMGetElementsByName(xmlHandle, "bookentry", nodeListHandle), nodeListHandle should point to elements <ENTRY id="id1" name="bookentry"> and <ENTRY ID="id2" NAME="bookentry">. ?<xml version="1.0" encoding="utf-8"?> <ADDRBOOK cmt="my address book"> <ENTRY id="id1" name=”bookentry”> <NAME>Name One</NAME> <ADDRESS>101 Some Way</ADDRESS> <PHONENUM DESC="Work">303-111-1111</PHONENUM> <PHONENUM DESC="Fax">303-111-2222</PHONENUM> <PHONENUM DESC="Pager">303-111-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> <ENTRY ID="id2" NAME=”bookentry”> <NAME>Name Two</NAME> <ADDRESS>202 Some Way</ADDRESS> <PHONENUM DESC="Work">303-222-1111</PHONENUM> <PHONENUM DESC="Fax">303-222-2222</PHONENUM> <PHONENUM DESC="Home">303-222-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> </ADDRBOOK> XDOMGetElementsByTag The XDOMGetElementsByTag function tries to find all elements with the tag name you specify. The XDOMGetElementsByTag function behaves in the same way as: XDOMLocate(xmlHandle,"//tagname", ,"",XML.MULTI) Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetElementsByTag(xmlHandle, tagname,nodeListHandle) 479 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle Handle to the DOM structure. nodeListhandle The handle to the node list. Examples In this example, suppose xmlHandle points to the document root. After the call to XDOMGetElementsByTag(xmlHandle, "PHONENUM", nodeListHandle), nodeListHandle should point to all PHONENUM elements. ?<xml version="1.0" encoding="utf-8"?> <ADDRBOOK cmt="my address book"> <ENTRY id="id1" name=”bookentry”> <NAME>Name One</NAME> <ADDRESS>101 Some Way</ADDRESS> <PHONENUM DESC="Work">303-111-1111</PHONENUM> <PHONENUM DESC="Fax">303-111-2222</PHONENUM> <PHONENUM DESC="Pager">303-111-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> <ENTRY ID="id2" NAME=”bookentry”> <NAME>Name Two</NAME> <ADDRESS>202 Some Way</ADDRESS> <PHONENUM DESC="Work">303-222-1111</PHONENUM> <PHONENUM DESC="Fax">303-222-2222</PHONENUM> <PHONENUM DESC="Home">303-222-3333</PHONENUM> <EMAIL>[email protected]</EMAIL> </ENTRY> </ADDRBOOK> XDOMGetNodeName XDOMGetNodeName gets the node name. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetNodeName(nodeHandle, nodeName) Parameters The following table describes each parameter of the syntax. 480 Parameter Description nodeHandle Handle to the DOM node. [IN] XDOMGetNodeType Parameter Description nodeName String to store the node name. [OUT] The nodeName parameter uses the out-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMGetNodeType XDOMGetNodeType gets the node type. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetNodeType(nodeHandle, nodeType) Parameters The following table describes each parameter of the syntax. Parameter Description nodeHandle Handle to the DOM node. [IN] nodeType An integer to store the node type. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. 481 Chapter 1: UniBasic commands and functions XDOMGetNodeValue XDOMGetNodeValue gets the node value. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetNodeValue(nodeHandle, nodeValue) Parameters The following table describes each parameter of the syntax. Parameter Description nodeHandle Handle to the DOM node. [IN] nodeValue The string to hold the node value. [OUT] The nodeValue parameter uses the out-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMGetOwnerDocument XDOMGetOwnerDocument gets the DOM handle to which the nodeHandle belongs. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetOwnerDocument(nodeHandle, domHandle) Parameters The following table describes each parameter of the syntax. 482 XDOMGetUserData Parameter Description nodeHandle Handle to the DOM node. [IN] domHandle Handle to the opened DOM structure. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMGetUserData XDOMGetUserData gets the user data associated with the node. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMGetUserData(nodeHandle, userData) Parameters The following table describes each parameter of the syntax. Parameter Description nodeHandle Handle to the DOM node. [IN] userData String to hold the user data. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. 483 Chapter 1: UniBasic commands and functions XDOMImportNode The XDOMImportNode function imports a node from another document into the current document. The returned node has no parent. The source node is not altered or removed from the original document. Syntax XDOMImportNode(xmlHandle, depth, importedNodeHandle, outNodeHandle) Description For all nodes, importing a node creates a node object owned by the document from which you are importing. The attribute values are identical to the source node's nodeName and nodeType, as well as attributes related to namespaces (prefix, localName, and namespaceURI). UniData attempts to mirror the behavior expected if a fragment of the XML source was copied from one document to another by copying additional information, as appropriate, to the nodeType. UniData recognizes that the two documents may have different DTDs. The following describes the specifics for each type of node: ▪ ATTRIBUTE_NODE: UniData sets the ownerElement attribute to null and the specified flag to true on the generated DOMAttr. UniData recursively imports the descendants of the source DOMAttr and reassembles the resulting nodes to form a corresponding subtree. Note: The depth parameter has no effect on DOMAttr nodes. These nodes always carry their children with them when imported. 484 ▪ DOCUMENT_FRAGMENT_NODE: If the value of the depth option is true, UniData recursively imports the descendants of the source element and reassembles the resulting nodes to form the corresponding subtree. If the value of the depth option is false, UniData generates an empty DOMDocumentFragment. ▪ DOCUMENT_NODE: You cannot import DOMDocument nodes. ▪ DOCUMENT_TYPE_NODE: You cannot import DOMDocumentType nodes. ▪ ELEMENT_NODE: UniData imports specified attribute nodes of the source document, and attaches the generated DOMAttr nodes to the generated DOMElement. UniData does not copy default attributes, although they are assigned if the document to which you are importing defines default attributes for this element name. If the value of the importNode depth parameter is true, UniData recursively imports the descendants of the source element and reassembles the resulting nodes to form the corresponding subtree. ▪ ENTITY_NODE: You can import DOMEntity nodes, but in the current release of the DOM, the DOMDocumentType is read only. When you import and ENTITY_NODE, UniData copies the publicId, systemId, and notationName attributes. If the value of the depth parameter is true, UniData recursively imports the descendants of the source DOMEntity and reassembles the resulting node to form the corresponding subtree. ▪ ENTITY_REFERENCE_NODE: If you import this type of node, UniData only copies the DOMEntityReference itself, even if the value of the depth parameter is true. This is because the source and destination documents may have defined the entity differently. If the document you are importing provides a definition for this entity name, UniData assigns that value. ▪ NOTATION_NODE: You can import DOMNotation nodes, but in the current release of the DOM, the DOMDocumentType is read only. When you import a NOTATION_NODE, UniData copies the publicId and systemId attributes. The depth parameter has no effect on DOMNotation nodes, since they do not have children. XDOMInsert ▪ PROCESSING_INSTRUCTION_NODE: UniData copies the target and data values from the source node to the current document. ▪ TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE: With these types of nodes, inheriting from DOMCharacterData, UniData copies the data and length attributes from the source node to the current document. Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle The target XML document to which you are importing. [IN] depth XDOM.FALSE - import only the node itself. XDOM.TRUE - recursively import the subtree under the node specified by importedNodeHandle. This parameter has no effect on DOMAttr, DOMEntityReference, and DOMNotation nodes. [IN] importedNodeHandle The handle to the node you are importing. [IN] newXMLHandle The handle to the new node. [IN] Return status Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Status Description XML.SUCCESS The import was successful. XML.ERROR An error occurred during import. XML.INVALID.HANDLE The xmlHandle or importedNodeHandle is not a valid XML handle. XDOMInsert XDOMInsert finds the xpathString in the context xmlHandle in the DOM structure, and inserts nodeHandle into the DOM structure as the previous sibling of the found node. If the inserted node type is XDOM.ATTR.NODE, this node is inserted as an attribute. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMInsert (xmlHandle, xpathString, nsMap, nodeHandle, dupFlag) Parameters The following table describes each parameter of the syntax. 485 Chapter 1: UniBasic commands and functions Parameter Description xmlHandle The handle to the context. [IN] xpathString Relative or absolute xpathString. [IN] nsMap The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] nodeHandle dupFlag The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to a DOM subtree. If nodeHandle points to a DOM document, all of its children are inserted, in the same order. [IN] XDOM.DUP: Clones nodeHandle, and inserts the duplicate node. XDOM.NODUP: Inserts the original node. The subtree is also removed from its original location. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMItem The XDOMItem function returns the index-th item in the list. If the index is less than 1 or greater than the number of items in the list, use Error(errorCode,errorMessage) to return the error message "index out of bounds." Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. 486 XDOMItem Syntax XDOMItem(nodeListHandle, index, dataHandle, dataType) Parameters The following table describes each parameter of the syntax. Parameter Description nodeListhandle The handle to the node list. index The index item to return. dataHandle UniVerse stores the returned value, either a DOM handle or a string, in dataHandle. dataType The data type that is stored in dataHandle. If nodeListHandle was generated from an API other than XDOMQuery(), the dataType must be XQ.ITEM.NODE (1). If nodeListHandle was generated by XDOMQuery(), the dataType could be XQ.ITEM.NODE(1), or a simple value type such as XQ.ITEM.ANY_SIMPLE_TYPE(2), XQ.ITEM.STRING(21). Data types The following is a list of the data types available. ▪ XQ.ITEM.NODE (1) ▪ XQ.ITEM.ANY_SIMPLE_TYPE (2) ▪ XQ.ITEM.ANY_URI (3) ▪ XQ.ITEM.BASE_64_BINARY (4) ▪ XQ.ITEM.BOOLEAN (5) ▪ XQ.ITEM.DATA (6) ▪ XQ.ITEM.DATE_TIME (7) ▪ XQ.ITEM.DAY_TIME_DURATION (8) ▪ XQ.ITEM.DECIMAL (9) ▪ XQ.ITEM.DOUBLE (10) ▪ XQ.ITEM.DURATION (11) ▪ XQ.ITEM.FLOAT (12) ▪ XQ.ITEM.G_DAY (13) ▪ XQ.ITEM.G_MONTH (14) ▪ XQ.ITEM.G_MONTH_DAY (15) ▪ XQ.ITEM.G_YEAR (16) ▪ XQ.ITEM.G_YEAR_MONTH (17) ▪ XQ.ITEM.HEX_BINARY (18) ▪ XQ.ITEM.NOTATION (19) ▪ XQ.ITEM.STRING (21) ▪ XQ.ITEM.TIME (22) ▪ XQ.ITEM.UNTYPED_ATOMIC (23) ▪ XQ.ITEM.YEAR_MONTH_DURATION (24) 487 Chapter 1: UniBasic commands and functions XDOMLength The XDOMLength function determines the number of nodes in the list. The range of the valid child node index is to 1 to length, inclusive. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMLength (nodeListHandle, length) Parameters The following table describes each parameter of the syntax. Parameter Description nodeListHandle The handle to the node list. length The length of the node list. XDOMLocate XDOMLocate finds a starting point for relative XPath searching in context xmlHandle in the DOM structure. The xpathString should specify only one node; otherwise, this function will return an error. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMLocate(xmlHandle, xpathString, nsMap, nodeHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle A handle to the DOM structure. [IN] xpathString A string to specify the starting point. [IN] The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. 488 XDOMLocateNode Parameter Description nsMap The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] nodeHandle The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to the found attribute node. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. Note: In this document, xmlHandle is a generic type, it can be domHandle or nodeHandle. DomHandle stands for a whole document, while nodeHandle stands for a subtree. DomHandle is also a nodeHandle. XDOMLocateNode XDOMLocateNode traverses from nodeHandle and gets the next node according to direction and childIndex. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMLocateNode(nodeHandle, direction, childIndex, nodeType, newNodeHandle) Parameters The following table describes each parameter of the syntax. 489 Chapter 1: UniBasic commands and functions Parameter Description nodeHandle The handle to the starting node. [IN] direction Direction to traverse. Valid values are: XDOM.PREV.SIBLING XDOM.NEXT.SIBLING XDOM.NEXT.SIBLING.WITH.SAME.NAME XDOM.PREV.SIBLING.WITH.SAME.NAME XDOM.PARENT XDOM.CHILD [IN] childIndex The index in the child array. Valid values are: XDOM.FIRST.CHILD XDOM.LAST.CHILD Positive Integer [IN] nodeType The type of node to be located. Valid values are: XDOM.NONE XDOM.ELEMENT.NODE XDOM.ATTR.NODE XDOM.TEXT.NODE XDOM.CDATA.NODE XDOM.ENTITY.REF.NODE XDOM.ENTITY.NODE XDOM.PROC.INST.NODE XDOM.COMMENT.NODE XDOM.DOC.NODE XDOM.DOC.TYPE.NODE XDOM.DOC.FRAG.NODE XDEOM.NOTATION.NODE XDOM.XML.DECL.NODE If nodeType is not XDOM.NONE, UniData uses this argument, along with direction and childIndex, to get the right typed node. For example, if direction is XDOM.PREV.SIBLING, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node which is the first previous sibling of nodeHandle. If direction is XDOM.CHILD, childIndex is XDOM.FIRST.CHILD, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node which is the first element child of nodeHandle. If the direction is XDOM.CHILD, childIndex is 2, and nodeType is XDOM.ELEMENT.NODE, UniData finds the element node which is the second element child of nodeHandle. When the direction is XDOM.NEXT.SIBLING.WITH.SAME.NAME, XDOM.PREV.SIBLING.WITH.SAME.NAME, or XDOM.PARENT, this argument is not used. [IN] 490 XDOMOpen Parameter Description newNodeHandle Handle to the found node. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMOpen XDOMOpen reads an XML document and creates a DOM structure. If the DTD is included in the document, UniData validates the document. The XML document can be from a string, or from a file, depending on the docLocation flag. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMOpen(xmlDocument, docLocation, domHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlDocument The XML document. [IN] docLocation A flag to specify whether xmlDocument is a string holding the XML document, or it is a file containing the XML document. Valid values are: XML.FROM.FILE XML.FROM.STRING [IN] domHandle Handle to the opened DOM structure. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. 491 Chapter 1: UniBasic commands and functions Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. Options When the XML does not have an encoding set in the declaration and the data in the document is not UTF-8, as of UniData 8.1.0 the encoding is assumed to be UTF-8, as shown in the following example: <?xml version="1.0" ?> <ROOT> <PRODUCTS _ID = "M1000" PRODID = "M1000" LIST = "$1,990" DESCRIPTION = "Low cost , entry level, light duty, monochrome copier"/> </ROOT> Since there is no encoding set in the declaration line, opening the file with the XDOMOpen function fails if there is a character from another encoding set (for example an ISO-8859-1 character) in the data. Reading a file from a browser that has the wrong encoding of the data will also produce an error similar to the following example: An invalid character was found in text content. Error processing resource 'file:///C:/U2/UD81/_XML_/example.xml'. Line 4, Po... At UniData 8.1.0, a new XML option, xdomopen-encoding, was added. This option specifies what encoding to use when there is no encoding defined in the declaration. After you set xdomopenencoding to ISO-885901 in the xmlconfig file, the XDOMOpen() function can open the document successfully. When xdomopen-encoding is not set, or is set to “”, UTF-8 is assumed. XDOMRemove XDOMRemove finds the xpathString in the context xmlHandle in the DOM structure, then removes the found node or its attribute with name attrName. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMRemove(xmlHandle, xpathString, nsMap, attrName, nodeHandle) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle The handle to the context. [IN] xpathString Relative or absolute xpathString. [IN] The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. 492 XDOMReplace Parameter Description nsMap The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] attrName nodeHandle The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Attribute name. [IN] The attrName parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The removed node, if nodeHandle is not NULL. [OUT] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMReplace XDOMReplace finds the xpathString in the context xmlHandle in the DOM structure, and replaces the found node with nodeHandle. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMReplace(xmlHandle, xpathString, nsMap, nodeHandle, dupFlag) Parameters The following table describes each parameter of the syntax. Parameter Description xmlHandle The handle to the context. [IN] 493 Chapter 1: UniBasic commands and functions Parameter Description xpathString Relative or absolute xpathString. [IN] nsMap The xpathString parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. The map of namespaces which resolve the prefixes in the xpathString. Format is xmlns=default_url xmlns:prefix1=prefix1_url xmlns:prefix2=prefix2_url For example: xmlns=http://myproject.mycompany.com xmlns:a_prefix=a.mycompany.com [IN] nodeHandle dupFlag The nsMap parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Handle to a DOM subtree. If nodeHandle points to a DOM document, all of its children are inserted, in the same order. [IN] XDOM.DUP: Clones nodeHandle, and inserts the duplicate node. XDOM.NODUP: Inserts the original node. The subtree is also removed from its original location. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMSetNodeValue XDOMSetNodeValue sets the node value. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMSetNodeValue(nodeHandle, nodeValue) Parameters The following table describes each parameter of the syntax. 494 XDOMSetUserData Parameter Description nodeHandle Handle to the DOM node. [IN] nodeValue String to hold the node value. [IN] The nodeValue parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API. Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMSetUserData XDOMSetUserData sets the user data associated with the node. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMSetUserData(nodeHandle, userData) Parameters The following table describes each parameter of the syntax. Parameter Description nodeHandle Handle to the DOM node. [IN] userData String to hold the user data. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. 495 Chapter 1: UniBasic commands and functions Return codes Description XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMTransform XDOMTransform transforms the input DOM structure using the style sheet specified by styleSheetFile to output the DOM structure, file, or string. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMTransform(domHandle, styleSheet, ssLocation, outHandle[, outFormat]) Parameters The following table describes each parameter of the syntax. Parameter Description domHandle Handle to the DOM structure. [IN] styleSheet Handle to the context [IN] ssLocation A flag to specify whether styleSheet contains style sheet itself, or is just the style sheet file name. Valid values are: XML.FROM.FILE (default) XML.FROM.STRING [IN] outHandle Handle to the resulting DOM structure, file, or string. [OUT] outFormat Specifies one of the following values as the output format for the DOM structure: ▪ XML.TO.DOM – Transforms the input DOM structure using the style sheet specified by styleSheet, and outputs the resulting document into a DOM structure. ▪ XML.TO.FILE – Transforms the input DOM structure using the style sheet specified by styleSheet, and outputs the resulting document into a file. ▪ XML.TO.STRING – Transforms the input DOM structure using the style sheet specified by styleSheet, and outputs the resulting document into a string. Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. 496 XDOMValidate Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMValidate XDOMValidate validates the DOM document using an external nonamespace schema specified by noNsSchema and, optionally, external namespace schemas specified by NsSchemas. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMValidate(xmlDocument, docLocation, noNsSchema, noNsSchemaLocation[, NsSchemas]) Parameters The following table describes each parameter of the syntax. Parameter Description xmlDocument The name of the XML document. [IN] docLocation A flag to specify whether xmlDocument is the document itself, or the document file name. Valid values are: XML.FROM.FILE (default) XML.FROM.STRING XML.FROM.DOM [IN] noNsSchema The external no-namespace schema file. [IN] noNsSchemaLocation A flag to specify whether noNsSchema is the schema itself, or the schema file name. Valid values are: XML.FROM.FILE (default) XML.FROM.STRING [IN] NsSchemas The external namespace schema files. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. 497 Chapter 1: UniBasic commands and functions Return codes Description XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMValidateDom XDOMValidateDom validates the DOM document using an external no-namespace schema specified by noNsSchema and, optionally, external namespace schemas specified by NsSchemas. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMValidateDom(domHandle, noNsSchema, noNsSchemaLocation[, NsSchemas]) Parameters The following table describes each parameter of the syntax. Parameter Description domHandle Handle to the DOM structure. [IN] noNsSchema The external no-namespace schema file. [IN] noNsSchemaLocation A flag to specify whether noNsSchema is the schema itself, or the schema file name. Valid values are: XML.FROM.FILE (default) XML.FROM.STRING [IN] NsSchemas The external namespace schema files. [IN] Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XDOMWrite XDOMWrite writes the DOM structure to xmlDocument. xmlDocument can be a string or a file, depending on the value of the docLocation flag. 498 XDOMWrite Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XDOMWrite(domHandle, xmlDocument, docLocation[, xmlOptions]) Parameters The following table describes each parameter of the syntax. Parameter Description domHandle Handle to the opened DOM structure. [IN] xmlDocument The XML document [OUT] docLocation A flag to specify whether xmlDocument is an output string which should hold the XML document, or it is a file where the XML document should be written. Valid values are: XML.TO.FILE XML.TO.STRING [IN] xmlOptions A string specifying the key/value pairs of the XML options to be used in the XML document written by this function. [IN] The string can be entered in either of the following formats: encoding=ISO-8859-1 standalone=yes newline=CR-LF or encoding="iso-8859-1" standalone="no" The XML options are the same as those in the xmlconfig file and accept the same values. Keys and values are case-insensitive. Valid encoding settings can be found at http://www.iana.org/ assignments/character-sets Return codes Note: The following return codes are defined in the XML.H section of the INCLUDE file. The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. If an error is encountered in xmlOptions, XMLGetError() returns one of the following error codes: ▪ 38 Invalid XML config key: ’key_name’ ▪ 39 Invalid XML config value: ’value_string’ ▪ 40 Invalid XML config format: ’name_value_string’ 499 Chapter 1: UniBasic commands and functions Return codes Description XML.INVALID.HANDLE An invalid DOM handle was returned to the function. XLATE The UniBasic XLATE function returns the contents of an attribute, and takes additional action if the record does not exist or the attribute is empty. This function performs the same action as the TRANS virtual attribute function. Syntax XLATE(filename, rec.id.expr, attrib.expr, "code") Parameters The following table describes each parameter of the syntax. Parameter Description filename Specifies the name of a file from which to return the contents of an attribute. file.expr must be the name of a valid UniData file, not the value of a file variable, even if the same file was opened within the program. rec.id.expr Specifies a record ID in file.expr. attrib.expr Specifies a valid attribute in file.expr. "code" Enter a code specifying action to be taken if the record does not exist or the attribute is empty: C – Substitutes the id.expr for the value of the function. V – Returns an empty string and prints an error message. X – Returns an empty string. Related commands Language Command UniData TRANS For information, see the Using UniData XMAPAppendRec The XMAPAppendRec function formats the specified record from the UniData file as a U2XMAP dataset record and appends it to the U2XMAP dataset. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPAppendRec(XMAPhandle, file_name, record) 500 XMAPClose Parameters The following table describes each parameter of the syntax. Parameter Description XMAPhandle The handle to the U2XMAP dataset. file_name record The XMAPhandle parameter uses the in-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API for the input record value. The name of the UniData file that is being mapped in the U2 XMAP dataset The data record formatted according to the dictionary record of the UniData file. Return values The following table describes the return values for this function. Return Value Description XML_SUCCESS The XML document was opened successfully. XML_ERROR An error occurred opening the XML document. XML_INVALID_HANDLE The XMAP dataset was invalid. XMAPClose The XMAPClose function closes the U2XMAP dataset handle and frees all related structures and memory. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPClose(XMAPhandle) Parameter The following table describes each parameter of the syntax. Parameter Description XMAPhandle The handle to the U2XMAP dataset. Return values The following table describes the return values for this function. Return Value Description XML_SUCCESS The XML document was opened successfully. XML_ERROR An error occurred opening the XML document. XML_INVALID_HANDLE The XMAP dataset was invalid. 501 Chapter 1: UniBasic commands and functions XMAPCreate The XMAPCreate function creates an empty XML document for transferring data from the UniData database to XML according the mapping rules you define. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPCreate(u2xmapping_rules, mapping_flag, XMAPhandle) Parameters The following table describes each parameter of the syntax. Parameter Description u2xmapping_rules The name of the U2XMAP file, or the UniBasic variable containing the XML to Database mapping rules. mapping_flag A flag indicating if the mapping file is the U2XMAP file itself or a string located within the UniBasic program. Valid values are: XMAPhandle ▪ XMAP.FROM.FILE - the mapping rules are contained in a U2XMAP file. ▪ XMAP.FROM.STRING - u2xmapping_rules is the name of the variable containing the mapping rules. The handle to the XMAP dataset. The following table describes the return values for this function. Return Value Description XML_SUCCESS The XML document was opened successfully. XML_ERROR An error occurred opening the XML document. XML_INVALID_HANDLE The XMAP dataset was invalid. XMAPOpen The XMAPOpen function opens an XML document as a U2XMAP data set. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPOpen(xml_document, doc_flag, u2xmapping_rules, u2xmap_flag, XMAPhandle) Parameters The following table describes each parameter of the syntax. 502 XMAPReadNext Parameter Description xml_document The name of the XML document. doc_flag A flag defining the type of xml_document. Valid values are: ▪ XML.FROM.DOM - xml_document is a DOM handle. ▪ XML.FROM.FILE - xml_document is a file name. ▪ XML.FROM.STRING -xml_document is the name of variable containing the XML document. u2xmapping_rules The name of the U2XMAP file, or the UniBasic variable containing the XML to Database mapping rules. u2xmap_flag A flag indicating if the mapping file is the U2XMAP file itself or a string located within the UniBasic program. Valid values are: XMAPhandle ▪ XMAP.FROM.FILE - the mapping rules are contained in a U2XMAP file. ▪ XMAP.FROM.STRING - u2xmap_flag is the name of the variable containing the mapping rules. The handle to the XMAP dataset. This API registers the current in-encoding and out-encoding parameters in the XMAPhandle. These parameters are used throughout the life of the XMAPhandle. Return values The following table describes the return values for this function. Return value Description XML_SUCCESS The XML document was opened successfully. XML_ERROR An error occurred opening the XML document. XMAPReadNext The XMAPReadNext function retrieves the next record from the U2XMAP dataset and formats it as a record of the UniData file that is being mapped. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPReadNext(XMAPhandle, file_name, record) Parameters The following table describes each parameter of the syntax. 503 Chapter 1: UniBasic commands and functions Parameter Description XMAPhandle The U2XMAP dataset handle. The XMAPhandle parameter uses the out-encoding parameter set in the system-level or account-level xmlconfig file, the XMLSETOPTIONS command, or the XMLSetOptions() API for the record value. file_name The name of the UniData file that is being mapped in the U2XMAP dataset. record The data record formatted according to the dictionary record of the file. Return values The following table describes the return values for this function. Return value Description XML_SUCCESS The XMAPReadNext was executed successfully. XML_ERROR XML_INVALID_HANDLE XML_EOF Error in executing XMAPReadNext. U2 XMAP dataset handle was invalid. The end of the U2XMAP dataset has been reached. XMAPToXMLDoc The XMAPToXMLDoc function generates an XML document from the data in the U2XMAP dataset using the mapping rules you define. The XML document can be either an XML DOM handle or an XML document. UniData writes the data to a file or a UniBasic variable. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMAPToXMLDoc(XMAPhandle, xmlfile, doc_flag[, xmlOptions]) Parameters The following table describes each parameter of the syntax. 504 Parameter Description XMAPhandle The handle to the XMAP dataset. xmlfile The name of the XML file, or the name of a UniBasic variable to hold the XML document. doc_flag A flag defining the type of xml_document. Valid values are: ▪ XML.FROM.DOM - xml_document is a DOM handle. ▪ XML.FROM.FILE - xml_document is a file name. ▪ XML.FROM.STRING -xml_document is the name of variable containing the XML document. XMLError Parameter Description xmlOptions A string specifying the key/value pairs of the XML options to be used in the XML document generated by this function. [IN] The string can be entered in either of the following formats: encoding=ISO-8859-1 standalone=yes newline=CR-LF or encoding="iso-8859-1" standalone="no" The XML options are the same as those in the xmlconfig file and accept the same values. Keys and values are case-insensitive. Valid encoding settings can be found at http://www.iana.org/ assignments/character-sets Return values The following table describes the return values for this function. Return value Description XML_SUCCESS The XML document was opened successfully. XML_ERROR An error occurred. If an error is encountered in xmlOptions, XMLGetError() returns one of the following error codes: XML_INVALID_HANDLE ▪ 38 Invalid XML config key: ’key_name’ ▪ 39 Invalid XML config value: ’value_string’ ▪ 40 Invalid XML config format: ’name_value_string’ The XMAP dataset was invalid. XMLError Use the XMLError function to get the last error message. Errmsg is the error message string, or one of the following return values: ▪ XML.SUCCESS: Success ▪ XML.ERROR: Failure Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMLError(errmsg) XMLExecute The XMLExecute function enables you to create an XML document using the UniQuery LIST statement or the UniData SQL SELECT statement from a UniBasic program. 505 Chapter 1: UniBasic commands and functions Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMLExecute(cmd, options, xmlvar, xsdvar) Parameters The following table describes each parameter of the syntax. 506 Parameter Description cmd Holds the text string of the UniQuery LIST statement or the UniData SQL SELECT statement. [IN] XMLExecute Parameter Description options Each XML-related option is separated by a field mark (@FM). If the option requires a value, the values are contained in the same field, separated by value marks (@VM). WITHDTD Creates a DTD and binds it with the XML document. By default, UniData creates an XML schema. However, if you include WITHDTD in your UniQuery or UniData SQL statement, UniData does not create an XML schema, but only produces the DTD. ELEMENTS The XML output is in element-centric format. ‘XMLMAPPING’: @VM:’mapping_file_ name’ Specifies the mapping file containing transformation rules for display. This file must exist in the _XML_ directory. ‘SCHEMA’:@VM: ’type’ The default schema format is ref type schema. You can use the SCHEMA attribute to define a different schema format. HIDEMV, HIDEMS Normally, when UniData processes multivalued or multi-subvalued fields, UniData adds another level of elements to produce multiple levels of nesting. You have the option of disabling this additional level by adding the HIDEMV and HIDEMS attributes. When these options are on, the generated XML document and the associated DTD or XML schema have fewer levels of nesting. HIDEROOT Allows you to specify to only create a segment of an XML document, for example, using the SAMPLE keyword and other conditional clauses. If you specify HIDEROOT, UniData only creates the record portion of the XML document, it does not create a DTD or XML schema. ‘RECORD’:@VM: ’newrecords’ The default record name is FILENAME_record. The record attribute in the ROOT element changes the record name. ‘ROOT’:@VM: ’newroot’ The default root element name in an XML document is ROOT. You can change the name of the root element as shown in the following example: root=”root_element_name” TARGETNAMESPACE:@FM:’namespaceURL’ UniData displays the targetnamespace attribute in the XMLSchema as targetNamespace, and uses the URL you specify to define schemaLocation. If you define the targetnamespace and other explicit namespace definitions, UniData checks if the explicitly defined namespace has the same URL and the targetnamespace. If it does, UniData uses the namespace name to qualify the schema element, and the XML document element name. COLLAPSEMV, COLLAPSEMS Normally, when UniData processes multivalued or multi-subvalued fields, UniData adds another level of elements to produce multiple levels of nesting. You have the option of disabling this additional level by adding the COLLAPSEMV and COLLAPSE MS attributes. When these options are on, the generated XML document and the associated DTD or XML Schema have fewer levels of nesting. 507 Chapter 1: UniBasic commands and functions Parameter Description XmlVar The name of the variable to which to write the generated XML document [OUT] XsdVar The name of the variable in which to store the XML Schema if one is generated along with the XML document. [OUT] Examples The following example illustrates the XMLExecute function: CMD="SELECT SEMESTER,COURSE_NBR FROM STUDENT;" OPTIONS := "COLLAPSEMS" OPTIONS := @FM:"HIDEROOT" OPTIONS := @FM:"root":@VM:"mystudent" OPTIONS :=@FM:"record":@VM:"myrecord" OPTIONS :=@FM:"targetnamespace":@VM:"http://www.rocketsoftware.com" OPTIONS := @FM:"elementformdefault" STATUS = XMLEXECUTE(CMD,OPTIONS,XMLVAR,XSDVAR) PRINT XSDVAR PRINT XMLVAR XMLGetError XMLGetError gets the error code and error message after the previous XML API failed. Note: This function is case-sensitive. If you want it to be case-insensitive, you must compile your programs using the BASIC command with the -i option. Syntax XMLGetError(errorCode, errorMessage) Parameters The following table describes each parameter of the syntax. Parameter Description errorCode The error code. [OUT] errorMessage The error message. [OUT] Return codes The return code indicates success or failure. The following table describes the value of each return code. 508 Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR An error occurred. XMLGetOptions XMLGetOptions Use this function in UniBasic programs to return the values for encoding and other XML options in effect in the current UniData session. Syntax XMLGetOptions(outOptions[, delimiterString]) Parameters The following table describes each parameter of the syntax. Parameter Description outOptions A variable used to retrieve the XML options key/value pairs in effect in the current UniData session. [OUT] delimiterString Optional. Specifies the string to be used to separate the key/value pairs returned by the command. By default, delimiterString is a space. [IN] Examples The following example shows the format for entering delimiterString as the string used to separate the key/value pairs returned by the function. Key/value pairs can be separated by a space or by any string, such as <>, as shown in this example: (xmlOptions, "<>") encoding=default<>in-encoding=UTF-8<>version=1.1<>standalone=no<> out-xml-declaration=true<>out-format-pretty-print=false<>outnormalizecharacters=true<>out-split-cdata-sections=true<>outvalidation= false<>out-expand-entity-references=false<>outwhitespacein-element-content=true<>out-discard-defaultcontent= true<>out-format-canonical=true<>out-write-bom=false<> If you enter the XMLGetOptions function with no delimiterString, the key/value pairs are separated by a space, as shown in the next example: XMLGetOptions(xmlOptions) encoding=default in-encoding=UTF-8 version=1.1 standalone=no outxmldeclaration=true out-format-pretty-print=false out-normalizecharacters= true out-split-cdata-sections=true out-validation=false out-expand-entity-references=false out-whitespace-in-elementcontent= true out-discard-default-content=true out-formatcanonical= true out-write-bom=false Return codes The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. 509 Chapter 1: UniBasic commands and functions XMLGetOptionValue Use this function in UniBasic programs to return the value of encoding or any other XML option in effect in the current UniData session. Syntax XMLGetOptionValue(optionName, outOptionValue) Parameters The following table describes each parameter of the syntax. Parameter Description optionName The name of the XML option for which you want to retrieve the current value. [IN] The XML options are the same as those in the xmlconfig file. outOptionValue A variable used to retrieve the value of the specified XML option in the current UniData session. [OUT] Examples The following example shows the format for entering the optionName and outOptionValue variables: XMLGetOptionValue("encoding", xmlOptionValue) This function returns the value of the encoding option in the second argument, xmlOptionValue. Return codes The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR When the return status is XML.ERROR, XMLGetError() returns the following error code: 38 Invalid XML config key: ‘key_name’ XMLSetOptions Use this function in UniBasic programs to set the encoding parameter and other XML options in the current UniData session. The settings specified in this API override the settings in the system-level and account-level xmlconfig files and in ECL commands during the current session. Syntax XMLSetOptions("options") Parameters The following table describes each parameter of the syntax. 510 XMLTODB Parameter Description options A string in the format of space-delimited key/value pairs. [IN] The XML options are the same as those in the xmlconfig file and accept the same values. Keys and values are case-insensitive. The XMLSetOptions function also accepts three special strings as the options parameter. ▪ defaults – Sets all XML options to their default settings in the current session. ▪ reload – Reloads the current system-level and account-level xmlconfig files, since they may have changed after you started your UniData session. ▪ reset – Resets XML options to the original settings that were loaded when you started the UniData session A special string must be entered as the only option. Examples The following example shows the format for entering the XML options in this API. XMLSetOptions("encoding=iso-8859-1 newline=CR-LF") The next example shows the format for entering a special string as the options parameter: XMLSetOptions("defaults") Return codes The return code indicates success or failure. The following table describes the value of each return code. Return codes Description XML.SUCCESS The function completed successfully. XML.ERROR When the return status is XML.ERROR, XMLGetError() returns one of the following error codes: ▪ 38 Invalid XML config key: ‘key_name’ ▪ 39 Invalid XML config value: ‘value_string’ ▪ 40 Invalid XML config format: ‘name_value_string’ When the return code is XML.ERROR, none of the XML parameters are changed. XMLTODB The XMLTODB function populates the UniData database from UniBasic. If you want to transform specific data, use the XMAP API. Syntax XMLTODB(xml_document, doc_flag, u2xmapping_rules, u2xmap_ flag, status) 511 Chapter 1: UniBasic commands and functions Parameters The following table describes each parameter of the syntax. Parameter Description xml_document The name of the XML document. doc_flag A flag defining the type of xml_document. Valid values are: XML.FROM.DOM - xml_document is a DOM handle. ▪ XML.FROM.FILE - xml_document is a file name. ▪ XML.FROM.STRING -xml_document is the name of variable containing the XML document. u2xmapping_rules The mapping rules for the XML document. u2xmap_flag A flag indicating if the mapping file is the U2XMAP file itself or a string located within the UniBasic program. Valid values are: Status 512 ▪ ▪ XMAP.FROM.FILE - the mapping rules are contained in a U2XMAP file. ▪ XMAP.FROM.STRING - u2xmap_flag is the name of the variable containing the mapping rules. The return status. Appendix A: ASCII character codes The following table describes each ASCII code. ASCII value Character Hex character 000 NUL 0 001 SOH 1 002 STX 2 003 ETX 3 004 EOT 4 005 ENQ 5 006 ACK 6 007 BEL 7 008 BS 8 009 HT 9 010 LF A 011 VT B 012 FF C 013 CR D 014 SO E 015 SI F 016 DLE 10 017 DC1 11 018 DC2 12 019 DC3 13 020 DC4 14 021 NAK 15 022 SYN 16 023 ETB 17 024 CAN 18 025 EM 19 026 SUB 1A 027 ESC 1B 028 FS 1C 029 GS 1D 030 RS 1E 031 US 1F 032 (space) 20 033 ! 21 034 " 22 035 # 23 036 $ 24 037 % 25 513 Appendix A: ASCII character codes 514 ASCII value Character Hex character 038 & 26 039 ’ 27 040 ( 28 041 ) 29 042 * 2A 043 + 2B 044 , 2C 045 - 2D 046 . 2E 047 / 2F 048 0 30 049 1 31 050 2 32 051 3 33 052 4 34 053 5 35 054 6 36 055 7 37 056 8 38 057 9 39 058 : 3A 059 ; 3B 060 < 3C 061 = 3D 062 > 3E 063 ? 3F 064 @ 40 065 A 41 066 B 42 067 C 43 068 D 44 069 E 45 070 F 46 071 G 47 072 H 48 073 I 49 074 J 4A 075 K 4B 076 L 4C 077 M 4D 078 N 4E 079 O 4F 080 P 50 ASCII character codes ASCII value Character Hex character 081 Q 51 082 R 52 083 S 53 084 T 54 085 U 55 086 V 56 087 W 57 088 X 58 089 Y 59 090 Z 5A 091 [ 5B 092 \ 5C 093 ] 5D 094 ^ 5E 095 _ 5F 096 ‘ 60 097 a 61 098 b 62 099 c 63 100 d 64 101 e 65 102 f 66 103 g 67 104 h 68 105 i 69 106 j 6A 107 k 6B 108 l 6C 109 m 6D 110 n 6E 111 o 6F 112 p 70 113 q 71 114 r 72 115 s 73 116 t 74 117 u 75 118 v 76 119 w 77 120 x 78 121 y 79 122 z 7A 123 { 7B 515 Appendix A: ASCII character codes 516 ASCII value Character Hex character 124 | 7C 125 } 7D 126 ~ 7E 127 DEL 7F 128 Ç 80 129 ü 81 130 é 82 131 â 83 132 ä 84 133 à 85 134 å 86 135 ç 87 136 ê 88 137 ë 89 138 è 8A 139 ï 8B 140 î 8C 141 ì 8D 142 Ä 8E 143 Å 8F 144 É 90 145 æ 91 146 Æ 92 147 ô 93 148 ö 94 149 ò 95 150 û 96 151 ù 97 152 ÿ 98 153 Ö 99 154 Ü 9A 155 ¢ 9B 156 £ 9C 157 ¥ 9D 158 ¤ 9E 159 ƒ 9F 160 á A0 161 í A1 162 ó A2 163 ú A3 164 ñ A4 165 Ñ A5 166 ª A6 ASCII character codes ASCII value Character Hex character 167 º A7 168 ¿ A8 169 “ A9 170 ” AA 171 ‹ AB 172 › AC 173 ¡¦ AD 174 « AE 175 » AF 176 ã B0 177 õ B1 178 Ø B2 179 ø B3 180 œ B4 181 Œ B5 182 À B6 183 à B7 184 Õ B8 185 § B9 186 ‡ BA 187 † BB 188 ¶ BC 189 © BD 190 ® BE 191 ™ BF 192 „ C0 193 … C1 194 ‰ C2 195 • C3 196 – C4 197 — C5 198 ° C6 199 Á C7 200  C8 201 È C9 202 Ê CA 203 Ë CB 204 Ì CC 205 Í CD 206 Î CE 207 Ï CF 208 Ò D0 209 Ó D1 517 Appendix A: ASCII character codes 518 ASCII value Character Hex character 210 Ô D2 211 nonprinting D3 212 nonprinting D4 213 Ù D5 214 Ú D6 215 Û D7 216 Ÿ D8 217 ß D9 218 nonprinting DA 219 nonprinting DB 220 nonprinting DC 221 nonprinting DD 222 nonprinting DE 223 nonprinting DF 224 nonprinting E0 225 nonprinting E1 226 nonprinting E2 227 nonprinting E3 228 nonprinting E4 229 nonprinting E5 230 nonprinting E6 231 nonprinting E7 232 nonprinting E8 233 nonprinting E9 234 nonprinting EA 235 nonprinting EB 236 nonprinting EC 237 nonprinting ED 238 nonprinting EE 239 nonprinting EF 240 nonprinting F0 241 nonprinting F1 242 nonprinting F2 243 nonprinting F3 244 nonprinting F4 245 nonprinting F5 246 nonprinting F6 247 nonprinting F7 248 nonprinting F8 249 nonprinting F9 250 nonprinting FA 251 text mark FB 252 subvalue mark FC ASCII character codes ASCII value Character Hex character 253 value mark FD 254 attribute mark FE 255 record mark FF 519 Appendix B: UniBasic@variables This appendix lists the @variables available in UniBasic, the delimiter @variables, and the codes returned by @SYSTEM.RETURN.CODE. @variables The following table describes the valid @variables. @variable Description @ACCOUNT Returns the operating system path where you first entered UniData. Note that the value of @ACCOUNT does not change when a LOGTO statement is executed. @AM Inserts an attribute mark at compile time. For information about other system delimiter @ variables, see Delimiter @variables, on page 522. @COMMAND @CONV Used with CALCULATE and the braces {} function. Returns the conversion code from a dictionary item. @CRTHIGH Height of the CRT screen. @CRTWIDE Width of the CRT screen. @DATA DATA statements used in conjunction with INPUT statements are stored in a data stack or input queue. This stack is accessible in the @DATA variable. Data elements are delimited by ASCII 013 (CR). @DATA is a READ ONLY variable. @DATE System date, in internal format, when the program began executing. @DAY Two-digit day of the month. @DICT Current dictionary (must perform an assignment). @FORMAT Used with CALCULATE and the braces {} function. Returns the format code from a dictionary item. @GID For UNIX, returns the group ID assigned to a user. For Windows NT or Windows 2000, returns a string that contains all the group names (separated by value marks) to which the user belongs. @HEADER Used with CALCULATE and the braces {} function. Returns the column heading from a dictionary item. @ID Current record ID. @LASTVERB Stores the last executed command. @LEVEL Current PERFORM or EXECUTE level. @LOGNAME 520 Last UniData command executed. Changes the value for each statement executed at the UniData ECL prompt ( : ) and in the UniBasic EXECUTE statement. Returns the user’s login name. @LPTRHIGH Page length (height) of the system line printer. @LPTRWIDE Page width of the system line printer. @MONTH Two-digit representation of the current month. @variables @variable Description @PARASENTENCE The last paragraph or sentence entered. It retains the name and parameters of the current executing paragraph. If no paragraph is being executed, an empty string is returned. If another paragraph is called within the first paragraph executed, the returned value is of the called paragraph until control is returned to the calling paragraph. @PATH Current operating system path for the directory where the user resides. The value of @PATH changes with the LOGTO command. @RECORD @RECUR0 @RECUR1 Current record (must be assigned). Recursive user defined. @RECUR# variables are reset at the ECL prompt. @RECUR2 @RECUR3 @RECUR4 @RM Inserts a record mark at compile time. For information about other system delimiter @ variables, see Delimiter @variables, on page 522. @SENTENCE The statement that invoked the current UniBasic program in progress. Reflects the last command entered at the ECL prompt or in a paragraph or sentence executed by a UniBasic program. Each UniBasic EXECUTE and CHAIN statement also resets @SENTENCE. @SM Inserts a subvalue mark (same as @SVM) at compile time. For information about other delimiter variables, see Delimiter @variables, on page 522. @SVM Inserts a subvalue mark (same as @SM) at compile time. For information about other system delimiter @ variables, see Delimiter @variables, on page 522. @SYS.BELL Enables or disables a user’s terminal bell. @SYSTEM.RETURN.CODE Returns a value indicating a condition or error after the execution of an ECL command. For most commands, 0 indicates the command was completed correctly, and -1 indicates that the command was not completed correctly. For more information, see Delimiter @variables. @TIME The time (in internal format) when the first program in the call string program. @TM Inserts a text mark at compile time. The text mark has no direct effect, but can be used by UniBasic programs. For information about other system delimiter @ variables, see Delimiter @variables, on page 522. @TRANSACTION Returns 1 if there is a transaction occurring, and returns 0 if there is no transaction occurring. @TTY Returns the terminal port name, such as tty01, tty1a, or console. 521 Appendix B: UniBasic@variables @variable Description @UDTNO Returns an integer between 1 and the maximum number of users allowed on the system. Numbers are assigned sequentially based on the sequence of entry into UniData. Phantom processes are counted. @UID The operating system user ID number for the user. @USER0 User-defined. @USER# variables retain their value throughout a user session unless the values are explicitly changed. @USER1 @USER2 @USER3 @USER4 @USERNO Current udt process ID number. @USER.RETURN.CODE User-defined. @USER.TYPE Returns the type of process currently running. UniBasic has four types of processes: 0 – Normal terminal processes. 1 – Background (phantom) processes. 2 – Redirected standard input. 3 – UniObjects, or any other client process. @VM Inserts a value mark at compile time. For information about other delimiter @variables, see Delimiter @variables, on page 522. @WHO Retrieves your current directory. For example, if you are in UNIX directory /u/ud/AP, the value of @WHO is AP. @YEAR Two-digit representation of the year. Delimiter @variables The following @variables are replaced by the compiler with dynamic arrays delimiters. Use the same @variables to place delimiters in UniData hashed files. @variable Description @AM Attribute mark @VM Value mark @SM Subvalue mark @RM Record mark @TM Text mark @SVM Subvalue mark (same as @SM) @SYSTEM.RETURN.CODE values @SYSTEM.RETURN.CODE returns various values based on the last command executed. @SYSTEM.RETURN.CODE is available in UniBasic, and is set by many commands, both UniBasic and ECL. 522 @SYSTEM.RETURN.CODE values ECL @SYSTEM.RETURN.CODE values The following table describes the possible @SYSTEM.RETURN.CODE values for various ECL commands. Command Success return value Error return value BSELECT The number of items in the select list. -1 BASIC 0 -1 BUILD.INDEX The number of indexes built. -1 COMPILE.DICT 0 -1 CREATE.INDEX The number of indexes created. -1 DELETE.INDEX The number of indexes deleted. -1 ESEARCH The number of items in the select list. -1 FORM.LIST The number of items in the select list. -1 GET.LIST The number of items in the select list. -1 LIST The number of items listed. -1 LIST.INDEX The number of indexes listed. -1 LIST.ITEM The number of items listed. -1 LIST.LABEL The number of items listed. -1 LOCK 0 -1 if you specify an invalid lock number. -2 if the resource is locked by another user. MERGE.LIST The number of items in the select list. -1 MODIFY The number of records modified. -1 NSELECT The number of items in the select list. 0 QSELECT The number of items in the select list. -1 SAVE.LIST The number of items saved. -1 SELECT The number of items in the select list. -1 SORT The number of items listed. -1 SORT.ITEM The number of items listed. -1 SORT.LABEL The number of items listed. -1 SSELECT The number of items in the select list. -1 STACKCOMMON 1 – On N/A 0 – Off UniBasic @SYSTEM.RETURN.CODE values The following table describes the possible @SYSTEM.RETURN.CODE values for UniBasic commands.. Command Success return value Error return value GETQUEUE The number of locks waiting to be released. -1 GETREADU The number of locks set. -1 INPUT (with FOR or WAITING clause included) 0 -1 (used if timeout option is set; INPUT timed out) 523 Appendix B: UniBasic@variables 524 Command Success return value Error return value INPUT @ (with FOR or WAITING clause included) 0 -1 (used if timeout option is set; INPUT timed out) PCPERFORM 0 -1 Appendix C: Operators in UniBasic This appendix describes the arithmetic, Boolean, and relational operators available you can use in UniBasic. Arithmetic operators The following table describes the arithmetic operators for UniBasic. Operator Action Examples + Unary plus (same as multiplying VAR = +VAR by +1). ABS - Unary minus (changes to the opposite sign, same as multiplying by -1). VAR = -VAR NEG + Addition. X = VAR1 + VAR2 SADD, SUM VAR = VAR + 1 X = VAR1 - VAR2 - Subtraction. * Multiplication. / Division. ** or ^ Exponentiation. :, CAT Concatenation. += Increments the value of a variable. -= Decrements the value of a variable. *= Multiplies the value to the left of VAR1 *= VAR2 the operator by the value to the right of the operator. /= Divides the value to the left of the operator by the value to the right of the operator. VAR1 /= VAR2 := Concatenates the value to the left of the operator by the value to the right of the operator. VAR1 := VAR2 VAR = VAR - 1 Related function SSUB X = VAR1 * VAR2 SMUL X = VAR^2 PWR QUANTITY = PRICE/COST SDIV X = VAR1:VAR2 LINES += 1 LINES -= 1 Note: You must include the REUSE function to apply arithmetic operations to all elements of a dynamic array. Boolean operators The following table describes the Boolean operators for UniBasic. 525 Appendix C: Operators in UniBasic Operator Action Examples AND, & When both expressions are true, the result is true. OR, ! When either expression is true, the result is true. IF (X < Y) AND (Y < Z) THEN GOSUB 1000 NOT Inverts the result of conditional statements. NOTS Inverts the logical result of each element of a dynamic array. IF (X < Y) OR (Y < Z) THEN GOSUB 1000 IF (X < Y) AND NOT (Y < z) GOSUB 1000 A = 1:@FM:0:@FM:1:@FM:30B = NOTS(A) B contains 0}1}0}0. Relational operators The following table describes the relational operators for UniBasic. Operator Multivalued equivalent Description Examples =, EQ EQS Equal to. IF VAR1 = VAR2 THEN GOSUB SUB1 #, <>, ><, NE NES >, GT GTS <, LT LTS DO UNTIL VAR1 = VAR2 Not equal to. The # can IF X # Y THEN be used to negate other GOSUB 1000 operators. IF X #> Y THEN GOSUB 1000 Greater than. Less than. IF VAR1 > VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 > VAR2 IF VAR1 < VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 < VAR2 >=, =<, #<, GE generateKey <=, =<, #>, LE LES Greater than or equal to. Less than or equal to. IF VAR1 >= VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 => VAR2 IF VAR1 <= VAR2 THEN GOSUB SUB1 DO UNTIL VAR1 =< VAR2 526 Appendix D: Reserved words This appendix lists the reserved keywords, commands, functions, and @variables. Do not use any of them for subroutine names or for UniBasic variable names. Reserved words $BASICTYPE $DEFINE $IFDEF $IFNDEF $F $INCLUDE $T $UNDEFINE @ACCOUNT @CONV @CRTWIDE @DATE @DICT @FORMAT @HEADER @LASTVERB @LOGNAME @LPTRWIDE @NULL @PATH @RECORD @RECUR1 @RECUR3 @SENTENCE @SYSTEM.RETURN.CODE @TRANSACTION @TTY @UDTNO @USER.RETURN.CODE @USER0 @USER2 @USER4 @WHO ABORT $FALSE $INSERT $TRUE @ @COMMAND @CRTHIGH @DATA @DAY @FALSE @GID @ID @LEVEL @LPTRHIGH @MONTH @PARASENTENCE @PROCTYPE @RECUR0 @RECUR2 @RECUR4 @SYS.BELL @TIME @TRUE @TUPLE @UID @USER.TYPE @USER1 @USER3 @USERNO @YEAR ABS ABSOLUTE ACOS ALPHA AND APPEND AS ASSIGN ASYNC ASCII AT ASIN ATAN 527 Appendix D: Reserved words Reserved words BEFORE BEGIN BITOR BITXOR BPIOCP BPIOCPN BREAK BUFFER.KEYS BITANDBITAND BY BYTELEN CALCULATE CALL CALLC CALLING CAPTURING CASE CAT CATS CHAIN CHANGE CHAR CHARLEN CHARS CHECKSUM CLEAR CLEARCOM CLEARCOMMON CLEARDATA CLEARFILE CLEARINPUT CLEARSELECT CLEARSQL CLOSE CLOSESEQ COL1 COL2 COM COMMIT CONNECT CONTINUE COMMON COMPILE.DICT.ITEM CONVERT COS COUNT COUNTS CRT CURRENT DATA DATE DCOUNT DEBUG DECLARE DEFFUN DEL DELETE DELETELIST DELETEU DIM DIMENSION DIR DISPLAY DISCONNECT DISPLAYWIDTH DO DOWNCASE DQUOTE DROUND DTX EBCDIC END ENTER ECHO ELSE EQ EQS EQU EQUATE EXECUTE 528 BITNOT EXECUTESQL EXIT EXP EXTRACT FIELD Reserved words Reserved words FIELDS FIELDSTORE FILEINFO FILELOCK FILEUNLOCK FIND FINDSTR FIRST_ALT_KEY FLUSH FMT FMTS FOOTING FROM FUNCTION FOR FORMLIST GARBAGECOLLECT GE GES GET GETCOLUMNDATA GETCOLUMNNAME GETLIST GETMSG GETENV GETNEXTTUPLE GETERRMSG GETPTR GETPU GETQUEUE GETREADU GETUSERGROUP GETUSERID GETUSERNAME GETX GO GROUP GROUPSTORE GT GTS HASH HEADING HELP HUSH ICONV ICONVS IF IN INDEXS INDICES GOSUB GOTO INCLUDE INDEX INMAT INPUT INPUTCLEAR INPUTERR INPUTIF INPUTNULL INPUTTRAP INS INSERT INT ISMB ISNV ISNVS ISOLATION ITYPE LAST_ALT_KEY LEN LENS JRNL_STATUS LE LENGTH LES LINEMARK LN LOCATE LOCK LOCKED LOOP LTS MAT LOWER LT 529 Appendix D: Reserved words Reserved words MATBUILD MATCH MATCHES MATCHFIELD MATPARSE MATREAD MATREADL MATREADU MATWRITE MATWRITEU MAXIMUM MBLEN MDPERFORM MINIMUM MOD NE NEG NES NEXT NOCONVERT NODELAY NOT NOTS NULL NULLVAL_ALT_KEY NUM NUMS OCONV OCONVS OFF ON OPENSEQ OR OSBREAD OSBWRITE OSCLOSE OSCLOSE OSOPEN OSREAD OSWRITE PAGE PASSCOM PASSCOMMON PCPERFORM PERFORM PRECISION PREVIOUS PASSLIST PRINT PRINTERR PROCREAD PAUSE PRINTER PRIOR PROCWRITE PROGRAM PROMPT PWR QUOTE RAISE READ READBCK READBCKL READBCKU READFWD READFWDL READFWDU READL READLIST READNEXT READNEXTTUPLE READONLY READSEQ READT READU READV READVL READVU READWRITE READXBCK 530 OPEN READXFWD RECORDLOCKED RECORDLOCKL RECORDLOCKU RELATIVE Reserved words Reserved words RELEASE REM REMOVE REPEAT REPLACE RETURN REUSE RESIZET RETURNING REWIND RND RNDSEED RQM RTNLIST SADD SCMP SDIV SELECT SELECTINDEX SELECTINFO SEND SENDX SEQ SETINDEX SETROW SETTING SEQS SETMARK SETTABLE SIN SLEEP SMUL SOUNDEX SPACE SPACES SPLICE SQRT SQUOTE SSUB STATUS STEP STOP STR STRS SUBROUTINE SUBSTRINGS SUM SWAP SYNC SYSTEM TIME TIMEDATE TAN THEN TIMEOUT TO TRIMB TRIMF TRIMS UDTEXECUTE UNASSIGNED UNFILTERED TRANSACTION UNLOCK UPCASE USING VERB WAITING TRIM UNTIL USE VALIDATE.KEY WAIT WAKE WEOF WEOFSEQ WHILE WITH WRITEONLY WRITESEQ WRITESEQF WRITET WRITEU WRITEV WRITE WRITELIST 531 Appendix D: Reserved words Reserved words WRITEVU XTD 532 XLATE Appendix E: Commands affected by BASICTYPEs and UDT.OPTIONS This appendix lists the UniBasic commands and functions that behave differently or have different syntax depending on the BASICTYPE or UDT.OPTIONS you have set at the time you compile the program. For detailed information about how BASICTYPEs or UDT.OPTIONS affect a particular command or function, see the documentation for that command or function in this manual. For descriptions of BASICTYPEs, see the UniBasic $BASICTYPE command in this manual. For more detailed information about UDT.OPTIONS, see the UDT.OPTIONS Commands Reference. Command or function The BASICTYPE setting determines... UDT.OPTIONS $INCLUDE Whether you can use INCLUDE for the $INCLUDE command. N/A Whether the [] (square brackets) function can entirely remove parts or all of a substring. N/A ABORT Whether you can specify multiple messages to display when the program aborts. The BASICTYPE setting also determines whether you can specify a message ID that evaluates to a key in the UniData error message file. 8 CALLC N/A 88 CHAIN N/A 6, 11, 27, 40, 54 CLEAR Whether the CLEAR command can set all variables in unnamed common areas to 0. N/A COMMON Whether zero elements are maintained in arrays. The BASICTYPE setting also determines whether you can use the PASSCOM option. N/A COUNT Whether the COUNT function can find overlapping character substrings in a string. N/A COUNTS Whether the COUNTS function can find overlapping character substrings in an array of strings. N/A CRT N/A 5, 46 DATA N/A 11, 27 DEBUG N/A 14 DISPLAY N/A 5, 46 DIM Whether excess data (including delimiters) resulting from redimensioning an array can be placed in position 0,0 of the dimensioned array. N/A EBCDIC Whether ASCII data is converted to EBCDIC before it is written to tape. N/A ECHO N/A 99 N/A 78 [] ENTER 533 Appendix E: Commands affected by BASICTYPEs and UDT.OPTIONS 534 Command or function The BASICTYPE setting determines... UDT.OPTIONS EXECUTE Whether commands are parsed by using the 11, 27, 35, 46, 93, 105 standard UniData parser or the P-type parser. EXECUTESQL N/A 35 FLUSH N/A 46 FMT How the data is formatted (in cases for which the BASICTYPE setting can produce different results). N/A FOOTING N/A 34, 64 HEADING N/A 32, 34 ICONV Whether the ICONV function returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 56 (for ICONV D, also 60 and 82; for ICONV MC, also 62) ICONVS Whether the ICONVS function returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 56 IN N/A 46 INPUT N/A 12, 18, 46, 65, 83 INPUT @ N/A 101 LOCATE The number of array elements you can include in a search and the search driven by those elements. 85 MATPARSE Whether excess data (including delimiters) N/A resulting from executing the MATPARSE command can be placed in position 0,0 of the dimensioned array. MATREAD Whether excess data (including delimiters) N/A resulting from executing the MATREAD command can be placed in position 0,0 of the dimensioned array. MATREADL Whether excess data (including delimiters) N/A resulting from executing the MATREADL command can be placed in position 0,0 of the dimensioned array. MATREADU Whether excess data (including delimiters) N/A resulting from executing the MATREADU command can be placed in position 0,0 of the dimensioned array. MDPERFORM N/A 35 OCONV Whether the OCONV function returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 56 (for OCONV D, also 4 and 29; for OCONV MD, also 13 and 63) OCONVS Whether the OCONVS function returns an empty string if UDT.OPTIONS 56 is on and the input value or conversion code is invalid. 56 Commands affected by BASICTYPEs and UDT.OPTIONS Command or function The BASICTYPE setting determines... UDT.OPTIONS ON/GOSUB Whether UniData bypasses the GOSUB clause and executes the next program statement (contingent on whether the expression in the ON/GOSUB command is nonnumeric or less than 1). N/A ON/GOTO Whether UniData bypasses the GOTO clause and executes the next program statement (contingent on whether the expression in the ON/GOTO command is nonnumeric or less than 1). N/A PCPERFORM N/A 35 PERFORM Whether commands are parsed by using the 11, 27, 35, 46, 93, 105 standard UniData parser or the P-type parser. PRINT N/A 5, 46 PROCREAD N/A 75, 102 PROCWRITE N/A 75 READLIST Whether you should use the READLIST or READSELECT command to assign values in an active select list to a dynamic array. The BASICTYPE setting also determines whether you can assign values in a select list, based on an account other than the current one, to a dynamic array. It also determines whether you can use the SETTING clause to set the number of elements in the select list to a variable. N/A READNEXT Whether you can assign the next record ID 23, 71 from an active select list, based on an account other than the current one, to a variable. It also determines whether you can use the SETTING clause to set the number of elements in the select list to a variable. RECORDLOCKED SELECT N/A 35 RELEASE N/A 78 N/A SELECTINFO Whether you can specify a numbered select list (0–9) in the SELECT command. What the -1 SELECTINFO function return value means. N/A SLEEP N/A 46 STOP Whether you can specify multiple messages to display when the program stops. The BASICTYPE setting also determines whether you can specify a message ID that evaluates to a key in the UniData error message file. 8, 46 SYSTEM N/A 100 535 Appendix E: Commands affected by BASICTYPEs and UDT.OPTIONS 536 Command or function The BASICTYPE setting determines... UDT.OPTIONS TRIM Whether all leading and trailing spaces or occurrences of a specified character are removed from each element in a dynamic array. For a simple string expression, any BASICTYPE setting produces the same result. N/A UDTEXECUTE N/A 35 Appendix F: Commands that set STATUS() return values This appendix lists the UniBasic commands and functions that set STATUS function return values and describes each value. Command or function STATUS() return values FILELOCK 0 – File locked successfully. usernum – If the file was already locked, and if the LOCKED clause was included in the FILELOCK statement, STATUS() returns the user number of the process that locked the file. FMT 0 – Successful completion. 1 – String expression is invalid or exceeds the allowable string size. 2 – Conversion code is invalid. GETPTR 0 – Successful completion. 1 – No more rows exist. 2 – Other error. ICONV 0 – Successful conversion. 1 – Invalid input data. 2 – Invalid conversion specification. 3 – Invalid date for “D” conversion code only. 5 – Null value if null value handling is turned on. ICONV D 0 – Successful conversion of a valid date. 1 – Invalid input date. 2 – Invalid conversion specification. 3 – Date was converted correctly, but month and day were inverted in input value. ICONVS 0 – Successful conversion. 1 – Invalid input data. 2 – Invalid conversion specification. 3 – Invalid date for “D” conversion code only. 5 – Null value if null value handling is turned on. 537 Appendix F: Commands that set STATUS() return values Command or function STATUS() return values MATWRITE 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). 10 – Non-RFS files: WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files: WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. MATWRITEU 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). 10 – Non-RFS files: WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files: WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. OCONV D 0 – Successful conversion of a valid date. 1 – The input date was invalid. 2 – The conversion code was invalid. OPENSEQ 0 – The record does not exist. 1 – The file you specify is not a sequential-access file. 2 – The file does not exist. 3 – The READONLY clause was included in the command statement and the record does not exist. 4 – An unknown error occurred (such as having too many files open or permission problems). OSBREAD 0 – The read was successful. 1 – The file name is invalid. 2 – Access is denied by the operating system. 3 – The file does not exist. 4 – An unknown error occurred. OSBWRITE 0 – The write was successful. 1 – The file name is invalid. 2 – You do not have permission to access the file. 4 – The file does not exist. 538 Commands that set STATUS() return values Command or function STATUS() return values OSCLOSE 0 – The file has closed successfully. 5 – The file did not close. OSDELETE 0 – The file was deleted. 1 – The directory name is invalid. 2 – UniData cannot access the file (such as user does not have permission). 4 – The file does not exist. READ 0 – Successful read. 2 – A read error occurred. READBCK 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READBCKL 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READBCKU 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READFWD 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READFWDL 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READFWDU 0 – Successful read. 10 – UniBasic found and read a duplicate alternate index key value, and ECL DUP.STATUS is on. READL 0 – Successful read. 1 – UniData was unable to read the record. n – The record is locked. The user number of the user who locked the record. READT 0 – Successful read. 1 – End of file encountered. 2 – End of tape encountered. 3 – Tape not assigned. 4 – Parity error. 5 – Unknown hardware error. 6 – Other unspecified error. 539 Appendix F: Commands that set STATUS() return values Command or function STATUS() return values READU 0 – Successful read. 1 – UniData was unable to read the record. n – The record is locked. The user number of the user who locked the file is returned in n. RECORDLOCKED n – The record is locked. The user number of the user who owns the lock is returned in n. 0 – The record is not locked. -1 – The file is NFA. Currently, RECORDLOCKED does not support NFA files. -2 – Invalid file type. file.var can contain the null value. -3 – System error: unknown user. SELECTINDEX 0 – The select list is loaded with alternate key values or record IDs for the specified file. 1 – No alternate index key exists for this attribute using the name specified. The select list is empty. SETINDEX 0 – The alternate key specified exists. 1 – Error. 2 – The alternate key specified does not exist. SUBROUTINE (Update Trigger) 0 – No error. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the update or delete is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). SUBROUTINE (Delete Trigger) 0 – No error. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the update or delete is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). TRANSACTION COMMIT 0 – The commit completed successfully. 1 – Transaction not started. 3 – Transaction cannot commit. TRANSACTION START 0 – The transaction was started. 1 – The transaction was not started. 540 Commands that set STATUS() return values Command or function STATUS() return values WEOF 0 – Successful read. 1 – End of file encountered. 2 – End of tape encountered. 3 – Tape not assigned. 4 – Parity error. 5 – Unknown hardware error. 6 – Other unspecified error. WRITE 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, the trigger subroutine is not cataloged). 10 – Non-RFS files: WRITE created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITE failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files: WRITE created a duplicate value in the index, and ECL DUP.STATUS is on. WRITET 0 – Successful read. 1 – End of file encountered. 2 – End of tape encountered. 3 – Tape not assigned. 4 – Parity error. 5 – Unknown hardware error. 6 – Other unspecified error. WRITEU 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITEU is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 10 – Non-RFS files: WRITEU created a duplicate alternate index key and ECL DUP.STATUS is ON; or WRITEU failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files: WRITEU created a duplicate value in the index, and ECL DUP.STATUS is ON. 541 Appendix F: Commands that set STATUS() return values Command or function STATUS() return values WRITEV 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITEV is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 10 – Non-RFS files: WRITEV created a duplicate alternate index key and ECL DUP.STATUS is on; or WRITEV failed because a duplicate value exists in the index and NO.DUPS was specified when the index was created. RFS files: WRITEV created a duplicate value in the index, and ECL DUP.STATUS is on. WRITEVU 0 – Successful write. 1 – System error, such as a damaged file. 2 – Constraint violation. In this case, the UniBasic trigger subroutine returns a value of 0 in the parameter execstat, indicating that the WRITE VU is not allowed. 3 – Trigger execution error or unexpected return from trigger routine (for example, trigger subroutine is not cataloged). 10 – Non-RFS files: WRITEVU created a duplicate alternate index key and ECL DUP.STATUS is ON; or WRITEVU failed because a duplicate value exists in the index, and NO.DUPS was specified when the index was created. RFS files: WRITEVU created a duplicate value in the index, and ECL DUP.STATUS is ON. 542