1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package file
import (
"encoding/binary"
"fmt"
"io"
"github.com/apache/arrow-go/v18/parquet"
"github.com/apache/arrow-go/v18/parquet/internal/encryption"
"github.com/apache/arrow-go/v18/parquet/internal/utils"
"github.com/apache/arrow-go/v18/parquet/metadata"
"github.com/apache/arrow-go/v18/parquet/schema"
)
// Writer is the primary interface for writing a parquet file
type Writer struct {
sink utils.WriteCloserTell
open bool
footerFlushed bool
props *parquet.WriterProperties
rowGroups int
nrows int
metadata metadata.FileMetaDataBuilder
fileEncryptor encryption.FileEncryptor
rowGroupWriter *rowGroupWriter
pageIndexBuilder *metadata.PageIndexBuilder
// The Schema of this writer
Schema *schema.Schema
}
type writerConfig struct {
props *parquet.WriterProperties
keyValueMetadata metadata.KeyValueMetadata
}
type WriteOption func(*writerConfig)
func WithWriterProps(props *parquet.WriterProperties) WriteOption {
return func(c *writerConfig) {
c.props = props
}
}
func WithWriteMetadata(meta metadata.KeyValueMetadata) WriteOption {
return func(c *writerConfig) {
c.keyValueMetadata = meta
}
}
// NewParquetWriter returns a Writer that writes to the provided WriteSeeker with the given schema.
//
// If props is nil, then the default Writer Properties will be used. If the key value metadata is not nil,
// it will be added to the file.
func NewParquetWriter(w io.Writer, sc *schema.GroupNode, opts ...WriteOption) *Writer {
config := &writerConfig{}
for _, o := range opts {
o(config)
}
if config.props == nil {
config.props = parquet.NewWriterProperties()
}
fileSchema := schema.NewSchema(sc)
fw := &Writer{
props: config.props,
sink: &utils.TellWrapper{Writer: w},
open: true,
Schema: fileSchema,
}
fw.metadata = *metadata.NewFileMetadataBuilder(fw.Schema, fw.props, config.keyValueMetadata)
fw.startFile()
return fw
}
// NumColumns returns the number of columns to write as defined by the schema.
func (fw *Writer) NumColumns() int { return fw.Schema.NumColumns() }
// NumRowGroups returns the current number of row groups that will be written for this file.
func (fw *Writer) NumRowGroups() int { return fw.rowGroups }
// NumRows returns the current number of rows that have be written
func (fw *Writer) NumRows() int { return fw.nrows }
// Properties returns the writer properties that are in use for this file.
func (fw *Writer) Properties() *parquet.WriterProperties { return fw.props }
// AppendBufferedRowGroup appends a rowgroup to the file and returns a writer
// that buffers the row group in memory allowing writing multiple columns
// at once to the row group. Data is not flushed out until the row group
// is closed.
//
// When calling Close, all columns must have the same number of rows written.
func (fw *Writer) AppendBufferedRowGroup() BufferedRowGroupWriter {
return fw.appendRowGroup(true)
}
// AppendRowGroup appends a row group to the file and returns a writer
// that writes columns to the row group in serial via calling NextColumn.
//
// When calling NextColumn, the same number of rows need to have been written
// to each column before moving on. Otherwise the rowgroup writer will panic.
func (fw *Writer) AppendRowGroup() SerialRowGroupWriter {
return fw.appendRowGroup(false)
}
func (fw *Writer) appendRowGroup(buffered bool) *rowGroupWriter {
if fw.rowGroupWriter != nil {
fw.nrows += fw.rowGroupWriter.nrows
fw.rowGroupWriter.Close()
}
fw.rowGroups++
fw.footerFlushed = false
rgMeta := fw.metadata.AppendRowGroup()
if fw.pageIndexBuilder != nil {
fw.pageIndexBuilder.AppendRowGroup()
}
fw.rowGroupWriter = newRowGroupWriter(fw.sink, rgMeta, int16(fw.rowGroups)-1,
fw.props, buffered, fw.fileEncryptor, fw.pageIndexBuilder)
return fw.rowGroupWriter
}
func (fw *Writer) startFile() {
encryptionProps := fw.props.FileEncryptionProperties()
magic := magicBytes
if encryptionProps != nil {
// check that all columns in columnEncryptionProperties exist in the schema
encryptedCols := encryptionProps.EncryptedColumns()
// if columnEncryptionProperties is empty, every column in the file schema will be encrypted with the footer key
if len(encryptedCols) != 0 {
colPaths := make(map[string]bool)
for i := 0; i < fw.Schema.NumColumns(); i++ {
colPaths[fw.Schema.Column(i).Path()] = true
}
for k := range encryptedCols {
if _, ok := colPaths[k]; !ok {
panic("encrypted column " + k + " not found in file schema")
}
}
}
fw.fileEncryptor = encryption.NewFileEncryptor(encryptionProps, fw.props.Allocator())
if encryptionProps.EncryptedFooter() {
magic = magicEBytes
}
}
n, err := fw.sink.Write(magic)
if n != 4 || err != nil {
panic("failed to write magic number")
}
if fw.props.PageIndexEnabled() {
fw.pageIndexBuilder = &metadata.PageIndexBuilder{
Schema: fw.Schema,
Encryptor: fw.fileEncryptor,
}
}
}
func (fw *Writer) writePageIndex() {
if fw.pageIndexBuilder != nil {
// serialize page index after all row groups have been written and report
// location to the file metadata
fw.pageIndexBuilder.Finish()
var pageIndexLocation metadata.PageIndexLocation
fw.pageIndexBuilder.WriteTo(fw.sink, &pageIndexLocation)
fw.metadata.SetPageIndexLocation(pageIndexLocation)
}
}
// AppendKeyValueMetadata appends a key/value pair to the existing key/value metadata
func (fw *Writer) AppendKeyValueMetadata(key string, value string) error {
return fw.metadata.AppendKeyValueMetadata(key, value)
}
// Close closes any open row group writer and writes the file footer. Subsequent
// calls to close will have no effect.
func (fw *Writer) Close() (err error) {
if fw.open {
// if any functions here panic, we set open to be false so
// that this doesn't get called again
fw.open = false
defer func() {
fw.closeEncryptor()
ierr := fw.sink.Close()
if err != nil {
if ierr != nil {
err = fmt.Errorf("error on close:%w, %s", err, ierr)
}
return
}
err = ierr
}()
err = fw.FlushWithFooter()
fw.metadata.Clear()
}
return nil
}
// FlushWithFooter closes any open row group writer and writes the file footer, leaving
// the writer open for additional row groups. Additional footers written by later
// calls to FlushWithFooter or Close will be cumulative, so that only the last footer
// written need ever be read by a reader.
func (fw *Writer) FlushWithFooter() error {
if !fw.footerFlushed {
if fw.rowGroupWriter != nil {
fw.nrows += fw.rowGroupWriter.nrows
fw.rowGroupWriter.Close()
}
fw.rowGroupWriter = nil
fw.writePageIndex()
fileMetadata, err := fw.metadata.Snapshot()
if err != nil {
return err
}
fileEncryptProps := fw.props.FileEncryptionProperties()
if fileEncryptProps == nil { // non encrypted file
if _, err = writeFileMetadata(fileMetadata, fw.sink); err != nil {
return err
}
} else {
if err := fw.flushEncryptedFile(fileMetadata, fileEncryptProps); err != nil {
return err
}
}
fw.footerFlushed = true
}
return nil
}
func (fw *Writer) flushEncryptedFile(fileMetadata *metadata.FileMetaData, props *parquet.FileEncryptionProperties) error {
// encrypted file with encrypted footer
if props.EncryptedFooter() {
footerLen := int64(0)
cryptoMetadata := fw.metadata.GetFileCryptoMetaData()
n, err := writeFileCryptoMetadata(cryptoMetadata, fw.sink)
if err != nil {
return err
}
footerLen += n
footerEncryptor := fw.fileEncryptor.GetFooterEncryptor()
n, err = writeEncryptedFileMetadata(fileMetadata, fw.sink, footerEncryptor, true)
if err != nil {
return err
}
footerLen += n
if err = binary.Write(fw.sink, binary.LittleEndian, uint32(footerLen)); err != nil {
return err
}
if _, err = fw.sink.Write(magicEBytes); err != nil {
return err
}
} else {
footerSigningEncryptor := fw.fileEncryptor.GetFooterSigningEncryptor()
if _, err := writeEncryptedFileMetadata(fileMetadata, fw.sink, footerSigningEncryptor, false); err != nil {
return err
}
}
return nil
}
func (fw *Writer) closeEncryptor() {
if fw.fileEncryptor != nil {
fw.fileEncryptor.WipeOutEncryptionKeys()
}
}
func writeFileMetadata(fileMetadata *metadata.FileMetaData, w io.Writer) (n int64, err error) {
n, err = fileMetadata.WriteTo(w, nil)
if err != nil {
return
}
if err = binary.Write(w, binary.LittleEndian, uint32(n)); err != nil {
return
}
if _, err = w.Write(magicBytes); err != nil {
return
}
return n + int64(4+len(magicBytes)), nil
}
func writeEncryptedFileMetadata(fileMetadata *metadata.FileMetaData, w io.Writer, encryptor encryption.Encryptor, encryptFooter bool) (n int64, err error) {
n, err = fileMetadata.WriteTo(w, encryptor)
if encryptFooter {
return
}
if err != nil {
return
}
if err = binary.Write(w, binary.LittleEndian, uint32(n)); err != nil {
return
}
if _, err = w.Write(magicBytes); err != nil {
return
}
return n + int64(4+len(magicBytes)), nil
}
func writeFileCryptoMetadata(crypto *metadata.FileCryptoMetadata, w io.Writer) (int64, error) {
return crypto.WriteTo(w)
}
|