View Javadoc
1   package com.github.davidmoten.rx.jdbc;
2   
3   import java.util.ArrayList;
4   import java.util.List;
5   
6   public class NamedParameters {
7   
8       public static final JdbcQuery parse(String namedSql) {
9           // was originally using regular expressions, but they didn't work well
10          // for ignoring parameter-like strings inside quotes.
11          List<String> names = new ArrayList<String>();
12          int length = namedSql.length();
13          StringBuffer parsedQuery = new StringBuffer(length);
14          boolean inSingleQuote = false;
15          boolean inDoubleQuote = false;
16          for (int i = 0; i < length; i++) {
17              char c = namedSql.charAt(i);
18              if (inSingleQuote) {
19                  if (c == '\'') {
20                      inSingleQuote = false;
21                  }
22              } else if (inDoubleQuote) {
23                  if (c == '"') {
24                      inDoubleQuote = false;
25                  }
26              } else {
27                  if (c == '\'') {
28                      inSingleQuote = true;
29                  } else if (c == '"') {
30                      inDoubleQuote = true;
31                  } else if (c == ':' && i + 1 < length
32                          && Character.isJavaIdentifierStart(namedSql.charAt(i + 1))) {
33                      int j = i + 2;
34                      while (j < length && Character.isJavaIdentifierPart(namedSql.charAt(j))) {
35                          j++;
36                      }
37                      String name = namedSql.substring(i + 1, j);
38                      c = '?'; // replace the parameter with a question mark
39                      i += name.length(); // skip past the end if the parameter
40                      names.add(name);
41                  }
42              }
43              parsedQuery.append(c);
44          }
45          return new JdbcQuery(parsedQuery.toString(), names);
46      }
47      
48      public static class JdbcQuery {
49          private final String sql;
50          private List<String> names;
51  
52          public JdbcQuery(String sql, List<String> names) {
53              this.sql = sql;
54              this.names = names;;
55          }
56  
57          public String sql() {
58              return sql;
59          }
60  
61          public List<String> names() {
62              return names;
63          }
64          
65  
66      }
67  
68  }