Skip to content
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

Escaping strings in map #16

Merged
merged 2 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
}
Loading