For a SQL DDL statement, replace (VoltDB) keywords not supported by
PostgreSQL/PostGIS with other, similar terms.
761695
@Override
    public String transformDDL(String ddl) {
        return transformQuery(super.transformDDL(ddl),
                geographyPointDdlTransformer, geographyDdlTransformer);
    }
290508
public String doTranslate(Dialect d, String sql) {
		if (StrUtils.isEmpty(sql))
			return sql;
		// if prefix not empty and SQL not include prefix, directly return
		if (!StrUtils.isEmpty(Dialect.getGlobalSqlFunctionPrefix())
				&& !StrUtils.containsIgnoreCase(sql, Dialect.getGlobalSqlFunctionPrefix()))
			return sql;
		char[] chars = (" " + sql + " ").toCharArray();
		DialectSqlItem[] items = seperateCharsToItems(chars, 1, chars.length - 2);
		for (DialectSqlItem item : items) {
			correctType(item);
		}
		String result = join(d, true, null, items);
		if (Dialect.getGlobalAllowShowSql())
			Dialect.logger.info("Translated sql: " + result);
		return result;
	}
1052605
def _substitute(self, query, model_class=None):
        '''
        
        '''
        if '$' in query:
            mapping = dict(db="`%s`" % self.db_name)
            if model_class:
                mapping['table'] = "`%s`.`%s`" % (self.db_name, model_class.table_name())
            query = Template(query).safe_substitute(mapping)
        return query
907575
MolgenisValidationException translateUniqueKeyViolation(PSQLException pSqlException) {
    ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
    String tableName = serverErrorMessage.getTable();
    String detailMessage = serverErrorMessage.getDetail();
    Matcher matcher =
        Pattern.compile("Key \\(\"?(.*?)\"?\\)=\\((.*?)\\) already exists.").matcher(detailMessage);
    boolean matches = matcher.matches();
    if (matches) {
      ConstraintViolation constraintViolation;

      // exception message when adding data that does not match constraint
      String[] columnNames = matcher.group(1).split(", ");
      if (columnNames.length == 1) {
        String columnName = columnNames[0];
        String value = matcher.group(2);

        constraintViolation =
            new ConstraintViolation(
                format(
                    "Duplicate value '%s' for unique attribute '%s' from entity '%s'.",
                    value,
                    tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
                    tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
                null);
      } else {
        String columnName = columnNames[columnNames.length - 1];
        String[] values = matcher.group(2).split(", ");
        String idValue = values[0];
        String value = values[1];

        constraintViolation =
            new ConstraintViolation(
                format(
                    "Duplicate list value '%s' for attribute '%s' from entity '%s' with id '%s'.",
                    value,
                    tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
                    tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN),
                    idValue),
                null);
      }
      return new MolgenisValidationException(singleton(constraintViolation));
    } else {
      // exception message when applying constraint on existing data
      matcher =
          Pattern.compile("Key \\(\"?(.*?)\"?\\)=\\((.*?)\\) is duplicated.")
              .matcher(detailMessage);
      matches = matcher.matches();
      if (matches) {
        String columnName = matcher.group(1);
        String value = matcher.group(2);

        ConstraintViolation constraintViolation =
            new ConstraintViolation(
                format(
                    "The attribute '%s' of entity '%s' contains duplicate value '%s'.",
                    tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
                    tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN),
                    value),
                null);
        return new MolgenisValidationException(singleton(constraintViolation));
      } else {
        LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
        throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
      }
    }
  }
834241
public <T> List<T> querySingleColumnTypedResults(String sql, String[] args) {
		@SuppressWarnings("unchecked")
		List<T> result = (List<T>) querySingleColumnResults(sql, args);
		return result;
	}
962733
private String buildAlterDDLQuery(TableInfo tableInfo, Map<String, String> newColumns)
    {
        String statement;
        StringBuilder builder = new StringBuilder();
        builder.append("ALTER TABLE ");
        builder.append(tableInfo.getTableName());
        builder.append(Constants.OPEN_ROUND_BRACKET);

        for (Map.Entry<String, String> entry : newColumns.entrySet())
        {
            builder.append("ADD ");
            builder.append(entry.getKey());
            builder.append(Constants.SPACE);
            String coulmnType = entry.getValue().toLowerCase();
            builder.append(OracleNoSQLValidationClassMapper.getValidType(coulmnType));
            builder.append(Constants.COMMA);
        }

        builder.deleteCharAt(builder.length() - 1);
        builder.append(Constants.CLOSE_ROUND_BRACKET);
        statement = builder.toString();
        return statement;
    }
