change module name 10
This commit is contained in:
@@ -402,6 +402,83 @@ func (j *JSONLFile) Read(options LineDbAdapterOptions) ([]any, error) {
|
||||
return records, scanner.Err()
|
||||
}
|
||||
|
||||
// ReadWithPhysicalLineIndexes как Read, но для каждой записи возвращает 0-based индекс строки (слота),
|
||||
// в том же смысле, что ReadByLineIndexes/WriteAtLineIndexes: смещение в файле = lineIndex * allocSize.
|
||||
// Пустые слоты (пробелы после удаления и т.п.) пропускаются; индекс — номер слота, а не порядковый номер записи.
|
||||
func (j *JSONLFile) ReadWithPhysicalLineIndexes(options LineDbAdapterOptions) ([]any, []int, error) {
|
||||
if !options.InTransaction {
|
||||
j.mutex.RLock()
|
||||
defer j.mutex.RUnlock()
|
||||
}
|
||||
|
||||
if !j.initialized {
|
||||
return nil, nil, fmt.Errorf("file not initialized")
|
||||
}
|
||||
if j.allocSize <= 0 {
|
||||
return nil, nil, fmt.Errorf("invalid allocSize")
|
||||
}
|
||||
|
||||
file, err := os.Open(j.filename)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("stat file: %w", err)
|
||||
}
|
||||
nSlots := int(info.Size()) / j.allocSize
|
||||
|
||||
buf := make([]byte, j.allocSize)
|
||||
var records []any
|
||||
var lineIndexes []int
|
||||
|
||||
for slot := 0; slot < nSlots; slot++ {
|
||||
n, err := io.ReadFull(file, buf)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read slot %d: %w", slot, err)
|
||||
}
|
||||
if n != j.allocSize {
|
||||
break
|
||||
}
|
||||
|
||||
line := string(buf[:n])
|
||||
line = strings.TrimRight(line, "\n")
|
||||
line = strings.TrimRight(line, " ")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if j.cypherKey != "" && !j.options.Encode {
|
||||
decoded, err := base64.StdEncoding.DecodeString(line)
|
||||
if err != nil {
|
||||
if j.options.SkipInvalidLines {
|
||||
continue
|
||||
}
|
||||
return nil, nil, fmt.Errorf("failed to decode base64: %w", err)
|
||||
}
|
||||
line = string(decoded)
|
||||
}
|
||||
|
||||
var record any
|
||||
if err := j.jsonUnmarshal([]byte(line), &record); err != nil {
|
||||
if j.options.SkipInvalidLines {
|
||||
continue
|
||||
}
|
||||
return nil, nil, fmt.Errorf("failed to unmarshal JSON: %w", err)
|
||||
}
|
||||
|
||||
records = append(records, record)
|
||||
lineIndexes = append(lineIndexes, slot)
|
||||
}
|
||||
|
||||
return records, lineIndexes, nil
|
||||
}
|
||||
|
||||
// ReadByLineIndexes читает записи по номерам строк (0-based) с использованием random access.
|
||||
// Ожидается, что файл нормализован и каждая строка имеет длину allocSize байт (включая \n),
|
||||
// как это обеспечивает Init/normalizeExistingFile/rewriteFile.
|
||||
|
||||
Reference in New Issue
Block a user