forked from FirebirdSQL/php-firebird
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebird_utils.cpp
More file actions
executable file
·4337 lines (3712 loc) · 143 KB
/
Copy pathfirebird_utils.cpp
File metadata and controls
executable file
·4337 lines (3712 loc) · 143 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
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
/* SPDX-License-Identifier: PHP-3.01
* SPDX-FileCopyrightText: The PHP Group and contributors (see CREDITS) */
#include <ibase.h>
#include <firebird/Interface.h>
#include <cstring>
#include <memory>
#include <optional>
#include <string_view>
#include <string>
#include <array>
#include <algorithm>
#include <cassert>
#include <utility>
#include <tuple>
/* PHP headers must be wrapped in extern "C" when included from C++
* to ensure proper symbol linkage (especially for TSRM in ZTS builds) */
extern "C" {
#include "php.h"
#include "php_fbird_includes.h"
}
#include "firebird_utils.h"
#include "firebird_utils_internal.h"
namespace string_utils {
inline void add_php_string_from_view(zval* array, const char* key, std::string_view value) noexcept {
add_assoc_stringl(array, key, value.data(), value.size());
}
inline void add_php_string_indexed(zval* array, int index, std::string_view value) noexcept {
add_index_stringl(array, index, value.data(), value.size());
}
constexpr bool is_valid_time_component(unsigned hours, unsigned minutes, unsigned seconds, unsigned fractions) noexcept {
return hours <= 23 && minutes <= 59 && seconds <= 59 && fractions <= 9999;
}
constexpr bool is_valid_date_component(unsigned year, unsigned month, unsigned day) noexcept {
return year >= 1 && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= 31;
}
}
namespace {
std::optional<unsigned> get_client_version_impl(void* master_ptr) noexcept {
if (!master_ptr) {
return std::nullopt;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return std::nullopt;
}
return util->getClientVersion();
} catch (...) {
return std::nullopt;
}
}
struct TimeComponents {
unsigned hours, minutes, seconds, fractions;
[[nodiscard]] constexpr bool is_valid() const noexcept {
return hours <= 23 &&
minutes <= 59 &&
seconds <= 59 &&
fractions <= 9999;
}
};
std::optional<ISC_TIME> encode_time_impl(void* master_ptr, const TimeComponents& components) noexcept {
if (!master_ptr || !components.is_valid()) {
return std::nullopt;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return std::nullopt;
}
return util->encodeTime(components.hours, components.minutes,
components.seconds, components.fractions);
} catch (...) {
return std::nullopt;
}
}
struct DateComponents {
unsigned year, month, day;
[[nodiscard]] constexpr bool is_valid() const noexcept {
return year >= 1 && year <= 9999 &&
month >= 1 && month <= 12 &&
day >= 1 && day <= 31;
}
};
std::optional<ISC_DATE> encode_date_impl(void* master_ptr, const DateComponents& components) noexcept {
if (!master_ptr || !components.is_valid()) {
return std::nullopt;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return std::nullopt;
}
return util->encodeDate(components.year, components.month, components.day);
} catch (...) {
return std::nullopt;
}
}
#if FB_API_VER >= 40
struct DecodedTimestampTz {
unsigned year{0}, month{0}, day{0};
unsigned hours{0}, minutes{0}, seconds{0}, fractions{0};
std::string timeZone;
[[nodiscard]] auto tie() const noexcept {
return std::tie(year, month, day, hours, minutes, seconds, fractions);
}
[[nodiscard]] bool is_valid() const noexcept {
return year >= 1 && year <= 9999 &&
month >= 1 && month <= 12 &&
day >= 1 && day <= 31 &&
hours <= 23 && minutes <= 59 && seconds <= 59 && fractions <= 9999;
}
};
std::optional<DecodedTimestampTz> decode_timestamp_tz_impl(
void* master_ptr, const ISC_TIMESTAMP_TZ* timestampTz) noexcept {
if (!master_ptr || !timestampTz) {
return std::nullopt;
}
try {
FirebirdMasterWrapper master(master_ptr);
FirebirdStatusManager status_mgr(nullptr, master.getMaster());
auto* util = master.getUtil();
if (!util) {
return std::nullopt;
}
unsigned year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0, fractions = 0;
constexpr size_t TZ_BUFFER_SIZE = 64;
std::array<char, TZ_BUFFER_SIZE> tz_buffer{};
util->decodeTimeStampTz(status_mgr.get(), timestampTz,
&year, &month, &day,
&hours, &minutes, &seconds, &fractions,
TZ_BUFFER_SIZE, tz_buffer.data());
if (status_mgr.hasError()) {
return std::nullopt;
}
return DecodedTimestampTz{
year, month, day,
hours, minutes, seconds, fractions,
std::string(tz_buffer.data())
};
} catch (...) {
return std::nullopt;
}
}
int insert_field_info_modern(void* master_ptr, ISC_STATUS* status_vec,
bool is_output_var, int field_num, zval* target_array,
Firebird::IStatement* statement) noexcept {
try {
FirebirdMasterWrapper master(master_ptr);
FirebirdStatusManager status_mgr(status_vec, master.getMaster());
auto* metadata = is_output_var
? statement->getOutputMetadata(status_mgr.get())
: statement->getInputMetadata(status_mgr.get());
if (!metadata) {
return -1;
}
FirebirdMetadataWrapper meta_wrapper(metadata, true);
const auto field_name = meta_wrapper.getFieldName(status_mgr.get(), field_num);
const auto alias_name = meta_wrapper.getAlias(status_mgr.get(), field_num);
const auto relation_name = meta_wrapper.getRelation(status_mgr.get(), field_num);
if (status_mgr.hasError()) {
return -1;
}
string_utils::add_php_string_indexed(target_array, 0, field_name);
string_utils::add_php_string_from_view(target_array, "name", field_name);
string_utils::add_php_string_indexed(target_array, 1, alias_name);
string_utils::add_php_string_from_view(target_array, "alias", alias_name);
string_utils::add_php_string_indexed(target_array, 2, relation_name);
string_utils::add_php_string_from_view(target_array, "relation", relation_name);
return 0;
} catch (...) {
return -1;
}
}
int insert_aliases_modern(void* master_ptr, ISC_STATUS* status_vec, fbird_query* ib_query,
Firebird::IStatement* statement) noexcept {
try {
FirebirdMasterWrapper master(master_ptr);
FirebirdStatusManager status_mgr(status_vec, master.getMaster());
auto* metadata = statement->getOutputMetadata(status_mgr.get());
if (!metadata) {
return -1;
}
FirebirdMetadataWrapper meta_wrapper(metadata, true);
unsigned cols = metadata->getCount(status_mgr.get());
if (status_mgr.hasError()) {
return -1;
}
assert(cols == ib_query->out_fields_count);
for (unsigned i = 0; i < cols; ++i) {
const auto alias = meta_wrapper.getAlias(status_mgr.get(), i);
if (status_mgr.hasError()) {
return -1;
}
std::string alias_str(alias);
_php_fbird_insert_alias(ib_query->ht_aliases, alias_str.c_str());
}
return 0;
} catch (...) {
return -1;
}
}
#endif // FB_API_VER >= 40
} // end anonymous namespace
// Undefine min/max macros from php_fbird_includes.h to avoid C++ STL conflicts
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#include "src/cpp/fb_core.hpp"
#include "src/cpp/fb_connection.hpp"
namespace fb {
/**
* Implementation of getMaster() - retrieves the global IMaster instance
* from PHP extension globals (IBG macro).
*
* This function provides the bridge between the C++ wrapper layer and the
* PHP extension's global state.
*/
Firebird::IMaster* getMaster() noexcept {
// During MSHUTDOWN, the Firebird client library may already be released.
// Return nullptr to prevent dangling pointer access in persistent connection
// destructors (fixes pconnect shutdown SIGSEGV — Issue #50, #51).
if (IBG(in_mshutdown)) {
return nullptr;
}
// IBG(master_instance) is defined in php_fbird_includes.h
// It's stored as void* for C compatibility
return static_cast<Firebird::IMaster*>(IBG(master_instance));
}
} // namespace fb
/* Returns the client version. 0 bytes are minor version, 1 bytes are major version. */
extern "C" unsigned fbu_get_client_version(void *master_ptr)
{
auto version = get_client_version_impl(master_ptr);
return version.value_or(0);
}
extern "C" ISC_TIME fbu_encode_time(void *master_ptr, unsigned hours, unsigned minutes, unsigned seconds, unsigned fractions)
{
TimeComponents components{hours, minutes, seconds, fractions};
auto result = encode_time_impl(master_ptr, components);
return result.value_or(0);
}
extern "C" ISC_DATE fbu_encode_date(void *master_ptr, unsigned year, unsigned month, unsigned day)
{
DateComponents components{year, month, day};
auto result = encode_date_impl(master_ptr, components);
return result.value_or(0);
}
extern "C" long fbu_sqlcode(const ISC_STATUS *status_vector)
{
return (long)isc_sqlcode(status_vector);
}
extern "C" ISC_STATUS fba_array_lookup_bounds(ISC_STATUS *status_vector,
isc_db_handle *db_handle, isc_tr_handle *tr_handle,
const char *relation_name, const char *field_name,
ISC_ARRAY_DESC *desc)
{
return isc_array_lookup_bounds(status_vector, db_handle, tr_handle,
relation_name, field_name, desc);
}
extern "C" ISC_TIMESTAMP fbu_encode_timestamp(void *master_ptr, unsigned year, unsigned month, unsigned day,
unsigned hours, unsigned minutes, unsigned seconds, unsigned fractions)
{
ISC_TIMESTAMP result = {0, 0};
if (!master_ptr) {
return result;
}
// Validate components
if (!string_utils::is_valid_date_component(year, month, day) ||
!string_utils::is_valid_time_component(hours, minutes, seconds, fractions)) {
return result;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return result;
}
result.timestamp_date = util->encodeDate(year, month, day);
result.timestamp_time = util->encodeTime(hours, minutes, seconds, fractions);
return result;
} catch (...) {
return result;
}
}
extern "C" void fbu_decode_time(void *master_ptr, ISC_TIME time,
unsigned* hours, unsigned* minutes, unsigned* seconds, unsigned* fractions)
{
// Initialize outputs to zero for safety
if (hours) *hours = 0;
if (minutes) *minutes = 0;
if (seconds) *seconds = 0;
if (fractions) *fractions = 0;
if (!master_ptr) {
return;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return;
}
// Temporary storage (in case caller passes null for some outputs)
unsigned h = 0, m = 0, s = 0, f = 0;
util->decodeTime(time, &h, &m, &s, &f);
if (hours) *hours = h;
if (minutes) *minutes = m;
if (seconds) *seconds = s;
if (fractions) *fractions = f;
} catch (...) {
// Error case - outputs already initialized to zero
}
}
extern "C" void fbu_decode_date(void *master_ptr, ISC_DATE date,
unsigned* year, unsigned* month, unsigned* day)
{
// Initialize outputs to zero for safety
if (year) *year = 0;
if (month) *month = 0;
if (day) *day = 0;
if (!master_ptr) {
return;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return;
}
// Temporary storage (in case caller passes null for some outputs)
unsigned y = 0, m = 0, d = 0;
util->decodeDate(date, &y, &m, &d);
if (year) *year = y;
if (month) *month = m;
if (day) *day = d;
} catch (...) {
// Error case - outputs already initialized to zero
}
}
extern "C" void fbu_decode_timestamp(void *master_ptr, const ISC_TIMESTAMP* timestamp,
unsigned* year, unsigned* month, unsigned* day,
unsigned* hours, unsigned* minutes, unsigned* seconds, unsigned* fractions)
{
// Initialize all outputs to zero for safety
if (year) *year = 0;
if (month) *month = 0;
if (day) *day = 0;
if (hours) *hours = 0;
if (minutes) *minutes = 0;
if (seconds) *seconds = 0;
if (fractions) *fractions = 0;
if (!master_ptr || !timestamp) {
return;
}
try {
FirebirdMasterWrapper master(master_ptr);
auto* util = master.getUtil();
if (!util) {
return;
}
// Decode date portion
unsigned y = 0, mon = 0, d = 0;
util->decodeDate(timestamp->timestamp_date, &y, &mon, &d);
// Decode time portion
unsigned h = 0, min = 0, s = 0, f = 0;
util->decodeTime(timestamp->timestamp_time, &h, &min, &s, &f);
// Assign to outputs
if (year) *year = y;
if (month) *month = mon;
if (day) *day = d;
if (hours) *hours = h;
if (minutes) *minutes = min;
if (seconds) *seconds = s;
if (fractions) *fractions = f;
} catch (...) {
// Error case - outputs already initialized to zero
}
}
static void fbu_copy_status(const ISC_STATUS* from, ISC_STATUS* to, size_t maxLength)
{
if (!from || !to || maxLength == 0) return;
copy_status_vector(from, maxLength, to, maxLength);
}
extern "C" void* fbc_connect(
void* master_ptr,
const char* database, size_t db_len,
const char* user, size_t user_len,
const char* password, size_t password_len,
const char* charset, size_t charset_len,
const char* role, size_t role_len,
int num_buffers,
int dialect,
int force_write,
ISC_STATUS* status_vector
) {
// Validate master pointer
if (!master_ptr || !database) {
return nullptr;
}
try {
auto* master = static_cast<Firebird::IMaster*>(master_ptr);
// Build connection parameters
fb::ConnectionParams params;
params.database = std::string_view(database, db_len);
if (user && user_len > 0) params.user = std::string_view(user, user_len);
if (password && password_len > 0) params.password = std::string_view(password, password_len);
if (charset && charset_len > 0) params.charset = std::string_view(charset, charset_len);
if (role && role_len > 0) params.role = std::string_view(role, role_len);
params.dialect = static_cast<unsigned short>(dialect);
if (num_buffers > 0) {
params.num_buffers = static_cast<unsigned short>(num_buffers);
}
// Create connection using factory method
auto conn = fb::Connection::create(master, params);
if (!conn.isConnected()) {
// Connection failed - copy error status if provided
if (status_vector) {
conn.copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
return nullptr;
}
// Move to heap and return as opaque pointer
return reinterpret_cast<void*>(new fb::Connection(std::move(conn)));
} catch (const fb::Exception& e) {
// Copy error status from exception to output status vector
if (status_vector) {
const ISC_STATUS* exc_status = e.statusVector();
if (exc_status) {
for (size_t i = 0; i < ISC_STATUS_LENGTH; ++i) {
status_vector[i] = exc_status[i];
}
}
}
return nullptr;
} catch (...) {
return nullptr;
}
}
extern "C" int fbc_disconnect(void* connection, ISC_STATUS* status_vector) {
if (!connection) {
return 0;
}
try {
auto* conn = reinterpret_cast<fb::Connection*>(connection);
// Try graceful disconnect
bool success = conn->detachNoThrow();
// Copy status if provided
if (status_vector) {
conn->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
delete conn;
return success ? 0 : 1;
} catch (...) {
// Clean up even on exception
delete reinterpret_cast<fb::Connection*>(connection);
return 1;
}
}
extern "C" int fbc_drop_database(void* connection, ISC_STATUS* status_vector) {
if (!connection) {
return -1;
}
try {
auto* conn = reinterpret_cast<fb::Connection*>(connection);
// dropDatabase() throws fb::Exception on failure
conn->dropDatabase();
delete conn;
return 0;
} catch (const fb::Exception&) {
auto* conn = reinterpret_cast<fb::Connection*>(connection);
if (status_vector) {
conn->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
delete conn;
return -1;
} catch (...) {
delete reinterpret_cast<fb::Connection*>(connection);
return -1;
}
}
extern "C" void* fbc_create_database(
void* master_ptr,
const char* create_sql,
unsigned dialect,
ISC_STATUS* status_vector
) {
if (!master_ptr || !create_sql) {
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_bad_req_handle;
status_vector[2] = isc_arg_end;
}
return nullptr;
}
try {
auto* master = static_cast<Firebird::IMaster*>(master_ptr);
// Get IUtil interface for executeCreateDatabase
Firebird::IUtil* util = master->getUtilInterface();
if (!util) {
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_unavailable;
status_vector[2] = isc_arg_end;
}
return nullptr;
}
// Create status wrapper
Firebird::IStatus* raw_status = master->getStatus();
Firebird::CheckStatusWrapper check_status(raw_status);
// Execute CREATE DATABASE statement using OO API
// This returns an IAttachment* connected to the new database
Firebird::IAttachment* attachment = util->executeCreateDatabase(
&check_status,
static_cast<unsigned>(strlen(create_sql)),
create_sql,
dialect,
nullptr // stmtIsCreateDb - not used in modern API
);
if (check_status.isDirty() || !attachment) {
// Copy error status
if (status_vector) {
const ISC_STATUS* errors = raw_status->getErrors();
if (errors) {
for (size_t i = 0; i < ISC_STATUS_LENGTH; ++i) {
status_vector[i] = errors[i];
if (errors[i] == isc_arg_end) break;
}
}
}
return nullptr;
}
// Extract database path from CREATE DATABASE statement for Connection
// The SQL contains the database path, e.g., "CREATE SCHEMA 'path' ..."
std::string db_path;
const char* quote_start = strchr(create_sql, '\'');
if (quote_start) {
const char* quote_end = strchr(quote_start + 1, '\'');
if (quote_end) {
db_path = std::string(quote_start + 1, quote_end - quote_start - 1);
}
}
// Use the new factory method to create a proper Connection from the attachment
// This transfers ownership of the attachment to the Connection object
fb::Connection conn = fb::Connection::createFromAttachment(
master,
attachment,
db_path,
static_cast<unsigned short>(dialect)
);
// Move to heap and return as opaque pointer (compatible with fbc_get_attachment)
return reinterpret_cast<void*>(new fb::Connection(std::move(conn)));
} catch (const fb::Exception& e) {
if (status_vector) {
const ISC_STATUS* exc_status = e.statusVector();
if (exc_status) {
for (size_t i = 0; i < ISC_STATUS_LENGTH; ++i) {
status_vector[i] = exc_status[i];
}
}
}
return nullptr;
} catch (...) {
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_random;
status_vector[2] = isc_arg_end;
}
return nullptr;
}
}
extern "C" void* fbc_get_attachment(void* connection) {
if (!connection) {
return nullptr;
}
auto* conn = reinterpret_cast<fb::Connection*>(connection);
return conn->get(); // Returns IAttachment*
}
extern "C" int fbc_is_connected(void* connection) {
if (!connection) {
return 0;
}
auto* conn = reinterpret_cast<fb::Connection*>(connection);
return conn->isConnected() ? 1 : 0;
}
extern "C" int fbc_ping(void* master_ptr, void* connection, ISC_STATUS* status_vector) {
if (!master_ptr || !connection) {
return 0;
}
if (!fbc_is_connected(connection)) {
return 0;
}
/* Use fbc_get_info with isc_info_ods_version as a lightweight server roundtrip */
void* attachment = fbc_get_attachment(connection);
if (!attachment) {
return 0;
}
unsigned char info_items[] = { isc_info_ods_version };
unsigned char info_buffer[32] = {0};
ISC_STATUS local_status[ISC_STATUS_LENGTH] = {0};
int ok = fbc_get_info(master_ptr, attachment,
sizeof(info_items), info_items,
sizeof(info_buffer), info_buffer,
status_vector ? status_vector : local_status);
return ok;
}
extern "C" unsigned fbc_get_server_version(void* connection) {
if (!connection) {
return 0;
}
auto* conn = reinterpret_cast<fb::Connection*>(connection);
return conn->getVersion().getVersion();
}
#include "src/cpp/fb_transaction.hpp"
extern "C" void* fbt_start(
void* master_ptr,
void* attachment_ptr,
unsigned tpb_len,
const unsigned char* tpb,
ISC_STATUS* status_vector
) {
if (!master_ptr || !attachment_ptr) {
return nullptr;
}
try {
auto* master = static_cast<Firebird::IMaster*>(master_ptr);
auto* attachment = static_cast<Firebird::IAttachment*>(attachment_ptr);
// Create transaction using factory method
auto trans = fb::Transaction::start(master, attachment, tpb_len, tpb);
if (!trans.isActive()) {
if (status_vector) {
trans.copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
return nullptr;
}
// Move to heap and return as opaque pointer
return reinterpret_cast<void*>(new fb::Transaction(std::move(trans)));
} catch (const fb::Exception& e) {
// Copy error status from exception to output status vector
if (status_vector) {
const ISC_STATUS* exc_status = e.statusVector();
if (exc_status) {
for (size_t i = 0; i < ISC_STATUS_LENGTH; ++i) {
status_vector[i] = exc_status[i];
}
} else {
// No status available - set generic error
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_random;
status_vector[2] = isc_arg_end;
}
}
return nullptr;
} catch (...) {
// Unknown exception - set generic error
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_random;
status_vector[2] = isc_arg_end;
}
return nullptr;
}
}
extern "C" int fbt_commit(void* transaction, ISC_STATUS* status_vector) {
if (!transaction) {
return 0;
}
try {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
trans->commit();
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
/* Do NOT delete wrapper here - let PHP resource destructor call fbt_free().
* The wrapper stays valid (but inactive) so any PHP code holding a reference
* won't dereference freed memory. fbt_is_active() will return false.
* This fixes Issue #9: segfault in transaction cleanup after DDL commit. */
return 0;
} catch (const fb::Exception&) {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
/* On error, still don't delete - let PHP handle cleanup */
return -1;
} catch (...) {
/* On unknown exception, still don't delete */
return -1;
}
}
extern "C" int fbt_rollback(void* transaction, ISC_STATUS* status_vector) {
if (!transaction) {
return 0;
}
try {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
trans->rollback();
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
/* Do NOT delete wrapper here - let PHP resource destructor call fbt_free().
* Consistent with fbt_commit() behavior for Issue #9 fix. */
return 0;
} catch (const fb::Exception&) {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
/* On error, still don't delete - let PHP handle cleanup */
return -1;
} catch (...) {
/* On unknown exception, still don't delete */
return -1;
}
}
extern "C" int fbt_commit_retaining(void* transaction, ISC_STATUS* status_vector) {
if (!transaction) {
return -1;
}
try {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
trans->commitRetaining();
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
// Transaction remains valid after retaining commit - do NOT delete
return 0;
} catch (const fb::Exception&) {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
return -1;
} catch (...) {
return -1;
}
}
extern "C" int fbt_rollback_retaining(void* transaction, ISC_STATUS* status_vector) {
if (!transaction) {
return -1;
}
try {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
trans->rollbackRetaining();
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
// Transaction remains valid after retaining rollback - do NOT delete
return 0;
} catch (const fb::Exception&) {
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
if (status_vector) {
trans->copyLastStatus(status_vector, ISC_STATUS_LENGTH);
}
return -1;
} catch (...) {
return -1;
}
}
extern "C" int fbt_is_active(void* transaction) {
if (!transaction) {
return 0;
}
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
return trans->isActive() ? 1 : 0;
}
extern "C" void* fbt_get_handle(void* transaction) {
if (!transaction) {
return nullptr;
}
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
return trans->get(); // Returns ITransaction*
}
extern "C" void fbt_free(void* transaction) {
if (transaction) {
// Use rollbackNoThrow to safely clean up without throwing
auto* trans = reinterpret_cast<fb::Transaction*>(transaction);
trans->rollbackNoThrow();
delete trans;
}
}
extern "C" int fbt_get_info(
void* master_ptr,
void* transaction_ptr,
unsigned items_length,
const unsigned char* items,
unsigned buffer_length,
unsigned char* buffer,
ISC_STATUS* status_vector
) {
if (!master_ptr || !transaction_ptr || !items || !buffer) {
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_bad_req_handle;
status_vector[2] = isc_arg_end;
}
return 0;
}
auto* master = static_cast<Firebird::IMaster*>(master_ptr);
auto* transaction = static_cast<Firebird::ITransaction*>(transaction_ptr);
try {
Firebird::IStatus* fb_status = master->getStatus();
Firebird::CheckStatusWrapper status(fb_status);
transaction->getInfo(&status, items_length, items, buffer_length, buffer);
if (fb::statusHasError(fb_status)) {
if (status_vector) {
copy_status_vector(fb_status->getErrors(), ISC_STATUS_LENGTH, status_vector, ISC_STATUS_LENGTH);
}
return 0;
}
if (status_vector) {
status_vector[0] = 1;
status_vector[1] = 0;
}
return 1;
} catch (...) {
if (status_vector) {
status_vector[0] = isc_arg_gds;
status_vector[1] = isc_except2;
status_vector[2] = isc_arg_end;
}
return 0;