feat(redshift): read a Parquet column missing from a partition's files as NULL (#7406)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-03 10:29:39 -04:00
1 parent 240193e624
commit e82fa60617
8 files changed
+381 -12

No files matched your search

+7 -2
View File
@@ -711,8 +711,13 @@ GROUP BY c.country ORDER BY total DESC;
This path needs Docker for PostgreSQL and the existing floci-duck runtime used to read external
data. Use the `floci.duck` configuration described under [Athena](athena.md) to supply a reachable
runtime when container management is unsuitable. This iteration validates CSV relational reads;
it does not add new file formats or partition pruning.
runtime when container management is unsuitable.
Tables declared `STORED AS PARQUET` (or with a Parquet input format or SerDe in Glue) are read the same
way. Columns are matched to the Parquet files by name, ignoring case. A declared column that a partition's
files do not carry, as when the column was added to the table after those files were written, reads as
`NULL`. A value that cannot be converted to the declared type fails the query. Partition pruning is not
supported: every registered partition is listed, authorized and loaded.
Materialized relations are cached in the cluster database. Each new query checks the associated
role, trust policy and S3 access before using cached data, following the existing S3 enforcement
@@ -88,6 +88,21 @@ public final class GlueTableResolver {
return new ReadPlan(fromClause, false, columns);
}
/** Whether {@link #readPlan(Table, List)} reads this table's objects with {@code read_parquet}. */
public static boolean readsParquet(Table table) {
return !isIcebergTable(table) && "read_parquet".equals(inferReadFunction(table));
}
/**
* Lists the field names each given Parquet object carries, one row per object and field, nested
* fields and the schema root included. The object is named as it was passed in.
*/
public static String parquetSchemaSql(List<String> objectUris) {
String fileList = "[" + objectUris.stream().map(GlueTableResolver::sqlLiteral)
.collect(Collectors.joining(", ")) + "]";
return "SELECT file_name, name FROM parquet_schema(" + fileList + ")";
}
/**
* A table that declares CSV options (header lines to skip, a delimiter) is read with exactly
* those options and its declared columns rather than sniffed: a headerless file otherwise gets
@@ -30,7 +30,10 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@@ -720,8 +723,13 @@ public class ExternalTableMaterializer {
private void readWithDuckDb(String accountId, RedshiftRoleAccess.RoleSession roleSession,
Table table, List<ReadSource> sources, long maxRows,
String scratchKey) {
List<String> selects = sources.stream().filter(source -> source.partition() == null || !source.objects().isEmpty())
.map(this::readSelect).toList();
Map<String, Set<String>> columnsByObject = parquetColumnsByObject(accountId, roleSession, sources);
List<String> selects = new ArrayList<>();
for (ReadSource source : sources) {
if (source.partition() == null || !source.objects().isEmpty()) {
selects.add(readSelect(source, fileColumns(source, columnsByObject)));
}
}
if (selects.isEmpty() && GlueTableResolver.isIcebergTable(table)) {
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(table);
selects = List.of("SELECT " + projection(plan.columns()) + " FROM " + fromClause(plan, table));
@@ -749,17 +757,22 @@ public class ExternalTableMaterializer {
private List<Map<String, Object>> duckQuery(String accountId, RedshiftRoleAccess.RoleSession roleSession,
String sql) {
return duckQuery(accountId, roleSession, sql, ICEBERG_SETUP);
}
private List<Map<String, Object>> duckQuery(String accountId, RedshiftRoleAccess.RoleSession roleSession,
String sql, String setup) {
try {
if (!s3Service.isAuthEnforced()) {
return duckClient.query(sql, ICEBERG_SETUP, accountId);
return duckClient.query(sql, setup, accountId);
}
requireSignedSession(roleSession);
return duckClient.query(sql, ICEBERG_SETUP,
return duckClient.query(sql, setup,
roleSession.accessKeyId(), roleSession.secretAccessKey(), roleSession.sessionToken());
} catch (RuntimeException exception) {
if (isAccessDenied(exception)) {
throw new SpectrumReadException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
"Access denied during Iceberg metadata scan", exception);
"Access denied during external table metadata scan", exception);
}
throw exception;
}
@@ -842,17 +855,77 @@ public class ExternalTableMaterializer {
}
}
private String readSelect(ReadSource source) {
List<String> objectUris = source.objects().stream()
/**
* The field names, lower-cased, that each Parquet object of the read carries, from one query over all of
* them. A Parquet file written before a column was added to the table lacks it, and Spectrum reads that
* column as NULL, where naming it in the SELECT would fail the whole query. Nested field names are
* listed too, so a nested field that shares the name of a missing column leaves the column to be read,
* and fail, as before. Empty when no source is Parquet or the files cannot be described, which leaves
* every declared column to be read as declared.
*/
private Map<String, Set<String>> parquetColumnsByObject(String accountId,
RedshiftRoleAccess.RoleSession roleSession,
List<ReadSource> sources) {
List<String> objectUris = new ArrayList<>();
for (ReadSource source : sources) {
if (GlueTableResolver.readsParquet(source.table())) {
objectUris.addAll(objectUris(source));
}
}
if (objectUris.isEmpty()) {
return Map.of();
}
List<Map<String, Object>> rows;
try {
rows = duckQuery(accountId, roleSession, GlueTableResolver.parquetSchemaSql(objectUris), null);
} catch (SpectrumSqlException | SpectrumReadException exception) {
throw exception;
} catch (RuntimeException exception) {
// the read that follows names the same files, so a file that is really unreadable still fails there
LOG.warnv(exception, "Unable to describe the Parquet files of a read of {0} objects, "
+ "reading every declared column", objectUris.size());
return Map.of();
}
Map<String, Set<String>> columnsByObject = new HashMap<>();
for (Map<String, Object> row : rows) {
if (row.get("file_name") instanceof String file && row.get("name") instanceof String name) {
columnsByObject.computeIfAbsent(file, ignored -> new HashSet<>()).add(name.toLowerCase(Locale.ROOT));
}
}
return columnsByObject;
}
/** The columns the objects of one source carry; null when they are unknown, so every column is read. */
private static Set<String> fileColumns(ReadSource source, Map<String, Set<String>> columnsByObject) {
if (!GlueTableResolver.readsParquet(source.table())) {
return null;
}
Set<String> columns = new HashSet<>();
for (String uri : objectUris(source)) {
Set<String> described = columnsByObject.get(uri);
if (described == null) {
return null;
}
columns.addAll(described);
}
return columns.isEmpty() ? null : columns;
}
private static List<String> objectUris(ReadSource source) {
return source.objects().stream()
.map(object -> "s3://" + source.location().bucket() + "/" + object.getKey()).toList();
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(source.table(), objectUris);
}
private String readSelect(ReadSource source, Set<String> fileColumns) {
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(source.table(), objectUris(source));
String projection;
if (source.partition() == null) {
projection = projection(plan.columns());
projection = plan.columns().stream().map(column -> dataProjection(column, fileColumns))
.collect(Collectors.joining(", "));
} else {
List<Column> dataColumns = source.table().getStorageDescriptor().getColumns();
List<String> parts = new ArrayList<>(dataColumns.stream()
.map(column -> GlueTypeMapper.duckProjection(column.getName(), column.getType())).toList());
.map(column -> dataProjection(column, fileColumns)).toList());
List<Column> partitionKeys = source.table().getPartitionKeys();
List<String> values = source.partition().getValues();
for (int index = 0; index < partitionKeys.size(); index++) {
@@ -883,6 +956,13 @@ public class ExternalTableMaterializer {
return "iceberg_scan(" + sqlPathLiteral(GlueTableResolver.icebergMetadataLocation(table)) + ")";
}
private static String dataProjection(Column column, Set<String> fileColumns) {
if (fileColumns != null && !fileColumns.contains(column.getName().toLowerCase(Locale.ROOT))) {
return GlueTypeMapper.nullProjection(column.getName());
}
return GlueTypeMapper.duckProjection(column.getName(), column.getType());
}
private static String projection(List<Column> columns) {
return columns.stream().map(column -> GlueTypeMapper.duckProjection(column.getName(), column.getType()))
.collect(Collectors.joining(", "));
@@ -106,6 +106,11 @@ public final class GlueTypeMapper {
return "COALESCE(CAST(" + expression + " AS VARCHAR), " + NULL_MARKER + ") AS " + column;
}
/** A column the data files do not carry reads as NULL, the same marker a NULL value takes. */
public static String nullProjection(String columnName) {
return "COALESCE(CAST(NULL AS VARCHAR), " + NULL_MARKER + ") AS " + quote(columnName);
}
private static boolean isTypeOrSized(String type, String base) {
return type.equals(base) || type.startsWith(base + "(");
}
@@ -44,6 +44,24 @@ class GlueTableResolverTest {
assertThat(plan.iceberg(), is(false));
}
@Test
void listsParquetSchemasEscapingGlobCharactersAndQuotes() {
assertThat(GlueTableResolver.parquetSchemaSql(List.of("s3://bucket/a[1]/it's*.parquet", "s3://bucket/b.parquet")),
equalTo("SELECT file_name, name FROM parquet_schema("
+ "['s3://bucket/a[[]1]/it''s[*].parquet', 's3://bucket/b.parquet'])"));
}
@Test
void readsParquetOnlyForAParquetTableThatIsNotIceberg() {
Table parquet = table("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", "s3://bucket/events/",
List.of(column("id", "int")));
assertThat(GlueTableResolver.readsParquet(parquet), is(true));
assertThat(GlueTableResolver.readsParquet(table("org.apache.hadoop.mapred.TextInputFormat",
"s3://bucket/events/", List.of(column("id", "int")))), is(false));
parquet.setParameters(Map.of("table_type", "ICEBERG", "metadata_location", "s3://bucket/m/v1.json"));
assertThat(GlueTableResolver.readsParquet(parquet), is(false));
}
@Test
void readPlanForIcebergUsesMetadataLocation() {
Table table = table(null, "s3://bucket/iceberg/", List.of(column("id", "int")));
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Database;
import io.github.hectorvent.floci.services.glue.model.Table;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalCatalogRegistry;
@@ -34,7 +35,9 @@ import java.sql.Savepoint;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -43,6 +46,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -534,6 +539,72 @@ class RedshiftSpectrumIntegrationTest {
}
}
/**
* Parquet written by DuckDB: {@code id INTEGER, name VARCHAR, amt DECIMAL(5,2)} with zstd, and an older file
* that has {@code id INTEGER, NAME VARCHAR} only, with snappy and a different case.
*/
private static final String PARQUET_WITH_AMOUNT = "UEFSMRUAFQgVGiwVAhUAFQYVBgAAKLUv/SAEIQAAAQAAABUAFRIVJCwVAhUAFQYVBgAAKLUv/SAJSQAABQAAAEFsaWNlFQAVCBUaLBUCFQAVBhUGAAAotS/9IAQhAACWAAAAFQIZTDUAGA1kdWNrZGJfc2NoZW1hFQYAFQIlABgCaWQlIgAVDCUAGARuYW1lJQAAFQIlABgDYW10JQoVBBUKLFwVBBUKAAAAFgIZHBk8JgAcFQIZFQAZGAJpZBUMFgIWKhY8Jgg8GAQBAAAAGAQBAAAAFgAoBAEAAAAYBAEAAAAREQAZHBUAFQAVAgAAACYAHBUMGRUAGRgEbmFtZRUMFgIWNBZGJkQ8GAVBbGljZRgFQWxpY2UWACgFQWxpY2UYBUFsaWNlEREAGRwVABUAFQIAAAAmABwVAhkVABkYA2FtdBUMFgIWKhY8JooBPBgElgAAABgElgAAABYAKASWAAAAGASWAAAAEREAGRwVABUAFQIAAAAWiAEWAiYIFr4BACgoRHVja0RCIHZlcnNpb24gdjIuMC4wIChidWlsZCBkNTRjYmJlM2RmKRk8HAAAHAAAHAAAAFcBAABQQVIx";
private static final String PARQUET_WITHOUT_AMOUNT = "UEFSMRUAFQgVDCwVAhUAFQYVBgAABAwCAAAAFQAVDhUSLBUCFQAVBhUGAAAHGAMAAABCb2IVAhk8NQAYDWR1Y2tkYl9zY2hlbWEVBAAVAiUAGAJpZCUiABUMJQAYBE5BTUUlAAAWAhkcGSwmABwVAhkVABkYAmlkFQIWAhYqFi4mCDwYBAIAAAAYBAIAAAAWACgEAgAAABgEAgAAABERABkcFQAVABUCAAAAJgAcFQwZFQAZGAROQU1FFQIWAhYwFjQmNjwYA0JvYhgDQm9iFgAoA0JvYhgDQm9iEREAGRwVABUAFQIAAAAWWhYCJggWYgAoKER1Y2tEQiB2ZXJzaW9uIHYyLjAuMCAoYnVpbGQgZDU0Y2JiZTNkZikZLBwAABwAAADwAAAAUEFSMQ==";
@Test
@Timeout(120)
void queriesParquetPartitionsAndReadsAColumnTheOlderFilesLackAsNull() throws Exception {
glueDatabase = "spectrum_parquet_" + System.nanoTime();
Database database = new Database();
database.setName(glueDatabase);
glueService.createDatabase(database);
bucket = "spectrum-parquet-" + System.nanoTime();
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "events/day=2026-01-01/part-1.parquet",
Base64.getDecoder().decode(PARQUET_WITH_AMOUNT), "application/octet-stream", null);
s3Service.putObject(bucket, "events/day=2026-01-02/part-1.parquet",
Base64.getDecoder().decode(PARQUET_WITHOUT_AMOUNT), "application/octet-stream", null);
String schemaName = "parquet_lake";
String externalDdl = "CREATE EXTERNAL TABLE " + schemaName + ".events (id INTEGER, name VARCHAR(20), "
+ "amt DECIMAL(5,2)) PARTITIONED BY (day VARCHAR(10)) STORED AS PARQUET "
+ "LOCATION 's3://" + bucket + "/events/'";
ExternalStatement.CreateTable external = (ExternalStatement.CreateTable)
new ExternalStatementParser().parse(externalDdl).orElseThrow();
Table glueTable = GlueTableBuilder.toGlueTable(external);
glueService.createTable(glueDatabase, glueTable);
glueService.createPartition(glueDatabase, "events", GlueTableBuilder.toGluePartition(glueTable,
new ExternalStatement.PartitionSpec(Map.of("day", "2026-01-01"),
"s3://" + bucket + "/events/day=2026-01-01/")));
glueService.createPartition(glueDatabase, "events", GlueTableBuilder.toGluePartition(glueTable,
new ExternalStatement.PartitionSpec(Map.of("day", "2026-01-02"),
"s3://" + bucket + "/events/day=2026-01-02/")));
clusterId = "it-parquet-" + System.nanoTime();
Cluster cluster = createClusterWithRole(clusterId);
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE EXTERNAL SCHEMA " + schemaName + " FROM DATA CATALOG DATABASE '"
+ glueDatabase + "' IAM_ROLE '" + ROLE_ARN + "'");
try (ResultSet rows = statement.executeQuery(
"SELECT id, name, amt::text AS amt, day FROM " + schemaName + ".events ORDER BY id")) {
assertTrue(rows.next());
assertEquals(1, rows.getInt("id"));
assertEquals("Alice", rows.getString("name"));
assertEquals("1.50", rows.getString("amt"));
assertEquals("2026-01-01", rows.getString("day"));
assertTrue(rows.next());
assertEquals(2, rows.getInt("id"));
assertEquals("Bob", rows.getString("name"));
assertNull(rows.getString("amt"));
assertEquals("2026-01-02", rows.getString("day"));
assertFalse(rows.next());
}
statement.execute("DROP SCHEMA IF EXISTS " + schemaName + " CASCADE");
} finally {
s3Service.deleteObject(bucket, "events/day=2026-01-01/part-1.parquet");
s3Service.deleteObject(bucket, "events/day=2026-01-02/part-1.parquet");
}
}
private static void assertTotal(Statement statement, long total) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT COALESCE(SUM(amount),0) FROM lake.events")) {
assertTrue(rows.next());
@@ -62,6 +62,7 @@ import static org.mockito.Mockito.when;
class ExternalTableMaterializerTest {
private static final String ACCOUNT = "000000000000";
private static final String EVENTS_FILE = "s3://bucket/events/p1.parquet";
private static final ExternalSchemaBinding BINDING = new ExternalSchemaBinding(ACCOUNT, ACCOUNT + ":c",
"dev", "analytics", "lake", "arn:aws:iam::000000000000:role/R");
private static final String TRUST_POLICY = """
@@ -969,6 +970,174 @@ class ExternalTableMaterializerTest {
}
}
@Test
void readsAParquetColumnMissingFromThePartitionFilesAsNull() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(duck.query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), isNull(), eq(ACCOUNT)))
.thenReturn(List.of(schemaRow(EVENTS_FILE, "id")));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).query(argThat(sql -> sql.equals(
"SELECT file_name, name FROM parquet_schema(['s3://bucket/events/p1.parquet'])")),
isNull(), eq(ACCOUNT));
verify(duck).execute(argThat(sql -> sql.contains("COALESCE(CAST(NULL AS VARCHAR), '\\N') AS \"name\"")
&& !sql.contains("CAST(\"name\"")), any(), anyString(), eq(ACCOUNT));
}
@Test
void matchesParquetColumnsToTheDeclaredNamesIgnoringCase() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(duck.query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), isNull(), eq(ACCOUNT)))
.thenReturn(List.of(schemaRow(EVENTS_FILE, "ID"), schemaRow(EVENTS_FILE, "Name")));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("CAST(\"id\" AS VARCHAR)")
&& sql.contains("CAST(\"name\" AS VARCHAR)")
&& !sql.contains("CAST(NULL AS VARCHAR)")), any(), anyString(), eq(ACCOUNT));
}
@Test
void describesAndProjectsEachParquetPartitionOnItsOwn() {
Table table = parquetPartitionedTable();
Column amt = new Column();
amt.setName("amt");
amt.setType("int");
List<Column> columns = new ArrayList<>(table.getStorageDescriptor().getColumns());
columns.add(amt);
table.getStorageDescriptor().setColumns(columns);
when(glue.getTable("lake", "events")).thenReturn(table);
Partition current = parquetPartitionAt(table, "s3://bucket/current/", "2026-01-02");
Partition older = parquetPartitionAt(table, "s3://bucket/older/", "2026-01-01");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(older, current));
when(duck.query(argThat(sql -> sql != null && sql.startsWith("SELECT file_name, name FROM parquet_schema")),
isNull(), eq(ACCOUNT)))
.thenReturn(List.of(schemaRow("s3://bucket/current/part-1.parquet", "id"),
schemaRow("s3://bucket/current/part-1.parquet", "name"),
schemaRow("s3://bucket/current/part-1.parquet", "amt"),
schemaRow("s3://bucket/older/part-1.parquet", "id"),
schemaRow("s3://bucket/older/part-1.parquet", "name")));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")
&& sql.contains("s3://bucket/current/part-1.parquet") && sql.contains("s3://bucket/older/part-1.parquet")),
isNull(), eq(ACCOUNT));
verify(duck).execute(argThat(sql -> sql.contains("CAST(\"amt\" AS VARCHAR)")
&& sql.contains("COALESCE(CAST(NULL AS VARCHAR), '\\N') AS \"amt\"")), any(), anyString(), eq(ACCOUNT));
}
@Test
void describesParquetFilesAsTheRoleSessionWhenS3AuthIsEnforced() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(s3.isAuthEnforced()).thenReturn(true);
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"}
]}""")));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), isNull(),
startsWith("ASIA"), anyString(), notNull());
verify(duck, never()).query(anyString(), any(), eq(ACCOUNT));
}
@Test
void readsEveryDeclaredColumnWhenDescribingTheParquetFilesFails() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(duck.query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), isNull(), eq(ACCOUNT)))
.thenThrow(new IllegalStateException("sidecar rejected the statement"));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("CAST(\"name\" AS VARCHAR)")), any(), anyString(), eq(ACCOUNT));
}
@Test
void deniesTheLoadWhenDescribingTheParquetFilesIsDenied() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(duck.query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), isNull(), eq(ACCOUNT)))
.thenThrow(new IllegalStateException("HTTP 403 Forbidden"));
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void readsEveryDeclaredColumnWhenTheParquetFilesCannotBeDescribed() {
Table table = parquetPartitionedTable();
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = parquetPartition(table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("CAST(\"id\" AS VARCHAR)")
&& sql.contains("CAST(\"name\" AS VARCHAR)")), any(), anyString(), eq(ACCOUNT));
}
@Test
void doesNotDescribeTheFilesOfATextTable() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck, never()).query(argThat(sql -> sql.startsWith("SELECT file_name, name FROM parquet_schema")), any(), anyString());
verify(duck, never()).query(anyString(), any(), anyString(), anyString(), any());
}
private static Map<String, Object> schemaRow(String file, String name) {
return Map.of("file_name", file, "name", name);
}
private Partition parquetPartitionAt(Table table, String location, String day) {
Partition partition = partitionAt("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", table);
partition.getStorageDescriptor().setLocation(location);
partition.setValues(List.of(day));
String prefix = location.substring("s3://bucket/".length());
when(s3.listObjectsWithPrefixes(eq("bucket"), eq(prefix), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", prefix + "part-1.parquet", new byte[]{1},
"application/octet-stream", "etag-" + day)), List.of(), false, null));
return partition;
}
private Table parquetPartitionedTable() {
Table table = csvTable();
table.getStorageDescriptor().setInputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat");
table.setPartitionKeys(List.of(new Column("day", "string")));
return table;
}
private Partition parquetPartition(Table table) {
Partition partition = partitionAt("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", table);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.parquet", new byte[]{1}, "application/octet-stream", "etag1")),
List.of(), false, null));
return partition;
}
private Partition partitionAt(String inputFormat, Table table) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation("s3://bucket/events/");
@@ -38,6 +38,12 @@ class GlueTypeMapperTest {
equalTo("COALESCE(CAST('\\x' || hex(\"payload\") AS VARCHAR), '\\N') AS \"payload\""));
}
@Test
void projectsAMissingColumnAsTheNullMarkerUnderItsQuotedName() {
assertThat(GlueTypeMapper.nullProjection("we\"ird"),
equalTo("COALESCE(CAST(NULL AS VARCHAR), '\\N') AS \"we\"\"ird\""));
}
@Test
void nullsSizedStringValuesWiderThanTheColumnInBytes() {
String expected = "COALESCE(CAST(CASE WHEN strlen(CAST(\"name\" AS VARCHAR)) > %d THEN NULL ELSE \"name\" END"