-
Notifications
You must be signed in to change notification settings - Fork 8
/
EXADBI.R
1607 lines (1449 loc) · 50.7 KB
/
EXADBI.R
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
#' @include EXADBI-internal.R
#' @include exa.readData.R
#' @include exa.writeData.R
#' @include exa.createScript.R
#'
## These are the DBI related classes and methods, which work as an abstraction layer over the basic
## exa functions and provide compabibility to the DBI package. The structure may also serve as a
## foundation for a later implemntation of a proprietary CLI interface that does not depend on RODBC.
##
## First version written in 2015 by Marcel Boldt <marcel.boldt@exasol.com>
## as part of the EXASOL R interface & SDK package. It may be used, changed and distributed freely
## with no further restrictions than already stipulated in the package license, with the exception
## that this statement must stay included and unchanged.
#' @export dbDriver
#' @export dbUnloadDriver
#' @export dbConnect
#' @export dbListConnections
#' @export dbDisconnect
#' @export dbSendQuery
#' @export dbGetQuery
#' @export dbGetException
#' @export dbListResults
#' @export dbListFields
#' @export dbListTables
#' @export dbReadTable
#' @export dbWriteTable
#' @export dbExistsTable
#' @export dbRemoveTable
#' @export dbBegin
#' @export dbCommit
#' @export dbRollback
#' @export dbFetch
#' @export dbClearResult
#' @export dbColumnInfo
#' @export dbGetStatement
#' @export dbHasCompleted
#' @export dbGetRowsAffected
#' @export dbGetRowCount
NULL
# Class definitions ------------------------------------------------------------
#' EXAObject class.
#'
#' The virtual object constituting a basis to all other EXA DBI Objects.
#' @seealso \code{\link{DBIObject-class}}
#' @family DBI classes
#'
#' @docType class
setClass("EXAObject", contains = c("DBIObject", "VIRTUAL"))
#' Returns metadata on a given EXAObject.
#' @name dbGetInfo
#'
#' @param dbObj An EXAObject.
#' @return A named list.
#' @export
setMethod(
"dbGetInfo", "EXAObject",
definition = function(dbObj) {
return("EXASOL DBI Object.")
}
)
setMethod(
"summary", "EXAObject",
definition = function(object, ...) {
NextMethod(generic = "summary", object, ...)
}
)
# the S3 class RODBC will be registered as a superclass of EXAConnection
setOldClass("RODBC")
#' An interface driver object to the EXASOL Database.
#'
#' @seealso \code{\link{DBIDriver-class}}
#' @family DBI classes
#' @family EXADriver related objects
#' @slot driver A string containing the path to the EXASOL ODBC driver file.
setClass("EXADriver",
contains = c("DBIDriver", "EXAObject"),
slots = c(odbc_drv = "character")
)
# Instantiates an EXADriver object.
# @family EXADriver related objects
# @param driver The path to an ODBC driver file. If missing, the driver contained in the exasol package
# is used if possible, otherwise the driver installed on the system is used.
# If "SYSTEM": the EXASOL ODBC driver installed on the system is used immediately.
# Alternatively a path to an ODBC driver library can be provided.
# @param silent If TRUE, no message is print.
# @return An EXADriver object.
exasol <- function(driver = NULL, silent = FALSE) {
#TODO: determine driver file according to OS
# path.package("exasol")
if(missing(driver) | is.null(driver)) {
if (!silent) print("Using the included driver...")
driver <- file.path(
switch(
Sys.info()['sysname'],
'Darwin' = paste0(system.file(package = packageName()),
'/odbc/lib/darwin/x86_64/libexaodbc-io418sys.dylib'
), # Mac OS
'Linux' = paste0(system.file(package = packageName()),
'/odbc/lib/linux/x86_64/libexaodbc-uo2214lv1.so'
), # Linux
"{EXASolution Driver}" # default
)
)
} else if (driver =="SYSTEM") {
if(!silent) print("Using the system driver...")
driver <- "{EXASolution Driver}"
} else {
if (!silent) print(paste("Using the driver at", driver))
}
if (!silent) print("EXASOL driver loaded")
new("EXADriver", odbc_drv = driver)
}
exa <- exasol # define an alias
#TODO: set method dbDriver
setMethod(
"summary", "EXADriver",
definition = function(object, ...)
NextMethod(generic = "summary", object,...)
)
setMethod(
"dbGetInfo", "EXADriver",
definition = function(dbObj) {
list(
driver.version = packageVersion("exasol"),
max.connections = 999,
DBI.version = packageVersion("DBI"),
RODBC.version = packageVersion("RODBC"),
client.version = R.Version()$version.string
)
}
)
#' An Object holding a connection to an EXASOL Database.
#'
#' @seealso \code{\link{DBIConnection-class}}
#' @family DBI classes
#' @family EXAConnection related objects
#'
#' @slot init_connection_string A string containing the ODBC connection sting used to
#' initialise the connection.
#' @slot current_schema A string reflecting the current schema.
#' @slot autocom_default A logical indicating if autocommit is active.
#' @slot db_host A string containing the hostname or IP.
#' @slot db_port An integer containing the connection port.
#' @slot db_user A string containing the DB user name.
#' @slot db_name A string containing the database name.
#' @slot db_prod_name A string containing the database product name.
#' @slot db_version A string containing the database version.
#' @slot drv_name A string containing the connection driver version.
#' @slot connection.string RODBC
#' @slot handle_ptr RODBC
#' @slot case RODBC
#' @slot id RODBC
#' @slot believedNRows RODBC
#' @slot colQuote RODBC
#' @slot tabQuote RODBC
#' @slot encoding RODBC
#' @slot rows_at_time RODBC
#' @export
EXAConnection <- setClass(
"EXAConnection",
slots = c(
init_connection_string = "character",
current_schema = "character",
autocom_default = "logical",
db_host = "character",
db_port = "numeric",
db_user = "character",
db_name = "character",
db_prod_name = "character",
db_version = "character",
drv_name = "character"
),
contains = c("DBIConnection", "EXAObject", "RODBC")
)
# db.version, dbname, username, host, port
setMethod(
"dbGetInfo","EXAConnection",
definition = function(dbObj) {
if (!dbIsValid(dbObj)) {
stop("Connection exipired.")
}
list(
db.version = paste(dbObj@db_prod_name, dbObj@db_version),
dbname = dbObj@db_name,
username = dbObj@db_user,
host = dbObj@db_host,
port = dbObj@db_port
)
}
)
setMethod(
"summary", "EXAConnection",
definition = function(object, ...) {
NextMethod(generic = "summary", object,...)
}
)
#' An object that is associated with a result set in an EXASOL Database.
#'
#' The result set is persisted
#' in a DB table, which is dropped when the object is deleted in R (on garbage collection), or manually by
#' `dbClearResult()'. R versions before 3.3.0 do not finalise objects on R exit, so if R is quit with an
#' active EXAResult object, the table may stay in the DB.
#'
#' @seealso \code{\link{DBIResult-class}}
#' @family DBI classes
#' @family EXAResult related objects
#'
#' @field connection An EXAConnection object.
#' @field statement A string containing the SQL query statement.
#' @field rows_fetched An int reflecting the rows already fetched from the DB.
#' @field rows_affected An int reflecting the length of the dataset in the DB.
#' @field is_complete A logical indcating if the result set has been entirely fetched.
#' @field with_output A logical indicating whether the query produced a result set.
#' @field profile A data.frame containing profile information on the query.
#' @field columns A data.frame containing column metadata.
#' @field temp_result_tbl A string reflecting the name of the (temporary) table that holds the result set.
#' @field query_sent_time A POSIXct timestamp indicating when the query was sent to the DB.
#' @field errors A character vector containing errors.
#' @field default_fetch_rec An int reflecting the default fetch size.
#' @export
EXAResult <- setRefClass(
"EXAResult",
fields = c(
connection = "EXAConnection",
statement = "character",
rows_fetched = "numeric",
rows_affected = "numeric",
is_complete = "logical",
with_output = "logical",
profile = "data.frame",
columns = "data.frame",
temp_result_tbl = "character",
query_sent_time = "POSIXct",
errors = "character",
default_fetch_rec = "numeric"
),
contains = c("DBIResult", "EXAObject"),
methods = list(
refreshMetaData = function(x) {
"Refreshes the object's metadata."
print("TODO: not yet implemented.")
},
addRowsFetched = function(x) {
"Add an int (the length of a newly fetched result set) to rows_fetched."
rows_fetched <<- rows_fetched + as.numeric(x)
},
# close = function(commit=TRUE) { # dbClearResult is in row 880
# "Frees up all resources, in particular drops the temporary table in the DB."
#
# if (!dbIsValid(.self)) {
# warning("Connection seems exipired.\n ...it's gone...")
# return(FALSE)
# }
#
# if(odbcEndTran(connection, commit)==0) {
# if(commit) message("Changes commited.")
# } else stop("Commit failed. Changes NOT commited. Closing aborted.")
# message("Closing connection...")
# res <- try(odbcClose(connection),silent=TRUE)
# if(res==1) {
# message("Connection closed.")
# return(TRUE)
# } else if(res==0) {
# warning("Closing not successful.")
# return(FALSE)
# } else {
# warning(res)
# return(FALSE)
# }
# },
finalize = function(...) {
#close()
if(dbClearResult(.self)) message("Table dropped in EXASOL DB.") else warning("Table not dropped in EXASOL DB")
message("EXAResult object disposed.")
}
)
)
setMethod(
"dbGetInfo","EXAResult",
definition = function(dbObj) {
if(dbObj$temp_result_tbl == "CLEARED") stop("GetInfo: Result set cleared.")
list(
statement = dbObj$statement,
row.count = dbObj$rows_fetched,
rows.affected = dbObj$rows_affected,
has.completed = dbObj$is_complete,
is.select = dbObj$with_output
)
}
)
setMethod(
"dbHasCompleted", signature("EXAResult"),
definition = function(res) {
if(res$temp_result_tbl == "CLEARED") stop("GetInfo: Result set cleared.");
return(res$is_complete);
}
)
setMethod(
"summary", "EXAResult",
definition = function(object, ...) {
NextMethod(generic = "summary", object,...)
}
)
setMethod("dbGetRowsAffected", signature("EXAResult"), function(res) {
return(res$rows_affected)
})
#' Checks if an EXAObject is still valid.
#'
#' @name dbIsValid
#' @param conn An object that inherits EXAObject.
#' @return A logical indicating if the connection still works.
setMethod(
"dbIsValid", signature("EXAObject"),
definition = function(dbObj) {
return(TRUE) # TODO
}
)
#' Determine the EXASOL data type of an object.
#'
#'@seealso \code{\link{dbDataType,DBIObject-method}}
#' @export
#' @name dbDataType
setMethod("dbDataType", "EXAObject", function(dbObj, obj, ...) {
if(any(class(obj) %in% c("factor", "data.frame")))
EXADataType(obj)
else
EXADataType(unclass(obj))
})
setGeneric("EXADataType", function(x)
standardGeneric("EXADataType"))
setMethod("EXADataType", "data.frame", function(x) {
vapply(x, EXADataType, FUN.VALUE = character(1), USE.NAMES = FALSE)
})
setMethod("EXADataType", "integer", function(x)
"INT")
setMethod("EXADataType", "numeric", function(x)
"DECIMAL(36,15)")
setMethod("EXADataType", "logical", function(x)
"BOOLEAN")
setMethod("EXADataType", "Date", function(x)
"DATE")
setMethod("EXADataType", "POSIXct", function(x)
"TIMESTAMP")
varchar <- function(x) {
paste0("VARCHAR(", max(nchar(as.character(x)), na.rm=TRUE), ")")
}
setMethod("EXADataType", "character", varchar)
setMethod("EXADataType", "factor", varchar)
setMethod("EXADataType", "list", function(x) {
vapply(x, EXADataType, FUN.VALUE = character(1), USE.NAMES = FALSE)
})
setMethod("EXADataType", "raw", varchar)
#setOldClass("AsIs")
#setMethod("EXADataType", "ANY", definition=function(x) EXADataType(unclass(x)))
setMethod("EXADataType", "ANY", function(x) {
warning(paste("Unrecognised datatype:", x, "Trying to convert to varchar."))
varchar(x)
})
setMethod(
"dbListConnections", "EXADriver",
definition = function(drv, ...)
dbGetInfo(drv, "connectionIds")[[1]]
)
# Connection -------------------------------------------------------------------
#' Creates a connection to an EXASOL Database.
#'
#' @family EXADriver related objects
#' @family EXAConnection related objects
#'
#' @name dbConnect
#' @param drv An EXAdriver object, a character string "exasol" or "exa", or an
#' existing EXAConnection object (for connection cloning).
#' @param exahost DNS or IP (or range of IPs) and port of the database cluster,
#' e.g. '10.0.2.15..20:8563'
#' @param uid DB username, e.g. 'sys'
#' @param pwd DB user password, e.g. 'exasol'
#' @param schema Schema in EXASOL db which is opened directly after the
#' connection.
#' @param exalogfile the EXASOL odbc driver log file. By standard a tempfile is
#' created. Log data may be accessed with 'EXAlog(EXAConnection)'.
#' @param logmode EXASOL ODBC driver log mode. Allowed options are:
#' \describe{
#' \item{NONE}{no log is written (default)}
#' \item{DEFAULT}{most important function calls & SQL commands}
#' \item{VERBOSE}{also additional data about internal steps & result data}
#' \item{ON ERROR ONLY}{only errors are logged}
#' \item{DEBUGCOMM}{extended logs, similar to verbose but w/o data & parameter
#' tables}
#' }
#' @param encryption ODBC encryption. By default off. Switch on with 'Y'.
#' @param autocommit By default 'Y'. If Y' each SQL statement is committed. 'N'
#' means that no commits are executed automatically. The transaction will be
#' rolled back on disconnect, which causes the loss of all data written during
#' the transaction.
#' @param querytimeout Time EXASOL DB computes a query before it is aborted.
#' The default \code{'0'} (zero) means no timeout, i.e. runs until finished.
#' @param connectionlcctype Sets the connection locale \code{LC CTYPE}.
#' The default is the setting of the client's current R session.
#' @param connectionlcnumeric Sets the connection locale \code{LC NUMERIC}.
#' The default is the setting of the client's current R session.
#' @param encoding The connection encoding. TODO.
#' @param ... Additional parameters to the connection string. If a connection is
#' cloned, these override the old connection settings.
#' @param dsn A preconfigured ODBC Data Source Name. Parameter being evaluated
#' with priority to \code{EXAHOST}.
#' @param connection_string alternatively to everything else, a custom ODBC
#' connection sting can be provided. See EXASOL DB manual secion 4.2.5 for
#' details, available at \url{https://www.exasol.com/portal}.
#' @return A fresh EXAConnection object.
#' @examples \dontrun{
#' con <- dbConnect("exa", dsn = "EXASolo")
#' con <- dbConnect("exa", exahost = "212.209.123.20..25:8563",
#' uid = "peter", pwd = "password123", schema = "sales")
#' }
setMethod(
"dbConnect", "EXADriver",
definition = function(drv, # change defaults also below
exahost = "",
uid = "",
pwd = "",
schema = "SYS",
exalogfile = tempfile(pattern = "EXAODBC_", fileext = ".log"),
logmode = "NONE",
encryption = "N",
autocommit = "Y",
querytimeout = "0",
connectionlcctype = Sys.getlocale(category = "LC_CTYPE"),
connectionlcnumeric = Sys.getlocale(category = "LC_NUMERIC"),
...,
dsn = "",
connection_string = "")
{
EXANewConnection(
drv = drv,
exahost = exahost,
uid = uid,
pwd = pwd,
schema = schema,
exalogfile = exalogfile,
logmode = logmode,
encryption = encryption,
autocommit = autocommit,
querytimeout = querytimeout,
connectionlcctype = connectionlcctype,
connectionlcnumeric = connectionlcnumeric,
... = ...,
dsn = dsn,
connection_string = connection_string
)
},
valueClass = "EXAConnection"
)
# @family EXADriver related objects
# @family EXAConnection related objects
#
# @inheritParams dbConnect
setMethod(
"dbConnect", "character",
definition = function(drv, ...)
EXANewConnection(drv = dbDriver(drv), ...),
valueClass = "EXAConnection"
)
# @family EXADriver related objects
# @family EXAConnection related objects
#
# @inheritParams dbConnect
setMethod(
"dbConnect", "EXAConnection",
definition = function(drv, ...)
EXACloneConnection(drv, ...),
valueClass = "EXAConnection"
)
#' Fetches and outputs the current schema from an EXASOL DB. Also updates EXAConnection metadata.
#' @family EXAConnection related objects
#'
#' @name dbCurrentSchema
#' @param con a valid EXAConnection
#' @return an updated EXAConnection
#' @export
dbCurrentSchema <- function(con, setSchema=NULL) {
if(!missing(setSchema)) {
sqlQuery(con, paste("open schema", processIDs(setSchema)))
con@current_schema <- setSchema
} else {
res <- sqlQuery(con, "select current_schema")
con@current_schema <- as.character(res[1,1])
}
message(paste("Schema: ", con@current_schema))
con
}
EXANewConnection <- function(# change defaults also above
drv,
exahost = "",
uid = "",
pwd = "",
schema = "SYS",
exalogfile = tempfile(pattern = "EXAODBC_", fileext = ".log"),
logmode = "NONE",
encryption = "N",
autocommit = "Y",
querytimeout = "0",
connectionlcctype = Sys.getlocale(category = "LC_CTYPE"),
connectionlcnumeric = Sys.getlocale(category = "LC_NUMERIC"),
...,
dsn = "",
connection_string = "") {
exaschema <- c(schema)
if (connection_string != "") {
con_str <- connection_string
}
else {
if (dsn != "") {
con_str <- paste0("DSN=",dsn)
}
else if (exahost != "" & uid != "") {
con_str <- paste0("DRIVER=", drv@odbc_drv ,";", "EXAHOST=",exahost)
}
else {
stop(
"Connect failed. Either DSN, host & db_user or a connection string must be given.\n
Hint: No lazy declaration of connection parameters - these have to be stated ' dsn=...'.\n
See also the examples in the help ('?dbConnect')."
)
}
# all additional parameters...
if (uid != "") {
con_str <- paste0(con_str,";UID=",uid,";PWD=",pwd)
}
# EXASCHEMA
if (exaschema != "SYS") {
con_str <- paste0(con_str,";EXASCHEMA=",exaschema)
}
# EXALOGFILE
con_str <- paste0(con_str,";EXALOGFILE=",exalogfile)
# LOGMODE
con_str <- paste0(con_str,";LOGMODE=",logmode)
# locale
con_str <-
paste0(
con_str,";CONNECTIONLCCTYPE=",connectionlcctype,";CONNECTIONLCNUMERIC=",connectionlcnumeric
)
# autocommit
con_str <- paste0(con_str,";autocommit=",autocommit)
# dots
d <- list(...)
while (length(d) > 0) {
con_str <- paste0(con_str,";", names(d[1]),"=",d[1])
d[1] <- NULL
}
}
con <- odbcDriverConnect(con_str)
exa_metadata <- odbcGetInfo(con)
new(
"EXAConnection",init_connection_string = con_str,
current_schema = exaschema,
autocom_default = ifelse(autocommit == "Y",TRUE,FALSE),
db_host = strsplit(exa_metadata["Server_Name"],":")[[1]][1],
db_port = as.numeric(strsplit(exa_metadata["Server_Name"],":")[[1]][2]),
db_user = substring(
regmatches(
attributes(con)$connection.string, gregexpr("UID=[\\w]+?;", attributes(con)$connection.string,perl =
TRUE)
)[[1]],
5,
nchar(regmatches(
attributes(con)$connection.string, gregexpr("UID=[\\w]+?;", attributes(con)$connection.string,perl =
TRUE)
)[[1]]) - 1
),
db_name = exa_metadata["Data_Source_name"],
db_prod_name = exa_metadata["DBMS_Name"],
db_version = exa_metadata["DBMS_Ver"],
drv_name = exa_metadata["Driver_Name"],
con
)
}
# Opens a new connection with the same settings as an existing one.
# @family EXADriver related objects
# @family EXAConnection related objects
#
# @param drv an EXAConnection object to be dublicated.
# @param ... additional connection string parameter that may override the old settings.
# @return a fresh EXAConnection
EXACloneConnection <-
function(drv, autocommit, ...) {
# todo: parameters
drv <- dbCurrentSchema(drv) # update schema metadata
# dots
d <- data.frame(...,stringsAsFactors = FALSE)
names(d) <- toupper(names(d))
con_str <- drv@init_connection_string
s <- strsplit(con_str, ";")
s <- sapply(s, strsplit, "=")
s <- lapply(s, function(x)
toupper(x))
con_str <- ""
while (length(s) > 0) {
# as long as there is at least one parameter in S
if (is.null(d[[s[[1]][1]]])) {
# if the first parameter of s (S is the conn_str) is not in d (the dots
# parameters)
con_str <-
paste0(con_str, ";", s[[1]][1],"=", s[[1]][2]) # take the s parameter
s[1] <- NULL # delete the first parameter from S
} else {
# else take the value out of d, delete the parameter from d, then
# delete the first S parameter
con_str <-
paste0(con_str, ";", s[[1]][1], "=", d[[s[[1]][1]]])
d[[s[[1]][1]]] <- NULL
s[1] <- NULL
}
} # add the remaining dots parameters
while (ncol(d) > 0) {
con_str <- paste0(con_str, ";", names(d)[1], "=", d[[1]])
d[1] <- NULL
}
con_str <-
substr(con_str,2,nchar(con_str)) # remove the initial semicolon
con <- odbcDriverConnect(con_str)
if (con == -1) {
stop(
paste(
"EXACloneConnection error: failed to initialise connection.\nConnection String:", con_str
)
)
}
exa_metadata <- odbcGetInfo(con)
new(
"EXAConnection",
init_connection_string = con_str,
current_schema = drv@current_schema,
autocom_default = ifelse(
!missing(autocommit),ifelse(autocommit == "Y",TRUE,FALSE),drv@autocom_default
),
db_host = strsplit(exa_metadata["Server_Name"],":")[[1]][1],
db_port = as.numeric(strsplit(exa_metadata["Server_Name"],":")[[1]][2]),
db_user = substring(
regmatches(
attributes(con)$connection.string, gregexpr("UID=[\\w]+?;", attributes(con)$connection.string,perl =
TRUE)
)[[1]],
5,
nchar(regmatches(
attributes(con)$connection.string, gregexpr("UID=[\\w]+?;", attributes(con)$connection.string,perl =
TRUE)
)[[1]]) - 1
),
db_name = exa_metadata["Data_Source_name"],
db_prod_name = exa_metadata["DBMS_Name"],
db_version = exa_metadata["DBMS_Ver"],
drv_name = exa_metadata["Driver_Name"],
con
)
}
#' Sends a commit.
#'
#' @family EXAConnection related objects
#' @family transaction management functions
#'
#' @name dbCommit
#' @param conn An EXAConnection object
#' @return a logical indicating success.
setMethod("dbCommit", signature("EXAConnection"),
function(conn, silent = FALSE) {
switch(as.character(odbcEndTran(conn,commit = TRUE)),
"-1" = {
stop(paste0("Commit failed:\n",odbcGetErrMsg(conn)));return(FALSE)
},
"0" = {
if (!silent) message("Transaction committed.");return(TRUE)
},
{
print("Commit failed.")
stop(odbcGetErrMsg(conn))
return(FALSE)
})
})
#' Rolls the current DB transaction back.
#'
#' @family EXAConnection related objects
#' @family transaction management functions
#'
#' @name dbRollback
#' @param conn An EXAConnection object
#' @return a logical indicating success.
setMethod("dbRollback", signature("EXAConnection"),
function(conn) {
switch(as.character(odbcEndTran(conn,commit = FALSE)),
"-1" = {
stop(paste0("Rollback failed:\n", odbcGetErrMsg(conn)))
return(FALSE)
},
"0" = {
message("Transaction rolled back.")
return(TRUE)
},
{
print("Rollback failed.")
stop(odbcGetErrMsg(conn))
return(FALSE) # this line gets never executed
})
})
#' Starts a DB transaction. In EXASOL, it disables autocommit.
#'
#' @family EXAConnection related objects
#' @family transaction management functions
#'
#' @name dbBegin
#' @param conn An EXAConnection object
#' @return a logical indicating success.
setMethod("dbBegin", signature("EXAConnection"),
function(conn) {
odbcSetAutoCommit(conn, autoCommit = FALSE)
#message("Transaction started.")
return(TRUE)
})
#' Ends a DB transaction. In EXASOL, it commits and reinstates the connection's standard autocommit mode.
#' This is an EXASOL specific addition to the DBI interface and may not work with other RDBMS.
#'
#' @family EXAConnection related objects
#' @family transaction management functions
#'
#' @name dbEnd
#' @param conn An EXAConnection object
#' @param commit Logical. on TRUE the transaction is commmitted, otherwise rolled back.
#' @return a logical indicating success.
#' @export
setGeneric(
"dbEnd",
def = function(conn,...)
standardGeneric("dbEnd"),
valueClass = "logical"
)
setMethod("dbEnd", signature("EXAConnection"),
function(conn,commit = TRUE, silent = FALSE) {
ifelse(commit, dbCommit(conn, silent = silent), dbRollback(conn))
odbcSetAutoCommit(conn, autoCommit = conn@autocom_default)
# message("Transaction completed.")
return(TRUE)
})
#' Disconnects the connection.
#'
#' @name dbDisconnect
#' @param conn An EXAConnection object.
#' @return A logical indicating success.
setMethod(
"dbDisconnect",signature("EXAConnection"),
definition = function(conn) {
odbcClose(conn)
}
)
# Querying & Result ------------------------------------------------------------
#' Sends an SQL statment to an EXASOL DB, prepares for result fetching.
#' @family EXAConnection related objects
#' @family DQL functions
#'
#' @name dbSendQuery
#' @param conn A valid EXAConnection
#' @param statement vector mode character : an SQL statement to be executed in EXASOL db
#' @param schema vector mode character : a focus schema. This must have write access for the result
#' set to be temporarily stored. If the user has only read permission on the schema to be read,
#' another schema may be entered here, and table identifiers in stmt parameter must be
#' fully qualified (schema.table).
#' @param profile logical, default TRUE : collect profiling information
#' @param default_fetch_req numeric, default 100 :
#' @param ... additional parameters to be passed on to dbConnect (used to clone the connection to
#' one without autocommit)
#' @return EXAResult object which can be used for fetching rows. It also contains metadata.
setMethod(
"dbSendQuery",
signature(conn = "EXAConnection", statement = "character"),
definition = function(conn,
statement,
schema = "",
profile = TRUE,
default_fetch_rec = 100,
...)
EXAExecStatement(
con = conn,
stmt = statement,
schema = schema,
profile = profile,
default_fetch_rec = default_fetch_rec,
... = ...
),
valueClass = "EXAResult"
)
isSelectStatement <-
function(statement) {
return(grepl("^\\s*(\\/\\*.*\\*\\/)?\\s*(WITH.*)?SELECT",toupper(statement),perl=TRUE))
}
EXAExecStatement <-
function(con, stmt, schema = "", profile = TRUE, default_fetch_rec = 100, ...) {
if (isSelectStatement(stmt)){
stmt_cmd <- "SELECT"
} else {
stmt_cmd <- "NOSELECT"
}
qtime <- Sys.time()
err <- vector(mode = "character")
if (profile) {
err <- append(err,sqlQuery(con, "alter session set profile='ON'"))
}
dbBegin(con)
on.exit(dbEnd(con,commit = FALSE))
if (stmt_cmd == "SELECT") {# ---------------if select ----------------------------------------
temp_schema <- FALSE
tbl_name <-
paste0("TEMP_",floor(rnorm(1,1000,100) ^ 2),"_CREATED_BY_R")
# con <- dbConnect(con, autocommit="N",...) # clone the connection with autocommit=off
ids <- EXAGetIdentifier(stmt, statement = TRUE)
if (schema == "") {
# try to grep schema from stmt
if (length(ids)>0) schema <- ids[[length(ids)]][1]
if (schema != "" & schema != "\"\"") {
message(paste("Using Schema from statement:", schema))
} else {
if (con@current_schema != "SYS") {
message(paste("Using connection schema: ", con@current_schema))
schema <- con@current_schema
}
}
}
if (schema == "" || schema == "\"\"") {
# if nothing helps use temp_schema
schema <- tbl_name
temp_schema <- TRUE
err <- append(err, paste("Using temporary schema:", schema))
message(paste("Using temporary schema:", schema))
}
schema <- processIDs(schema)
if (temp_schema)
err <- append(err, sqlQuery(con, paste("create schema", schema)))
sq1 <- paste0("create table ", schema, ".", tbl_name," as (", stmt, ")")
#print(paste("-sql: ", sq1, " -END"))
errr <-
try(sqlQuery(con, sq1, errors = FALSE))
# on success this won't return anything
# dbCommit(con)
if (errr == -1) {
warning(odbcGetErrMsg(con))
err <- append(err, odbcGetErrMsg(con))
} else {
dbEnd(con, commit = TRUE)
# on.exit(dbEnd(con, commit = TRUE)) # commit after select in order to store indices that may have been created.
}
} else {
# if NOT SELECT ------------------
#
if (schema != "") {
schema <- processIDs(schema)
err1 <-
try(sqlQuery(con, paste("open schema", schema), errors = FALSE))
if (err1 == -1) {
# schema cannot be opened
warning(paste("Schema cannot be opened:", schema,"\n",err1))
err <- append(err, odbcGetErrMsg(con))
}
}
err2 <- try(sqlQuery(con, stmt, errors = FALSE))
if (err2 == -1) {
err <- append(err, odbcGetErrMsg(con))
stop(paste("Query failed.\n", odbcGetErrMsg(con)))
} else {
#on.exit(
dbEnd(con,commit = TRUE)
#)
}
}
sqlQuery(con,"flush statistics")
if (stmt_cmd == "SELECT") {
rc <- try(sqlQuery(con, paste0("select count(*) from ", schema, ".", tbl_name))[1,1], silent = TRUE)
rowcount <- ifelse(is.numeric(rc), rc, 0)
} else rowcount <- 0
p <- exa.readData(
con, "select
session_id,
stmt_id,
part_id,
command_name,
object_name,
object_rows,
duration,
cpu,
temp_db_ram_peak,
hdd_read,
net
from exa_user_profile_last_day
where session_id = current_session and stmt_id=current_statement-4
order by part_id desc"
) # current_statement: -2 if autocommit=N, otherwise -4, -3 if dbCommit (all +1 due to rowcount)