- 
                Notifications
    
You must be signed in to change notification settings  - Fork 268
 
Refactor SQL module to use PreparedStatement (#1611) #1612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            ferCancholaCruz
  wants to merge
  3
  commits into
  apache:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
ferCancholaCruz:refactor/sql-prepared-statements
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            3 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| 
          
            
          
           | 
    @@ -21,6 +21,7 @@ | |
| import java.sql.Connection; | ||
| import java.sql.PreparedStatement; | ||
| import java.sql.SQLException; | ||
| import java.util.Locale; | ||
| import java.util.Map; | ||
| import org.apache.commons.lang.StringUtils; | ||
| import org.apache.storm.metric.api.MultiCountMetric; | ||
| 
        
          
        
         | 
    @@ -35,33 +36,26 @@ | |
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| 
     | 
||
| /** Stores URL and selected metadata into a SQL table * */ | ||
| /** Stores URL and selected metadata into a SQL table */ | ||
| public class IndexerBolt extends AbstractIndexerBolt { | ||
| 
     | 
||
| private static final Logger LOG = LoggerFactory.getLogger(IndexerBolt.class); | ||
| 
     | 
||
| public static final String SQL_INDEX_TABLE_PARAM_NAME = "sql.index.table"; | ||
| 
     | 
||
| private OutputCollector _collector; | ||
| 
     | 
||
| private MultiCountMetric eventCounter; | ||
| 
     | 
||
| private Connection connection; | ||
| 
     | 
||
| private String tableName; | ||
| 
     | 
||
| private Map<String, Object> conf; | ||
| 
     | 
||
| @Override | ||
| public void prepare( | ||
| Map<String, Object> conf, TopologyContext context, OutputCollector collector) { | ||
| super.prepare(conf, context, collector); | ||
| _collector = collector; | ||
| 
     | 
||
| this.eventCounter = context.registerMetric("SQLIndexer", new MultiCountMetric(), 10); | ||
| 
     | 
||
| this.tableName = ConfUtils.getString(conf, SQL_INDEX_TABLE_PARAM_NAME); | ||
| 
     | 
||
| this.conf = conf; | ||
| } | ||
| 
     | 
||
| 
        
          
        
         | 
    @@ -87,39 +81,32 @@ public void execute(Tuple tuple) { | |
| } | ||
| 
     | 
||
| try { | ||
| 
     | 
||
| // which metadata to display? | ||
| Map<String, String[]> keyVals = filterMetadata(metadata); | ||
| 
     | 
||
| StringBuilder query = | ||
| new StringBuilder(" insert into ") | ||
| .append(tableName) | ||
| .append(" (") | ||
| .append(fieldNameForURL()); | ||
| 
     | 
||
| Object[] keys = keyVals.keySet().toArray(); | ||
| 
     | 
||
| for (Object o : keys) { | ||
| query.append(", ").append((String) o); | ||
| } | ||
| // Build SQL statement with prepared statement | ||
| StringBuilder fieldsBuilder = new StringBuilder(fieldNameForURL()); | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree with @sigee here. We shouldn't create a lot of StringBuilders here and instead use parameter replacement were needed. In addition, I would add a simple (regex) check for the table name to avoid anything unexpected.  | 
||
| StringBuilder placeholdersBuilder = new StringBuilder("?"); | ||
| StringBuilder updatesBuilder = new StringBuilder(); | ||
| 
     | 
||
| query.append(") values(?"); | ||
| 
     | 
||
| for (int i = 0; i < keys.length; i++) { | ||
| query.append(", ?"); | ||
| } | ||
| 
     | 
||
| query.append(")"); | ||
| 
     | 
||
| query.append(" ON DUPLICATE KEY UPDATE "); | ||
| for (int i = 0; i < keys.length; i++) { | ||
| String key = (String) keys[i]; | ||
| if (i > 0) { | ||
| query.append(", "); | ||
| } | ||
| query.append(key).append("=VALUES(").append(key).append(")"); | ||
| fieldsBuilder.append(", ").append(key); | ||
| placeholdersBuilder.append(", ?"); | ||
| if (i > 0) updatesBuilder.append(", "); | ||
| updatesBuilder.append(key).append("=VALUES(").append(key).append(")"); | ||
| } | ||
| 
     | 
||
| String sql = | ||
| String.format( | ||
| Locale.ROOT, | ||
| "INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s", | ||
| tableName, | ||
| fieldsBuilder, | ||
| placeholdersBuilder, | ||
| updatesBuilder); | ||
| 
     | 
||
| if (connection == null) { | ||
| try { | ||
| connection = SQLUtil.getConnection(conf); | ||
| 
        
          
        
         | 
    @@ -129,29 +116,30 @@ public void execute(Tuple tuple) { | |
| } | ||
| } | ||
| 
     | 
||
| LOG.debug("PreparedStatement => {}", query); | ||
| LOG.debug("PreparedStatement => {}", sql); | ||
| 
     | 
||
| // create the mysql insert preparedstatement | ||
| PreparedStatement preparedStmt = connection.prepareStatement(query.toString()); | ||
| // Create the MySQL insert PreparedStatement | ||
| PreparedStatement preparedStmt = connection.prepareStatement(sql); | ||
| 
     | 
||
| // TODO store the text of the document? | ||
| if (StringUtils.isNotBlank(fieldNameForText())) { | ||
| // builder.field(fieldNameForText(), trimText(text)); | ||
| } | ||
| 
     | 
||
| // send URL as field? | ||
| // Send URL as first parameter | ||
| if (fieldNameForURL() != null) { | ||
| preparedStmt.setString(1, normalisedurl); | ||
| } | ||
| 
     | 
||
| // Send metadata values | ||
| for (int i = 0; i < keys.length; i++) { | ||
| insert(preparedStmt, i + 2, (String) keys[i], keyVals); | ||
| } | ||
| 
     | 
||
| preparedStmt.executeUpdate(); | ||
| preparedStmt.close(); | ||
| 
     | 
||
| eventCounter.scope("Indexed").incrBy(1); | ||
| 
     | 
||
| _collector.emit(StatusStreamName, tuple, new Values(url, metadata, Status.FETCHED)); | ||
| _collector.ack(tuple); | ||
| 
     | 
||
| 
        
          
        
         | 
    @@ -164,6 +152,7 @@ public void execute(Tuple tuple) { | |
| try { | ||
| connection.close(); | ||
| } catch (SQLException e1) { | ||
| // ignore | ||
| } | ||
| connection = null; | ||
| } | ||
| 
        
          
        
         | 
    @@ -180,11 +169,11 @@ private void insert( | |
| String value = ""; | ||
| if (values == null || values.length == 0) { | ||
| LOG.info("No values found for label {}", label); | ||
| } else if (values.length > 1) { | ||
| LOG.info("More than one value found for label {}", label); | ||
| value = values[0]; | ||
| } else { | ||
| value = values[0]; | ||
| if (values.length > 1) { | ||
| LOG.info("More than one value found for label {}", label); | ||
| } | ||
| } | ||
| preparedStmt.setString(position, value); | ||
| } | ||
| 
          
            
          
           | 
    ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To be honest, I do not really get why do you changed the single
StringBuilder querytoStringBuilder fieldsBuilder,StringBuilder placeholdersBuilderandStringBuilder updatesBuilderwith the overcomplicated query building? One single for loop appends different parts to different StringBuilders. The original version was already aPreparedStatement. I can't see any additional value replacing it. Finally it is the same SQL query generated with more resource is used.Am I missing something?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The original intention of the issue was to replace direct String concat with parameter replacements and pre-build queries. The SQL strings could be prepared on init and just looked up (might open the was for a more sophisticated solution using a connection pool).
Side note: One would need to sanitize table names, too, because they cannot be set as ? In a prepared statement, so might be good to add a simple check.