Skip to content

Commit

Permalink
Merge pull request #16 from Ecwid/map_escaping
Browse files Browse the repository at this point in the history
Escaping strings in map
  • Loading branch information
kitty-ecwid authored Aug 21, 2024
2 parents ce2cbc1 + cff4047 commit 52862e2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 32 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ try (RawResponse response = client.select("http://localhost:8123", "SELECT * FRO
## How to add clickhouse-client into your project
### Gradle
```
compile "com.ecwid.clickhouse:clickhouse-client:0.15.0"
compile "com.ecwid.clickhouse:clickhouse-client:0.16.0"
```
### Maven
```
<dependency>
<groupId>com.ecwid.clickhouse</groupId>
<artifactId>clickhouse-client</artifactId>
<version>0.15.0</version>
<version>0.16.0</version>
</dependency>
```

Expand Down
62 changes: 32 additions & 30 deletions src/main/kotlin/com/ecwid/clickhouse/convert/Convert.kt
Original file line number Diff line number Diff line change
Expand Up @@ -386,34 +386,6 @@ object Convert {

@JvmStatic
fun fromNullableArray(array: List<String?>) = array.map(::fromNullableValue)

private const val QUOTE: Char = '\''
private const val BACKSLASH = '\\'

private fun escapeAndQuoteString(str: String): String {
// 2 symbols for quotes and 8 for possible escaping
// it's just heuristics, no serious science behind :)
val capacity = str.length + 10

return buildString(capacity) {
append(QUOTE)

for (char in str) {
when (char) {
QUOTE -> {
append(BACKSLASH)
append(QUOTE)
}
BACKSLASH -> {
append(BACKSLASH)
append(BACKSLASH)
}
else -> append(char)
}
}
append(QUOTE)
}
}
}

object DateTime {
Expand Down Expand Up @@ -538,11 +510,41 @@ object Convert {
@JvmStatic
fun fromValue(map: kotlin.collections.Map<String, String?>) =
map.map { kv ->
val value = kv.value?.let { "'$it'" } ?: "NULL"
"'${kv.key}'" to value
val value = kv.value?.let { escapeAndQuoteString(it) } ?: "NULL"
escapeAndQuoteString(kv.key) to value
}.toMap()

@JvmStatic
fun toMapValue(map: kotlin.collections.Map<String, String?>) = fromValue(map)
}

private const val QUOTE: Char = '\''
private const val BACKSLASH = '\\'

private fun escapeAndQuoteString(str: String): String {
// 2 symbols for quotes and 8 for possible escaping
// it's just heuristics, no serious science behind :)
val capacity = str.length + 10

return buildString(capacity) {
append(QUOTE)

for (char in str) {
when (char) {
QUOTE -> {
append(BACKSLASH)
append(QUOTE)
}

BACKSLASH -> {
append(BACKSLASH)
append(BACKSLASH)
}

else -> append(char)
}
}
append(QUOTE)
}
}
}

0 comments on commit 52862e2

Please sign in to comment.