Debian Codegraph @

src/utilities/gstat/dba.epp

raw
1 /*
2 * PROGRAM: JRD Access Method
3 * MODULE: dba.epp
4 * DESCRIPTION: Database analysis tool
5 *
6 * The contents of this file are subject to the Interbase Public
7 * License Version 1.0 (the "License"); you may not use this file
8 * except in compliance with the License. You may obtain a copy
9 * of the License at http://www.Inprise.com/IPL.html
10 *
11 * Software distributed under the License is distributed on an
12 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
13 * or implied. See the License for the specific language governing
14 * rights and limitations under the License.
15 *
16 * The Original Code was created by Inprise Corporation
17 * and its predecessors. Portions created by Inprise Corporation are
18 * Copyright (C) Inprise Corporation.
19 *
20 * All Rights Reserved.
21 * Contributor(s): ______________________________________.
22 *
23 * 2001.08.07 Sean Leyne - Code Cleanup, removed "#ifdef READONLY_DATABASE"
24 * conditionals, as the engine now fully supports
25 * readonly databases.
26 *
27 * 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
28 *
29 */
30
31
32 #include "firebird.h"
33 #include "../common/classes/fb_string.h"
34 #include <stdio.h>
35 #include "../common/classes/alloc.h"
36 #include <errno.h>
37 #include <string.h>
38 #include <fcntl.h>
39 #include "../jrd/ibsetjmp.h"
40 #include "../common/classes/timestamp.h"
41 #include "../jrd/ibase.h"
42 #include "../jrd/ods.h"
43 #include "../jrd/btn.h"
44 #include "../jrd/license.h"
45 #include "../common/msg_encode.h"
46 #include "../common/gdsassert.h"
47 #include "../utilities/gstat/ppg_proto.h"
48 #include "../utilities/gstat/dbaswi.h"
49 #include "../yvalve/gds_proto.h"
50 #include "../common/isc_f_proto.h"
51 #include "../common/utils_proto.h"
52 #include "../common/classes/ClumpletWriter.h"
53 #include "../jrd/constants.h"
54 #include "../jrd/ods_proto.h"
55 #include "../common/classes/MsgPrint.h"
56 #include "../common/classes/UserBlob.h"
57 #include "../common/os/os_utils.h"
58 #include "../common/StatusHolder.h"
59 #include "../common/ThreadStart.h"
60
61 #ifdef TIME_WITH_SYS_TIME
62 # include <sys/time.h>
63 # include <time.h>
64 #else
65 # ifdef HAVE_SYS_TIME_H
66 # include <sys/time.h>
67 # else
68 # include <time.h>
69 # endif
70 #endif
71
72 using MsgFormat::SafeArg;
73
74
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78
79 #ifdef HAVE_IO_H
80 #include <io.h>
81 #endif
82
83 using namespace Firebird;
84 using namespace Jrd;
85 using namespace Ods;
86
87
88 // For Netware the follow DB handle and isc_status is #defined to be a
89 // local variable on the stack in main. This is to avoid multiple
90 // threading problems with module level statics.
91 DATABASE DB = STATIC "yachts.lnk";
92 #define DB db_handle
93 #define isc_status status_vector
94
95 const SSHORT BUCKETS = 5;
96 //#define WINDOW_SIZE (1 << 17)
97
98 struct dba_idx
99 {
100 dba_idx* idx_next;
101 SSHORT idx_id;
102 ULONG idx_root;
103 SSHORT idx_depth;
104 ULONG idx_leaf_buckets;
105 FB_UINT64 idx_total_duplicates;
106 FB_UINT64 idx_max_duplicates;
107 FB_UINT64 idx_nodes;
108 FB_UINT64 idx_total_length;
109 FB_UINT64 idx_prefix_length;
110 FB_UINT64 idx_data_length;
111 FB_UINT64 idx_unpacked_length;
112 FB_UINT64 idx_packed_length;
113 FB_UINT64 idx_diff_pages;
114 ULONG idx_fill_distribution[BUCKETS];
115 SCHAR idx_name[MAX_SQL_IDENTIFIER_SIZE];
116 };
117
118 struct dba_fmt
119 {
120 dba_fmt* fmt_next;
121 USHORT fmt_number;
122 USHORT fmt_length;
123 bool fmt_used;
124 };
125
126 struct dba_rel
127 {
128 dba_rel* rel_next;
129 dba_idx* rel_indexes;
130 dba_fmt* rel_formats;
131 ULONG rel_index_root;
132 ULONG rel_pointer_page;
133 ULONG rel_slots;
134 ULONG rel_pointer_pages;
135 ULONG rel_data_pages;
136 ULONG rel_empty_pages;
137 ULONG rel_full_pages;
138 ULONG rel_primary_pages;
139 ULONG rel_swept_pages;
140 ULONG rel_blob_pages;
141 ULONG rel_bigrec_pages;
142 FB_UINT64 rel_records;
143 FB_UINT64 rel_record_space;
144 FB_UINT64 rel_versions;
145 FB_UINT64 rel_version_space;
146 FB_UINT64 rel_max_versions;
147 FB_UINT64 rel_fragments;
148 FB_UINT64 rel_fragment_space;
149 FB_UINT64 rel_max_fragments;
150 FB_UINT64 rel_blobs_level_0;
151 FB_UINT64 rel_blobs_level_1;
152 FB_UINT64 rel_blobs_level_2;
153 FB_UINT64 rel_blob_space;
154 ULONG rel_fill_distribution[BUCKETS];
155 FB_UINT64 rel_format_space;
156 FB_UINT64 rel_total_space;
157 USHORT rel_total_formats;
158 USHORT rel_used_formats;
159 SSHORT rel_id;
160 SCHAR rel_name[MAX_SQL_IDENTIFIER_SIZE];
161 };
162
163 // kidnapped from jrd/pio.h and abused
164
165 struct dba_fil
166 {
167 dba_fil* fil_next; // Next file in database
168 ULONG fil_min_page; // Minimum page number in file
169 ULONG fil_max_page; // Maximum page number in file
170 USHORT fil_fudge; // Fudge factor for page relocation
171 #ifdef WIN_NT
172 void *fil_desc;
173 #else
174 int fil_desc;
175 #endif
176 USHORT fil_length; // Length of expanded file name
177 SCHAR fil_string[1]; // Expanded file name
178 };
179
180 static char* alloc(size_t);
181 static void analyze_blob(dba_rel*, const blh*, int length);
182 static void analyze_data(dba_rel*, bool);
183 static bool analyze_data_page(dba_rel*, const data_page*, bool);
184 static ULONG analyze_fragments(dba_rel*, const rhdf*);
185 static ULONG analyze_versions(dba_rel*, const rhdf*);
186 static void analyze_index(const dba_rel*, dba_idx*);
187 static ULONG lastUsedPage(ULONG);
188
189 #if (defined WIN_NT)
190 static void db_error(SLONG);
191 #else
192 static void db_error(int);
193 #endif
194
195 static USHORT get_format_length(ISC_STATUS*, isc_db_handle, isc_tr_handle, ISC_QUAD&);
196
197 static dba_fil* db_open(const char*, USHORT);
198 static const pag* db_read(SLONG page_number, bool ok_enc = false);
199 #ifdef WIN_NT
200 static void db_close(void* file_desc);
201 #else
202 static void db_close(int);
203 #endif
204 static void dba_error(USHORT, const SafeArg& arg = SafeArg());
205 static void dba_print(bool, USHORT, const SafeArg& arg = SafeArg());
206 static void print_distribution(const SCHAR*, const ULONG*);
207 static void print_help();
208
209
210 #include "../common/db_alias.h"
211
212 #include <fcntl.h>
213 #if (defined WIN_NT)
214 #include <share.h>
215 #endif
216
217 #include "../utilities/gstat/dba_proto.h"
218
219 struct open_files
220 {
221 #ifdef WIN_NT
222 void* desc;
223 #else
224 int desc;
225 #endif
226 open_files* open_files_next;
227 };
228
229 struct dba_mem
230 {
231 char* memory;
232 dba_mem* mem_next;
233 };
234
235 // threading declarations for thread data
236
237 class tdba : public ThreadData
238 {
239 public:
240 explicit tdba(Firebird::UtilSvc* us)
241 : ThreadData(tddDBA), uSvc(us)
242 {
243 //dba_throw = false;
244 files = 0;
245 relations = 0;
246 page_size = 0;
247 dp_per_pp = 0;
248 max_records = 0;
249 page_number = 0;
250 buffer1 = 0;
251 buffer2 = 0;
252 global_buffer = 0;
253 exit_code = 0;
254 head_of_mem_list = 0;
255 head_of_files_list = 0;
256 memset(dba_status_vector, 0, sizeof (dba_status_vector));
257 dba_status = dba_status_vector;
258 }
259
260 //bool dba_throw;
261 Firebird::UtilSvc* uSvc;
262 dba_fil* files;
263 dba_rel* relations;
264 USHORT page_size;
265 USHORT dp_per_pp;
266 USHORT max_records;
267 SLONG page_number;
268 pag* buffer1;
269 pag* buffer2;
270 pag* global_buffer;
271 int exit_code;
272 dba_mem *head_of_mem_list;
273 open_files *head_of_files_list;
274 ISC_STATUS *dba_status;
275 ISC_STATUS_ARRAY dba_status_vector;
276
277 static inline tdba* getSpecific()
278 {
279 return (tdba*) ThreadData::getSpecific();
280 }
281 static inline void putSpecific(tdba* &tddba, tdba* thd_context)
282 {
283 tddba = thd_context;
284 tddba->ThreadData::putSpecific();
285 }
286 static inline void restoreSpecific()
287 {
288 ThreadData::restoreSpecific();
289 }
290 };
291
292
293 void inline dba_exit(int code, tdba* tddba)
294 {
295 tddba->exit_code = code;
296 // Throw this kind of exception, because gstat uses status vector (and stuffException) to
297 // handle errors
298 Firebird::LongJump::raise();
299 }
300
301 namespace
302 {
303 // all this stuff gets activated ONLY in utility mode
304 // therefore we can safely use static variables here
305
306 bool shutdownRequested = false;
307
308 int gstatShutdown(const int reason, const int, void*)
309 {
310 if (reason == fb_shutrsn_signal)
311 {
312 shutdownRequested = true;
313 return FB_FAILURE;
314 }
315 return FB_SUCCESS;
316 }
317
318 void checkForShutdown(tdba* tddba)
319 {
320 if (shutdownRequested)
321 {
322 dba_exit(FINI_OK, tddba);
323 }
324 }
325
326 void getDateTime(char* datetime, FB_SIZE_T sizeof_datetime)
327 {
328 time_t t;
329 time(&t);
330 #if defined(HAVE_CTIME_R)
331 ctime_r(&t, datetime);
332 #elif defined(HAVE_CTIME_S)
333 ctime_s(datetime, sizeof_datetime, &t);
334 #else
335 error: missing thread-safe version of ctime()
336 #endif
337 }
338 } // namespace
339
340 const USHORT GSTAT_MSG_FAC = 21;
341
342
343 int main_gstat(Firebird::UtilSvc* uSvc)
344 {
345 /**********************************************
346 *
347 * m a i n _ g s t a t
348 *
349 **********************************************
350 * Functional Description:
351 * Entrypoint for GSTAT via the services manager
352 **********************************************/
353 int exit_code = FINI_OK;
354
355 try {
356 exit_code = gstat(uSvc);
357 }
358 catch (const Firebird::Exception& e)
359 {
360 Firebird::StaticStatusVector status;
361 e.stuffException(status);
362 uSvc->initStatus();
363 uSvc->setServiceStatus(status.begin());
364 exit_code = FB_FAILURE;
365 }
366
367 return exit_code;
368 }
369
370
371 int gstat(Firebird::UtilSvc* uSvc)
372 {
373 /**************************************
374 *
375 * g s t a t
376 *
377 **************************************
378 *
379 * Functional description
380 * Gather information from system relations to do analysis
381 * of a database.
382 *
383 **************************************/
384 isc_db_handle db_handle = 0;
385
386 TEXT pass_buff[128], user_buff[128], *password = pass_buff, *username = user_buff;
387 TEXT role_buff[128], *role = role_buff;
388 MOVE_CLEAR(user_buff, sizeof(user_buff));
389 MOVE_CLEAR(pass_buff, sizeof(pass_buff));
390 MOVE_CLEAR(role_buff, sizeof(role_buff));
391
392 // TEXT tr_buff[128], *tr_user = tr_buff;
393 // MOVE_CLEAR(tr_buff, sizeof(tr_buff));
394
395 #ifdef TRUSTED_AUTH
396 bool trusted_auth = false;
397 #endif
398
399 tdba thd_context(uSvc), *tddba;
400 tdba::putSpecific(tddba, &thd_context);
401 int exit_code = FINI_OK;
402
403 const int argc = uSvc->argv.getCount();
404 const char** argv = uSvc->argv.begin();
405
406 ISC_STATUS* status_vector = NULL;
407 Firebird::DynamicStatusVector permStatus;
408
409 bool fl_print_complete = false;
410 char datetime[32];
411
412 try {
413
414 tddba->dba_status = tddba->dba_status_vector;
415 status_vector = tddba->dba_status;
416
417 if (argc == 1) // no parameters at all.
418 {
419 dba_error(45); // use gstat -? to get help'
420 }
421
422 bool sw_system = false;
423 bool sw_data = false;
424 bool sw_index = false;
425 bool sw_version = false;
426 bool sw_header = false;
427 bool sw_enc = false;
428 //bool sw_log = false;
429 bool sw_record = false;
430 bool sw_relation = false;
431 bool sw_nocreation = false;
432
433 const Switches switches(dba_in_sw_table, FB_NELEM(dba_in_sw_table), false, true);
434 const char* name = NULL;
435
436 const TEXT* const* const end = argv + argc;
437 ++argv;
438 while (argv < end)
439 {
440 const TEXT* str = *argv++;
441 if (*str != '-')
442 {
443 if (name)
444 {
445 dba_error(40); // database name was already specified
446 }
447
448 name = str;
449 continue;
450 }
451
452 const Switches::in_sw_tab_t* in_sw_tab = switches.findSwitch(str);
453 if (!in_sw_tab)
454 {
455 if (!tddba->uSvc->isService()) // normally service manager doesn't pass illegal switches
456 {
457 if (!str[1])
458 str = "-*NONE*";
459 dba_print(true, 20, SafeArg() << (str + 1)); // msg 20: unknown switch "%s"
460 print_help();
461 }
462
463 dba_error(1); // msg 1: found unknown switch
464 break; // redundant
465 }
466
467 switch (in_sw_tab->in_sw)
468 {
469 case IN_SW_DBA_HELP:
470 print_help();
471 dba_exit(FINI_OK, tddba);
472 break;
473 case IN_SW_DBA_USERNAME:
474 if (argv < end)
475 fb_utils::copy_terminate(username, *argv++, sizeof(user_buff));
476 break;
477 case IN_SW_DBA_ROLE:
478 if (argv < end)
479 fb_utils::copy_terminate(role, *argv++, sizeof(role_buff));
480 break;
481 case IN_SW_DBA_PASSWORD:
482 if (argv < end)
483 {
484 uSvc->hidePasswd(uSvc->argv, argv - uSvc->argv.begin());
485 fb_utils::copy_terminate(password, *argv++, sizeof(pass_buff));
486 }
487 break;
488 case IN_SW_DBA_FETCH_PASS:
489 if (argv < end)
490 {
491 const char* passwd = NULL;
492 if (fb_utils::fetchPassword(*argv++, passwd) == fb_utils::FETCH_PASS_OK)
493 {
494 fb_utils::copy_terminate(password, passwd, sizeof(pass_buff));
495 }
496 }
497 break;
498 #ifdef TRUSTED_AUTH
499 case IN_SW_DBA_TRUSTEDAUTH:
500 trusted_auth = true;
501 break;
502 #endif
503 case IN_SW_DBA_SYSTEM:
504 sw_system = true;
505 break;
506 case IN_SW_DBA_DATA:
507 sw_data = true;
508 break;
509 case IN_SW_DBA_INDEX:
510 sw_index = true;
511 break;
512 case IN_SW_DBA_VERSION:
513 sw_version = true;
514 break;
515 case IN_SW_DBA_HEADER:
516 sw_header = true;
517 break;
518 case IN_SW_DBA_ENCRYPTION:
519 sw_enc = true;
520 break;
521 // case IN_SW_DBA_LOG:
522 // sw_log = true;
523 // break;
524 case IN_SW_DBA_DATAIDX:
525 sw_index = sw_data = true;
526 break;
527 case IN_SW_DBA_RECORD:
528 sw_record = true;
529 break;
530 case IN_SW_DBA_RELATION:
531 sw_relation = true;
532 while (argv < end && **argv != '-')
533 {
534 if (strlen(*argv) > MAX_SQL_IDENTIFIER_LEN)
535 {
536 char tbname[MAX_SQL_IDENTIFIER_LEN + 5];
537 fb_utils::copy_terminate(tbname, *argv, MAX_SQL_IDENTIFIER_SIZE);
538 memcpy(tbname + MAX_SQL_IDENTIFIER_LEN, "...\0", 4);
539 dba_error(42, SafeArg() << tbname); // option -t got a too long table name @1
540 break;
541 }
542
543 dba_rel* relation = (dba_rel*) alloc(sizeof(struct dba_rel));
544 strcpy(relation->rel_name, *argv++);
545 fb_utils::exact_name(relation->rel_name);
546 relation->rel_id = -1;
547 dba_rel** next = &tddba->relations;
548 while (*next) {
549 next = &(*next)->rel_next;
550 }
551 *next = relation;
552
553 // CVC: If the db name wasn't given yet, only one table name can be specified
554 // after -t to avoid ambiguity.
555 if (!name)
556 break;
557 }
558 break;
559 case IN_SW_DBA_NOCREATION:
560 sw_nocreation = true;
561 break;
562 }
563 }
564
565 if (sw_version)
566 dba_print(false, 5, SafeArg() << FB_VERSION); // msg 5: gstat version %s
567
568 if (sw_header && (sw_system || sw_data || sw_index || sw_record || sw_relation))
569 {
570 dba_error(38); //option -h is incompatible with options -a, -d, -i, -r, -s and -t
571 }
572
573 if (sw_enc && (sw_header || sw_system || sw_data || sw_index || sw_record || sw_relation))
574 {
575 dba_error(50); //option -e is incompatible with options -a, -d, -h, -i, -r, -s and -t
576 }
577
578 if (!name)
579 {
580 dba_error(2); // msg 2: please retry, giving a database name
581 }
582
583 if (sw_relation && !tddba->relations)
584 {
585 dba_error(41); // option -t needs a table name.
586 }
587
588 if (!sw_data && !sw_index)
589 sw_data = sw_index = true;
590
591 if (sw_record && !sw_data)
592 sw_data = true;
593
594 // Open database and go to work
595
596 Firebird::PathName fileName = name;
597 const Firebird::PathName connName = fileName;
598 Firebird::PathName tempStr;
599
600 #ifdef WIN_NT
601 if (!ISC_analyze_pclan(fileName, tempStr))
602 #endif
603 {
604 if (!ISC_analyze_tcp(fileName, tempStr))
605 {
606 #ifndef NO_NFS
607 if (!ISC_analyze_nfs(fileName, tempStr))
608 #endif
609 {
610 fileName = connName;
611 }
612 }
613 }
614
615 expandDatabaseName(fileName, tempStr, NULL);
616 fileName = tempStr;
617
618 dba_fil* current = db_open(fileName.c_str(), fileName.length());
619
620 SCHAR temp[RAW_HEADER_SIZE];
621 tddba->page_size = sizeof(temp);
622 tddba->global_buffer = (pag*) temp;
623 tddba->page_number = -1;
624 const header_page* header = (const header_page*) db_read((SLONG) 0);
625
626 uSvc->started();
627
628 if (!Ods::isSupported(header))
629 {
630 const int oversion = (header->hdr_ods_version & ~ODS_FIREBIRD_FLAG);
631 dba_error(3, SafeArg() << ODS_VERSION << oversion);
632 // msg 3: Wrong ODS version, expected %d, encountered %d?
633 }
634
635 char file_name[1024];
636 fileName.copyTo(file_name, sizeof(file_name));
637 dba_print(false, 6, SafeArg() << file_name); // msg 6: \nDatabase \"@1\"\n
638
639 getDateTime(datetime, sizeof(datetime));
640 dba_print(false, 59, SafeArg() << datetime); // msg 59: Gstat execution time @1
641 fl_print_complete = true;
642
643 tddba->page_size = header->hdr_page_size;
644 tddba->dp_per_pp = Ods::dataPagesPerPP(tddba->page_size);
645 tddba->max_records = Ods::maxRecsPerDP(tddba->page_size);
646 tddba->buffer1 = (pag*) alloc(tddba->page_size);
647 tddba->buffer2 = (pag*) alloc(tddba->page_size);
648 tddba->global_buffer = (pag*) alloc(tddba->page_size);
649 tddba->page_number = -1;
650
651 // gather continuation files
652
653 ULONG page = HEADER_PAGE;
654 do {
655 if (page != HEADER_PAGE)
656 current = db_open(file_name, static_cast<USHORT>(strlen(file_name)));
657 do {
658 header = (const header_page*) db_read(page);
659 if (current != tddba->files)
660 current->fil_fudge = 1; // ignore header page once read it
661 *file_name = '\0';
662 const UCHAR* vp = header->hdr_data;
663 for (const UCHAR* const vend = vp + header->hdr_page_size;
664 vp < vend && *vp != HDR_end; vp += 2 + vp[1])
665 {
666 if (*vp == HDR_file)
667 {
668 memcpy(file_name, vp + 2, vp[1]);
669 *(file_name + vp[1]) = '\0';
670 }
671 if (*vp == HDR_last_page) {
672 memcpy(&current->fil_max_page, vp + 2, sizeof(current->fil_max_page));
673 }
674 }
675 } while (page = header->hdr_next_page);
676 page = current->fil_max_page + 1; // first page of next file
677 } while (*file_name);
678
679 // Print header page
680
681 page = HEADER_PAGE;
682 do {
683 header = (const header_page*) db_read(page);
684 PPG_print_header(header, page, sw_nocreation, uSvc);
685 page = header->hdr_next_page;
686 } while (page);
687
688 if (sw_header)
689 dba_exit(FINI_OK, tddba);
690
691 if (sw_enc)
692 {
693 class Statist
694 {
695 public:
696 Statist()
697 : enc(0), non(0)
698 { }
699
700 void print(USHORT messageNo)
701 {
702 dba_print(false, messageNo, SafeArg() << enc + non << enc << non);
703 // msg 5[2-4]: <TYPE> pages: total @1, encrypted @2, non-crypted @3
704 }
705
706 void log(UCHAR flags)
707 {
708 if (flags & crypted_page)
709 ++enc;
710 else
711 ++non;
712 }
713
714 bool hasCrypted()
715 {
716 return enc > 0;
717 }
718
719 private:
720 ULONG enc, non;
721 };
722 Statist data, index, blob, generator, other;
723
724 ULONG last = lastUsedPage(header->hdr_page_size);
725 for (page = 0; page <= last; ++page)
726 {
727 const pag* p = db_read(page, true);
728 if (!p)
729 {
730 break;
731 }
732
733 switch(p->pag_type)
734 {
735 case pag_data:
736 data.log(p->pag_flags);
737 break;
738 case pag_index:
739 index.log(p->pag_flags);
740 break;
741 case pag_blob:
742 blob.log(p->pag_flags);
743 break;
744 case pag_ids:
745 generator.log(p->pag_flags);
746 break;
747 default:
748 other.log(p->pag_flags);
749 break;
750 }
751 }
752
753 uSvc->printf(false, "\n");
754 data.print(52);
755 index.print(53);
756 blob.print(54);
757 generator.print(62);
758 if (other.hasCrypted())
759 other.print(58);
760
761 dba_exit(FINI_OK, tddba);
762 }
763
764 // print continuation file sequence
765
766 dba_print(false, 7);
767 // msg 7: \n\nDatabase file sequence:
768 for (current = tddba->files; current->fil_next; current = current->fil_next)
769 {
770 dba_print(false, 8, SafeArg() << current->fil_string << current->fil_next->fil_string);
771 // msg 8: File %s continues as file %s
772 }
773 dba_print(false, 9, SafeArg() << current->fil_string << ((current == tddba->files) ? "only" : "last"));
774 // msg 9: File %s is the %s file\n
775
776 // Check to make sure that the user accessing the database is either
777 // SYSDBA or owner of the database
778
779 Firebird::ClumpletWriter dpb(Firebird::ClumpletReader::dpbList, MAX_DPB_SIZE);
780 uSvc->fillDpb(dpb);
781 dpb.insertTag(isc_dpb_gstat_attach);
782 dpb.insertTag(isc_dpb_no_garbage_collect);
783
784 const unsigned char* authBlock;
785 unsigned int authBlockSize = uSvc->getAuthBlock(&authBlock);
786 if (authBlockSize)
787 {
788 dpb.insertBytes(isc_dpb_auth_block, authBlock, authBlockSize);
789 }
790 else
791 {
792 if (*username)
793 dpb.insertString(isc_dpb_user_name, username, fb_strlen(username));
794
795 if (*password)
796 {
797 dpb.insertString(uSvc->isService() ? isc_dpb_password_enc : isc_dpb_password,
798 password, fb_strlen(password));
799 }
800
801 #ifdef TRUSTED_AUTH
802 if (trusted_auth)
803 dpb.insertTag(isc_dpb_trusted_auth);
804 #endif
805 }
806 if (*role)
807 dpb.insertString(isc_dpb_sql_role_name, role, fb_strlen(role));
808
809 isc_attach_database(status_vector, 0, connName.c_str(), &DB, dpb.getBufferLength(),
810 reinterpret_cast<const char*>(dpb.getBuffer()));
811 if (status_vector[1])
812 dba_exit(FINI_ERROR, tddba);
813
814 if (sw_version)
815 isc_version(&DB, NULL, NULL);
816
817 isc_tr_handle transact1 = 0;
818 START_TRANSACTION transact1 READ_ONLY;
819 ON_ERROR
820 dba_exit(FINI_ERROR, tddba);
821 END_ERROR
822
823 isc_req_handle request1 = 0;
824 isc_req_handle request2 = 0;
825 isc_req_handle request3 = 0;
826 isc_req_handle request4 = 0;
827
828 FOR(TRANSACTION_HANDLE transact1 REQUEST_HANDLE request1)
829 X IN RDB$RELATIONS SORTED BY DESC X.RDB$RELATION_NAME
830
831 if (!sw_system && X.RDB$SYSTEM_FLAG) {
832 continue;
833 }
834 if (!X.RDB$VIEW_BLR.NULL || !X.RDB$EXTERNAL_FILE.NULL) {
835 continue;
836 }
837 //rel_virtual, rel_global_temp_preserve, rel_global_temp_delete
838 if (!X.RDB$SYSTEM_FLAG.NULL && X.RDB$SYSTEM_FLAG == fb_sysflag_system &&
839 X.RDB$RELATION_TYPE >= rel_virtual && X.RDB$RELATION_TYPE <= rel_global_temp_delete)
840 {
841 continue;
842 }
843
844 dba_rel* relation;
845 if (sw_relation)
846 {
847 fb_utils::exact_name(X.RDB$RELATION_NAME);
848 for (relation = tddba->relations; relation; relation = relation->rel_next)
849 {
850 if (!(strcmp(relation->rel_name, X.RDB$RELATION_NAME)))
851 {
852 relation->rel_id = X.RDB$RELATION_ID;
853 break;
854 }
855 }
856 if (!relation)
857 continue;
858 }
859 else
860 {
861 relation = (dba_rel*) alloc(sizeof(struct dba_rel));
862 relation->rel_next = tddba->relations;
863 tddba->relations = relation;
864 relation->rel_id = X.RDB$RELATION_ID;
865 strcpy(relation->rel_name, X.RDB$RELATION_NAME);
866 fb_utils::exact_name(relation->rel_name);
867 }
868
869 FOR(TRANSACTION_HANDLE transact1 REQUEST_HANDLE request2)
870 Y IN RDB$PAGES WITH Y.RDB$RELATION_ID EQ relation->rel_id AND
871 Y.RDB$PAGE_SEQUENCE EQ 0
872
873 if (Y.RDB$PAGE_TYPE == pag_pointer) {
874 relation->rel_pointer_page = Y.RDB$PAGE_NUMBER;
875 }
876 if (Y.RDB$PAGE_TYPE == pag_root) {
877 relation->rel_index_root = Y.RDB$PAGE_NUMBER;
878 }
879 END_FOR;
880 ON_ERROR
881 dba_exit(FINI_ERROR, tddba);
882 END_ERROR
883
884 if (sw_index)
885 {
886 FOR(TRANSACTION_HANDLE transact1 REQUEST_HANDLE request3)
887 Y IN RDB$INDICES WITH Y.RDB$RELATION_NAME EQ relation->rel_name
888 SORTED BY DESC Y.RDB$INDEX_NAME
889 if (Y.RDB$INDEX_INACTIVE)
890 continue;
891 dba_idx* index = (dba_idx*) alloc(sizeof(struct dba_idx));
892 index->idx_next = relation->rel_indexes;
893 relation->rel_indexes = index;
894 strcpy(index->idx_name, Y.RDB$INDEX_NAME);
895 fb_utils::exact_name(index->idx_name);
896 index->idx_id = Y.RDB$INDEX_ID - 1;
897 END_FOR;
898 ON_ERROR
899 dba_exit(FINI_ERROR, tddba);
900 END_ERROR
901 }
902
903 if (sw_record)
904 {
905 FOR(TRANSACTION_HANDLE transact1 REQUEST_HANDLE request4)
906 Y IN RDB$FORMATS WITH Y.RDB$RELATION_ID EQ X.RDB$RELATION_ID
907 SORTED BY Y.RDB$FORMAT
908 dba_fmt* format = (dba_fmt*) alloc(sizeof(struct dba_fmt));
909 format->fmt_next = relation->rel_formats;
910 relation->rel_formats = format;
911 format->fmt_number = Y.RDB$FORMAT;
912 format->fmt_length = get_format_length(status_vector, DB, transact1, Y.RDB$DESCRIPTOR);
913 if (!format->fmt_length)
914 {
915 dba_exit(FINI_ERROR, tddba);
916 }
917 format->fmt_used = false;
918 ++relation->rel_total_formats;
919 END_FOR;
920 ON_ERROR
921 dba_exit(FINI_ERROR, tddba);
922 END_ERROR
923 }
924 END_FOR;
925 ON_ERROR
926 dba_exit(FINI_ERROR, tddba);
927 END_ERROR
928
929 if (request1) {
930 isc_release_request(status_vector, &request1);
931 }
932 if (request2) {
933 isc_release_request(status_vector, &request2);
934 }
935 if (request3) {
936 isc_release_request(status_vector, &request3);
937 }
938 if (request4) {
939 isc_release_request(status_vector, &request4);
940 }
941
942 COMMIT transact1;
943 ON_ERROR
944 dba_exit(FINI_ERROR, tddba);
945 END_ERROR
946
947 if (!tddba->uSvc->isService())
948 {
949 // Now it's time to take care ourselves about shutdown handling
950 if (fb_shutdown_callback(status_vector, gstatShutdown, fb_shut_confirmation, NULL))
951 {
952 dba_exit(FINI_ERROR, tddba);
953 }
954 }
955
956 // FINISH; error!
957 FINISH
958 ON_ERROR
959 dba_exit(FINI_ERROR, tddba);
960 END_ERROR
961
962 if (sw_relation)
963 {
964 for (const dba_rel* relation = tddba->relations; relation; relation = relation->rel_next)
965 {
966 checkForShutdown(tddba);
967 if (relation->rel_id == -1)
968 {
969 dba_error(44, SafeArg() << relation->rel_name);
970 // msg 44: table "@1" not found
971 }
972 }
973 }
974
975
976 dba_print(false, 10);
977 // msg 10: \nAnalyzing database pages ...\n
978
979 for (dba_rel* relation = tddba->relations; relation; relation = relation->rel_next)
980 {
981 checkForShutdown(tddba);
982
983 // This condition should never happen because relations not found cause an error before.
984 if (relation->rel_id == -1)
985 {
986 fb_assert(sw_relation && relation->rel_id >= 0);
987 continue;
988 }
989
990 if (sw_data) {
991 analyze_data(relation, sw_record);
992 }
993 for (dba_idx* index = relation->rel_indexes; index; index = index->idx_next)
994 {
995 checkForShutdown(tddba);
996 analyze_index(relation, index);
997 }
998 }
999
1000 // Print results
1001
1002 UCHAR buf[BUFFER_SMALL], buf2[BUFFER_SMALL];
1003
1004 for (const dba_rel* relation = tddba->relations; relation; relation = relation->rel_next)
1005 {
1006 if (relation->rel_id == -1) {
1007 continue;
1008 }
1009
1010 uSvc->printf(false, "%s (%d)\n", relation->rel_name, relation->rel_id);
1011
1012 if (sw_data)
1013 {
1014 dba_print(false, 11, SafeArg() << relation->rel_pointer_page << relation->rel_index_root);
1015 // msg 11: " Primary pointer page: %ld, Index root page: %ld"
1016
1017 if (sw_record)
1018 {
1019 uSvc->printf(false, " Total formats: %d, used formats: %d\n",
1020 relation->rel_total_formats, relation->rel_used_formats);
1021
1022 double average = relation->rel_records ?
1023 (double) relation->rel_record_space / relation->rel_records : 0.0;
1024 sprintf((char*) buf, "%.2f", average);
1025 uSvc->printf(false, " Average record length: %s, total records: %" UQUADFORMAT "\n",
1026 buf, relation->rel_records);
1027 // dba_print(false, 18, SafeArg() << buf << relation->rel_records);
1028 // msg 18: " Average record length: %s, total records: %ld
1029
1030 average = relation->rel_versions ?
1031 (double) relation->rel_version_space / relation->rel_versions : 0.0;
1032 sprintf((char*) buf, "%.2f", average);
1033 uSvc->printf(false, " Average version length: %s, total versions: %" UQUADFORMAT ", max versions: %" UQUADFORMAT "\n",
1034 buf, relation->rel_versions, relation->rel_max_versions);
1035 // dba_print(false, 19, SafeArg() << buf << relation->rel_versions <<
1036 // relation->rel_max_versions);
1037 // msg 19: " Average version length: %s, total versions: %ld, max versions: %ld
1038
1039 average = relation->rel_fragments ?
1040 (double) relation->rel_fragment_space / relation->rel_fragments : 0.0;
1041 sprintf((char*) buf, "%.2f", average);
1042 uSvc->printf(false, " Average fragment length: %s, total fragments: %" UQUADFORMAT ", max fragments: %" UQUADFORMAT "\n",
1043 buf, relation->rel_fragments, relation->rel_max_fragments);
1044
1045 average = relation->rel_records ?
1046 (double) relation->rel_format_space / relation->rel_records : 0.0;
1047 sprintf((char*) buf, "%.2f", average);
1048 average = relation->rel_record_space ?
1049 (double) relation->rel_format_space / relation->rel_record_space : 0.0;
1050 sprintf((char*) buf2, "%.2f", average);
1051 uSvc->printf(false, " Average unpacked length: %s, compression ratio: %s\n",
1052 buf, buf2);
1053
1054 }
1055
1056 uSvc->printf(false, " Pointer pages: %ld, data page slots: %ld\n",
1057 relation->rel_pointer_pages, relation->rel_slots);
1058
1059 const double average = (relation->rel_data_pages) ?
1060 (double) relation->rel_total_space * 100 /
1061 ((double) relation->rel_data_pages * (tddba->page_size - DPG_SIZE)) : 0.0;
1062 sprintf((char*) buf, "%.0f%%", average);
1063 //dba_print(false, 12, SafeArg() << relation->rel_data_pages << relation->rel_slots << buf);
1064 // msg 12: " Data pages: %ld, data page slots: %ld, average fill: %s
1065 uSvc->printf(false, " Data pages: %ld, average fill: %s\n", relation->rel_data_pages, buf);
1066
1067 dba_print(false, 46, SafeArg() << relation->rel_primary_pages <<
1068 relation->rel_data_pages - relation->rel_primary_pages <<
1069 relation->rel_swept_pages);
1070 // msg 46: " Primary pages: @1, secondary pages: @2, swept pages: @3
1071
1072 dba_print(false, 56, SafeArg() << relation->rel_empty_pages << relation->rel_full_pages);
1073 // msg 56: " Empty pages: @1, full pages: @2
1074
1075 if (relation->rel_bigrec_pages)
1076 {
1077 dba_print(false, 47, SafeArg() << relation->rel_bigrec_pages);
1078 // msg 47: " Big record pages: @1
1079 }
1080
1081 if (relation->rel_blobs_level_0 || relation->rel_blobs_level_1 || relation->rel_blobs_level_2)
1082 {
1083 dba_print(false, 48, SafeArg() << (relation->rel_blobs_level_0 + relation->rel_blobs_level_1 +
1084 relation->rel_blobs_level_2) << relation->rel_blob_space <<
1085 relation->rel_blob_pages);
1086 // msg 48: " Blobs: @1, total length: @2, blob pages: @3
1087
1088 dba_print(false, 49, SafeArg() << relation->rel_blobs_level_0 << relation->rel_blobs_level_1 <<
1089 relation->rel_blobs_level_2);
1090 // msg 49: " Level 0: @1, Level 1: @2, Level 2: @3
1091 }
1092
1093 dba_print(false, 13); // msg 13: " Fill distribution:"
1094 print_distribution("\t", relation->rel_fill_distribution);
1095 }
1096 uSvc->printf(false, "\n");
1097
1098 for (const dba_idx* index = relation->rel_indexes; index; index = index->idx_next)
1099 {
1100 dba_print(false, 14, SafeArg() << index->idx_name << index->idx_id);
1101 // msg 14: " Index %s (%d)"
1102 //dba_print(false, 15, SafeArg() << index->idx_depth << index->idx_leaf_buckets << index->idx_nodes);
1103 // msg 15: \tDepth: %d, leaf buckets: %ld, nodes: %ld
1104 uSvc->printf(false, "\tRoot page: %d, depth: %d, leaf buckets: %ld, nodes: %" UQUADFORMAT "\n",
1105 index->idx_root, index->idx_depth, index->idx_leaf_buckets, index->idx_nodes);
1106 double average = (index->idx_nodes) ?
1107 (double) index->idx_total_length / index->idx_nodes : 0.0;
1108 sprintf((char*) buf, "%.2f", average);
1109 // dba_print(false, 16, SafeArg() << buf << index->idx_total_duplicates << index->idx_max_duplicates);
1110 // msg 16: \tAverage data length: %s, total dup: %ld, max dup: %ld"
1111 uSvc->printf(false, "\tAverage node length: %s, total dup: %" UQUADFORMAT ", max dup: %" UQUADFORMAT "\n",
1112 buf, index->idx_total_duplicates, index->idx_max_duplicates);
1113 average = (index->idx_nodes) ?
1114 (double) index->idx_packed_length / index->idx_nodes : 0.0;
1115 sprintf((char*) buf, "%.2f", average);
1116 average = index->idx_packed_length ?
1117 (double) index->idx_unpacked_length / index->idx_packed_length : 0.0;
1118 sprintf((char*) buf2, "%.2f", average);
1119 uSvc->printf(false, "\tAverage key length: %s, compression ratio: %s\n", buf, buf2);
1120 average = (index->idx_nodes) ?
1121 (double) index->idx_prefix_length / index->idx_nodes : 0.0;
1122 sprintf((char*) buf, "%.2f", average);
1123 average = (index->idx_nodes) ?
1124 (double) index->idx_data_length / index->idx_nodes : 0.0;
1125 sprintf((char*) buf2, "%.2f", average);
1126 uSvc->printf(false, "\tAverage prefix length: %s, average data length: %s\n", buf, buf2);
1127 average = (index->idx_nodes) ?
1128 (double) index->idx_diff_pages / index->idx_nodes : 0.0;
1129 sprintf((char*) buf, "%.2f", average);
1130 uSvc->printf(false, "\tClustering factor: %" UQUADFORMAT ", ratio: %s\n",
1131 index->idx_diff_pages, buf);
1132 dba_print(false, 17);
1133 // msg 17: \tFill distribution:
1134 print_distribution("\t ", index->idx_fill_distribution);
1135 uSvc->printf(false, "\n");
1136 }
1137 }
1138
1139 dba_exit(FINI_OK, tddba);
1140
1141 } // try
1142 catch (const Firebird::LongJump&)
1143 {
1144 // do nothing
1145 }
1146 catch (const Firebird::Exception& ex)
1147 {
1148 ex.stuffException(permStatus);
1149 fb_utils::copyStatus(status_vector, ISC_STATUS_LENGTH, permStatus.value(), permStatus.length());
1150 tddba->exit_code = FB_FAILURE;
1151 }
1152
1153 // free mem
1154
1155 if (status_vector[1])
1156 {
1157 tddba->uSvc->setServiceStatus(status_vector);
1158 if (!tddba->uSvc->isService())
1159 {
1160 const ISC_STATUS* vector = status_vector;
1161 SCHAR s[1024];
1162 if (fb_interpret(s, sizeof(s), &vector))
1163 {
1164 tddba->uSvc->printf(true, "\n%s\n", s);
1165 s[0] = '-';
1166 while (fb_interpret(s + 1, sizeof(s) - 1, &vector))
1167 tddba->uSvc->printf(true, "%s\n", s);
1168 }
1169 }
1170 }
1171
1172 // if there still exists a database handle, disconnect from the server
1173 // This is isc_detach_database
1174 FINISH;
1175
1176 if (fl_print_complete)
1177 {
1178 getDateTime(datetime, sizeof(datetime));
1179 dba_print(false, 60, SafeArg() << datetime); // msg 60: Gstat completion time @1
1180 }
1181
1182 uSvc->started();
1183 dba_mem* alloced = tddba->head_of_mem_list;
1184 while (alloced != 0)
1185 {
1186 delete[] alloced->memory;
1187 alloced = alloced->mem_next;
1188 }
1189
1190 // close files
1191 open_files* open_file = tddba->head_of_files_list;
1192 while (open_file)
1193 {
1194 db_close(open_file->desc);
1195 open_file = open_file->open_files_next;
1196 }
1197
1198 // free linked lists
1199 while (tddba->head_of_files_list != 0)
1200 {
1201 open_files* tmp1 = tddba->head_of_files_list;
1202 tddba->head_of_files_list = tddba->head_of_files_list->open_files_next;
1203 delete tmp1;
1204 }
1205
1206 while (tddba->head_of_mem_list != 0)
1207 {
1208 dba_mem* tmp2 = tddba->head_of_mem_list;
1209 tddba->head_of_mem_list = tddba->head_of_mem_list->mem_next;
1210 delete tmp2;
1211 }
1212
1213 exit_code = tddba->exit_code;
1214 tdba::restoreSpecific();
1215
1216 if ((exit_code != FINI_OK) && uSvc->isService() && tddba->dba_status[1])
1217 {
1218 uSvc->initStatus();
1219 uSvc->setServiceStatus(tddba->dba_status);
1220 }
1221
1222 return exit_code;
1223 }
1224
1225
1226 static ULONG lastUsedPage(ULONG pageSize)
1227 {
1228 const ULONG pipFirst = FIRST_PIP_PAGE;
1229 ULONG pipLast = pipFirst;
1230 ULONG pagesPerPIP = Ods::pagesPerPIP(pageSize);
1231 ULONG bytesBitPIP = Ods::bytesBitPIP(pageSize);
1232 page_inv_page* pip;
1233
1234 while (true)
1235 {
1236 const pag* page = db_read(pipLast, true);
1237 if (page->pag_type != pag_pages)
1238 {
1239 tdba* tddba = tdba::getSpecific();
1240 tddba->uSvc->printf(true, "Expected page inventory page %" ULONGFORMAT, pipLast);
1241 return 0;
1242 }
1243
1244 pip = (page_inv_page*) page;
1245 if (pip->pip_used != pagesPerPIP)
1246 break;
1247
1248 UCHAR lastByte = pip->pip_bits[bytesBitPIP - 1];
1249 if (lastByte & 0x80)
1250 break;
1251
1252 if (pipLast == pipFirst)
1253 pipLast = pagesPerPIP - 1;
1254 else
1255 pipLast += pagesPerPIP;
1256 }
1257
1258 int last_bit = pip->pip_used;
1259 int byte_num = last_bit / 8;
1260 UCHAR mask = 1 << (last_bit % 8);
1261 while (last_bit >= 0 && (pip->pip_bits[byte_num] & mask))
1262 {
1263 if (mask == 1)
1264 {
1265 mask = 0x80;
1266 byte_num--;
1267 //fb_assert(byte_num > -1); ???
1268 }
1269 else
1270 mask >>= 1;
1271
1272 last_bit--;
1273 }
1274
1275 return last_bit + (pipLast == pipFirst ? 0 : pipLast);
1276 }
1277
1278
1279 static char* alloc(size_t size)
1280 {
1281 /**************************************
1282 *
1283 * a l l o c
1284 *
1285 **************************************
1286 *
1287 * Functional description
1288 * Allocate and zero a piece of memory.
1289 *
1290 **************************************/
1291 tdba* tddba = tdba::getSpecific();
1292 char* const block = FB_NEW_POOL(*getDefaultMemoryPool()) SCHAR[size];
1293
1294 if (!block)
1295 {
1296 // NOMEM: return error
1297 dba_error(31);
1298 }
1299
1300 memset(block, 0, size);
1301
1302 dba_mem* mem_list = FB_NEW_POOL(*getDefaultMemoryPool()) dba_mem;
1303 if (!mem_list)
1304 {
1305 // NOMEM: return error
1306 dba_error(31);
1307 }
1308 mem_list->memory = block;
1309 mem_list->mem_next = 0;
1310
1311 if (tddba->head_of_mem_list == 0)
1312 tddba->head_of_mem_list = mem_list;
1313 else
1314 {
1315 mem_list->mem_next = tddba->head_of_mem_list;
1316 tddba->head_of_mem_list = mem_list;
1317 }
1318
1319 return block;
1320 }
1321
1322
1323 static void analyze_data( dba_rel* relation, bool sw_record)
1324 {
1325 /**************************************
1326 *
1327 * a n a l y z e _ d a t a
1328 *
1329 **************************************
1330 *
1331 * Functional description
1332 * Analyze data pages associated with relation.
1333 *
1334 **************************************/
1335 tdba* tddba = tdba::getSpecific();
1336
1337 pointer_page* ptr_page = (pointer_page*) tddba->buffer1;
1338
1339 for (SLONG next_pp = relation->rel_pointer_page; next_pp; next_pp = ptr_page->ppg_next)
1340 {
1341 ++relation->rel_pointer_pages;
1342 memcpy(ptr_page, (const SCHAR*) db_read(next_pp), tddba->page_size);
1343 const ULONG* ptr = ptr_page->ppg_page;
1344 for (const ULONG* const end = ptr + ptr_page->ppg_count; ptr < end; ptr++)
1345 {
1346 ++relation->rel_slots;
1347 if (*ptr)
1348 {
1349 ++relation->rel_data_pages;
1350 if (!analyze_data_page(relation, (const data_page*) db_read(*ptr), sw_record))
1351 {
1352 dba_print(false, 18, SafeArg() << *ptr);
1353 // msg 18: " Expected data on page %ld"
1354 }
1355 }
1356 }
1357 }
1358
1359 if (sw_record)
1360 {
1361 for (const dba_fmt* format = relation->rel_formats; format; format = format->fmt_next)
1362 {
1363 if (format->fmt_used)
1364 {
1365 ++relation->rel_used_formats;
1366 }
1367 }
1368 }
1369 }
1370
1371
1372 static bool analyze_data_page( dba_rel* relation, const data_page* page, bool sw_record)
1373 {
1374 /**************************************
1375 *
1376 * a n a l y z e _ d a t a _ p a g e
1377 *
1378 **************************************
1379 *
1380 * Functional description
1381 * Analyze space utilization for data page.
1382 *
1383 **************************************/
1384 tdba* tddba = tdba::getSpecific();
1385
1386 if (page->dpg_header.pag_type != pag_data)
1387 return false;
1388
1389 if (sw_record)
1390 {
1391 memcpy(tddba->buffer2, (const SCHAR*) page, tddba->page_size);
1392 page = (const data_page*) tddba->buffer2;
1393 }
1394
1395 USHORT space = page->dpg_count * sizeof(data_page::dpg_repeat);
1396
1397 const data_page::dpg_repeat* tail = page->dpg_rpt;
1398 for (const data_page::dpg_repeat* const end = tail + page->dpg_count; tail < end; tail++)
1399 {
1400 if (tail->dpg_offset && tail->dpg_length)
1401 {
1402 space += tail->dpg_length;
1403
1404 if (sw_record)
1405 {
1406 const rhdf* header = (const rhdf*) ((SCHAR *) page + tail->dpg_offset);
1407 if (!(header->rhdf_flags & (rhd_blob | rhd_chain | rhd_fragment)))
1408 {
1409 ++relation->rel_records;
1410 relation->rel_record_space += tail->dpg_length;
1411
1412 for (dba_fmt* format = relation->rel_formats; format; format = format->fmt_next)
1413 {
1414 if (format->fmt_number == header->rhdf_format)
1415 {
1416 relation->rel_format_space += format->fmt_length;
1417 format->fmt_used = true;
1418 break;
1419 }
1420 }
1421
1422 if (header->rhdf_flags & rhd_incomplete)
1423 {
1424 relation->rel_record_space -= RHDF_SIZE;
1425 relation->rel_record_space += analyze_fragments(relation, header);
1426 }
1427 else
1428 {
1429 relation->rel_record_space -= RHD_SIZE;
1430 }
1431
1432 if (header->rhdf_b_page)
1433 {
1434 relation->rel_version_space += analyze_versions(relation, header);
1435 }
1436 }
1437
1438 if (header->rhdf_flags & rhd_blob)
1439 {
1440 analyze_blob(relation, (blh*)header, tail->dpg_length);
1441 }
1442 }
1443 }
1444 }
1445
1446 relation->rel_total_space += space;
1447 SSHORT bucket = (space * BUCKETS) / (tddba->page_size - DPG_SIZE);
1448
1449 if (bucket == BUCKETS)
1450 --bucket;
1451
1452 if (page->dpg_count == 0)
1453 ++relation->rel_empty_pages;
1454 if (page->dpg_header.pag_flags & dpg_full)
1455 ++relation->rel_full_pages;
1456 if (!(page->dpg_header.pag_flags & dpg_secondary))
1457 ++relation->rel_primary_pages;
1458 if (page->dpg_header.pag_flags & dpg_swept)
1459 ++relation->rel_swept_pages;
1460 ++relation->rel_fill_distribution[bucket];
1461
1462 return true;
1463 }
1464
1465
1466 static void analyze_blob(dba_rel* relation, const blh* blob, int length)
1467 {
1468 relation->rel_blob_space += blob->blh_length;
1469 if (!blob->blh_level)
1470 {
1471 relation->rel_blobs_level_0++;
1472 }
1473 else
1474 {
1475 const int slots = (length - BLH_SIZE) / static_cast<int>(sizeof(SLONG));
1476 relation->rel_blob_pages += slots;
1477 if (blob->blh_level == 1)
1478 {
1479 relation->rel_blobs_level_1++;
1480 }
1481 else
1482 {
1483 relation->rel_blobs_level_2++;
1484
1485 SLONG pages[MAX_PAGE_SIZE / sizeof(SLONG)];
1486 memcpy(pages, blob->blh_page, slots * sizeof(SLONG));
1487
1488 for (int i = 0; i < slots; i++)
1489 {
1490 const blob_page* bpage = (const blob_page*) db_read(pages[i]);
1491 relation->rel_blob_pages += bpage->blp_length / sizeof(SLONG);
1492 }
1493 }
1494 }
1495 }
1496
1497
1498 static ULONG analyze_fragments(dba_rel* relation, const rhdf* header)
1499 {
1500 /**************************************
1501 *
1502 * a n a l y z e _ f r a g m e n t s
1503 *
1504 **************************************
1505 *
1506 * Functional description
1507 * Analyze space used by a record's fragments.
1508 *
1509 **************************************/
1510 //tdba* tddba = tdba::getSpecific();
1511 ULONG space = 0, fragments = 0;
1512
1513 while (header->rhdf_flags & rhd_incomplete)
1514 {
1515 const SLONG f_page = header->rhdf_f_page;
1516 const USHORT f_line = header->rhdf_f_line;
1517 const data_page* page = (const data_page*) db_read(f_page);
1518 if (page->dpg_header.pag_type != pag_data || page->dpg_relation != relation->rel_id ||
1519 page->dpg_count <= f_line)
1520 {
1521 break;
1522 }
1523
1524 if ((page->dpg_header.pag_flags & (dpg_orphan | dpg_full)) && page->dpg_count == 1) {
1525 relation->rel_bigrec_pages++;
1526 }
1527
1528 const data_page::dpg_repeat* index = &page->dpg_rpt[f_line];
1529 if (!index->dpg_offset)
1530 break;
1531 space += index->dpg_length;
1532 space -= RHDF_SIZE;
1533 header = (const rhdf*) ((SCHAR *) page + index->dpg_offset);
1534
1535 fragments++;
1536 }
1537
1538 relation->rel_fragments += fragments;
1539 relation->rel_fragment_space += space;
1540 if (fragments > relation->rel_max_fragments) {
1541 relation->rel_max_fragments = fragments;
1542 }
1543
1544 return space;
1545 }
1546
1547
1548 static void analyze_index( const dba_rel* relation, dba_idx* index)
1549 {
1550 /**************************************
1551 *
1552 * a n a l y z e _ i n d e x
1553 *
1554 **************************************
1555 *
1556 * Functional description
1557 *
1558 **************************************/
1559 tdba* tddba = tdba::getSpecific();
1560
1561 const index_root_page* index_root = (const index_root_page*) db_read(relation->rel_index_root);
1562
1563 SLONG page;
1564 if (index_root->irt_count <= index->idx_id ||
1565 !(page = index_root->irt_rpt[index->idx_id].getRoot()))
1566 {
1567 return;
1568 }
1569
1570 // CVC: The two const_cast's for bucket can go away if BTreeNode's functions
1571 // are overloaded for constness. They don't modify bucket and pointer's contents.
1572 const btree_page* bucket = (const btree_page*) db_read(page);
1573 index->idx_root = page;
1574 index->idx_depth = bucket->btr_level + 1;
1575
1576 UCHAR* pointer;
1577 IndexNode node;
1578 while (bucket->btr_level)
1579 {
1580 pointer = const_cast<UCHAR*>(bucket->btr_nodes) + bucket->btr_jump_size;
1581 node.readNode(pointer, false);
1582 bucket = (const btree_page*) db_read(node.pageNumber);
1583 }
1584
1585 bool firstLeafNode = true;
1586 SLONG number;
1587 FB_UINT64 duplicates = 0;
1588 // AB: In fact length for KEY should be MAX_KEY (1/4 of used page-size)
1589 // This value should be kept equal with size declared in btr.h
1590 //UCHAR key[4096];
1591 UCHAR* key = (UCHAR*) alloc(tddba->page_size / 4);
1592 USHORT key_length = 0;
1593 ULONG prior_pagno = MAX_ULONG;
1594 while (true)
1595 {
1596 ++index->idx_leaf_buckets;
1597 pointer = const_cast<UCHAR*>(bucket->btr_nodes) + bucket->btr_jump_size;
1598 const UCHAR* const firstNode = pointer;
1599 while (true)
1600 {
1601 pointer = node.readNode(pointer, true);
1602
1603 if (node.isEndBucket || node.isEndLevel) {
1604 break;
1605 }
1606
1607 ++index->idx_nodes;
1608 index->idx_total_length += pointer - node.nodePointer;
1609 index->idx_prefix_length += node.prefix;
1610 index->idx_data_length += node.length;
1611
1612 size_t specials = 1;
1613 if (node.prefix > 127)
1614 specials += 2;
1615 else if (node.prefix > 0)
1616 specials += 1;
1617 if (node.length > 127)
1618 specials += 2;
1619 else if (node.length > 1)
1620 specials += 1;
1621 index->idx_packed_length += specials + node.length;
1622
1623 ULONG pp_sequence;
1624 USHORT slot, line;
1625 node.recordNumber.decompose(tddba->max_records, tddba->dp_per_pp, line, slot, pp_sequence);
1626
1627 const ULONG pagno = pp_sequence * tddba->dp_per_pp + slot;
1628 if (pagno != prior_pagno)
1629 ++index->idx_diff_pages;
1630 prior_pagno = pagno;
1631
1632 const USHORT l = node.length + node.prefix;
1633 index->idx_unpacked_length += l;
1634
1635 bool dup;
1636 if (node.nodePointer == firstNode) {
1637 dup = node.keyEqual(key_length, key);
1638 }
1639 else {
1640 dup = (!node.length) && (l == key_length);
1641 }
1642 if (firstLeafNode)
1643 {
1644 dup = false;
1645 firstLeafNode = false;
1646 }
1647 if (dup)
1648 {
1649 ++index->idx_total_duplicates;
1650 ++duplicates;
1651 }
1652 else
1653 {
1654 if (duplicates > index->idx_max_duplicates) {
1655 index->idx_max_duplicates = duplicates;
1656 }
1657 duplicates = 0;
1658 }
1659
1660 key_length = l;
1661 if (node.length) {
1662 memcpy(key + node.prefix, node.data, node.length);
1663 }
1664 }
1665
1666 if (duplicates > index->idx_max_duplicates) {
1667 index->idx_max_duplicates = duplicates;
1668 }
1669
1670 const USHORT header = (USHORT)(firstNode - (UCHAR*) bucket);
1671 const USHORT space = bucket->btr_length - header;
1672 USHORT n = (space * BUCKETS) / (tddba->page_size - header);
1673 if (n == BUCKETS) {
1674 --n;
1675 }
1676 ++index->idx_fill_distribution[n];
1677
1678 if (node.isEndLevel) {
1679 break;
1680 }
1681 number = page;
1682 page = bucket->btr_sibling;
1683 bucket = (const btree_page*) db_read(page);
1684 if (bucket->btr_header.pag_type != pag_index)
1685 {
1686 dba_print(false, 19, SafeArg() << page << number);
1687 // mag 19: " Expected b-tree bucket on page %ld from %ld"
1688 break;
1689 }
1690 }
1691 }
1692
1693
1694 static ULONG analyze_versions( dba_rel* relation, const rhdf* header)
1695 {
1696 /**************************************
1697 *
1698 * a n a l y z e _ v e r s i o n s
1699 *
1700 **************************************
1701 *
1702 * Functional description
1703 * Analyze space used by a record's back versions.
1704 *
1705 **************************************/
1706 //tdba* tddba = tdba::getSpecific();
1707 ULONG space = 0, versions = 0;
1708 SLONG b_page = header->rhdf_b_page;
1709 USHORT b_line = header->rhdf_b_line;
1710
1711 while (b_page)
1712 {
1713 const data_page* page = (const data_page*) db_read(b_page);
1714 if (page->dpg_header.pag_type != pag_data || page->dpg_relation != relation->rel_id ||
1715 page->dpg_count <= b_line)
1716 {
1717 break;
1718 }
1719 const data_page::dpg_repeat* index = &page->dpg_rpt[b_line];
1720 if (!index->dpg_offset)
1721 break;
1722 space += index->dpg_length;
1723 ++relation->rel_versions;
1724 ++versions;
1725 header = (const rhdf*) ((SCHAR *) page + index->dpg_offset);
1726 b_page = header->rhdf_b_page;
1727 b_line = header->rhdf_b_line;
1728 if (header->rhdf_flags & rhd_incomplete)
1729 {
1730 space -= RHDF_SIZE;
1731 space += analyze_fragments(relation, header);
1732 }
1733 else
1734 space -= RHD_SIZE;
1735 }
1736
1737 if (versions > relation->rel_max_versions)
1738 relation->rel_max_versions = versions;
1739
1740 return space;
1741 }
1742
1743
1744 static USHORT get_format_length(ISC_STATUS* status_vector, isc_db_handle database,
1745 isc_tr_handle transaction, ISC_QUAD& blob_id)
1746 {
1747 UserBlob blob(status_vector);
1748
1749 if (!blob.open(database, transaction, blob_id))
1750 {
1751 return 0;
1752 }
1753
1754 const UCHAR blob_items[] = {isc_info_blob_total_length};
1755 UCHAR blob_info[BUFFER_TINY];
1756 if (!blob.getInfo(sizeof(blob_items), blob_items, sizeof(blob_info), blob_info))
1757 {
1758 return 0;
1759 }
1760
1761 const UCHAR* p = blob_info;
1762 if (*p++ != isc_info_blob_total_length)
1763 {
1764 return 0;
1765 }
1766
1767 const USHORT l = isc_vax_integer((const char*) p, 2);
1768 p += 2;
1769 const ULONG length = isc_vax_integer((const char*) p, l);
1770
1771 FB_SIZE_T return_length = 0;
1772 Firebird::UCharBuffer buffer;
1773 if (!blob.getData(length, buffer.getBuffer(length), return_length))
1774 {
1775 return 0;
1776 }
1777
1778 buffer.resize(return_length);
1779
1780 const USHORT count = buffer[0] | (buffer[1] << 8);
1781 const Ods::Descriptor* const desc = (Ods::Descriptor*) &buffer[2] + count - 1;
1782 return desc->dsc_offset + desc->dsc_length;
1783 }
1784
1785
1786 #ifdef WIN_NT
1787 static void db_close(void* file_desc)
1788 {
1789 /**************************************
1790 *
1791 * d b _ c l o s e ( W I N _ N T )
1792 *
1793 **************************************
1794 *
1795 * Functional description
1796 * Close an open file
1797 *
1798 **************************************/
1799 CloseHandle(file_desc);
1800 }
1801
1802 static void db_error( SLONG status)
1803 {
1804 /**************************************
1805 *
1806 * d b _ e r r o r ( W I N _ N T )
1807 *
1808 **************************************
1809 *
1810 * Functional description
1811 *
1812 **************************************/
1813 TEXT s[128];
1814
1815 tdba* tddba = tdba::getSpecific();
1816 tddba->page_number = -1;
1817
1818 if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1819 NULL,
1820 status,
1821 GetUserDefaultLangID(),
1822 s,
1823 sizeof(s),
1824 NULL) &&
1825 !FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_MAX_WIDTH_MASK,
1826 NULL,
1827 status,
1828 0, // TMN: Fallback to system known language
1829 s,
1830 sizeof(s),
1831 NULL))
1832 {
1833 sprintf(s, "unknown Windows NT error %ld", status);
1834 }
1835
1836 if (!tddba->uSvc->isService())
1837 {
1838 tddba->uSvc->printf(true, "%s\n", s);
1839 }
1840 dba_exit(FINI_ERROR, tddba);
1841 }
1842
1843
1844 // CVC: This function was using cast to char* for the first param always
1845 // and the callers had to cast their char*'s to UCHAR*, too. Since the
1846 // real parameter is char* and always the usage is char*, I changed signature.
1847 static dba_fil* db_open(const char* file_name, USHORT file_length)
1848 {
1849 /**************************************
1850 *
1851 * d b _ o p e n ( W I N _ N T )
1852 *
1853 **************************************
1854 *
1855 * Functional description
1856 * Open a database file.
1857 *
1858 **************************************/
1859 tdba* tddba = tdba::getSpecific();
1860
1861 dba_fil* fil;
1862
1863 if (tddba->files)
1864 {
1865 for (fil = tddba->files; fil->fil_next; fil = fil->fil_next);
1866 fil->fil_next = (dba_fil*) alloc(sizeof(dba_fil) + file_length + 1);
1867 fil->fil_next->fil_min_page = fil->fil_max_page + 1;
1868 fil = fil->fil_next;
1869 }
1870 else
1871 {
1872 // empty list
1873 fil = tddba->files = (dba_fil*) alloc(sizeof(dba_fil) + file_length + 1);
1874 fil->fil_min_page = 0L;
1875 }
1876
1877 fil->fil_next = NULL;
1878 strcpy(fil->fil_string, file_name);
1879 fil->fil_length = file_length;
1880 fil->fil_fudge = 0;
1881 fil->fil_max_page = 0L;
1882
1883 fil->fil_desc = CreateFile( file_name,
1884 GENERIC_READ,
1885 FILE_SHARE_READ | FILE_SHARE_WRITE,
1886 NULL,
1887 OPEN_EXISTING,
1888 FILE_ATTRIBUTE_NORMAL,
1889 0);
1890
1891 if (fil->fil_desc == INVALID_HANDLE_VALUE)
1892 {
1893 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 29, SafeArg() << file_name);
1894 // msg 29: Can't open database file %s
1895 db_error(GetLastError());
1896 }
1897
1898 open_files* file_list = FB_NEW_POOL(*getDefaultMemoryPool()) open_files;
1899 if (!file_list)
1900 {
1901 // NOMEM: return error
1902 dba_error(31);
1903 }
1904 file_list->desc = fil->fil_desc;
1905 file_list->open_files_next = 0;
1906
1907 if (tddba->head_of_files_list == 0)
1908 tddba->head_of_files_list = file_list;
1909 else
1910 {
1911 file_list->open_files_next = tddba->head_of_files_list;
1912 tddba->head_of_files_list = file_list;
1913 }
1914
1915 return fil;
1916 }
1917
1918
1919 static const pag* db_read( SLONG page_number, bool ok_enc)
1920 {
1921 /**************************************
1922 *
1923 * d b _ r e a d ( W I N _ N T )
1924 *
1925 **************************************
1926 *
1927 * Functional description
1928 * Read a database page.
1929 *
1930 **************************************/
1931 tdba* tddba = tdba::getSpecific();
1932
1933 if (tddba->uSvc->finished())
1934 dba_exit(FINI_OK, tddba);
1935
1936 if (tddba->page_number == page_number)
1937 return tddba->global_buffer;
1938
1939 tddba->page_number = page_number;
1940
1941 dba_fil* fil;
1942 for (fil = tddba->files; page_number > (SLONG) fil->fil_max_page && fil->fil_next;)
1943 {
1944 fil = fil->fil_next;
1945 }
1946
1947 page_number -= fil->fil_min_page - fil->fil_fudge;
1948
1949 LARGE_INTEGER liOffset;
1950 liOffset.QuadPart = UInt32x32To64((DWORD) page_number, (DWORD) tddba->page_size);
1951 if (SetFilePointer(fil->fil_desc, (LONG) liOffset.LowPart, &liOffset.HighPart, FILE_BEGIN) ==
1952 (DWORD) -1)
1953 {
1954 int lastError = GetLastError();
1955 if (lastError != NO_ERROR)
1956 {
1957 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 30, SafeArg());
1958 // msg 30: Can't read a database page
1959 db_error(lastError);
1960 }
1961 }
1962
1963 SLONG actual_length;
1964 if (!ReadFile( fil->fil_desc,
1965 tddba->global_buffer,
1966 tddba->page_size,
1967 reinterpret_cast<LPDWORD>(&actual_length),
1968 NULL))
1969 {
1970 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 30, SafeArg());
1971 // msg 30: Can't read a database page
1972 db_error(GetLastError());
1973 }
1974 if (actual_length != tddba->page_size)
1975 {
1976 if (ok_enc)
1977 {
1978 return NULL;
1979 }
1980 dba_error(4);
1981 // msg 4: Unexpected end of database file.
1982 }
1983
1984 if (tddba->global_buffer->pag_flags & Ods::crypted_page && !ok_enc)
1985 {
1986 dba_error(55);
1987 }
1988
1989 return tddba->global_buffer;
1990 }
1991 #endif // ifdef WIN_NT
1992
1993
1994 #ifndef WIN_NT
1995 static void db_close( int file_desc)
1996 {
1997 /**************************************
1998 *
1999 * d b _ c l o s e
2000 *
2001 **************************************
2002 *
2003 * Functional description
2004 * Close an open file
2005 *
2006 **************************************/
2007 close(file_desc);
2008 }
2009
2010 static void db_error( int status)
2011 {
2012 /**************************************
2013 *
2014 * d b _ e r r o r
2015 *
2016 **************************************
2017 *
2018 * Functional description
2019 *
2020 **************************************/
2021 tdba* tddba = tdba::getSpecific();
2022 tddba->page_number = -1;
2023
2024 // FIXME: The strerror() function returns the appropriate description
2025 // string, or an unknown error message if the error code is unknown.
2026 // EKU: p cannot be NULL!
2027 if (!tddba->uSvc->isService())
2028 {
2029 tddba->uSvc->printf(true, "%s\n", strerror(status));
2030 }
2031 dba_exit(FINI_ERROR, tddba);
2032 }
2033
2034
2035 // CVC: This function was using cast to char* for the first param always
2036 // and the callers had to cast their char*'s to UCHAR*, too. Since the
2037 // real parameter is char* and always the usage is char*, I changed signature.
2038 static dba_fil* db_open(const char* file_name, USHORT file_length)
2039 {
2040 /**************************************
2041 *
2042 * d b _ o p e n
2043 *
2044 **************************************
2045 *
2046 * Functional description
2047 * Open a database file.
2048 * Put the file on an ordered list.
2049 *
2050 **************************************/
2051 tdba* tddba = tdba::getSpecific();
2052
2053 dba_fil* fil;
2054 if (tddba->files)
2055 {
2056 for (fil = tddba->files; fil->fil_next; fil = fil->fil_next)
2057 ;
2058 fil->fil_next = (dba_fil*) alloc(sizeof(dba_fil) + file_length + 1);
2059 fil->fil_next->fil_min_page = fil->fil_max_page + 1;
2060 fil = fil->fil_next;
2061 }
2062 else
2063 {
2064 // empty list
2065
2066 fil = tddba->files = (dba_fil*) alloc(sizeof(dba_fil) + file_length + 1);
2067 fil->fil_min_page = 0L;
2068 }
2069
2070 fil->fil_next = NULL;
2071 strcpy(fil->fil_string, file_name);
2072 fil->fil_length = file_length;
2073 fil->fil_fudge = 0;
2074 fil->fil_max_page = 0L;
2075
2076 if ((fil->fil_desc = os_utils::open(file_name, O_RDONLY)) == -1)
2077 {
2078 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 29, SafeArg() << file_name);
2079 // msg 29: Can't open database file %s
2080 db_error(errno);
2081 }
2082
2083 open_files* file_list = FB_NEW_POOL(*getDefaultMemoryPool()) open_files;
2084 if (!file_list)
2085 {
2086 // NOMEM: return error
2087 dba_error(31);
2088 }
2089 file_list->desc = fil->fil_desc;
2090 file_list->open_files_next = 0;
2091
2092 if (tddba->head_of_files_list == 0)
2093 tddba->head_of_files_list = file_list;
2094 else
2095 {
2096 file_list->open_files_next = tddba->head_of_files_list;
2097 tddba->head_of_files_list = file_list;
2098 }
2099
2100 return fil;
2101 }
2102
2103
2104 static const pag* db_read( SLONG page_number, bool ok_enc)
2105 {
2106 /**************************************
2107 *
2108 * d b _ r e a d
2109 *
2110 **************************************
2111 *
2112 * Functional description
2113 * Read a database page.
2114 *
2115 **************************************/
2116 tdba* tddba = tdba::getSpecific();
2117
2118 if (tddba->page_number == page_number)
2119 return tddba->global_buffer;
2120
2121 tddba->page_number = page_number;
2122
2123 dba_fil* fil;
2124 for (fil = tddba->files; page_number > (SLONG) fil->fil_max_page && fil->fil_next;)
2125 {
2126 fil = fil->fil_next;
2127 }
2128
2129 page_number -= fil->fil_min_page - fil->fil_fudge;
2130 const FB_UINT64 offset = ((FB_UINT64) page_number) * ((FB_UINT64) tddba->page_size);
2131 if (lseek (fil->fil_desc, offset, 0) == -1)
2132 {
2133 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 30, SafeArg());
2134 // msg 30: Can't read a database page
2135 db_error(errno);
2136 }
2137
2138 USHORT length = tddba->page_size;
2139 for (SCHAR* p = (SCHAR *) tddba->global_buffer; length > 0;)
2140 {
2141 const int l = read(fil->fil_desc, p, length);
2142 if (l < 0)
2143 {
2144 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, 30, SafeArg());
2145 // msg 30: Can't read a database page
2146 db_error(errno);
2147 }
2148 if (!l)
2149 {
2150 if (ok_enc)
2151 {
2152 return NULL;
2153 }
2154 dba_error(4);
2155 // msg 4: Unexpected end of database file.
2156 }
2157 p += l;
2158 length -= l;
2159 }
2160
2161 if (tddba->global_buffer->pag_flags & Ods::crypted_page && !ok_enc)
2162 {
2163 dba_error(55);
2164 }
2165
2166 return tddba->global_buffer;
2167 }
2168 #endif
2169
2170
2171 static void dba_error(USHORT errcode, const SafeArg& arg)
2172 {
2173 /**************************************
2174 *
2175 * d b a _ e r r o r
2176 *
2177 **************************************
2178 *
2179 * Functional description
2180 * Format and print an error message, then punt.
2181 *
2182 **************************************/
2183 tdba* tddba = tdba::getSpecific();
2184 tddba->page_number = -1;
2185
2186 tddba->uSvc->setServiceStatus(GSTAT_MSG_FAC, errcode, arg);
2187 if (!tddba->uSvc->isService())
2188 {
2189 dba_print(true, errcode, arg);
2190 }
2191 dba_exit(FINI_ERROR, tddba);
2192 }
2193
2194
2195 static void dba_print(bool err, USHORT number, const SafeArg& arg)
2196 {
2197 /**************************************
2198 *
2199 * d b a _ p r i n t
2200 *
2201 **************************************
2202 *
2203 * Functional description
2204 * Retrieve a message from the error file, format it, and print it.
2205 *
2206 **************************************/
2207 TEXT buffer[256];
2208 tdba* tddba = tdba::getSpecific();
2209
2210 fb_msg_format(NULL, GSTAT_MSG_FAC, number, sizeof(buffer), buffer, arg);
2211 tddba->uSvc->printf(err, "%s\n", buffer);
2212 }
2213
2214
2215 static void print_distribution(const SCHAR* prefix, const ULONG* vector)
2216 {
2217 /**************************************
2218 *
2219 * p r i n t _ d i s t r i b u t i o n
2220 *
2221 **************************************
2222 *
2223 * Functional description
2224 * Print distribution as percentages.
2225 *
2226 **************************************/
2227 tdba* tddba = tdba::getSpecific();
2228
2229 for (SSHORT n = 0; n < BUCKETS; n++)
2230 {
2231 tddba->uSvc->printf(false, "%s%2d - %2d%% = %" ULONGFORMAT "\n",
2232 prefix, n * 100 / BUCKETS, (n + 1) * 100 / BUCKETS - 1, vector[n]);
2233 }
2234 }
2235
2236
2237 // Print the help explanation
2238 static void print_help()
2239 {
2240 dba_print(true, 39); // msg 39: usage: gstat [options] <database> or gstat <database> [options]
2241 dba_print(true, 21); // msg 21: Available switches:
2242 for (const Switches::in_sw_tab_t* in_sw_tab = dba_in_sw_table; in_sw_tab->in_sw; in_sw_tab++)
2243 {
2244 if (in_sw_tab->in_sw_msg)
2245 dba_print(true, in_sw_tab->in_sw_msg);
2246 }
2247 dba_print(true, 43); // option -t accepts...
2248 }