forked from oracle/node-oracledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnjsConnection.cpp
More file actions
3072 lines (2744 loc) · 112 KB
/
njsConnection.cpp
File metadata and controls
3072 lines (2744 loc) · 112 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
/* Copyright (c) 2015, 2019, Oracle and/or its affiliates.
All rights reserved. */
/******************************************************************************
*
* You may not use the identified files except in compliance with the Apache
* License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file uses NAN:
*
* Copyright (c) 2015 NAN contributors
*
* NAN contributors listed at https://github.com/rvagg/nan#contributors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* NAME
* njsConnection.cpp
*
* DESCRIPTION
* Connection class implementation.
*
*****************************************************************************/
#include "njsConnection.h"
#include "njsResultSet.h"
#include "njsSubscription.h"
#include "njsIntLob.h"
#include "njsSodaDatabase.h"
#include <stdlib.h>
#include <limits>
using namespace std;
// persistent Connection class handle
Nan::Persistent<FunctionTemplate> njsConnection::connectionTemplate_s;
// default value for bind option maxSize
#define NJS_MAX_OUT_BIND_SIZE 200
// max number of bytes for data converted to string with fetchAsString or fetchInfo
#define NJS_MAX_FETCH_AS_STRING_SIZE 200
//-----------------------------------------------------------------------------
// njsConnection::Init()
// Initialization function of Connection class. Maps functions and properties
// from JS to C++.
//-----------------------------------------------------------------------------
void njsConnection::Init(Local<Object> target)
{
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(Nan::New<v8::String>("Connection").ToLocalChecked());
Nan::SetPrototypeMethod(tpl, "execute", Execute);
Nan::SetPrototypeMethod(tpl, "executeMany", ExecuteMany);
Nan::SetPrototypeMethod(tpl, "getStatementInfo", GetStatementInfo);
Nan::SetPrototypeMethod(tpl, "close", Close);
Nan::SetPrototypeMethod(tpl, "commit", Commit);
Nan::SetPrototypeMethod(tpl, "rollback", Rollback);
Nan::SetPrototypeMethod(tpl, "break", Break);
Nan::SetPrototypeMethod(tpl, "createLob", CreateLob);
Nan::SetPrototypeMethod(tpl, "changePassword", ChangePassword);
Nan::SetPrototypeMethod(tpl, "ping", Ping);
Nan::SetPrototypeMethod(tpl, "subscribe", Subscribe);
Nan::SetPrototypeMethod(tpl, "unsubscribe", Unsubscribe);
Nan::SetPrototypeMethod(tpl, "getSodaDatabase", GetSodaDatabase);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("stmtCacheSize").ToLocalChecked(),
njsConnection::GetStmtCacheSize, njsConnection::SetStmtCacheSize);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("clientId").ToLocalChecked(),
njsConnection::GetClientId, njsConnection::SetClientId);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("module").ToLocalChecked(),
njsConnection::GetModule, njsConnection::SetModule);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("action").ToLocalChecked(),
njsConnection::GetAction, njsConnection::SetAction);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("oracleServerVersion").ToLocalChecked(),
njsConnection::GetOracleServerVersion,
njsConnection::SetOracleServerVersion);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("oracleServerVersionString").ToLocalChecked(),
njsConnection::GetOracleServerVersionString,
njsConnection::SetOracleServerVersionString);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("callTimeout").ToLocalChecked(),
njsConnection::GetCallTimeout, njsConnection::SetCallTimeout);
Nan::SetAccessor(tpl->InstanceTemplate(),
Nan::New<v8::String>("tag").ToLocalChecked(),
njsConnection::GetTag, njsConnection::SetTag);
connectionTemplate_s.Reset(tpl);
Nan::Set(target, Nan::New<v8::String>("Connection").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
//-----------------------------------------------------------------------------
// njsConnection::~njsConnection()
// Destructor.
//-----------------------------------------------------------------------------
njsConnection::~njsConnection() {
uint32_t mode = DPI_MODE_CONN_CLOSE_DEFAULT, tagLength = 0;
const char *tag = NULL;
jsOracledb.Reset();
if (this->dpiConnHandle) {
if (!this->retag) {
mode = DPI_MODE_CONN_CLOSE_RETAG;
tag = this->tag.c_str();
tagLength = this->tag.length();
}
dpiConn_close(dpiConnHandle, mode, tag, tagLength);
this->dpiConnHandle = NULL;
}
}
//-----------------------------------------------------------------------------
// njsConnection::CreateFromBaton()
// Create a new connection from the baton.
//-----------------------------------------------------------------------------
Local<Object> njsConnection::CreateFromBaton(njsBaton *baton)
{
Nan::EscapableHandleScope scope;
njsConnection *connection;
Local<Function> func;
Local<Object> obj;
func = Nan::GetFunction(
Nan::New<FunctionTemplate>(connectionTemplate_s)).ToLocalChecked();
obj = Nan::NewInstance(func).ToLocalChecked();
connection = Nan::ObjectWrap::Unwrap<njsConnection>(obj);
connection->dpiConnHandle = baton->dpiConnHandle;
baton->dpiConnHandle = NULL;
connection->jsOracledb.Reset(baton->jsOracledb);
if (!baton->tag.empty()) {
connection->tag = baton->tag;
connection->retag = true;
}
return scope.Escape(obj);
}
//-----------------------------------------------------------------------------
// njsConnection::ProcessQueryVars()
// Process query variables on all of the columns in the query. The actual
// ODPI-C variable will not be created at this point, nor will it be defined.
// This is deferred until just prior to the fetch.
//-----------------------------------------------------------------------------
bool njsConnection::ProcessQueryVars(njsBaton *baton, dpiStmt *dpiStmtHandle,
njsVariable *vars, uint32_t numVars)
{
dpiQueryInfo queryInfo;
// populate variables with query metadata
for (uint32_t i = 0; i < numVars; i++) {
// get query information for the specified column
vars[i].pos = i + 1;
vars[i].isArray = false;
vars[i].bindDir = NJS_BIND_OUT;
if (dpiStmt_getQueryInfo(dpiStmtHandle, vars[i].pos, &queryInfo) < 0) {
baton->GetDPIError();
return false;
}
vars[i].name = std::string(queryInfo.name, queryInfo.nameLength);
vars[i].maxArraySize = baton->fetchArraySize;
vars[i].dbSizeInBytes = queryInfo.typeInfo.dbSizeInBytes;
vars[i].precision = queryInfo.typeInfo.precision +
queryInfo.typeInfo.fsPrecision;
vars[i].scale = queryInfo.typeInfo.scale;
vars[i].isNullable = queryInfo.nullOk;
// determine the type of data
vars[i].dbTypeNum = queryInfo.typeInfo.oracleTypeNum;
vars[i].varTypeNum = queryInfo.typeInfo.oracleTypeNum;
vars[i].nativeTypeNum = queryInfo.typeInfo.defaultNativeTypeNum;
if (queryInfo.typeInfo.oracleTypeNum != DPI_ORACLE_TYPE_VARCHAR &&
queryInfo.typeInfo.oracleTypeNum != DPI_ORACLE_TYPE_NVARCHAR &&
queryInfo.typeInfo.oracleTypeNum != DPI_ORACLE_TYPE_CHAR &&
queryInfo.typeInfo.oracleTypeNum != DPI_ORACLE_TYPE_NCHAR &&
queryInfo.typeInfo.oracleTypeNum != DPI_ORACLE_TYPE_ROWID) {
if (!njsConnection::MapByName(baton, &queryInfo,
vars[i].varTypeNum))
njsConnection::MapByType(baton, &queryInfo,
vars[i].varTypeNum);
}
// validate data type and determine size
if (vars[i].varTypeNum == DPI_ORACLE_TYPE_VARCHAR ||
vars[i].varTypeNum == DPI_ORACLE_TYPE_RAW) {
vars[i].maxSize = NJS_MAX_FETCH_AS_STRING_SIZE;
vars[i].nativeTypeNum = DPI_NATIVE_TYPE_BYTES;
} else {
vars[i].maxSize = 0;
}
switch (queryInfo.typeInfo.oracleTypeNum) {
case DPI_ORACLE_TYPE_VARCHAR:
case DPI_ORACLE_TYPE_NVARCHAR:
case DPI_ORACLE_TYPE_CHAR:
case DPI_ORACLE_TYPE_NCHAR:
case DPI_ORACLE_TYPE_RAW:
vars[i].maxSize = queryInfo.typeInfo.clientSizeInBytes;
if (queryInfo.typeInfo.oracleTypeNum == DPI_ORACLE_TYPE_RAW &&
vars[i].varTypeNum == DPI_ORACLE_TYPE_VARCHAR)
vars[i].maxSize *= 2;
break;
case DPI_ORACLE_TYPE_DATE:
case DPI_ORACLE_TYPE_TIMESTAMP:
case DPI_ORACLE_TYPE_TIMESTAMP_TZ:
case DPI_ORACLE_TYPE_TIMESTAMP_LTZ:
if (vars[i].varTypeNum != DPI_ORACLE_TYPE_VARCHAR) {
vars[i].varTypeNum = DPI_ORACLE_TYPE_TIMESTAMP_LTZ;
vars[i].nativeTypeNum = DPI_NATIVE_TYPE_DOUBLE;
}
break;
case DPI_ORACLE_TYPE_CLOB:
case DPI_ORACLE_TYPE_NCLOB:
if (vars[i].varTypeNum == DPI_ORACLE_TYPE_VARCHAR)
vars[i].maxSize = (uint32_t) -1;
break;
case DPI_ORACLE_TYPE_BLOB:
if (vars[i].varTypeNum == DPI_ORACLE_TYPE_RAW)
vars[i].maxSize = (uint32_t) -1;
break;
case DPI_ORACLE_TYPE_LONG_VARCHAR:
case DPI_ORACLE_TYPE_LONG_RAW:
vars[i].maxSize = (uint32_t) -1;
break;
case DPI_ORACLE_TYPE_NUMBER:
case DPI_ORACLE_TYPE_NATIVE_INT:
case DPI_ORACLE_TYPE_NATIVE_FLOAT:
case DPI_ORACLE_TYPE_NATIVE_DOUBLE:
case DPI_ORACLE_TYPE_ROWID:
break;
default:
baton->error = njsMessages::Get(errUnsupportedDataType,
queryInfo.typeInfo.oracleTypeNum, i + 1);
baton->ClearAsyncData();
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ProcessVars()
// Process variables used during binding or fetching. REF cursors must have
// their query variables defined and LOBs must be initially processed in order
// to have as much work as possible done in the worker thread and to avoid any
// round trips.
//-----------------------------------------------------------------------------
bool njsConnection::ProcessVars(njsBaton *baton, njsVariable *vars,
uint32_t numVars, uint32_t numRows)
{
for (uint32_t col = 0; col < numVars; col++) {
njsVariable *var = &vars[col];
var->buffer.numElements = numRows;
if (var->bindDir == NJS_BIND_IN)
continue;
if (var->dmlReturningBuffers) {
delete [] var->dmlReturningBuffers;
var->dmlReturningBuffers = NULL;
}
// for arrays, determine the number of elements in the array
if (var->isArray) {
if (dpiVar_getNumElementsInArray(var->dpiVarHandle,
&var->buffer.numElements) < 0) {
baton->GetDPIError();
return false;
}
// for DML returning statements, each row has its own set of rows, so
// acquire those from ODPI-C and store them in variable buffers for
// later processing
} else if (baton->isReturning && var->bindDir == NJS_BIND_OUT) {
var->dmlReturningBuffers = new njsVariableBuffer[numRows];
for (uint32_t row = 0; row < numRows; row++) {
njsVariableBuffer *buffer = &var->dmlReturningBuffers[row];
if (dpiVar_getReturnedData(var->dpiVarHandle, row,
&buffer->numElements, &buffer->dpiVarData) < 0) {
baton->GetDPIError();
return false;
}
if (!ProcessVarBuffer(baton, var, buffer))
return false;
}
}
// process the main buffer if DML returning is not in effect
if (!var->dmlReturningBuffers &&
!ProcessVarBuffer(baton, var, &var->buffer))
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ProcessVarBuffer()
// Process a variable buffer. REF cursors must have their query variables
// defined and LOBs must be initially processed in order to have as much work
// as possible done in the worker thread and avoid any round trips.
//-----------------------------------------------------------------------------
bool njsConnection::ProcessVarBuffer(njsBaton *baton, njsVariable *var,
njsVariableBuffer *buffer)
{
dpiStmt *stmt;
switch (var->varTypeNum) {
case DPI_ORACLE_TYPE_CLOB:
case DPI_ORACLE_TYPE_NCLOB:
case DPI_ORACLE_TYPE_BLOB:
if (buffer->lobs)
delete [] buffer->lobs;
buffer->lobs = new njsProtoILob[buffer->numElements];
for (uint32_t i = 0; i < buffer->numElements; i++) {
njsProtoILob *lob = &buffer->lobs[i];
lob->dataType = (var->varTypeNum == DPI_ORACLE_TYPE_BLOB) ?
NJS_DATATYPE_BLOB : NJS_DATATYPE_CLOB;
lob->isAutoClose = true;
uint32_t elementIndex = baton->bufferRowIndex + i;
dpiData *data = &buffer->dpiVarData[elementIndex];
if (data->isNull)
continue;
if (!lob->PopulateFromDPI(baton, data->value.asLOB, true))
return false;
}
break;
case DPI_ORACLE_TYPE_STMT:
stmt = buffer->dpiVarData->value.asStmt;
if (dpiStmt_getNumQueryColumns(stmt, &var->numQueryVars) < 0) {
baton->GetDPIError();
return false;
}
var->queryVars = new njsVariable[var->numQueryVars];
if (!ProcessQueryVars(baton, stmt, var->queryVars,
var->numQueryVars))
return false;
break;
default:
break;
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::MapByName()
// Apply "By-Name" rules, if applicable. Returns true if rules were applied
// (and targetType is set); false otherwise (and targetType is left untouched).
//-----------------------------------------------------------------------------
bool njsConnection::MapByName(njsBaton *baton, dpiQueryInfo *queryInfo,
dpiOracleTypeNum &targetType)
{
if (baton->fetchInfo) {
std::string name = std::string(queryInfo->name, queryInfo->nameLength);
for (uint32_t i = 0; i < baton->numFetchInfo; i++) {
if (baton->fetchInfo[i].name.compare(name) == 0) {
if (baton->fetchInfo[i].type == NJS_DATATYPE_STR) {
targetType = DPI_ORACLE_TYPE_VARCHAR;
} else if (baton->fetchInfo[i].type == NJS_DATATYPE_BUFFER) {
targetType = DPI_ORACLE_TYPE_RAW;
} else if (baton->fetchInfo[i].type == NJS_DATATYPE_DEFAULT) {
targetType = queryInfo->typeInfo.oracleTypeNum;
}
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// njsConnection::MapByType()
// Apply "By-Type" rules, if applicable. Returns true if rules were applied
// (and targetType is set); false otherwise (and targetType is left untouched).
//-----------------------------------------------------------------------------
bool njsConnection::MapByType(njsBaton *baton, dpiQueryInfo *queryInfo,
dpiOracleTypeNum &targetType)
{
uint32_t i;
// handle fetchAsString
for (i = 0; i < baton->numFetchAsStringTypes; i++) {
switch (queryInfo->typeInfo.oracleTypeNum) {
case DPI_ORACLE_TYPE_NUMBER:
case DPI_ORACLE_TYPE_NATIVE_FLOAT:
case DPI_ORACLE_TYPE_NATIVE_DOUBLE:
case DPI_ORACLE_TYPE_NATIVE_INT:
if (baton->fetchAsStringTypes[i] == NJS_DATATYPE_NUM) {
targetType = DPI_ORACLE_TYPE_VARCHAR;
return true;
}
break;
case DPI_ORACLE_TYPE_DATE:
case DPI_ORACLE_TYPE_TIMESTAMP:
case DPI_ORACLE_TYPE_TIMESTAMP_TZ:
case DPI_ORACLE_TYPE_TIMESTAMP_LTZ:
if (baton->fetchAsStringTypes[i] == NJS_DATATYPE_DATE) {
targetType = DPI_ORACLE_TYPE_VARCHAR;
return true;
}
break;
case DPI_ORACLE_TYPE_CLOB:
case DPI_ORACLE_TYPE_NCLOB:
if (baton->fetchAsStringTypes[i] == NJS_DATATYPE_CLOB) {
targetType = DPI_ORACLE_TYPE_VARCHAR;
return true;
}
break;
case DPI_ORACLE_TYPE_RAW:
if (baton->fetchAsStringTypes[i] == NJS_DATATYPE_BUFFER) {
targetType = DPI_ORACLE_TYPE_VARCHAR;
return true;
}
break;
default:
break;
}
}
// handle fetchAsBuffer
for (i = 0; i < baton->numFetchAsBufferTypes; i++) {
if (queryInfo->typeInfo.oracleTypeNum == DPI_ORACLE_TYPE_BLOB &&
baton->fetchAsBufferTypes[i] == NJS_DATATYPE_BLOB) {
targetType = DPI_ORACLE_TYPE_RAW;
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// njsConnection::PrepareAndBind()
// Prepare statement and bind data to the statement.
//-----------------------------------------------------------------------------
bool njsConnection::PrepareAndBind(njsBaton *baton)
{
// prepare DPI statement for use
if (dpiConn_prepareStmt(baton->dpiConnHandle, 0, baton->sql.c_str(),
(uint32_t) baton->sql.length(), NULL, 0,
&baton->dpiStmtHandle) < 0) {
baton->GetDPIError();
return false;
}
// determine statement information
dpiStmtInfo stmtInfo;
if (dpiStmt_getInfo(baton->dpiStmtHandle, &stmtInfo) < 0) {
baton->GetDPIError();
return false;
}
baton->isPLSQL = (stmtInfo.isPLSQL) ? true : false;
baton->isReturning = (stmtInfo.isReturning) ? true : false;
// result sets are incompatible with non-queries
if (!stmtInfo.isQuery && baton->getRS) {
baton->error = njsMessages::Get(errInvalidNonQueryExecution);
baton->ClearAsyncData();
return false;
}
// perform any binds necessary
for (uint32_t i = 0; i < baton->numBindVars; i++) {
int status;
njsVariable *var = &baton->bindVars[i];
if (var->name.empty()) {
status = dpiStmt_bindByPos(baton->dpiStmtHandle, var->pos,
var->dpiVarHandle);
} else {
status = dpiStmt_bindByName(baton->dpiStmtHandle,
var->name.c_str(), (uint32_t) var->name.length(),
var->dpiVarHandle);
}
if (status < 0) {
baton->GetDPIError();
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::GetMetaData()
// Populate array of metadata for JS from list of variables.
//-----------------------------------------------------------------------------
Local<Value> njsConnection::GetMetaData(njsVariable *vars, uint32_t numVars,
bool extendedMetaData)
{
Nan::EscapableHandleScope scope;
Local<Array> metaArray = Nan::New<Array>((int)numVars);
for (uint32_t i = 0; i < numVars; i++) {
njsVariable *var = &vars[i];
Local<Object> column = Nan::New<Object>();
Nan::Set(column, Nan::New<v8::String>("name").ToLocalChecked(),
Nan::New<v8::String>(var->name).ToLocalChecked());
if (extendedMetaData) {
njsDBType dbType = var->DBType();
Nan::Set(column,
Nan::New<v8::String>("fetchType").ToLocalChecked(),
Nan::New<v8::Number>(var->DataType()));
Nan::Set(column,
Nan::New<v8::String>("dbType").ToLocalChecked(),
Nan::New<v8::Number>(dbType));
Nan::Set(column,
Nan::New<v8::String>("nullable").ToLocalChecked(),
Nan::New<v8::Boolean>(var->isNullable));
switch (dbType) {
case NJS_DB_TYPE_VARCHAR:
case NJS_DB_TYPE_NVARCHAR:
case NJS_DB_TYPE_CHAR:
case NJS_DB_TYPE_NCHAR:
case NJS_DB_TYPE_RAW:
Nan::Set(column,
Nan::New<v8::String>("byteSize").ToLocalChecked(),
Nan::New<v8::Number>(var->dbSizeInBytes));
break;
case NJS_DB_TYPE_NUMBER:
Nan::Set(column,
Nan::New<v8::String>("precision").ToLocalChecked(),
Nan::New<v8::Number>(var->precision));
Nan::Set(column,
Nan::New<v8::String>("scale").ToLocalChecked(),
Nan::New<v8::Number>(var->scale) );
break;
case NJS_DB_TYPE_TIMESTAMP:
case NJS_DB_TYPE_TIMESTAMP_TZ:
case NJS_DB_TYPE_TIMESTAMP_LTZ:
Nan::Set(column,
Nan::New<v8::String>("precision").ToLocalChecked(),
Nan::New<v8::Number>(var->precision));
break;
default:
break;
}
}
Nan::Set(metaArray, i, column);
}
return scope.Escape(metaArray);
}
//-----------------------------------------------------------------------------
// njsConnection::CreateVarBuffer()
// Create ODPI-C variables used to hold the bind data.
//-----------------------------------------------------------------------------
bool njsConnection::CreateVarBuffer(njsVariable *var, njsBaton *baton)
{
// if the variable is not an array use the bind array size
if (!var->isArray)
var->maxArraySize = baton->bindArraySize;
// if the variable has no data type assume string of size 1
if (var->bindDataType == NJS_DATATYPE_DEFAULT) {
var->bindDataType = NJS_DATATYPE_STR;
var->maxSize = 1;
}
// REF cursors are only supported as out binds currently
if (var->bindDataType == NJS_DATATYPE_CURSOR &&
var->bindDir != NJS_BIND_OUT) {
baton->error = njsMessages::Get(errInvalidPropertyValueInParam,
"type", 1);
return false;
}
// max size must be specified for in/out and out binds
if (!var->maxSize && var->bindDir != NJS_BIND_IN) {
baton->error = njsMessages::Get(errInvalidPropertyValueInParam,
"maxSize", 1);
return false;
}
// determine ODPI-C Oracle type and native type to use
switch (var->bindDataType) {
case NJS_DATATYPE_STR:
var->varTypeNum = DPI_ORACLE_TYPE_VARCHAR;
var->nativeTypeNum = DPI_NATIVE_TYPE_BYTES;
break;
case NJS_DATATYPE_NUM:
var->varTypeNum = DPI_ORACLE_TYPE_NUMBER;
var->nativeTypeNum = DPI_NATIVE_TYPE_DOUBLE;
break;
case NJS_DATATYPE_INT:
var->varTypeNum = DPI_ORACLE_TYPE_NUMBER;
var->nativeTypeNum = DPI_NATIVE_TYPE_INT64;
break;
case NJS_DATATYPE_DATE:
var->varTypeNum = DPI_ORACLE_TYPE_TIMESTAMP_LTZ;
var->nativeTypeNum = DPI_NATIVE_TYPE_DOUBLE;
break;
case NJS_DATATYPE_CURSOR:
var->varTypeNum = DPI_ORACLE_TYPE_STMT;
var->nativeTypeNum = DPI_NATIVE_TYPE_STMT;
break;
case NJS_DATATYPE_BUFFER:
var->varTypeNum = DPI_ORACLE_TYPE_RAW;
var->nativeTypeNum = DPI_NATIVE_TYPE_BYTES;
break;
case NJS_DATATYPE_CLOB:
var->varTypeNum = DPI_ORACLE_TYPE_CLOB;
var->nativeTypeNum = DPI_NATIVE_TYPE_LOB;
break;
case NJS_DATATYPE_BLOB:
var->varTypeNum = DPI_ORACLE_TYPE_BLOB;
var->nativeTypeNum = DPI_NATIVE_TYPE_LOB;
break;
default:
baton->error= njsMessages::Get(errInvalidBindDataType, 2);
return false;
}
// create ODPI-C variable
if (dpiConn_newVar(baton->dpiConnHandle, var->varTypeNum,
var->nativeTypeNum, var->maxArraySize, var->maxSize, 1,
var->isArray, NULL, &var->dpiVarHandle,
&var->buffer.dpiVarData) < 0) {
baton->GetDPIError();
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ProcessExecuteBinds()
// Process binds passed through to Execute() call.
//-----------------------------------------------------------------------------
bool njsConnection::ProcessExecuteBinds(Local<Object> binds, njsBaton *baton)
{
Nan::HandleScope scope;
Local<Array> bindNames;
// determine bind names (if binding by name)
baton->bindArraySize = 1;
if (!binds->IsUndefined() && !binds->IsArray())
bindNames = Nan::GetOwnPropertyNames(binds).ToLocalChecked();
// initialize variables; if there are no variables, nothing further to do!
if (!InitBindVars(binds, bindNames, baton))
return false;
if (baton->numBindVars == 0)
return true;
// scan the execute binds and populate the bind variables
return ScanExecuteBinds(binds, bindNames, baton);
}
//-----------------------------------------------------------------------------
// njsConnection::ScanExecuteBinds()
// Scan the binds passed through to Execute() and determine the bind
// type and maximum size (for strings/buffers).
//-----------------------------------------------------------------------------
bool njsConnection::ScanExecuteBinds(Local<Object> binds,
Local<Array> bindNames, njsBaton *baton)
{
Nan::HandleScope scope;
Local<Value> bindName, bindUnit, bindValue;
Local<Array> byPositionValues;
njsVariable *var;
bool byPosition;
// determine if binding is by position or by name
byPosition = (baton->bindVars[0].pos > 0);
if (byPosition)
byPositionValues = binds.As<Array>();
// scan each column
for (uint32_t i = 0; i < baton->numBindVars; i++) {
var = &baton->bindVars[i];
// determine bind information and value
if (byPosition) {
MaybeLocal<Value> mval = Nan::Get(byPositionValues, i);
if (!mval.ToLocal(&bindUnit))
return false;
} else {
MaybeLocal<Value> mval = Nan::Get(bindNames, i);
if (!mval.ToLocal(&bindName))
return false;
mval = Nan::Get(binds, bindName);
if(!mval.ToLocal(&bindUnit))
return false;
}
if (bindUnit->IsObject() && !bindUnit->IsDate() &&
!Buffer::HasInstance(bindUnit) &&
!njsILob::HasInstance(bindUnit)) {
if (!ScanExecuteBindUnit(bindUnit.As<Object>(), var, false, baton))
return false;
Local<String> key = Nan::New<String>("val").ToLocalChecked();
MaybeLocal<Value> mval = Nan::Get(bindUnit.As<Object>(), key);
if (!mval.ToLocal(&bindValue))
return false;
} else {
bindValue = bindUnit;
}
// get bind information from value if it has not already been specified
if (var->bindDataType == NJS_DATATYPE_DEFAULT || !var->maxSize ||
var->maxSize == NJS_MAX_OUT_BIND_SIZE) {
njsDataType defaultBindType = NJS_DATATYPE_DEFAULT;
uint32_t defaultMaxSize = 0;
if (!GetBindTypeAndSizeFromValue(var, bindValue, &defaultBindType,
&defaultMaxSize, baton))
return false;
if (var->bindDataType == NJS_DATATYPE_DEFAULT)
var->bindDataType = defaultBindType;
if (defaultMaxSize > var->maxSize)
var->maxSize = defaultMaxSize;
}
// for IN binds, maxArraySize is ignored and obtained from the actual
// array size; for INOUT binds, maxArraySize does need to be specified
// by the application; for OUT binds, the value from the application
// must be accepted as is as there is no way to validate it
if (bindValue->IsArray()) {
var->isArray = true;
Local<Array> arrayVal = Local<Array>::Cast(bindValue);
if (var->bindDir == NJS_BIND_IN) {
var->maxArraySize = arrayVal->Length();
if (var->maxArraySize == 0)
var->maxArraySize = 1;
} else if (var->maxArraySize == 0) {
baton->error = njsMessages::Get(errReqdMaxArraySize);
return false;
}
if (var->bindDir == NJS_BIND_INOUT &&
arrayVal->Length() > var->maxArraySize) {
baton->error = njsMessages::Get(errInvalidArraySize);
return false;
}
}
// create buffer for variable
if (!CreateVarBuffer(var, baton))
return false;
// process bind value (for all except OUT)
if (var->bindDir != NJS_BIND_OUT) {
if (!ProcessBindValue(bindValue, var, baton))
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ScanExecuteBindUnit()
// Scan the execute bind unit for bind information.
//-----------------------------------------------------------------------------
bool njsConnection::ScanExecuteBindUnit(Local<Object> bindUnit,
njsVariable *var, bool inExecuteMany, njsBaton *baton)
{
Nan::HandleScope scope;
// scan all keys and verify that one of "dir", "type", "maxSize" or "val"
// is found; if not, the bind information is considered invalid
Local<Array> keys = Nan::GetOwnPropertyNames(bindUnit).ToLocalChecked();
bool valid = false;
for (uint32_t i = 0; i < keys->Length(); i++) {
MaybeLocal<Value> mval = Nan::Get(keys, i );
Local<Value> tempVal;
if (!mval.ToLocal(&tempVal))
return false;
Local<String> temp = tempVal.As<String>();
Nan::Utf8String utf8str(temp);
std::string key =
std::string(*utf8str, static_cast<size_t>(utf8str.length()));
if (key.compare("dir") == 0 || key.compare("type") == 0 ||
key.compare("maxSize") == 0 || key.compare("val") == 0) {
valid = true;
break;
}
}
if (!valid) {
baton->error = njsMessages::Get(errNamedJSON);
return false;
}
// get and validate bind direction
uint32_t temp = (uint32_t) var->bindDir;
if (!baton->GetUnsignedIntFromJSON(bindUnit, "dir", 1, &temp))
return false;
var->bindDir = (njsBindDir) temp;
switch (var->bindDir) {
case NJS_BIND_OUT:
case NJS_BIND_IN:
case NJS_BIND_INOUT:
break;
default:
baton->error = njsMessages::Get(errInvalidBindDirection);
return false;
}
// get data type
temp = (uint32_t) var->bindDataType;
if (!baton->GetUnsignedIntFromJSON(bindUnit, "type", 1, &temp))
return false;
if (!temp && inExecuteMany) {
if (var->pos > 0) {
baton->error = njsMessages::Get(errMissingTypeByPos, var->pos);
} else {
baton->error = njsMessages::Get(errMissingTypeByName,
var->name.c_str());
}
}
var->bindDataType = (njsDataType) temp;
// get maximum size for strings/buffers; this value is only used for
// IN/OUT and OUT binds in execute() and at all times for executeMany()
if (var->bindDir != NJS_BIND_IN || inExecuteMany) {
if (var->bindDir != NJS_BIND_IN)
var->maxSize = NJS_MAX_OUT_BIND_SIZE;
if (!baton->GetUnsignedIntFromJSON(bindUnit, "maxSize", 1,
&var->maxSize))
return false;
if (inExecuteMany && var->maxSize == 0) {
if (var->bindDataType == NJS_DATATYPE_STR ||
var->bindDataType == NJS_DATATYPE_BUFFER) {
if (var->pos > 0) {
baton->error = njsMessages::Get(errMissingMaxSizeByPos,
var->pos);
} else {
baton->error = njsMessages::Get(errMissingMaxSizeByName,
var->name.c_str());
}
return false;
}
}
}
// get max array size (for array binds)
if (!inExecuteMany) {
if (!baton->GetUnsignedIntFromJSON(bindUnit, "maxArraySize", 1,
&var->maxArraySize))
return false;
if (var->maxArraySize > 0)
var->isArray = true;
}
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ProcessExecuteManyBinds()
// Process binds passed through to ExecuteMany() call.
//-----------------------------------------------------------------------------
bool njsConnection::ProcessExecuteManyBinds(Local<Array> binds,
Local<Object> options, njsBaton *baton)
{
Nan::HandleScope scope;
Local<Value> bindDefs, bindName, bindUnit;
Local<Array> bindNames;
bool scanRequired;
// determine if bind definitions have been specified
Local<String> key = Nan::New<v8::String>("bindDefs").ToLocalChecked();
if (!Nan::Get(options, key).ToLocal(&bindDefs))
return false;
scanRequired = bindDefs->IsUndefined();
// if no bind definitions are specified, the first row is used to determine
// the number of bind variables and types
if (scanRequired && !binds.IsEmpty()) {
MaybeLocal<Value> mval = Nan::Get(binds, 0);
if (!mval.ToLocal (&bindDefs))
return false;
}
// bindDefs must be an array or object
if (!bindDefs->IsUndefined() && !bindDefs->IsArray()) {
if (!bindDefs->IsObject()) {
baton->error = njsMessages::Get(errInvalidParameterValue, 2);
return false;
}
bindNames = Nan::GetOwnPropertyNames(bindDefs.As<Object>()).
ToLocalChecked();
}
// initialize variables; if there are no variables, nothing further to do!
if (!InitBindVars(bindDefs.As<Object>(), bindNames, baton))
return false;
if (baton->numBindVars == 0)
return true;
// if no bind definitions are specified, scan the binds to determine type
// and size
if (scanRequired) {
if (!ScanExecuteManyBinds(binds, bindNames, baton))
return false;
// otherwise, use the bind definitions to determine type and size
} else {
bool byPosition = (baton->bindVars[0].pos > 0);
Local<Array> byPositionValues;
if (byPosition)
byPositionValues = bindDefs.As<Array>();
for (uint32_t i = 0; i < baton->numBindVars; i++) {
njsVariable *var = &baton->bindVars[i];
if (byPosition) {
MaybeLocal<Value> mval = Nan::Get(byPositionValues, i);
if(!mval.ToLocal(&bindUnit))
return false;
} else {
MaybeLocal<Value> mval = Nan::Get(bindNames, i);
if(!mval.ToLocal(&bindName))
return false;
if (!Nan::Get(bindDefs.As<Object>(),
bindName).ToLocal(&bindUnit))
return false;
}
if (!ScanExecuteBindUnit(bindUnit.As<Object>(), var, true, baton))
return false;
}
}
// create the ODPI-C variables used to hold the data
for (uint32_t i = 0; i < baton->numBindVars; i++) {
if (!CreateVarBuffer(&baton->bindVars[i], baton))
return false;
}
// populate the ODPI-C variables with the data from JavaScript binds
if (!binds.IsEmpty() && !TransferExecuteManyBinds(binds, bindNames, baton))
return false;
return true;
}
//-----------------------------------------------------------------------------
// njsConnection::ScanExecuteManyBinds()
// Scan the binds passed through to ExecuteMany() and determine the bind
// type and maximum size (for strings/buffers).
//-----------------------------------------------------------------------------
bool njsConnection::ScanExecuteManyBinds(Local<Array> binds,
Local<Array> bindNames, njsBaton *baton)
{
njsDataType defaultBindType;
uint32_t defaultMaxSize;
bool byPosition;
Nan::HandleScope scope;
Local<Array> byPositionValues;
Local<Value> bindName, val;
Local<Object> row;