Skip to content

Commit

Permalink
Fix for generated SQL which would be truncate when word contains a qu…
Browse files Browse the repository at this point in the history
…ote character (#1402)

* Fix for generated SQL which would be truncate when word contains a quote character

---------

Co-authored-by: gaohaitao <[email protected]>
Co-authored-by: Erik Pragt <[email protected]>
  • Loading branch information
3 people authored Oct 26, 2024
1 parent 388052e commit 8260c40
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -219,19 +219,16 @@ private String handleObject(Object value) {
}

private String handledObjectToString(int length, String strValue) {
StringJoiner joiner = null;
StringBuilder builder = new StringBuilder(length);

int j = 0;
for (int k = 0; k < length; k++) {
if (strValue.charAt(k) == quote) {
if (joiner == null) {
joiner = new StringJoiner("" + quote);
}
joiner.add(strValue.substring(j, k + 1));
j = k + 1;
builder.append('\\').append(quote);
}else {
builder.append(strValue.charAt(k));
}
}
return joiner == null ? strValue : joiner.toString();
return builder.toString();
}

private String handlePrimitivesInArray(Class<?> componentType, Object value) {
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/net/datafaker/formats/SqlTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.junit.jupiter.params.provider.MethodSource;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
Expand Down Expand Up @@ -569,4 +570,28 @@ void testSqlBatch() {

assertThat(sql).isEqualTo(expected);
}

@Test
void testWordTruncated() {
BaseFaker faker = new BaseFaker(new Locale("test"),new Random(10L));
Schema<Integer, ?> schema = Schema.of(
field("Adress", () -> faker.address().country()),
field("Book", () -> faker.book().title())
);

SqlTransformer<Integer> transformer =
SqlTransformer
.<Integer>builder()
.batch(4)
.build();

String sql = transformer.generateStream(schema,3).collect(Collectors.joining(LINE_SEPARATOR));

String expected = "INSERT INTO \"MyTable\" (\"Adress\", \"Book\")" + LINE_SEPARATOR +
"VALUES ('Cote d\\'Ivoire', 'All the King\\'s Men')," + LINE_SEPARATOR +
" ('Cote d\\'Ivoire', 'Blood\\'s a Rover')," + LINE_SEPARATOR +
" ('Cote d\\'Ivoire', 'Blood\\'s a Rover');";

assertThat(sql).isEqualTo(expected);
}
}
7 changes: 7 additions & 0 deletions src/test/resources/test.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
test:
faker:
book:
title:
- "Blood's a Rover"
- "All the King's Men"
address:
country:
- "Cote d'Ivoire"
code:
isbn_gs1:
- "333"
Expand Down

0 comments on commit 8260c40

Please sign in to comment.