init elowdb go-port commit

This commit is contained in:
41 changed files with 7273 additions and 0 deletions

201
tests/linedb_test.go Normal file
View File

@@ -0,0 +1,201 @@
package tests
import (
"os"
"testing"
"time"
"linedb/pkg/linedb"
)
func TestLineDbBasic(t *testing.T) {
// Очищаем тестовую папку
os.RemoveAll("./testdata")
// Создаем опции инициализации
initOptions := &linedb.LineDbInitOptions{
CacheSize: 100,
CacheTTL: time.Minute,
DBFolder: "./testdata",
Collections: []linedb.JSONLFileOptions{
{
CollectionName: "test",
AllocSize: 256,
},
},
}
// Создаем базу данных
db := linedb.NewLineDb(nil)
defer db.Close()
// Инициализируем базу данных
if err := db.Init(false, initOptions); err != nil {
t.Fatalf("Failed to init database: %v", err)
}
// Тест вставки
testData := map[string]any{
"name": "test",
"value": 123,
}
if err := db.Insert(testData, "test", linedb.LineDbAdapterOptions{}); err != nil {
t.Fatalf("Failed to insert data: %v", err)
}
// Тест чтения
allData, err := db.Read("test", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to read data: %v", err)
}
if len(allData) != 1 {
t.Fatalf("Expected 1 record, got %d", len(allData))
}
// Тест фильтрации
filter := map[string]any{"name": "test"}
filteredData, err := db.ReadByFilter(filter, "test", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to filter data: %v", err)
}
if len(filteredData) != 1 {
t.Fatalf("Expected 1 filtered record, got %d", len(filteredData))
}
// Тест обновления
updateData := map[string]any{"value": 456}
updateFilter := map[string]any{"name": "test"}
updatedData, err := db.Update(updateData, "test", updateFilter, linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to update data: %v", err)
}
if len(updatedData) != 1 {
t.Fatalf("Expected 1 updated record, got %d", len(updatedData))
}
// Тест удаления
deleteFilter := map[string]any{"name": "test"}
deletedData, err := db.Delete(deleteFilter, "test", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to delete data: %v", err)
}
if len(deletedData) != 1 {
t.Fatalf("Expected 1 deleted record, got %d", len(deletedData))
}
// Проверяем что данных больше нет
remainingData, err := db.Read("test", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to read remaining data: %v", err)
}
if len(remainingData) != 0 {
t.Fatalf("Expected 0 remaining records, got %d", len(remainingData))
}
}
func TestLineDbPartitioning(t *testing.T) {
// Очищаем тестовую папку
os.RemoveAll("./testdata")
// Создаем опции инициализации с партиционированием
initOptions := &linedb.LineDbInitOptions{
CacheSize: 100,
CacheTTL: time.Minute,
DBFolder: "./testdata",
Collections: []linedb.JSONLFileOptions{
{
CollectionName: "orders",
AllocSize: 256,
},
},
Partitions: []linedb.PartitionCollection{
{
CollectionName: "orders",
PartIDFn: func(item any) string {
if itemMap, ok := item.(map[string]any); ok {
if userId, exists := itemMap["userId"]; exists {
return toString(userId)
}
}
return "default"
},
},
},
}
// Создаем базу данных
db := linedb.NewLineDb(nil)
defer db.Close()
// Инициализируем базу данных
if err := db.Init(false, initOptions); err != nil {
t.Fatalf("Failed to init database: %v", err)
}
// Создаем заказы для разных пользователей
orders := []any{
map[string]any{
"userId": 1,
"item": "laptop",
"price": 999.99,
},
map[string]any{
"userId": 1,
"item": "mouse",
"price": 29.99,
},
map[string]any{
"userId": 2,
"item": "keyboard",
"price": 89.99,
},
}
// Вставляем заказы
if err := db.Insert(orders, "orders", linedb.LineDbAdapterOptions{}); err != nil {
t.Fatalf("Failed to insert orders: %v", err)
}
// Читаем все заказы
allOrders, err := db.Read("orders", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to read orders: %v", err)
}
if len(allOrders) != 3 {
t.Fatalf("Expected 3 orders, got %d", len(allOrders))
}
// Фильтруем заказы пользователя 1
user1Filter := map[string]any{"userId": 1}
user1Orders, err := db.ReadByFilter(user1Filter, "orders", linedb.LineDbAdapterOptions{})
if err != nil {
t.Fatalf("Failed to filter user 1 orders: %v", err)
}
if len(user1Orders) != 2 {
t.Fatalf("Expected 2 orders for user 1, got %d", len(user1Orders))
}
}
// toString конвертирует значение в строку
func toString(value any) string {
switch v := value.(type) {
case string:
return v
case int:
return string(rune(v))
case int64:
return string(rune(v))
case float64:
return string(rune(int(v)))
default:
return ""
}
}

30
tests/main_test.go Normal file
View File

@@ -0,0 +1,30 @@
package tests
import (
"os"
"testing"
)
func TestMain(m *testing.M) {
// Настройка перед тестами
setup()
// Запуск тестов
code := m.Run()
// Очистка после тестов
teardown()
// Выход с кодом
os.Exit(code)
}
func setup() {
// Создаем тестовые директории
os.MkdirAll("./testdata", 0755)
}
func teardown() {
// Очищаем тестовые данные
os.RemoveAll("./testdata")
}