- Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathAttachment.h
1032 lines (843 loc) · 26.9 KB
/
Attachment.h
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PROGRAM: JRD access method
* MODULE: Attachment.h
* DESCRIPTION: JRD Attachment class
*
* The contents of this file are subject to the Interbase 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 http://www.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, 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 Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*/
#ifndef JRD_ATTACHMENT_H
#defineJRD_ATTACHMENT_H
#include"firebird.h"
// Definition of block types for data allocation in JRD
#include"../include/fb_blk.h"
#include"../jrd/scl.h"
#include"../jrd/PreparedStatement.h"
#include"../jrd/RandomGenerator.h"
#include"../jrd/RuntimeStatistics.h"
#include"../jrd/Coercion.h"
#include"../common/classes/ByteChunk.h"
#include"../common/classes/GenericMap.h"
#include"../jrd/QualifiedName.h"
#include"../common/classes/SyncObject.h"
#include"../common/classes/array.h"
#include"../common/classes/stack.h"
#include"../common/classes/timestamp.h"
#include"../common/classes/TimerImpl.h"
#include"../common/ThreadStart.h"
#include"../common/TimeZoneUtil.h"
#include"../jrd/EngineInterface.h"
#include"../jrd/sbm.h"
#include<atomic>
#defineDEBUG_LCK_LIST
namespaceEDS {
classConnection;
}
namespaceReplication
{
classTableMatcher;
}
classCharSetContainer;
namespaceJrd
{
classthread_db;
classDatabase;
classjrd_tra;
classRequest;
classLock;
classjrd_file;
classFormat;
classBufferControl;
classPageToBufferMap;
classSparseBitmap;
classjrd_rel;
classExternalFile;
classViewContext;
classIndexBlock;
classIndexLock;
classArrayField;
structsort_context;
classvcl;
classTextType;
classParameter;
classjrd_fld;
classdsql_dbb;
classPreparedStatement;
classTraceManager;
template <typename T> classvec;
classjrd_rel;
classjrd_prc;
classTrigger;
classTrigVector;
classFunction;
classStatement;
classProfilerManager;
classValidation;
classApplier;
structDSqlCacheItem
{
DSqlCacheItem(MemoryPool& pool)
: key(pool),
obsoleteMap(pool),
lock(nullptr),
locked(false)
{
}
Firebird::string key;
Firebird::GenericMap<Firebird::Pair<Firebird::Left<QualifiedName, bool> > > obsoleteMap;
Lock* lock;
bool locked;
};
typedef Firebird::GenericMap<Firebird::Pair<Firebird::Full<
Firebird::string, DSqlCacheItem> > > DSqlCache;
structDdlTriggerContext
{
DdlTriggerContext()
: eventType(*getDefaultMemoryPool()),
objectType(*getDefaultMemoryPool()),
objectName(*getDefaultMemoryPool()),
oldObjectName(*getDefaultMemoryPool()),
newObjectName(*getDefaultMemoryPool()),
sqlText(*getDefaultMemoryPool())
{
}
Firebird::string eventType;
Firebird::string objectType;
MetaName objectName;
MetaName oldObjectName;
MetaName newObjectName;
Firebird::string sqlText;
};
// Attachment flags
const ULONG ATT_no_cleanup = 0x00001L; // Don't expunge, purge, or garbage collect
const ULONG ATT_shutdown = 0x00002L; // attachment has been shutdown
const ULONG ATT_shutdown_manager = 0x00004L; // attachment requesting shutdown
const ULONG ATT_exclusive = 0x00008L; // attachment wants exclusive database access
const ULONG ATT_attach_pending = 0x00010L; // Indicate attachment is only pending
const ULONG ATT_exclusive_pending = 0x00020L; // Indicate exclusive attachment pending
const ULONG ATT_notify_gc = 0x00040L; // Notify garbage collector to expunge, purge ..
const ULONG ATT_garbage_collector = 0x00080L; // I'm a garbage collector
const ULONG ATT_cancel_raise = 0x00100L; // Cancel currently running operation
const ULONG ATT_cancel_disable = 0x00200L; // Disable cancel operations
const ULONG ATT_no_db_triggers = 0x00400L; // Don't execute database triggers
const ULONG ATT_manual_lock = 0x00800L; // Was locked manually
const ULONG ATT_async_manual_lock = 0x01000L; // Async mutex was locked manually
const ULONG ATT_overwrite_check = 0x02000L; // Attachment checks is it possible to overwrite DB
const ULONG ATT_system = 0x04000L; // Special system attachment
const ULONG ATT_creator = 0x08000L; // This attachment created the DB
const ULONG ATT_monitor_disabled = 0x10000L; // Monitoring lock is downgraded
const ULONG ATT_security_db = 0x20000L; // Attachment used for security purposes
const ULONG ATT_mapping = 0x40000L; // Attachment used for mapping auth block
const ULONG ATT_from_thread = 0x80000L; // Attachment from internal special thread (sweep, crypt)
const ULONG ATT_monitor_init = 0x100000L; // Attachment is registered in monitoring
const ULONG ATT_repl_reset = 0x200000L; // Replication set has been reset
const ULONG ATT_replicating = 0x400000L; // Replication is active
const ULONG ATT_resetting = 0x800000L; // Session reset is in progress
const ULONG ATT_worker = 0x1000000L; // Worker attachment, managed by the engine
const ULONG ATT_NO_CLEANUP = (ATT_no_cleanup | ATT_notify_gc);
classAttachment;
classDatabaseOptions;
structbid;
classActiveSnapshots
{
public:
explicitActiveSnapshots(Firebird::MemoryPool& p);
// Returns snapshot number given version belongs to.
// It is not needed to maintain two versions for the same snapshot, so the latter
// version can be garbage-collected.
//
// Function returns CN_ACTIVE if version was committed after we obtained
// our list of snapshots. It means GC is not possible for this version.
CommitNumber getSnapshotForVersion(CommitNumber version_cn);
private:
Firebird::SparseBitmap<CommitNumber> m_snapshots; // List of active snapshots as of the moment of time
CommitNumber m_lastCommit; // CN_ACTIVE here means object is not populated
ULONG m_releaseCount; // Release event counter when list was last updated
ULONG m_slots_used; // Snapshot slots used when list was last updated
friendclassTipCache;
};
//
// RefCounted part of Attachment object, placed into permanent pool
//
classStableAttachmentPart : publicFirebird::RefCounted, public Firebird::GlobalStorage
{
public:
classSync
{
public:
Sync()
: waiters(0), threadId(0), totalLocksCounter(0), currentLocksCounter(0)
{ }
voidenter(constchar* aReason)
{
ThreadId curTid = getThreadId();
if (threadId == curTid)
{
currentLocksCounter++;
return;
}
if (threadId || !syncMutex.tryEnter(aReason))
{
// we have contention with another thread
waiters.fetch_add(1, std::memory_order_relaxed);
syncMutex.enter(aReason);
waiters.fetch_sub(1, std::memory_order_relaxed);
}
threadId = curTid;
totalLocksCounter++;
fb_assert(currentLocksCounter == 0);
currentLocksCounter++;
}
booltryEnter(constchar* aReason)
{
ThreadId curTid = getThreadId();
if (threadId == curTid)
{
currentLocksCounter++;
returntrue;
}
if (threadId || !syncMutex.tryEnter(aReason))
returnfalse;
threadId = curTid;
totalLocksCounter++;
fb_assert(currentLocksCounter == 0);
currentLocksCounter++;
returntrue;
}
voidleave()
{
fb_assert(currentLocksCounter > 0);
if (--currentLocksCounter == 0)
{
threadId = 0;
syncMutex.leave();
}
}
boolhasContention() const
{
return (waiters.load(std::memory_order_relaxed) > 0);
}
FB_UINT64 getLockCounter() const
{
return totalLocksCounter;
}
boollocked() const
{
return threadId == getThreadId();
}
~Sync()
{
if (threadId == getThreadId())
{
syncMutex.leave();
}
}
private:
// copying is prohibited
Sync(const Sync&);
Sync& operator=(const Sync&);
Firebird::Mutex syncMutex;
std::atomic<int> waiters;
ThreadId threadId;
volatile FB_UINT64 totalLocksCounter;
int currentLocksCounter;
};
explicitStableAttachmentPart(Attachment* handle)
: att(handle), jAtt(NULL), shutError(0)
{ }
Attachment* getHandle() throw()
{
return att;
}
JAttachment* getInterface()
{
return jAtt;
}
voidsetInterface(JAttachment* ja)
{
if (jAtt)
jAtt->detachEngine();
jAtt = ja;
shutError = 0;
}
Sync* getSync(bool useAsync = false, bool forceAsync = false)
{
if (useAsync && !forceAsync)
{
fb_assert(!mainSync.locked());
}
return useAsync ? &async : &mainSync;
}
Firebird::Mutex* getBlockingMutex()
{
return &blockingMutex;
}
voidcancel()
{
fb_assert(async.locked());
fb_assert(mainSync.locked());
att = NULL;
}
jrd_tra* getEngineTransaction(Firebird::CheckStatusWrapper* status, Firebird::ITransaction* tra)
{
returngetInterface()->getEngineTransaction(status, tra);
}
JTransaction* getTransactionInterface(Firebird::CheckStatusWrapper* status, Firebird::ITransaction* tra)
{
returngetInterface()->getTransactionInterface(status, tra);
}
voidmanualLock(ULONG& flags, const ULONG whatLock = ATT_manual_lock | ATT_async_manual_lock);
voidmanualUnlock(ULONG& flags);
voidmanualAsyncUnlock(ULONG& flags);
voidsetShutError(ISC_STATUS code)
{
if (!shutError)
shutError = code;
}
ISC_STATUS getShutError() const
{
return shutError;
}
voidonIdleTimer(Firebird::TimerImpl* timer)
{
doOnIdleTimer(timer);
}
protected:
virtualvoiddoOnIdleTimer(Firebird::TimerImpl* timer);
private:
Attachment* att;
JAttachment* jAtt;
ISC_STATUS shutError;
// These syncs guarantee attachment existence. After releasing both of them with possibly
// zero att_use_count one should check does attachment still exists calling getHandle().
Sync mainSync, async;
// This mutex guarantees attachment is not accessed by more than single external thread.
Firebird::Mutex blockingMutex;
};
typedef Firebird::RaiiLockGuard<StableAttachmentPart::Sync> AttSyncLockGuard;
typedef Firebird::RaiiUnlockGuard<StableAttachmentPart::Sync> AttSyncUnlockGuard;
//
// the attachment block; one is created for each attachment to a database
//
classAttachment : publicpool_alloc<type_att>
{
public:
classSyncGuard
{
public:
SyncGuard(StableAttachmentPart* js, constchar* f, bool optional = false)
: jStable(js)
{
init(f, optional);
}
SyncGuard(Attachment* att, constchar* f, bool optional = false)
: jStable(att ? att->getStable() : NULL)
{
init(f, optional);
}
~SyncGuard()
{
if (jStable)
jStable->getSync()->leave();
}
private:
// copying is prohibited
SyncGuard(const SyncGuard&);
SyncGuard& operator=(const SyncGuard&);
voidinit(constchar* f, bool optional);
Firebird::RefPtr<StableAttachmentPart> jStable;
};
classGeneratorFinder
{
public:
explicitGeneratorFinder(MemoryPool& pool)
: m_objects(pool)
{}
voidstore(SLONG id, const MetaName& name)
{
fb_assert(id >= 0);
fb_assert(name.hasData());
if (id < (int) m_objects.getCount())
{
fb_assert(m_objects[id].isEmpty());
m_objects[id] = name;
}
else
{
m_objects.resize(id + 1);
m_objects[id] = name;
}
}
boollookup(SLONG id, MetaName& name)
{
if (id < (int) m_objects.getCount() && m_objects[id].hasData())
{
name = m_objects[id];
returntrue;
}
returnfalse;
}
SLONG lookup(const MetaName& name)
{
FB_SIZE_T pos;
if (m_objects.find(name, pos))
return (SLONG) pos;
return -1;
}
private:
Firebird::Array<MetaName> m_objects;
};
classInitialOptions
{
public:
InitialOptions(MemoryPool& p)
: bindings(p)
{
}
public:
voidsetInitialOptions(thread_db* tdbb, const DatabaseOptions& options);
voidresetAttachment(Attachment* attachment) const;
CoercionArray *getBindings()
{
return &bindings;
}
const CoercionArray *getBindings() const
{
return &bindings;
}
private:
Firebird::DecimalStatus decFloatStatus = Firebird::DecimalStatus::DEFAULT;
CoercionArray bindings;
USHORT originalTimeZone = Firebird::TimeZoneUtil::GMT_ZONE;
};
classDebugOptions
{
public:
boolgetDsqlKeepBlr() const
{
return dsqlKeepBlr;
}
voidsetDsqlKeepBlr(bool value)
{
dsqlKeepBlr = value;
}
private:
bool dsqlKeepBlr = false;
};
classUseCountHolder
{
public:
explicitUseCountHolder(Attachment* a)
: att(a)
{
if (att)
att->att_use_count++;
}
~UseCountHolder()
{
if (att)
att->att_use_count--;
}
private:
Attachment* att;
};
public:
static Attachment* create(Database* dbb, JProvider* provider);
staticvoiddestroy(Attachment* const attachment);
MemoryPool* const att_pool; // Memory pool
Firebird::MemoryStats att_memory_stats;
Database* att_database; // Parent database block
Attachment* att_next; // Next attachment to database
UserId* att_user; // User identification
UserId* att_ss_user; // User identification for SQL SECURITY actual user
Firebird::GenericMap<Firebird::Pair<Firebird::Left<
Firebird::MetaString, UserId*> > > att_user_ids; // set of used UserIds
jrd_tra* att_transactions; // Transactions belonging to attachment
jrd_tra* att_dbkey_trans; // transaction to control db-key scope
TraNumber att_oldest_snapshot; // GTT's record versions older than this can be garbage-collected
ActiveSnapshots att_active_snapshots; // List of currently active snapshots for GC purposes
private:
jrd_tra* att_sys_transaction; // system transaction
StableAttachmentPart* att_stable;
public:
Firebird::SortedArray<Statement*> att_statements; // Statements belonging to attachment
Firebird::SortedArray<Request*> att_requests; // Requests belonging to attachment
Lock* att_id_lock; // Attachment lock (if any)
AttNumber att_attachment_id; // Attachment ID
Lock* att_cancel_lock; // Lock to cancel the active request
Lock* att_monitor_lock; // Lock for monitoring purposes
ULONG att_monitor_generation; // Monitoring state generation
Lock* att_profiler_listener_lock; // Lock for remote profiler listener
const ULONG att_lock_owner_id; // ID for the lock manager
SLONG att_lock_owner_handle; // Handle for the lock manager
ULONG att_backup_state_counter; // Counter of backup state locks for attachment
SLONG att_event_session; // Event session id, if any
SecurityClass* att_security_class; // security class for database
SecurityClassList* att_security_classes; // security classes
RuntimeStatistics att_stats;
RuntimeStatistics att_base_stats;
ULONG att_flags; // Flags describing the state of the attachment
SSHORT att_client_charset; // user's charset specified in dpb
SSHORT att_charset; // current (client or external) attachment charset
// ASF: Attention: att_in_system_routine was initially added to support the profiler plugin
// writing to system tables. But a modified implementation used non-system tables and
// a problem was discovered that when writing to user's table from a "system context"
// (csb_internal) FK validations are not enforced becase MET_scan_relation is not called
// for the relation.
// Currently all "turning on" code for att_in_system_routine are disabled in SystemPackages.h.
bool att_in_system_routine = false; // running a system routine
Lock* att_long_locks; // outstanding two phased locks
#ifdef DEBUG_LCK_LIST
UCHAR att_long_locks_type; // Lock type of the first lock in list
#endif
std::atomic<SLONG> att_wait_owner_handle; // lock owner with which attachment waits currently
vec<Lock*>* att_compatibility_table; // hash table of compatible locks
Validation* att_validation;
Firebird::PathName att_working_directory; // Current working directory is cached
Firebird::PathName att_filename; // alias used to attach the database
ISC_TIMESTAMP_TZ att_timestamp; // Connection date and time
Firebird::StringMap att_context_vars; // Context variables for the connection
Firebird::Stack<DdlTriggerContext*> ddlTriggersContext; // Context variables for DDL trigger event
Firebird::string att_network_protocol; // Network protocol used by client for connection
Firebird::PathName att_remote_crypt; // Name of wire crypt plugin (if any)
Firebird::string att_remote_address; // Protocol-specific address of remote client
SLONG att_remote_pid; // Process id of remote client
ULONG att_remote_flags; // Flags specific for server/client link
Firebird::PathName att_remote_process; // Process name of remote client
Firebird::string att_client_version; // Version of the client library
Firebird::string att_remote_protocol; // Details about the remote protocol
Firebird::string att_remote_host; // Host name of remote client
Firebird::string att_remote_os_user; // OS user name of remote client
RandomGenerator att_random_generator; // Random bytes generator
Lock* att_temp_pg_lock; // temporary pagespace ID lock
DSqlCache att_dsql_cache; // DSQL cache locks
Firebird::SortedArray<void*> att_udf_pointers;
dsql_dbb* att_dsql_instance;
bool att_in_use; // attachment in use (can't be detached or dropped)
int att_use_count; // number of API calls running except of asynchronous ones
ThreadId att_purge_tid; // ID of thread running purge_attachment()
EDS::Connection* att_ext_connection; // external connection executed by this attachment
EDS::Connection* att_ext_parent; // external connection, parent of this attachment
ULONG att_ext_call_depth; // external connection call depth, 0 for user attachment
TraceManager* att_trace_manager; // Trace API manager
CoercionArray att_bindings;
CoercionArray* att_dest_bind;
USHORT att_original_timezone;
USHORT att_current_timezone;
int att_parallel_workers;
TriState att_opt_first_rows;
PageToBufferMap* att_bdb_cache; // managed in CCH, created in att_pool, freed with it
Firebird::RefPtr<Firebird::IReplicatedSession> att_replicator;
Firebird::AutoPtr<Replication::TableMatcher> att_repl_matcher;
Firebird::Array<Applier*> att_repl_appliers;
enum UtilType { UTIL_NONE, UTIL_GBAK, UTIL_GFIX, UTIL_GSTAT };
UtilType att_utility;
/// former Database members - start
vec<jrd_rel*>* att_relations; // relation vector
Firebird::Array<jrd_prc*> att_procedures; // scanned procedures
TrigVector* att_triggers[DB_TRIGGER_MAX];
TrigVector* att_ddl_triggers;
Firebird::Array<Function*> att_functions; // User defined functions
GeneratorFinder att_generators;
Firebird::Array<Statement*> att_internal; // internal statements
Firebird::Array<Statement*> att_dyn_req; // internal dyn statements
Firebird::ICryptKeyCallback* att_crypt_callback; // callback for DB crypt
Firebird::DecimalStatus att_dec_status; // error handling and rounding
Request* findSystemRequest(thread_db* tdbb, USHORT id, USHORT which);
Firebird::Array<CharSetContainer*> att_charsets; // intl character set descriptions
Firebird::GenericMap<Firebird::Pair<Firebird::Left<
MetaName, USHORT> > > att_charset_ids; // Character set ids
voidreleaseIntlObjects(thread_db* tdbb); // defined in intl.cpp
voiddestroyIntlObjects(thread_db* tdbb); // defined in intl.cpp
voidinitLocks(thread_db* tdbb);
voidreleaseLocks(thread_db* tdbb);
voiddetachLocks();
voidreleaseRelations(thread_db* tdbb);
staticintblockingAstShutdown(void*);
staticintblockingAstCancel(void*);
staticintblockingAstMonitor(void*);
staticintblockingAstReplSet(void*);
Firebird::Array<MemoryPool*> att_pools; // pools
MemoryPool* createPool();
voiddeletePool(MemoryPool* pool);
/// former Database members - end
boollocksmith(thread_db* tdbb, SystemPrivilege sp) const;
jrd_tra* getSysTransaction();
voidsetSysTransaction(jrd_tra* trans); // used only by TRA_init
boolisSystem() const
{
return (att_flags & ATT_system);
}
boolisWorker() const
{
return (att_flags & ATT_worker);
}
boolisGbak() const;
boolisRWGbak() const;
boolisUtility() const; // gbak, gfix and gstat.
PreparedStatement* prepareStatement(thread_db* tdbb, jrd_tra* transaction,
const Firebird::string& text, Firebird::MemoryPool* pool = NULL);
PreparedStatement* prepareStatement(thread_db* tdbb, jrd_tra* transaction,
const PreparedStatement::Builder& builder, Firebird::MemoryPool* pool = NULL);
PreparedStatement* prepareUserStatement(thread_db* tdbb, jrd_tra* transaction,
const Firebird::string& text, Firebird::MemoryPool* pool = NULL);
MetaName nameToMetaCharSet(thread_db* tdbb, const MetaName& name);
MetaName nameToUserCharSet(thread_db* tdbb, const MetaName& name);
Firebird::string stringToMetaCharSet(thread_db* tdbb, const Firebird::string& str,
constchar* charSet = NULL);
Firebird::string stringToUserCharSet(thread_db* tdbb, const Firebird::string& str);
voidstoreMetaDataBlob(thread_db* tdbb, jrd_tra* transaction,
bid* blobId, const Firebird::string& text, USHORT fromCharSet = CS_METADATA);
voidstoreBinaryBlob(thread_db* tdbb, jrd_tra* transaction, bid* blobId,
const Firebird::ByteChunk& chunk);
voidreleaseBatches();
voidreleaseGTTs(thread_db* tdbb);
voidresetSession(thread_db* tdbb, jrd_tra** traHandle);
voidsignalCancel();
voidsignalShutdown(ISC_STATUS code);
voidmergeStats(bool pageStatsOnly = false);
boolhasActiveRequests() const;
boolbackupStateWriteLock(thread_db* tdbb, SSHORT wait);
voidbackupStateWriteUnLock(thread_db* tdbb);
boolbackupStateReadLock(thread_db* tdbb, SSHORT wait);
voidbackupStateReadUnLock(thread_db* tdbb);
StableAttachmentPart* getStable() throw()
{
return att_stable;
}
voidsetStable(StableAttachmentPart *js) throw()
{
att_stable = js;
}
JAttachment* getInterface() throw();
unsignedintgetIdleTimeout() const
{
return att_idle_timeout;
}
voidsetIdleTimeout(unsignedint timeOut)
{
att_idle_timeout = timeOut;
}
unsignedintgetActualIdleTimeout() const;
unsignedintgetStatementTimeout() const
{
return att_stmt_timeout;
}
voidsetStatementTimeout(unsignedint timeOut)
{
att_stmt_timeout = timeOut;
}
// evaluate new value or clear idle timer
voidsetupIdleTimer(bool clear);
// returns time when idle timer will be expired, if set
boolgetIdleTimerClock(SINT64& clock) const
{
if (!att_idle_timer)
returnfalse;
clock = att_idle_timer->getExpireClock();
return (clock != 0);
}
// batches control
voidregisterBatch(DsqlBatch* b)
{
att_batches.add(b);
}
voidderegisterBatch(DsqlBatch* b)
{
att_batches.findAndRemove(b);
}
UserId* getUserId(const Firebird::MetaString& userName);
const Firebird::MetaString& getUserName(const Firebird::MetaString& emptyName = "") const
{
return att_user ? att_user->getUserName() : emptyName;
}
const Firebird::MetaString& getSqlRole(const Firebird::MetaString& emptyName = "") const
{
return att_user ? att_user->getSqlRole() : emptyName;
}
const UserId* getEffectiveUserId() const
{
if (att_ss_user)
return att_ss_user;
return att_user;
}
const Firebird::MetaString& getEffectiveUserName(const Firebird::MetaString& emptyName = "") const
{
constauto user = getEffectiveUserId();
return user ? user->getUserName() : emptyName;
}
voidsetInitialOptions(thread_db* tdbb, DatabaseOptions& options, bool newDb);
const CoercionArray* getInitialBindings() const
{
return att_initial_options.getBindings();
}
DebugOptions& getDebugOptions()
{
return att_debug_options;
}
voidcheckReplSetLock(thread_db* tdbb);
voidinvalidateReplSet(thread_db* tdbb, bool broadcast);
ProfilerManager* getProfilerManager(thread_db* tdbb);
ProfilerManager* getActiveProfilerManagerForNonInternalStatement(thread_db* tdbb);
boolisProfilerActive();
voidreleaseProfilerManager(thread_db* tdbb);
JProvider* getProvider()
{
fb_assert(att_provider);
return att_provider;
}
private:
Attachment(MemoryPool* pool, Database* dbb, JProvider* provider);
~Attachment();
unsignedint att_idle_timeout; // seconds
unsignedint att_stmt_timeout; // milliseconds
Firebird::RefPtr<Firebird::TimerImpl> att_idle_timer;
Firebird::Array<DsqlBatch*> att_batches;
InitialOptions att_initial_options; // Initial session options
DebugOptions att_debug_options;
Firebird::AutoPtr<ProfilerManager> att_profiler_manager; // ProfilerManager
Lock* att_repl_lock; // Replication set lock
JProvider* att_provider; // Provider which created this attachment
};
inlineboolAttachment::locksmith(thread_db* tdbb, SystemPrivilege sp) const
{
constauto user = getEffectiveUserId();
return (user && user->locksmith(tdbb, sp));
}
inline jrd_tra* Attachment::getSysTransaction()
{
return att_sys_transaction;
}
inlinevoidAttachment::setSysTransaction(jrd_tra* trans)
{
att_sys_transaction = trans;
}
// Connection is from GBAK
inlineboolAttachment::isGbak() const
{
return (att_utility == UTIL_GBAK);
}
// Gbak changes objects when it's restoring (creating) a db.
// Other attempts are fake. Gbak reconnects to change R/O status and other db-wide settings,
// but it doesn't modify generators or tables that seconds time.
inlineboolAttachment::isRWGbak() const
{
return (isGbak() && (att_flags & ATT_creator));
}
// Any of the three original utilities: gbak, gfix or gstat.
inlineboolAttachment::isUtility() const
{
return (att_utility != UTIL_NONE);
}
// This class holds references to all attachments it contains
classAttachmentsRefHolder
{
friendclassIterator;
public:
classIterator
{
public:
explicitIterator(AttachmentsRefHolder& list)
: m_list(list), m_index(0)
{}
StableAttachmentPart* operator*()
{
if (m_index < m_list.m_attachments.getCount())
return m_list.m_attachments[m_index];
returnNULL;
}
voidoperator++()
{
m_index++;
}
voidremove()
{
if (m_index < m_list.m_attachments.getCount())
{
m_list.m_attachments[m_index]->release();
m_list.m_attachments.remove(m_index);
}
}
private:
// copying is prohibited
Iterator(const Iterator&);
Iterator& operator=(const Iterator&);
AttachmentsRefHolder& m_list;
FB_SIZE_T m_index;
};
explicitAttachmentsRefHolder(MemoryPool& p)
: m_attachments(p)
{}
AttachmentsRefHolder()
: m_attachments(*MemoryPool::getContextPool())
{}
AttachmentsRefHolder& operator=(const AttachmentsRefHolder& other)
{
clear();
for (FB_SIZE_T i = 0; i < other.m_attachments.getCount(); i++)
add(other.m_attachments[i]);
return *this;
}
voidclear()
{
while (m_attachments.hasData())
{
m_attachments.pop()->release();
}
}
~AttachmentsRefHolder()
{
clear();
}
voidadd(StableAttachmentPart* jAtt)
{
if (jAtt)
{
jAtt->addRef();
m_attachments.add(jAtt);
}
}
boolhasData() const
{
return m_attachments.hasData();
}
private:
AttachmentsRefHolder(const AttachmentsRefHolder&);