public String toCsvField()

in server/pxf-api/src/main/java/org/greenplum/pxf/api/model/GreenplumCSV.java [229:283]


    public String toCsvField(String s,
                             boolean prependQuoteChar,
                             boolean appendQuoteChar,
                             boolean skipIfQuotingIsNotNeeded) {
        if (s == null) return null;

        final int length = s.length();
        int i, j, quotes = 0, specialChars = 0, pos = 0, total = length;

        // count all the quotes
        for (i = 0; i < length; i++) {
            char curr = s.charAt(i);
            if (escape != null && curr == quote) quotes++;
            if (delimiter != null && curr == delimiter)
                specialChars++;
            if (newlineLength > 0) {
                j = 0;

                // let's say we have input asd\r\nacd
                // and newline \r\n then we need to
                // increase the specialChars count by 1

                while (i < length && j < newlineLength
                        && newline.charAt(j) == s.charAt(i)) {
                    j++;
                    if (j < newlineLength) i++;
                }

                if (j == newlineLength) specialChars++;
            }
        }

        if (prependQuoteChar) total += 1;
        if (appendQuoteChar) total += 1;
        total += quotes;

        // if there are QUOTE, DELIMITER, NEWLINE characters
        // in the string we also need to quote the CSV field
        if (length == total || (skipIfQuotingIsNotNeeded && quotes == 0 && specialChars == 0))
            return s;

        char[] chars = new char[total];

        if (prependQuoteChar) chars[pos++] = quote;

        for (i = 0; i < length; i++) {
            if (escape != null && quotes > 0 && s.charAt(i) == quote)
                chars[pos++] = escape; // escape quote char
            chars[pos++] = s.charAt(i);
        }

        if (appendQuoteChar) chars[pos] = quote;

        return new String(chars);
    }