idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
152,100 | public void upload ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { if ( ! closed ) { serializeBinds ( bindValues ) ; putBinds ( ) ; } } | Upload the bindValues to stage |
152,101 | private void serializeBinds ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { List < ColumnTypeDataPair > columns = getColumnValues ( bindValues ) ; List < String [ ] > rows = buildRows ( columns ) ; writeRowsToCSV ( rows ) ; } | Save the binds to disk |
152,102 | private List < ColumnTypeDataPair > getColumnValues ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { List < ColumnTypeDataPair > columns = new ArrayList < > ( bindValues . size ( ) ) ; for ( int i = 1 ; i <= bindValues . size ( ) ; i ++ ) { String key = Integer . toString ( i ) ; if ( ! bindVa... | Convert bind map to a list of values for each column Perform necessary type casts and invariant checks |
152,103 | private List < String [ ] > buildRows ( List < ColumnTypeDataPair > columns ) throws BindException { List < String [ ] > rows = new ArrayList < > ( ) ; int numColumns = columns . size ( ) ; if ( columns . get ( 0 ) . data . isEmpty ( ) ) { throw new BindException ( "No binds found in first column" , BindException . Typ... | Transpose a list of columns and their values to a list of rows |
152,104 | private void writeRowsToCSV ( List < String [ ] > rows ) throws BindException { int numBytes ; int rowNum = 0 ; int fileCount = 0 ; while ( rowNum < rows . size ( ) ) { File file = getFile ( ++ fileCount ) ; try ( OutputStream out = openFile ( file ) ) { numBytes = 0 ; while ( numBytes < fileSize && rowNum < rows . siz... | Write the list of rows to compressed CSV files in the temporary directory |
152,105 | private OutputStream openFile ( File file ) throws BindException { try { return new GZIPOutputStream ( new FileOutputStream ( file ) ) ; } catch ( IOException ex ) { throw new BindException ( String . format ( "Failed to create output file %s: %s" , file . toString ( ) , ex . getMessage ( ) ) , BindException . Type . S... | Create a new output stream for the given file |
152,106 | private byte [ ] createCSVRecord ( String [ ] data ) { StringBuilder sb = new StringBuilder ( 1024 ) ; for ( int i = 0 ; i < data . length ; ++ i ) { if ( i > 0 ) { sb . append ( ',' ) ; } sb . append ( SnowflakeType . escapeForCSV ( data [ i ] ) ) ; } sb . append ( '\n' ) ; return sb . toString ( ) . getBytes ( UTF_8 ... | Serialize row to a csv Duplicated from StreamLoader class |
152,107 | private String getPutStmt ( String bindDir , String stagePath ) { return String . format ( PUT_STMT , bindDir , File . separator , stagePath ) . replaceAll ( "\\\\" , "\\\\\\\\" ) ; } | Build PUT statement string . Handle filesystem differences and escaping backslashes . |
152,108 | private void putBinds ( ) throws BindException { createStageIfNeeded ( ) ; String putStatement = getPutStmt ( bindDir . toString ( ) , stagePath ) ; for ( int i = 0 ; i < PUT_RETRY_COUNT ; i ++ ) { try { SFStatement statement = new SFStatement ( session ) ; SFBaseResultSet putResult = statement . execute ( putStatement... | Upload binds from local file to stage |
152,109 | private void createStageIfNeeded ( ) throws BindException { if ( session . getArrayBindStage ( ) != null ) { return ; } synchronized ( session ) { if ( session . getArrayBindStage ( ) == null ) { try { SFStatement statement = new SFStatement ( session ) ; statement . execute ( CREATE_STAGE_STMT , null , null ) ; sessio... | Check whether the session s temporary stage has been created and create it if not . |
152,110 | public static int arrayBindValueCount ( Map < String , ParameterBindingDTO > bindValues ) { if ( ! isArrayBind ( bindValues ) ) { return 0 ; } else { ParameterBindingDTO bindSample = bindValues . values ( ) . iterator ( ) . next ( ) ; List < String > bindSampleValues = ( List < String > ) bindSample . getValue ( ) ; re... | Compute the number of array bind values in the given bind map |
152,111 | public static boolean isArrayBind ( Map < String , ParameterBindingDTO > bindValues ) { if ( bindValues == null || bindValues . size ( ) == 0 ) { return false ; } ParameterBindingDTO bindSample = bindValues . values ( ) . iterator ( ) . next ( ) ; return bindSample . getValue ( ) instanceof List ; } | Return whether the bind map uses array binds |
152,112 | public static StorageObjectSummary createFromS3ObjectSummary ( S3ObjectSummary objSummary ) { return new StorageObjectSummary ( objSummary . getBucketName ( ) , objSummary . getKey ( ) , objSummary . getETag ( ) , objSummary . getSize ( ) ) ; } | Contructs a StorageObjectSummary object from the S3 equivalent S3ObjectSummary |
152,113 | public static StorageObjectSummary createFromAzureListBlobItem ( ListBlobItem listBlobItem ) throws StorageProviderException { String location , key , md5 ; long size ; try { location = listBlobItem . getContainer ( ) . getName ( ) ; CloudBlob cloudBlob = ( CloudBlob ) listBlobItem ; key = cloudBlob . getName ( ) ; Blo... | Contructs a StorageObjectSummary object from Azure BLOB properties Using factory methods to create these objects since Azure can throw while retrieving the BLOB properties |
152,114 | private boolean isSnowflakeAuthenticator ( ) { String authenticator = ( String ) connectionPropertiesMap . get ( SFSessionProperty . AUTHENTICATOR ) ; PrivateKey privateKey = ( PrivateKey ) connectionPropertiesMap . get ( SFSessionProperty . PRIVATE_KEY ) ; return ( authenticator == null && privateKey == null ) || Clie... | If authenticator is null and private key is specified jdbc will assume key pair authentication |
152,115 | boolean isExternalbrowserAuthenticator ( ) { String authenticator = ( String ) connectionPropertiesMap . get ( SFSessionProperty . AUTHENTICATOR ) ; return ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER . name ( ) . equalsIgnoreCase ( authenticator ) ; } | Returns true If authenticator is EXTERNALBROWSER . |
152,116 | synchronized void renewSession ( String prevSessionToken ) throws SFException , SnowflakeSQLException { if ( sessionToken != null && ! sessionToken . equals ( prevSessionToken ) ) { logger . debug ( "not renew session because session token has not been updated." ) ; return ; } SessionUtil . LoginInput loginInput = new ... | A helper function to call global service and renew session . |
152,117 | protected void startHeartbeatForThisSession ( ) { if ( enableHeartbeat && ! Strings . isNullOrEmpty ( masterToken ) ) { logger . debug ( "start heartbeat, master token validity: " + masterTokenValidityInSeconds ) ; HeartbeatBackground . getInstance ( ) . addSession ( this , masterTokenValidityInSeconds , this . heartbe... | Start heartbeat for this session |
152,118 | protected void stopHeartbeatForThisSession ( ) { if ( enableHeartbeat && ! Strings . isNullOrEmpty ( masterToken ) ) { logger . debug ( "stop heartbeat" ) ; HeartbeatBackground . getInstance ( ) . removeSession ( this ) ; } else { logger . debug ( "heartbeat not enabled for the session" ) ; } } | Stop heartbeat for this session |
152,119 | protected void heartbeat ( ) throws SFException , SQLException { logger . debug ( " public void heartbeat()" ) ; if ( isClosed ) { return ; } HttpPost postRequest = null ; String requestId = UUID . randomUUID ( ) . toString ( ) ; boolean retry = false ; do { try { URIBuilder uriBuilder ; uriBuilder = new URIBuilder ( (... | Send heartbeat for the session |
152,120 | void setCurrentObjects ( SessionUtil . LoginInput loginInput , SessionUtil . LoginOutput loginOutput ) { this . sessionToken = loginOutput . sessionToken ; runInternalCommand ( "USE ROLE IDENTIFIER(?)" , loginInput . getRole ( ) ) ; runInternalCommand ( "USE WAREHOUSE IDENTIFIER(?)" , loginInput . getWarehouse ( ) ) ; ... | Sets the current objects if the session is not up to date . It can happen if the session is created by the id token which doesn t carry the current objects . |
152,121 | private void executeImmediate ( String stmtText ) throws SQLException { try ( final Statement statement = this . createStatement ( ) ) { statement . execute ( stmtText ) ; } } | Execute a statement where the result isn t needed and the statement is closed before this method returns |
152,122 | public Statement createStatement ( ) throws SQLException { raiseSQLExceptionIfConnectionIsClosed ( ) ; Statement stmt = createStatement ( ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; openStatements . add ( stmt ) ; return stmt ; } | Create a statement |
152,123 | public void setTransactionIsolation ( int level ) throws SQLException { logger . debug ( "void setTransactionIsolation(int level), level = {}" , level ) ; raiseSQLExceptionIfConnectionIsClosed ( ) ; if ( level == Connection . TRANSACTION_NONE || level == Connection . TRANSACTION_READ_COMMITTED ) { this . transactionIso... | Sets the transaction isolation level . |
152,124 | public InputStream downloadStream ( String stageName , String sourceFileName , boolean decompress ) throws SQLException { logger . debug ( "download data to stream: stageName={}" + ", sourceFileName={}" , stageName , sourceFileName ) ; if ( Strings . isNullOrEmpty ( stageName ) ) { throw new SnowflakeSQLException ( Sql... | Download file from the given stage and return an input stream |
152,125 | public static InputStream decryptStream ( InputStream inputStream , String keyBase64 , String ivBase64 , RemoteStoreFileEncryptionMaterial encMat ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException , InvalidAlgorithmParameterException { byte... | Decrypt a InputStream |
152,126 | synchronized void startFlusher ( ) { flusher = Executors . newScheduledThreadPool ( 1 , new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } } ) ; flusher . scheduleWithFixedDelay ( new QueueFlusher ( )... | Creates and runs a new QueueFlusher thread |
152,127 | public void dumpLogBuffer ( String identifier ) { final ArrayList < LogRecord > logBufferCopy ; final PrintWriter logDumper ; final OutputStream outStream ; Formatter formatter = this . getFormatter ( ) ; boolean disableCompression = System . getProperty ( DISABLE_DUMP_COMPR_PROP ) != null ; if ( identifier == null ) {... | Dumps the contents of the in - memory log buffer to disk and clears the buffer . |
152,128 | protected void cleanupSfDumps ( boolean deleteOldest ) { int maxDumpFiles = System . getProperty ( MAX_NUM_DUMP_FILES_PROP ) != null ? Integer . valueOf ( System . getProperty ( MAX_NUM_DUMP_FILES_PROP ) ) : DEFAULT_MAX_DUMP_FILES ; int maxDumpDirSizeMB = System . getProperty ( MAX_SIZE_DUMPS_MB_PROP ) != null ? Intege... | Function to remove old Snowflake Dump files to make room for new ones . |
152,129 | private synchronized boolean needsToThrottle ( String signature ) { AtomicInteger sigCount ; if ( throttledIncidents . containsKey ( signature ) ) { if ( throttledIncidents . get ( signature ) . plusHours ( THROTTLE_DURATION_HRS ) . compareTo ( DateTime . now ( ) ) <= 0 ) { throttledIncidents . remove ( signature ) ; i... | Checks to see if the reporting of an incident should be throttled due to the number of times the signature has been seen in the last hour |
152,130 | public void start ( ) { LOGGER . debug ( "Start Loading" ) ; validateParameters ( ) ; if ( _op == null ) { this . abort ( new ConnectionError ( "Loader started with no operation" ) ) ; return ; } initDateFormats ( ) ; initQueues ( ) ; if ( _is_first_start_call ) { try { if ( _startTransaction ) { LOGGER . debug ( "Begi... | Starts the loader |
152,131 | private void flushQueues ( ) { LOGGER . debug ( "Flush Queues" ) ; try { _queueData . put ( new byte [ 0 ] ) ; _thread . join ( 10000 ) ; if ( _thread . isAlive ( ) ) { _thread . interrupt ( ) ; } } catch ( Exception ex ) { String msg = "Failed to join StreamLoader queue: " + ex . getMessage ( ) ; LOGGER . error ( msg ... | Flushes data by joining PUT and PROCESS queues |
152,132 | public void resetOperation ( Operation op ) { LOGGER . debug ( "Reset Loader" ) ; if ( op . equals ( _op ) ) { return ; } LOGGER . debug ( "Operation is changing from {} to {}" , _op , op ) ; _op = op ; if ( _stage != null ) { try { queuePut ( _stage ) ; } catch ( InterruptedException ex ) { LOGGER . error ( _stage . g... | If operation changes existing stage needs to be scheduled for processing . |
152,133 | void overrideCacheFile ( File newCacheFile ) { this . cacheFile = newCacheFile ; this . cacheDir = newCacheFile . getParentFile ( ) ; this . baseCacheFileName = newCacheFile . getName ( ) ; } | Override the cache file . |
152,134 | JsonNode readCacheFile ( ) { if ( cacheFile == null || ! this . checkCacheLockFile ( ) ) { return null ; } try { if ( ! cacheFile . exists ( ) ) { LOGGER . debug ( "Cache file doesn't exists. File: {}" , cacheFile ) ; return null ; } try ( Reader reader = new InputStreamReader ( new FileInputStream ( cacheFile ) , DEFA... | Reads the cache file . |
152,135 | private boolean tryLockCacheFile ( ) { int cnt = 0 ; boolean locked = false ; while ( cnt < 100 && ! ( locked = lockCacheFile ( ) ) ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ex ) { } ++ cnt ; } if ( ! locked ) { LOGGER . debug ( "Failed to lock the cache file." ) ; } return locked ; } | Tries to lock the cache file |
152,136 | private void verifyLocalFilePath ( String localFilePathFromGS ) throws SnowflakeSQLException { if ( command == null ) { logger . error ( "null command" ) ; return ; } if ( command . indexOf ( FILE_PROTOCOL ) < 0 ) { logger . error ( "file:// prefix not found in command: {}" , command ) ; return ; } int localFilePathBeg... | A helper method to verify if the local file path from GS matches what s parsed locally . This is for security purpose as documented in SNOW - 15153 . |
152,137 | private void uploadStream ( ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-stream-upload-worker-" , 1 ) ; RemoteStoreFileEncryptionMaterial encMat = encryptionMaterial . get ( 0 ) ; if ( commandType == CommandType . UPLOAD ) { threadExecutor . submit ( getUplo... | Helper to upload data from a stream |
152,138 | InputStream downloadStream ( String fileName ) throws SnowflakeSQLException { if ( stageInfo . getStageType ( ) == StageInfo . StageType . LOCAL_FS ) { logger . error ( "downloadStream function doesn't support local file system" ) ; throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERRO... | Download a file from remote and return an input stream |
152,139 | private void downloadFiles ( ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-file-download-worker-" , 1 ) ; for ( String srcFile : sourceFiles ) { FileMetadata fileMetadata = fileMetadataMap . get ( srcFile ) ; if ( fileMetadata . resultStatus != ResultStatus .... | Helper to download files from remote |
152,140 | private void uploadFiles ( Set < String > fileList , int parallel ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-file-upload-worker-" , parallel ) ; for ( String srcFile : fileList ) { FileMetadata fileMetadata = fileMetadataMap . get ( srcFile ) ; if ( fileMe... | This method create a thread pool based on requested number of threads and upload the files using the thread pool . |
152,141 | static public Set < String > expandFileNames ( String [ ] filePathList ) throws SnowflakeSQLException { Set < String > result = new HashSet < String > ( ) ; Map < String , List < String > > locationToFilePatterns ; locationToFilePatterns = new HashMap < String , List < String > > ( ) ; String cwd = System . getProperty... | process a list of file paths separated by and expand the wildcards if any to generate the list of paths for all files matched by the wildcards |
152,142 | private FileCompressionType mimeTypeToCompressionType ( String mimeTypeStr ) throws MimeTypeParseException { MimeType mimeType = null ; if ( mimeTypeStr != null ) { mimeType = new MimeType ( mimeTypeStr ) ; } if ( mimeType != null && mimeType . getSubType ( ) != null ) { return FileCompressionType . lookupByMimeSubType... | Derive compression type from mime type |
152,143 | private String getMimeTypeFromFileExtension ( String srcFile ) { String srcFileLowCase = srcFile . toLowerCase ( ) ; for ( FileCompressionType compressionType : FileCompressionType . values ( ) ) { if ( srcFileLowCase . endsWith ( compressionType . fileExtension ) ) { return compressionType . mimeType + "/" + compressi... | Derive mime type from file extension |
152,144 | static public remoteLocation extractLocationAndPath ( String stageLocationPath ) { String location = stageLocationPath ; String path = "" ; if ( stageLocationPath . contains ( "/" ) ) { location = stageLocationPath . substring ( 0 , stageLocationPath . indexOf ( "/" ) ) ; path = stageLocationPath . substring ( stageLoc... | A small helper for extracting location name and path from full location path |
152,145 | public List < SnowflakeColumnMetadata > describeColumns ( ) throws Exception { return SnowflakeUtil . describeFixedViewColumns ( commandType == CommandType . UPLOAD ? ( showEncryptionParameter ? UploadCommandEncryptionFacade . class : UploadCommandFacade . class ) : ( showEncryptionParameter ? DownloadCommandEncryption... | Describe the metadata of a fixed view . |
152,146 | private void populateStatusRows ( ) { for ( Map . Entry < String , FileMetadata > entry : fileMetadataMap . entrySet ( ) ) { FileMetadata fileMetadata = entry . getValue ( ) ; if ( commandType == CommandType . UPLOAD ) { statusRows . add ( showEncryptionParameter ? new UploadCommandEncryptionFacade ( fileMetadata . src... | Generate status rows for each file |
152,147 | public void flush ( ) { ObjectMapper mapper = ObjectMapperFactory . getObjectMapper ( ) ; String dtoDump ; URI incidentURI ; try { dtoDump = mapper . writeValueAsString ( new IncidentV2DTO ( this ) ) ; } catch ( JsonProcessingException ex ) { logger . error ( "Incident registration failed, could not map " + "incident r... | Sends incident to GS to log |
152,148 | private static String [ ] decideCipherSuites ( ) { String sysCipherSuites = System . getProperty ( "https.cipherSuites" ) ; String [ ] cipherSuites = sysCipherSuites != null ? sysCipherSuites . split ( "," ) : ( ( SSLServerSocketFactory ) SSLServerSocketFactory . getDefault ( ) ) . getDefaultCipherSuites ( ) ; if ( log... | Decide cipher suites that will be passed into the SSLConnectionSocketFactory |
152,149 | public static Telemetry createTelemetry ( Connection conn , int flushSize ) { try { return createTelemetry ( conn . unwrap ( SnowflakeConnectionV1 . class ) . getSfSession ( ) , flushSize ) ; } catch ( SQLException ex ) { logger . debug ( "input connection is not a SnowflakeConnection" ) ; return null ; } } | Initialize the telemetry connector |
152,150 | public void addLogToBatch ( TelemetryData log ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } if ( ! isTelemetryEnabled ( ) ) { return ; } synchronized ( locker ) { this . logBatch . add ( log ) ; } if ( this . logBatch . size ( ) >= this . forceFlushSize ) { this ... | Add log to batch to be submitted to telemetry . Send batch if forceFlushSize reached |
152,151 | public void tryAddLogToBatch ( TelemetryData log ) { try { addLogToBatch ( log ) ; } catch ( IOException ex ) { logger . debug ( "Exception encountered while sending metrics to telemetry endpoint." , ex ) ; } } | Attempt to add log to batch and suppress exceptions thrown in case of failure |
152,152 | public void close ( ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } try { this . sendBatch ( ) ; } catch ( IOException e ) { logger . error ( "Send logs failed on closing" , e ) ; } finally { this . isClosed = true ; } } | Close telemetry connector and send any unsubmitted logs |
152,153 | public boolean sendBatch ( ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } if ( ! isTelemetryEnabled ( ) ) { return false ; } LinkedList < TelemetryData > tmpList ; synchronized ( locker ) { tmpList = this . logBatch ; this . logBatch = new LinkedList < > ( ) ; } i... | Send all cached logs to server |
152,154 | static ObjectNode logsToJson ( LinkedList < TelemetryData > telemetryData ) { ObjectNode node = mapper . createObjectNode ( ) ; ArrayNode logs = mapper . createArrayNode ( ) ; for ( TelemetryData data : telemetryData ) { logs . add ( data . toJson ( ) ) ; } node . set ( "logs" , logs ) ; return node ; } | convert a list of log to a JSON object |
152,155 | public ResultSet executeQuery ( String sql ) throws SQLException { raiseSQLExceptionIfStatementIsClosed ( ) ; return executeQueryInternal ( sql , null ) ; } | Execute SQL query |
152,156 | ResultSet executeQueryInternal ( String sql , Map < String , ParameterBindingDTO > parameterBindings ) throws SQLException { SFBaseResultSet sfResultSet ; try { sfResultSet = sfStatement . execute ( sql , parameterBindings , SFStatement . CallingMethod . EXECUTE_QUERY ) ; sfResultSet . setSession ( this . connection . ... | Internal method for executing a query with bindings accepted . |
152,157 | void setParameter ( String name , Object value ) throws Exception { logger . debug ( "public void setParameter" ) ; try { if ( this . sfStatement != null ) { this . sfStatement . addProperty ( name , value ) ; } } catch ( SFException ex ) { throw new SnowflakeSQLException ( ex ) ; } } | Sets a parameter at the statement level . Used for internal testing . |
152,158 | private static ThreadPoolExecutor createChunkDownloaderExecutorService ( final String threadNamePrefix , final int parallel ) { ThreadFactory threadFactory = new ThreadFactory ( ) { private int threadCount = 1 ; public Thread newThread ( final Runnable r ) { final Thread thread = new Thread ( r ) ; thread . setName ( t... | Create a pool of downloader threads . |
152,159 | private void startNextDownloaders ( ) throws SnowflakeSQLException { long waitingTime = BASE_WAITING_MS ; while ( nextChunkToDownload - nextChunkToConsume < prefetchSlots && nextChunkToDownload < chunks . size ( ) ) { final SnowflakeResultChunk nextChunk = chunks . get ( nextChunkToDownload ) ; final long neededChunkMe... | Submit download chunk tasks to executor . Number depends on thread and memory limit |
152,160 | public void releaseAllChunkMemoryUsage ( ) { if ( chunks == null || chunks . size ( ) == 0 ) { return ; } for ( int i = 0 ; i < chunks . size ( ) ; i ++ ) { releaseCurrentMemoryUsage ( i , chunks . get ( i ) . computeNeededChunkMemory ( ) ) ; } } | release all existing chunk memory usage before close |
152,161 | private void logOutOfMemoryError ( ) { logger . error ( "Dump some crucial information below:\n" + "Total milliseconds waiting for chunks: {},\n" + "Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" + "total parsing time: {} milliseconds, total chunks: {},\n" + "currentMemoryUsage in Byte: ... | log out of memory error and provide the suggestion to avoid this error |
152,162 | public Metrics terminate ( ) { if ( ! terminated ) { logger . debug ( "Total milliseconds waiting for chunks: {}, " + "Total memory used: {}, total download time: {} millisec, " + "total parsing time: {} milliseconds, total chunks: {}" , numberMillisWaitingForChunks , Runtime . getRuntime ( ) . totalMemory ( ) , totalM... | terminate the downloader |
152,163 | public static String maskAWSSecret ( String sql ) { List < SecretDetector . SecretRange > secretRanges = SecretDetector . getAWSSecretPos ( sql ) ; for ( SecretDetector . SecretRange secretRange : secretRanges ) { sql = maskText ( sql , secretRange . beginPos , secretRange . endPos ) ; } return sql ; } | mask AWS secret in the input string |
152,164 | private void sanityCheckQuery ( String sql ) throws SQLException { if ( sql == null || sql . isEmpty ( ) ) { throw new SnowflakeSQLException ( SqlState . SQL_STATEMENT_NOT_YET_COMPLETE , ErrorCode . INVALID_SQL . getMessageCode ( ) , sql ) ; } } | Sanity check query text |
152,165 | private SFBaseResultSet executeQuery ( String sql , Map < String , ParameterBindingDTO > parametersBinding , boolean describeOnly , CallingMethod caller ) throws SQLException , SFException { sanityCheckQuery ( sql ) ; String trimmedSql = sql . trim ( ) ; if ( isFileTransfer ( trimmedSql ) ) { logger . debug ( "Executin... | Execute SQL query with an option for describe only |
152,166 | public SFStatementMetaData describe ( String sql ) throws SFException , SQLException { SFBaseResultSet baseResultSet = executeQuery ( sql , null , true , null ) ; describeJobUUID = baseResultSet . getQueryId ( ) ; return new SFStatementMetaData ( baseResultSet . getMetaData ( ) , baseResultSet . getStatementType ( ) , ... | Describe a statement |
152,167 | private void setTimeBomb ( ScheduledExecutorService executor ) { class TimeBombTask implements Callable < Void > { private final SFStatement statement ; private TimeBombTask ( SFStatement statement ) { this . statement = statement ; } public Void call ( ) throws SQLException { try { statement . cancel ( ) ; } catch ( S... | Set a time bomb to cancel the outstanding query when timeout is reached . |
152,168 | private void cancelHelper ( String sql , String mediaType ) throws SnowflakeSQLException , SFException { synchronized ( this ) { if ( isClosed ) { throw new SFException ( ErrorCode . INTERNAL_ERROR , "statement already closed" ) ; } } StmtUtil . StmtInput stmtInput = new StmtUtil . StmtInput ( ) ; stmtInput . setServer... | A helper method to build URL and cancel the SQL for exec |
152,169 | public boolean getMoreResults ( int current ) throws SQLException { if ( resultSet != null && ( current == Statement . CLOSE_CURRENT_RESULT || current == Statement . CLOSE_ALL_RESULTS ) ) { resultSet . close ( ) ; } resultSet = null ; if ( childResults == null || childResults . isEmpty ( ) ) { return false ; } SFChildR... | Sets the result set to the next one if available . |
152,170 | public boolean isServiceException404 ( ) { if ( ( Exception ) this instanceof AmazonServiceException ) { AmazonServiceException asEx = ( AmazonServiceException ) ( ( java . lang . Exception ) this ) ; return ( asEx . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) ; } return false ; } | Returns true if this is an exception corresponding to a HTTP 404 error returned by the storage provider |
152,171 | public static String oneLiner ( Throwable thrown ) { StackTraceElement [ ] stack = thrown . getStackTrace ( ) ; String topOfStack = null ; if ( stack . length > 0 ) { topOfStack = " at " + stack [ 0 ] ; } return thrown . toString ( ) + topOfStack ; } | Produce a one line description of the throwable suitable for error message and log printing . |
152,172 | public static void dumpVmMetrics ( String incidentId ) { PrintWriter writer = null ; try { String dumpFile = EventUtil . getDumpPathPrefix ( ) + "/" + INC_DUMP_FILE_NAME + incidentId + INC_DUMP_FILE_EXT ; final OutputStream outStream = new GZIPOutputStream ( new FileOutputStream ( dumpFile ) ) ; writer = new PrintWrite... | Dumps JVM metrics for this process . |
152,173 | public static Throwable generateIncidentV2WithException ( SFSession session , Throwable exc , String jobId , String requestId ) { new Incident ( session , exc , jobId , requestId ) . trigger ( ) ; return exc ; } | Makes a V2 incident object and triggers ir effectively reporting the given exception to GS and possibly to crashmanager |
152,174 | public static String getUTCNow ( ) { SimpleDateFormat dateFormatGmt = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; dateFormatGmt . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; return dateFormatGmt . format ( new Date ( ) ) ; } | Get current time in UTC in the following format |
152,175 | public void renew ( Map stageCredentials ) throws SnowflakeSQLException { stageInfo . setCredentials ( stageCredentials ) ; setupAzureClient ( stageInfo , encMat ) ; } | Re - creates the encapsulated storage client with a fresh access token |
152,176 | public StorageObjectMetadata getObjectMetadata ( String remoteStorageLocation , String prefix ) throws StorageProviderException { AzureObjectMetadata azureObjectMetadata = null ; try { CloudBlobContainer container = azStorageClient . getContainerReference ( remoteStorageLocation ) ; CloudBlob blob = container . getBloc... | Returns the metadata properties for a remote storage object |
152,177 | public void download ( SFSession connection , String command , String localLocation , String destFileName , int parallelism , String remoteStorageLocation , String stageFilePath , String stageRegion ) throws SnowflakeSQLException { int retryCount = 0 ; do { try { String localFilePath = localLocation + localFileSep + de... | Download a file from remote storage . |
152,178 | private static void handleAzureException ( Exception ex , int retryCount , String operation , SFSession connection , String command , SnowflakeAzureClient azClient ) throws SnowflakeSQLException { if ( ex . getCause ( ) instanceof InvalidKeyException ) { SnowflakeFileTransferAgent . throwJCEMissingError ( operation , e... | Handles exceptions thrown by Azure Storage It will retry transient errors as defined by the Azure Client retry policy It will re - create the client if the SAS token has expired and re - try |
152,179 | public void addDigestMetadata ( StorageObjectMetadata meta , String digest ) { if ( ! SnowflakeUtil . isBlank ( digest ) ) { meta . addUserMetadata ( "sfcdigest" , digest ) ; } } | Adds digest metadata to the StorageObjectMetadata object |
152,180 | private static long initMemoryLimit ( final ResultOutput resultOutput ) { long memoryLimit = SessionUtil . DEFAULT_CLIENT_MEMORY_LIMIT * 1024 * 1024 ; if ( resultOutput . parameters . get ( CLIENT_MEMORY_LIMIT ) != null ) { memoryLimit = ( int ) resultOutput . parameters . get ( CLIENT_MEMORY_LIMIT ) * 1024L * 1024L ; ... | initialize memory limit in bytes |
152,181 | static private Object effectiveParamValue ( Map < String , Object > parameters , String paramName ) { String upper = paramName . toUpperCase ( ) ; Object value = parameters . get ( upper ) ; if ( value != null ) { return value ; } value = defaultParameters . get ( upper ) ; if ( value != null ) { return value ; } logge... | Returns the effective parameter value using the value explicitly provided in parameters or the default if absent |
152,182 | static private SnowflakeDateTimeFormat specializedFormatter ( Map < String , Object > parameters , String id , String param , String defaultFormat ) { String sqlFormat = SnowflakeDateTimeFormat . effectiveSpecializedTimestampFormat ( ( String ) effectiveParamValue ( parameters , param ) , defaultFormat ) ; SnowflakeDat... | Helper function building a formatter for a specialized timestamp type . Note that it will be based on either the param value if set or the default format provided . |
152,183 | static public Timestamp adjustTimestamp ( Timestamp timestamp ) { long milliToAdjust = ResultUtil . msDiffJulianToGregorian ( timestamp ) ; if ( milliToAdjust != 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "adjust timestamp by {} days" , milliToAdjust / 86400000 ) ; } Timestamp newTimestamp = new Timest... | Adjust timestamp for dates before 1582 - 10 - 05 |
152,184 | static public long msDiffJulianToGregorian ( java . util . Date date ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; int year = cal . get ( Calendar . YEAR ) ; int month = cal . get ( Calendar . MONTH ) ; int dayOfMonth = cal . get ( Calendar . DAY_OF_MONTH ) ; if ( date . getTime ( ) < - 12220... | For dates before 1582 - 10 - 05 calculate the number of millis to adjust . |
152,185 | static public String getSFTimeAsString ( SFTime sft , int scale , SnowflakeDateTimeFormat timeFormatter ) { return timeFormatter . format ( sft , scale ) ; } | Convert a time value into a string |
152,186 | static public String getSFTimestampAsString ( SFTimestamp sfTS , int columnType , int scale , SnowflakeDateTimeFormat timestampNTZFormatter , SnowflakeDateTimeFormat timestampLTZFormatter , SnowflakeDateTimeFormat timestampTZFormatter , SFSession session ) throws SFException { SnowflakeDateTimeFormat formatter ; if ( c... | Convert a SFTimestamp to a string value . |
152,187 | static public String getDateAsString ( Date date , SnowflakeDateTimeFormat dateFormatter ) { return dateFormatter . format ( date , timeZoneUTC ) ; } | Convert a date value into a string |
152,188 | static public Date adjustDate ( Date date ) { long milliToAdjust = ResultUtil . msDiffJulianToGregorian ( date ) ; if ( milliToAdjust != 0 ) { return new Date ( date . getTime ( ) + milliToAdjust ) ; } else { return date ; } } | Adjust date for before 1582 - 10 - 05 |
152,189 | static public Date getDate ( String str , TimeZone tz , SFSession session ) throws SFException { try { long milliSecsSinceEpoch = Long . valueOf ( str ) * 86400000 ; SFTimestamp tsInUTC = SFTimestamp . fromDate ( new Date ( milliSecsSinceEpoch ) , 0 , TimeZone . getTimeZone ( "UTC" ) ) ; SFTimestamp tsInClientTZ = tsIn... | Convert a date internal object to a Date object in specified timezone . |
152,190 | static public int calculateUpdateCount ( SFBaseResultSet resultSet ) throws SFException , SQLException { int updateCount = 0 ; SFStatementType statementType = resultSet . getStatementType ( ) ; if ( statementType . isDML ( ) ) { while ( resultSet . next ( ) ) { if ( statementType == SFStatementType . COPY ) { SFResultS... | Calculate number of rows updated given a result set Interpret result format based on result set s statement type |
152,191 | public static int listSearchCaseInsensitive ( List < String > source , String target ) { for ( int i = 0 ; i < source . size ( ) ; i ++ ) { if ( target . equalsIgnoreCase ( source . get ( i ) ) ) { return i ; } } return - 1 ; } | Given a list of String do a case insensitive search for target string Used by resultsetMetadata to search for target column name |
152,192 | private static List < String > getResultIds ( JsonNode result ) { JsonNode resultIds = result . path ( "data" ) . path ( "resultIds" ) ; if ( resultIds . isNull ( ) || resultIds . isMissingNode ( ) || resultIds . asText ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } return new ArrayList < > ( Arrays . asL... | Return the list of result IDs provided in a result if available ; otherwise return an empty list . |
152,193 | private static List < SFStatementType > getResultTypes ( JsonNode result ) { JsonNode resultTypes = result . path ( "data" ) . path ( "resultTypes" ) ; if ( resultTypes . isNull ( ) || resultTypes . isMissingNode ( ) || resultTypes . asText ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } String [ ] typeStr... | Return the list of result types provided in a result if available ; otherwise return an empty list . |
152,194 | public static List < SFChildResult > getChildResults ( SFSession session , String requestId , JsonNode result ) throws SFException { List < String > ids = getResultIds ( result ) ; List < SFStatementType > types = getResultTypes ( result ) ; if ( ids . size ( ) != types . size ( ) ) { throw ( SFException ) IncidentUtil... | Return the list of child results provided in a result if available ; otherwise return an empty list |
152,195 | private synchronized void openFile ( ) { try { String fName = _directory . getAbsolutePath ( ) + File . separatorChar + StreamLoader . FILE_PREFIX + _stamp + _fileCount ; if ( _loader . _compressDataBeforePut ) { fName += StreamLoader . FILE_SUFFIX ; } LOGGER . debug ( "openFile: {}" , fName ) ; OutputStream fileStream... | Create local file for caching data before upload |
152,196 | boolean stageData ( final byte [ ] line ) throws IOException { if ( this . _rowCount % 10000 == 0 ) { LOGGER . debug ( "rowCount: {}, currentSize: {}" , this . _rowCount , _currentSize ) ; } _outstream . write ( line ) ; _currentSize += line . length ; _outstream . write ( newLineBytes ) ; this . _rowCount ++ ; if ( _l... | not thread safe |
152,197 | void completeUploading ( ) throws IOException { LOGGER . debug ( "name: {}, currentSize: {}, Threshold: {}," + " fileCount: {}, fileBucketSize: {}" , _file . getAbsolutePath ( ) , _currentSize , this . _csvFileSize , _fileCount , this . _csvFileBucketSize ) ; _outstream . flush ( ) ; _outstream . close ( ) ; if ( _curr... | Wait for all files to finish uploading and schedule stage for processing |
152,198 | private static String escapeFileSeparatorChar ( String fname ) { if ( File . separatorChar == '\\' ) { return fname . replaceAll ( File . separator + File . separator , "_" ) ; } else { return fname . replaceAll ( File . separator , "_" ) ; } } | Escape file separator char to underscore . This prevents the file name from using file path separator . |
152,199 | private Object executeSyncMethod ( Method method , Object [ ] args ) throws ApplicationException { if ( preparingForShutdown . get ( ) ) { throw new JoynrIllegalStateException ( "Preparing for shutdown. Only stateless methods can be called." ) ; } return executeMethodWithCaller ( method , args , new ConnectorCaller ( )... | executeSyncMethod is called whenever a method of the synchronous interface which is provided by the proxy is called . The ProxyInvocationHandler will check the arbitration status before the call is delegated to the connector . If the arbitration is still in progress the synchronous call will block until the arbitration... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.