-
Notifications
You must be signed in to change notification settings - Fork 154
/
SnowflakeStatementV1.java
793 lines (649 loc) · 18.2 KB
/
SnowflakeStatementV1.java
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
/*
* Copyright (c) 2012-2017 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.client.jdbc;
import net.snowflake.client.core.ParameterBindingDTO;
import net.snowflake.client.core.ResultUtil;
import net.snowflake.client.core.SFBaseResultSet;
import net.snowflake.client.core.SFException;
import net.snowflake.client.core.SFStatement;
import java.sql.BatchUpdateException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.Map;
import net.snowflake.client.core.StmtUtil;
import net.snowflake.client.log.SFLogger;
import net.snowflake.client.log.SFLoggerFactory;
/**
* Snowflake statement
*
* @author jhuang
*/
class SnowflakeStatementV1 implements Statement
{
static final SFLogger logger = SFLoggerFactory.getLogger(SnowflakeStatementV1.class);
protected SnowflakeConnectionV1 connection;
/*
* The maximum number of rows this statement ( should return (0 => all rows).
*/
private int maxRows = 0;
private ResultSet resultSet = null;
private ResultSet currentResultSet = null;
private int fetchSize = 50;
private Boolean isClosed = false;
private int updateCount = -1;
// TODO: escape processing for sql statement
private boolean escapeProcessing = false;
// timeout in seconds
private int queryTimeout = 0;
// max field size limited to 16MB
private final int maxFieldSize = 16777216;
protected SFStatement sfStatement;
/** batch of sql strings added by addBatch */
protected final List<BatchEntry> batch = new ArrayList<>();
protected SQLWarning sqlWarnings;
SnowflakeStatementV1(SnowflakeConnectionV1 conn)
{
logger.debug(
" public SnowflakeStatement(SnowflakeConnectionV1 conn)");
connection = conn;
sfStatement = new SFStatement(conn.getSfSession());
}
/**
* Execute SQL query
*
* @param sql sql statement
* @return ResultSet
* @throws java.sql.SQLException if @link{#executeQueryInternal(String, Map)} throws an exception
*/
@Override
public ResultSet executeQuery(String sql) throws SQLException
{
return executeQueryInternal(sql, null);
}
/**
* Execute an update statement
*
* @param sql sql statement
* @return number of rows updated
* @throws java.sql.SQLException if @link{#executeUpdateInternal(String, Map)} throws exception
*/
@Override
public int executeUpdate(String sql) throws SQLException
{
return executeUpdateInternal(sql, null);
}
int executeUpdateInternal(String sql,
Map<String, ParameterBindingDTO> parameterBindings)
throws SQLException
{
if (StmtUtil.checkStageManageCommand(sql) != null)
{
throw new SnowflakeSQLException(ErrorCode.
UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API,
sql.length() > 20 ? sql.substring(0, 20) + "..." : sql);
}
SFBaseResultSet sfResultSet = null;
try
{
sfResultSet = sfStatement.execute(sql, parameterBindings);
sfResultSet.setSession(this.connection.getSfSession());
updateCount = ResultUtil.calculateUpdateCount(sfResultSet);
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex.getCause(),
ex.getSqlState(), ex.getVendorCode(), ex.getParams());
}
if (updateCount == -1)
{
throw new SnowflakeSQLException(ErrorCode.
UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API,
sql.length() > 20 ? sql.substring(0, 20) + "..." : sql);
}
return updateCount;
}
/**
* Internal method for executing a query with bindings accepted.
*
* @param sql sql statement
* @param parameterBindings parameters bindings
* @return query result set
* @throws SQLException if @link{SFStatement.execute(String)} throws exception
*/
ResultSet executeQueryInternal(
String sql,
Map<String, ParameterBindingDTO> parameterBindings)
throws SQLException
{
SFBaseResultSet sfResultSet = null;
try
{
sfResultSet = sfStatement.execute(sql, parameterBindings);
sfResultSet.setSession(this.connection.getSfSession());
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex.getCause(),
ex.getSqlState(), ex.getVendorCode(), ex.getParams());
}
currentResultSet = null;
resultSet = new SnowflakeResultSetV1(sfResultSet, this);
// Fix a bug with getMoreResults returning true after a client
// calling executeQuery which has returned the result set already
return getResultSet();
}
/**
* Execute sql
*
* @param sql sql statement
* @return whether there is result set or not
* @throws java.sql.SQLException if @link{#executeQuery(String)} throws exception
*/
boolean executeInternal(String sql,
Map<String, ParameterBindingDTO> parameterBindings)
throws SQLException
{
connection.injectedDelay();
logger.debug("execute: " + sql);
String trimmedSql = sql.trim();
if (trimmedSql.length() >= 20
&& trimmedSql.toLowerCase().startsWith(
"set-sf-property"))
{
executeSetProperty(sql);
return false;
}
else
{
SFBaseResultSet sfResultSet = null;
try
{
sfResultSet = sfStatement.execute(sql, parameterBindings);
sfResultSet.setSession(this.connection.getSfSession());
currentResultSet = null;
resultSet = new SnowflakeResultSetV1(sfResultSet, this);
if (connection.getSfSession().isExecuteReturnCountForDML() &&
!sfResultSet.getStatementType().isGenerateResultSet())
{
updateCount = ResultUtil.calculateUpdateCount(sfResultSet);
resultSet = null;
currentResultSet = null;
return false;
}
updateCount = -1;
return true;
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex.getCause(),
ex.getSqlState(), ex.getVendorCode(), ex.getParams());
}
}
}
/**
* Execute sql
*
* @param sql sql statement
* @return whether there is result set or not
* @throws java.sql.SQLException if @link{#executeQuery(String)} throws exception
*/
@Override
public boolean execute(String sql) throws SQLException
{
return executeInternal(sql, null);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys)
throws SQLException
{
logger.debug(
"public int execute(String sql, int autoGeneratedKeys)");
if (autoGeneratedKeys == Statement.NO_GENERATED_KEYS)
{
return execute(sql);
}
else
{
throw new SQLFeatureNotSupportedException();
}
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException
{
logger.debug(
"public boolean execute(String sql, int[] columnIndexes)");
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException
{
logger.debug(
"public boolean execute(String sql, String[] columnNames)");
throw new SQLFeatureNotSupportedException();
}
/**
* Batch Execute. If one of the commands in the batch failed, JDBC will
* continuing processing and throw BatchUpdateException after all commands
* are processed.
* @return
* @throws SQLException
*/
@Override
public int[] executeBatch() throws SQLException
{
logger.debug("public int[] executeBatch()");
return executeBatchInternal();
}
/**
* This method will iterate through batch and provide sql and bindings to
* underlying SFStatement to get result set.
*
* Note, array binds use a different code path since only one network
* roundtrip in the array bind execution case.
*
* @return
* @throws SQLException
*/
int[] executeBatchInternal() throws SQLException
{
if (isClosed)
{
throw new SnowflakeSQLException(ErrorCode.STATEMENT_CLOSED);
}
SQLException exceptionReturned = null;
int updateCounts[] = new int[batch.size()];
for (int i=0; i<batch.size(); i++)
{
try
{
updateCounts[i] = this.executeUpdateInternal(
batch.get(i).getSql(), batch.get(i).getParameterBindings());
}
catch(SQLException e)
{
exceptionReturned = exceptionReturned == null ? e : exceptionReturned;
updateCounts[i] = EXECUTE_FAILED;
}
}
if (exceptionReturned != null)
{
throw new BatchUpdateException(exceptionReturned.getLocalizedMessage(),
exceptionReturned.getSQLState(),
exceptionReturned.getErrorCode(),
updateCounts,
exceptionReturned);
}
return updateCounts;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys)
throws SQLException
{
logger.debug(
"public int executeUpdate(String sql, int autoGeneratedKeys)");
if (autoGeneratedKeys == Statement.NO_GENERATED_KEYS)
{
return executeUpdate(sql);
}
else
{
throw new SQLFeatureNotSupportedException();
}
}
@Override
public int executeUpdate(String sql, int[] columnIndexes)
throws SQLException
{
logger.debug(
"public int executeUpdate(String sql, int[] columnIndexes)");
throw new SQLFeatureNotSupportedException();
}
@Override
public int executeUpdate(String sql, String[] columnNames)
throws SQLException
{
logger.debug(
"public int executeUpdate(String sql, String[] columnNames)");
throw new SQLFeatureNotSupportedException();
}
@Override
public Connection getConnection() throws SQLException
{
logger.debug("public Connection getConnection()");
return connection;
}
@Override
public int getFetchDirection() throws SQLException
{
logger.debug("public int getFetchDirection()");
return ResultSet.FETCH_FORWARD;
}
@Override
public int getFetchSize() throws SQLException
{
logger.debug("public int getFetchSize()");
return fetchSize;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException
{
logger.debug("public ResultSet getGeneratedKeys()");
throw new SQLFeatureNotSupportedException();
}
@Override
public int getMaxFieldSize() throws SQLException
{
logger.debug("public int getMaxFieldSize()");
return maxFieldSize;
}
@Override
public int getMaxRows() throws SQLException
{
logger.debug("public int getMaxRows()");
return maxRows;
}
@Override
public boolean getMoreResults() throws SQLException
{
logger.debug("public boolean getMoreResults()");
if (currentResultSet != null)
{
currentResultSet.close();
currentResultSet = null;
}
if (resultSet != null)
{
currentResultSet = resultSet;
resultSet = null;
return true;
}
return false;
}
@Override
public boolean getMoreResults(int current) throws SQLException
{
logger.debug("public boolean getMoreResults(int current)");
throw new SQLFeatureNotSupportedException();
}
@Override
public int getQueryTimeout() throws SQLException
{
logger.debug("public int getQueryTimeout()");
return this.queryTimeout;
}
@Override
public ResultSet getResultSet() throws SQLException
{
logger.debug("public ResultSet getResultSet()");
if (currentResultSet == null)
{
currentResultSet = resultSet;
resultSet = null;
}
return currentResultSet;
}
@Override
public int getResultSetConcurrency() throws SQLException
{
logger.debug("public int getResultSetConcurrency()");
throw new SQLFeatureNotSupportedException();
}
@Override
public int getResultSetHoldability() throws SQLException
{
logger.debug("public int getResultSetHoldability()");
throw new SQLFeatureNotSupportedException();
}
@Override
public int getResultSetType() throws SQLException
{
logger.debug("public int getResultSetType()");
return ResultSet.TYPE_FORWARD_ONLY;
}
@Override
public int getUpdateCount() throws SQLException
{
logger.debug("public int getUpdateCount()");
return updateCount;
}
@Override
public SQLWarning getWarnings() throws SQLException
{
logger.debug("public SQLWarning getWarnings()");
return sqlWarnings;
}
@Override
public boolean isClosed() throws SQLException
{
logger.debug("public boolean isClosed()");
return isClosed;
}
@Override
public boolean isPoolable() throws SQLException
{
logger.debug("public boolean isPoolable()");
throw new SQLFeatureNotSupportedException();
}
@Override
public void setCursorName(String name) throws SQLException
{
logger.debug("public void setCursorName(String name)");
throw new SQLFeatureNotSupportedException();
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException
{
logger.debug("public void setEscapeProcessing(boolean enable)");
escapeProcessing = true;
}
@Override
public void setFetchDirection(int direction) throws SQLException
{
logger.debug("public void setFetchDirection(int direction)");
if (direction != ResultSet.FETCH_FORWARD)
{
throw new SQLFeatureNotSupportedException();
}
}
@Override
public void setFetchSize(int rows) throws SQLException
{
logger.debug("public void setFetchSize(int rows), rows={}", rows);
fetchSize = rows;
}
@Override
public void setMaxFieldSize(int max) throws SQLException
{
logger.debug("public void setMaxFieldSize(int max)");
throw new SQLFeatureNotSupportedException();
}
@Override
public void setMaxRows(int max) throws SQLException
{
logger.debug("public void setMaxRows(int max)");
this.maxRows = max;
try
{
if (this.sfStatement != null)
this.sfStatement.addProperty("rows_per_resultset", max);
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex.getCause(),
ex.getSqlState(), ex.getVendorCode(), ex.getParams());
}
}
@Override
public void setPoolable(boolean poolable) throws SQLException
{
logger.debug("public void setPoolable(boolean poolable)");
if (poolable)
{
throw new SQLFeatureNotSupportedException();
}
}
@Override
public void setQueryTimeout(int seconds) throws SQLException
{
logger.debug("public void setQueryTimeout(int seconds)");
this.queryTimeout = seconds;
try
{
if (this.sfStatement != null)
this.sfStatement.addProperty("query_timeout", seconds);
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex.getCause(),
ex.getSqlState(), ex.getVendorCode(), ex.getParams());
}
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
logger.debug("public boolean isWrapperFor(Class<?> iface)");
return iface.isInstance(this);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(Class<T> iface) throws SQLException
{
logger.debug("public <T> T unwrap(Class<T> iface)");
if (!iface.isInstance(this))
{
throw new SQLException(
this.getClass().getName() + " not unwrappable from " + iface
.getName());
}
return (T) this;
}
@Override
public void closeOnCompletion() throws SQLException
{
logger.debug("public void closeOnCompletion()");
throw new SQLFeatureNotSupportedException();
}
@Override
public boolean isCloseOnCompletion() throws SQLException
{
logger.debug("public boolean isCloseOnCompletion()");
throw new SQLFeatureNotSupportedException();
}
@Override
public void close() throws SQLException
{
logger.debug("public void close()");
currentResultSet = null;
resultSet = null;
isClosed = true;
batch.clear();
sfStatement.close();
}
@Override
public void cancel() throws SQLException
{
logger.debug("public void cancel()");
try
{
sfStatement.cancel();
}
catch (SFException ex)
{
throw new SnowflakeSQLException(ex, ex.getSqlState(),
ex.getVendorCode(), ex.getParams());
}
}
@Override
public void clearWarnings() throws SQLException
{
logger.debug("public void clearWarnings()");
sqlWarnings = null;
}
@Override
public void addBatch(String sql) throws SQLException
{
logger.debug("public void addBatch(String sql)");
if (isClosed)
{
throw new SnowflakeSQLException(ErrorCode.STATEMENT_CLOSED);
}
batch.add(new BatchEntry(sql, null));
}
@Override
public void clearBatch() throws SQLException
{
logger.debug("public void clearBatch()");
if (isClosed)
{
throw new SnowflakeSQLException(ErrorCode.STATEMENT_CLOSED);
}
batch.clear();
}
private void executeSetProperty(final String sql)
{
logger.debug("setting property");
// tokenize the sql
String[] tokens = sql.split("\\s+");
if (tokens == null || tokens.length < 2)
{
return;
}
if ("tracing".equalsIgnoreCase(tokens[1]))
{
if (tokens.length >= 3)
{
/*connection.tracingLevel = Level.parse(tokens[2].toUpperCase());
if (connection.tracingLevel != null)
{
Logger snowflakeLogger = Logger.getLogger("net.snowflake");
snowflakeLogger.setLevel(connection.tracingLevel);
}*/
}
}
else
{
this.sfStatement.executeSetProperty(sql);
}
}
public SFStatement getSfStatement()
{
return sfStatement;
}
protected void appendWarning(SQLWarning w)
{
if (sqlWarnings == null)
{
sqlWarnings = w;
}
else
{
sqlWarnings.setNextWarning(w);
}
}
final class BatchEntry
{
private final String sql;
private final Map<String, ParameterBindingDTO> parameterBindings;
BatchEntry(String sql,
Map<String, ParameterBindingDTO> parameterBindings)
{
this.sql = sql;
this.parameterBindings = parameterBindings;
}
public String getSql()
{
return sql;
}
public Map<String, ParameterBindingDTO> getParameterBindings()
{
return parameterBindings;
}
}
}