-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy path03.select.pas
More file actions
324 lines (261 loc) · 9.25 KB
/
Copy path03.select.pas
File metadata and controls
324 lines (261 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
Program select;
{
* PROGRAM: Object oriented API samples.
* MODULE: 03.select.pas
* DESCRIPTION:
* A sample of running SELECT statement without parameters.
* Prints string fields in a table, coercing VARCHAR to CHAR.
* Learns how to coerce output data in prepared statement
* and execute it.
*
* Example for the following interfaces:
*
* IStatement - SQL statement execution
* IMessageMetadata - describe input and output data format
* IResultSet - fetch data returned by statement after execution
*
* Run something like this to build the program :
*
* fpc -Fu./common -Fu/opt/firebird/include/firebird -FUlib 03.select.pas
*
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* https://www.ibphoenix.com/about/firebird/idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Paul Reeves
* for the Firebird Open Source RDBMS project.
* Most of the code for GetOutput was taken from Denis
* Simonov's UDR-Book project.
*
* Copyright (c) 2020 Paul Reeves <preeves@ibphoenix.com>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________. }
{$mode Delphi}{$H+}
Uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads
, {$ENDIF} {$ENDIF}
SysUtils
, Firebird
, strutils
, FbCharsets
;
// Record to store received metadata
Type
TField = Record
fieldname: String;
fieldtype: Cardinal;
fieldlength: Integer;
offset: Integer;
sqlnullind: Wordbool;
charset: TFBCharSet;
charLength: Integer;
fieldvalue: String;
End;
Var
// master and status are required for all access to the API.
// This is main interface of firebird, and the only one
// for getting which there is special function in our API
master: IMaster;
// Status is used to return error descriptions to user
status: IStatus;
// Provides some miscellaneous utilities.
util: IUtil;
// Provider is needed to start to work with database (or service)
prov: IProvider;
// Attachment and Transaction contain methods to work with
// database attachment and transaction
att: IAttachment;
tra: ITransaction;
tpb: IXpbBuilder;
// to prepare an sql statement
stmt: IStatement;
// We geain access to the result set with a cursor
curs: IResultSet;
// Retrieve info about metadata of a statement
meta: IMessageMetadata;
builder: IMetadataBuilder;
// Store the meta data of each field in the result set
fields: Array Of TField;
// Store the titles of each field in the result set
title: String = '';
// msg is a pointer to each row in the result set.
msg: Pointer;
msgLen: Cardinal;
counter: Integer;
Const
// Firebird types
SQL_VARYING = 448; // VARCHAR
SQL_TEXT = 452; // CHAR
Procedure PrintError(AMaster: IMaster; AStatus: IStatus);
Var
maxMessage: Integer;
outMessage: PAnsiChar;
Begin
maxMessage := 256;
outMessage := StrAlloc(maxMessage);
AMaster.getUtilInterface.formatStatus(outMessage, maxMessage, AStatus);
writeln(outMessage);
StrDispose(outMessage);
End;
Function GetOutput(AStatus: IStatus; ABuffer: PByte; AMeta: IMessageMetadata; AUtil: IUtil;
AFieldsArray: Array Of TField): UnicodeString;
Var
i: Integer;
NullFlag: Wordbool;
pData: PByte;
CharBuffer: TBytes;
StringValue: UnicodeString;
current_field: TField;
Begin
Result := '';
For i := 0 To length(AFieldsArray) - 1 Do Begin
current_field := AfieldsArray[i];
With current_field Do Begin
NullFlag := PWordBool(ABuffer + AMeta.getNullOffset(AStatus, i))^;
If NullFlag Then Begin
StringValue := 'NULL';
continue;
End;
// get a pointer to the field data
pData := ABuffer + AMeta.getOffset(AStatus, i);
pData := ABuffer + offset;
Case fieldType Of
SQL_VARYING:
Begin
SetLength(CharBuffer, fieldLength);
// For VARCHAR, the first 2 bytes are the length
charLength := PSmallint(pData)^;
// For VARCHAR, the first 2 bytes are the length in bytes
// so we copy it to the buffer starting at 3 bytes
Move((pData + 2)^, CharBuffer[0], fieldLength);
StringValue := charset.GetString(CharBuffer, 0, charLength);
End;
Else
StringValue := ' Fieldtype not handled.';
End; // case fieldType of
If Result = '' Then
Result := Result + UnicodeString(PadRight(UTF8Encode(StringValue), fieldLength))
Else
Result := Result + ' ' + UnicodeString(PadRight(UTF8Encode(StringValue), fieldLength));
End; // end with current_field
End; // for i := 0 to length(AFieldsArray) - 1 do begin
End; // function GetOutput
Begin
master := fb_get_master_interface;
status := master.getStatus;
// Here we get access to the helper utility interfaces
// no errors can occur - this function will always succeed
util := master.getUtilInterface;
// the main dispatcher is returned by a call to IMaster
// no errors can occur - this function will always succeed
prov := master.getDispatcher;
Try
Try
// attach to employee db
// We assume that ISC_USER and ISC_PASSWORD env vars are set. Otherwise,
// see code in 01.create for an example of setting the un/pw via the dpb.
att := prov.attachDatabase(status, 'employee', 0, nil);
writeln('Attached to database employee.fdb');
// start read only transaction
tpb := util.getXpbBuilder(status, IXpbBuilder.TPB, nil, 0);
tpb.insertTag(status, isc_tpb_read_committed);
tpb.insertTag(status, isc_tpb_no_rec_version);
tpb.insertTag(status, isc_tpb_wait);
tpb.insertTag(status, isc_tpb_read);
// start transaction
tra := att.startTransaction(status, tpb.getBufferLength( status ), tpb.getBuffer( status ));
// prepare statement
stmt := att.prepare(status, tra, 0, 'Select last_name, first_name, phone_ext from phone_list ' +
'where location = ''Monterey'' order by last_name, first_name', 3,
IStatement.PREPARE_PREFETCH_METADATA);
// get list of columns
meta := stmt.getOutputMetadata(status);
builder := meta.getBuilder(status);
SetLength(fields, meta.getCount(status));
// parse columns list & coerce datatype(s)
For counter := 0 To length(fields) - 1 Do Begin
If ((meta.getType(status, counter) = (SQL_VARYING Or SQL_TEXT))) Then
builder.setType(status, counter, SQL_TEXT);
fields[counter].fieldname := meta.getField(status, counter);
End;
// release automatically created metadata
// metadata is not database object, therefore no specific call to close it
meta.Release;
// get metadata with coerced datatypes
meta := builder.getMetadata(status);
// builder is no longer needed
builder.Release;
builder := nil;
// now get field info
For counter := 0 To length(fields) - 1 Do Begin
If fields[counter].fieldname <> '' Then Begin
fields[counter].fieldlength := meta.getLength(status, counter);
fields[counter].offset := meta.getOffset(status, counter);
fields[counter].fieldType := meta.getType(status, counter) And Not 1;
Case fields[counter].fieldType Of
SQL_TEXT, SQL_VARYING:
fields[counter].charset := TFBCharSet(meta.getCharSet(status, counter));
Else
;
End;
// Set the title line for later use.
If title = '' Then
title := title + fields[counter].fieldname.PadRight(fields[counter].fieldlength)
Else
title := title + ' ' + fields[counter].fieldname.PadRight(fields[counter].fieldlength);
End;
End;
// open cursor
curs := stmt.openCursor(status, tra, nil, nil, meta, 0);
// allocate output buffer
msgLen := meta.getMessageLength(status);
msg := AllocMem(msgLen);
counter := 0;
While curs.fetchNext(status, msg) = IStatus.RESULT_OK Do Begin
If ((counter Mod 10) = 0) Then Begin
writeln('');
writeln(title);
End;
Inc(counter);
WriteLn(GetOutput(status, msg, meta, util, fields));
End;
// What is correct way to close and release?
// close interfaces
curs.Close(status);
stmt.Free(status);
meta.Release();
tra.commit(status);
att.detach(status);
Except
on e: FbException Do
PrintError(master, e.getStatus);
End;
Finally
If assigned(meta) Then
meta.Release;
If assigned(builder) Then
builder.Release;
If assigned(curs) Then
curs.Release;
If assigned(stmt) Then
stmt.Release;
If assigned(tra) Then
tra.Release;
If assigned(att) Then
att.Release;
If assigned(tpb) Then
tpb.dispose;
prov.Release;
status.dispose;
End;
End.