430301
def dmql(query):
        """"""
        if isinstance(query, dict):
            raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
                                " Did you mean to pass this to the search_filter parameter? ")

        # automatically surround the given query with parentheses if it doesn't have them already
        if len(query) > 0 and query != "*" and query[0] != '(' and query[-1] != ')':
            query = '({})'.format(query)
        return query
1109171
def sql_to_soql(frozen_sql)
      sql = frozen_sql.dup
      # Unescape column and table names
      sql.gsub!('`', '')

      # Remove table namespace from fields
      sql.gsub!("#{QueryBuilder::DUMMY_TABLE_NAME}.", '')

      # Add table name
      sql.gsub!(QueryBuilder::DUMMY_TABLE_NAME, klass.object_name)

      # Convert 1=0 to id IS NULL (id never be NULL, so it a false case)
      sql.gsub!(/\s+1=0(\s*)/i, ' id IS NULL\1')

      # Convert IS NOT to !=
      sql.gsub!(/\s+IS\s+NOT\s+/i, ' != ')

      # Convert IS to =
      sql.gsub!(/\s+IS\s+/i, ' = ')

      # Convert datatime to salesforce format
      sql.gsub!(/'(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)?'/, '\1T\2Z')

      # Convert date to salesforce format
      sql.gsub!(/'(\d{4}-\d{2}-\d{2})'/, '\1')

      # Convert boolean_field = (1|0) to boolean_field = (true|false)
      sql = boolean_data_type_conversion(sql)

      # Convert aliased fields
      convert_aliased_fields(sql).strip
    end
1224843
private DDF sql2ddf(String sqlCommand, String errorMessage) throws DDFException {
    try {
      return this.getManager().sql2ddf(String.format(sqlCommand, "{1}"),
          new SQLDataSourceDescriptor(sqlCommand, null, null, null, this
              .getDDF().getUUID().toString()));

    } catch (Exception e) {
      throw new DDFException(String.format(errorMessage, this.getDDF().getTableName()), e);
    }
  }
481855
public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) {
        final int MAX_PARAM_LINE_CHARS = 120;

        StringBuilder sb = new StringBuilder();
        String sql = new String(statement.sql, Charsets.UTF_8);
        sb.append(sql);

        Object[] params = paramsForStatement(statement, userparams);
        // convert params to strings of a certain max length
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];

            String paramLineStr = String.format("    Param %d: %s", i, param.toString());
            // trim param line if it's silly long
            if (paramLineStr.length() > MAX_PARAM_LINE_CHARS) {
                paramLineStr = paramLineStr.substring(0, MAX_PARAM_LINE_CHARS - 3);
                paramLineStr += "...";
            }

            sb.append('\n').append(paramLineStr);
        }

        return sb.toString();
    }
525559
def generalize_sql(sql):
    
    if sql is None:
        return None

    # multiple spaces
    sql = re.sub(r'\s{2,}', ' ', sql)

    # MW comments
    # e.g. /* CategoryDataService::getMostVisited N.N.N.N */
    sql = remove_comments_from_sql(sql)

    # handle LIKE statements
    sql = normalize_likes(sql)

    sql = re.sub(r"\\\\", '', sql)
    sql = re.sub(r"\\'", '', sql)
    sql = re.sub(r'\\"', '', sql)
    sql = re.sub(r"'[^\']*'", 'X', sql)
    sql = re.sub(r'"[^\"]*"', 'X', sql)

    # All newlines, tabs, etc replaced by single space
    sql = re.sub(r'\s+', ' ', sql)

    # All numbers => N
    sql = re.sub(r'-?[0-9]+', 'N', sql)

    # WHERE foo IN ('880987','882618','708228','522330')
    sql = re.sub(r' (IN|VALUES)\s*\([^,]+,[^)]+\)', ' \\1 (XYZ)', sql, flags=re.IGNORECASE)

    return sql.strip()
