package dbsync

import (
	"context"
	"path/filepath"
	"testing"
)

func TestEnsureTableFromRow(t *testing.T) {
	dir := t.TempDir()
	dsn := "file:" + filepath.ToSlash(filepath.Join(dir, "t.db")) + "?_pragma=busy_timeout(5000)"
	db, err := Open(DriverSQLite, dsn)
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	ctx := context.Background()
	row := map[string]any{"id": "u1", "title": "x"}
	if err := EnsureTableFromRow(ctx, db, DriverSQLite, "orders", "id", row); err != nil {
		t.Fatal(err)
	}
	if err := EnsureTableFromRow(ctx, db, DriverSQLite, "orders", "id", row); err != nil {
		t.Fatal(err)
	}
	var n int
	if err := db.QueryRowContext(ctx, `SELECT COUNT(1) FROM sqlite_master WHERE type='table' AND name='orders'`).Scan(&n); err != nil || n != 1 {
		t.Fatalf("table missing n=%d err=%v", n, err)
	}
}