1097605
@Override
    public void runDDL(String ddl) {
        String modifiedDdl = transformDDL(ddl);
        printTransformedSql(ddl, modifiedDdl);
        super.runDDL(modifiedDdl, false);
    }
422791
function reassignConditionalStatementIds(conditionalStatement) {
        conditionalStatement.sourceField = tempFieldPageIdsMap[conditionalStatement.sourceField] || conditionalStatement.sourceField;
        return conditionalStatement;
      }
250291
def convert(cls, **kwargsql):
        
        filters = []
        for k, v in kwargsql.items():
            terms = k.split('__')
            if terms[-1] in cls.KWARGQL_SUPPORTED_MONGO_OPS:
                v = {
                    '$' + terms[-1]: v
                }
                if terms[-1] == 'exists':
                    v['$exists'] = bool(v['$exists'])
                terms = terms[:-1]
            elif terms[-1] in cls.KWARGSQL_REGEX_OPS:
                config = cls.KWARGSQL_REGEX_OPS[terms[-1]]
                pattern = '^{prefix}{pattern}{suffix}$'.format(
                    prefix=config.get('prefix', ''),
                    pattern=re.escape(v),
                    suffix=config.get('suffix', '')
                )
                v = {
                    '$regex': pattern,
                    '$options': config.get('options', ''),
                }
                terms = terms[:-1]
            k = '.'.join(terms)
            filters.append({k: v})
        if len(filters) == 0:
            return {}
        if len(filters) == 1:
            return filters[0]
        else:
            return {
                '$and': filters
            }
1159252
public String transformDDL(String ddl) {
        return transformQuery(ddl, dropTableIfExistsDdlTransformer,
                varcharBytesDdlTransformer, varbinaryDdlTransformer,
                tinyintDdlTransformer, assumeUniqueDdlTransformer);
    }
870641
def _make_sql_params(self,kw):
        """"""
        return ['%s=?' %k for k in kw.keys() ]
        for k,v in kw.iteritems():
            vals.append('%s=?' %k)
        return vals
1061590
private void fixSchema(CmsSetupDb dbCon) throws SQLException {

        Map<String, String> replacer = new HashMap<String, String>();
        String tableName;
        String fieldName;
        String fieldType;
        String nullAcceptInfo;
        String defaultValue;
        String query;
        for (int i = 0; i < DB_ARRAY.length; i++) {
            tableName = DB_ARRAY[i][0];
            fieldName = DB_ARRAY[i][1];
            fieldType = DB_ARRAY[i][2];
            nullAcceptInfo = DB_ARRAY[i][3];
            defaultValue = DB_ARRAY[i][4];

            if ((fieldType != null) && (fieldType.length() > 0)) {
                initReplacer(replacer, tableName, fieldName);
                replacer.put(REPLACEMENT_FIELD_TYPE, fieldType);
                query = readQuery(QUERY_ALTER_FIELD);
                dbCon.updateSqlStatement(query, replacer, null);
            }

            if ((nullAcceptInfo != null) && (!nullAcceptInfo.equals(NO_CHANGE))) {
                String q;
                if (nullAcceptInfo.equals(DROP_NOT_NULL)) {
                    q = QUERY_DROP_NOT_NULL;
                } else {
                    q = QUERY_SET_NOT_NULL;
                }
                query = readQuery(q);
                initReplacer(replacer, tableName, fieldName);
                dbCon.updateSqlStatement(query, replacer, null);
            }

            if ((defaultValue != null) && (defaultValue.length() > 0)) {
                initReplacer(replacer, tableName, fieldName);
                if (defaultValue.equals(DV_DROP)) {
                    query = readQuery(QUERY_DROP_DEFAULT_VALUE);
                    dbCon.updateSqlStatement(query, replacer, null);
                } else {
                    query = readQuery(QUERY_SET_DEFAULT_VALUE);
                    replacer.put(REPLACEMENT_FIELD_DEFAULT_VALUE, defaultValue);
                    dbCon.updateSqlStatement(query, replacer, null);
                }
            }

        }

    }