import { ClickHouseClient, ResultSet, CommandResult } from '@clickhouse/client';
import { IJsonSchemaCollection, tags } from 'typia';
import { Pattern, TagBase } from 'typia/lib/tags';
import { Readable } from 'node:stream';

/**
 * Quote a ClickHouse identifier with backticks if not already quoted.
 * Backticks allow special characters (e.g., hyphens) in identifiers.
 */
declare const quoteIdentifier: (name: string) => string;
type IdentifierBrandedString = string & {
    readonly __identifier_brand?: unique symbol;
};
type NonIdentifierBrandedString = string & {
    readonly __identifier_brand?: unique symbol;
};
/**
 * Values supported by SQL engine.
 */
type Value = NonIdentifierBrandedString | number | boolean | Date | [string, string];
/**
 * Supported value or SQL instance.
 */
type RawValue = Value | Sql;
/**
 * Sql template tag interface with attached helper methods.
 */
interface SqlTemplateTag {
    /**
     * @deprecated Use `sql.statement` for full SQL statements or `sql.fragment` for SQL fragments.
     */
    (strings: readonly string[], ...values: readonly (RawValue | Column | OlapTable<any> | View)[]): Sql;
    /**
     * Template literal tag for complete SQL statements (e.g. SELECT, INSERT, CREATE).
     * Produces a Sql instance with `isFragment = false`.
     */
    statement(strings: readonly string[], ...values: readonly (RawValue | Column | OlapTable<any> | View)[]): Sql;
    /**
     * Template literal tag for SQL fragments (e.g. expressions, conditions, partial clauses).
     * Produces a Sql instance with `isFragment = true`.
     */
    fragment(strings: readonly string[], ...values: readonly (RawValue | Column | OlapTable<any> | View)[]): Sql;
    /**
     * Join an array of Sql fragments with a separator.
     * @param fragments - Array of Sql fragments to join
     * @param separator - Optional separator string (defaults to ", ")
     */
    join(fragments: Sql[], separator?: string): Sql;
    /**
     * Create raw SQL from a string without parameterization.
     * WARNING: SQL injection risk if used with untrusted input.
     */
    raw(text: string): Sql;
}
declare const sql: SqlTemplateTag;
/**
 * A SQL instance can be nested within each other to build SQL strings.
 */
declare class Sql {
    readonly values: Value[];
    readonly strings: string[];
    readonly isFragment: boolean | undefined;
    constructor(rawStrings: readonly string[], rawValues: readonly (RawValue | Column | OlapTable<any> | View | Sql)[], isFragment?: boolean);
    /**
     * Append another Sql fragment, returning a new Sql instance.
     */
    append(other: Sql): Sql;
}
declare const toStaticQuery: (sql: Sql) => string;
declare const toQuery: (sql: Sql) => [string, {
    [pN: string]: any;
}];
/**
 * Build a display-only SQL string with values inlined for logging/debugging.
 * Does not alter execution behavior; use toQuery for actual execution.
 */
declare const toQueryPreview: (sql: Sql) => string;
declare const getValueFromParameter: (value: any) => any;
declare function createClickhouseParameter(parameterIndex: number, value: Value): string;
/**
 * Convert the JS type (source is JSON format by API query parameter) to the corresponding ClickHouse type for generating named placeholder of parameterized query.
 * Only support to convert number to Int or Float, boolean to Bool, string to String, other types will convert to String.
 * If exist complex type e.g: object, Array, null, undefined, Date, Record.. etc, just convert to string type by ClickHouse function in SQL.
 * ClickHouse support converting string to other types function.
 * Please see Each section of the https://clickhouse.com/docs/en/sql-reference/functions and https://clickhouse.com/docs/en/sql-reference/functions/type-conversion-functions
 * @param value
 * @returns 'Float', 'Int', 'Bool', 'String'
 */
declare const mapToClickHouseType: (value: Value) => string;

type EnumValues = {
    name: string;
    value: {
        Int: number;
    };
}[] | {
    name: string;
    value: {
        String: string;
    };
}[];
type DataEnum = {
    name: string;
    values: EnumValues;
};
type Nested = {
    name: string;
    columns: Column[];
    jwt: boolean;
};
type ArrayType = {
    elementType: DataType;
    elementNullable: boolean;
};
type NamedTupleType = {
    fields: Array<[string, DataType]>;
};
type MapType = {
    keyType: DataType;
    valueType: DataType;
};
type JsonOptions = {
    max_dynamic_paths?: number;
    max_dynamic_types?: number;
    typed_paths?: Array<[string, DataType]>;
    skip_paths?: string[];
    skip_regexps?: string[];
};
type DataType = string | DataEnum | ArrayType | Nested | NamedTupleType | MapType | JsonOptions | {
    nullable: DataType;
};
interface Column {
    name: IdentifierBrandedString;
    data_type: DataType;
    required: boolean;
    unique: false;
    primary_key: boolean;
    default: string | null;
    materialized: string | null;
    alias: string | null;
    ttl: string | null;
    codec: string | null;
    annotations: [string, any][];
    comment: string | null;
}

/**
 * Type definition for typia validation functions
 */
interface TypiaValidators<T> {
    /** Typia validator function: returns { success: boolean, data?: T, errors?: any[] } */
    validate?: (data: unknown) => {
        success: boolean;
        data?: T;
        errors?: any[];
    };
    /** Typia assert function: throws on validation failure, returns T on success */
    assert?: (data: unknown) => T;
    /** Typia is function: returns boolean indicating if data matches type T */
    is?: (data: unknown) => data is T;
}
/**
 * Base class for all typed Moose dmv2 resources (OlapTable, Stream, etc.).
 * Handles the storage and injection of schema information (JSON schema and Column array)
 * provided by the Moose compiler plugin.
 *
 * @template T The data type (interface or type alias) defining the schema of the resource.
 * @template C The specific configuration type for the resource (e.g., OlapConfig, StreamConfig).
 */
declare class TypedBase<T, C> {
    /** The JSON schema representation of type T. Injected by the compiler plugin. */
    schema: IJsonSchemaCollection.IV3_1;
    /** The name assigned to this resource instance. */
    name: string;
    /** A dictionary mapping column names (keys of T) to their Column definitions. */
    columns: {
        [columnName in keyof Required<T>]: Column;
    };
    /** An array containing the Column definitions for this resource. Injected by the compiler plugin. */
    columnArray: Column[];
    /** The configuration object specific to this resource type. */
    config: C;
    /** Typia validation functions for type T. Injected by the compiler plugin for OlapTable. */
    validators?: TypiaValidators<T>;
    /** Optional metadata for the resource, always present as an object. */
    metadata: {
        [key: string]: any;
    };
    /**
     * Whether this resource allows extra fields beyond the defined columns.
     * When true, extra fields in payloads are passed through to streaming functions.
     * Injected by the compiler plugin when the type has an index signature.
     */
    allowExtraFields: boolean;
    /**
     * @internal Constructor intended for internal use by subclasses and the compiler plugin.
     * It expects the schema and columns to be provided, typically injected by the compiler.
     *
     * @param name The name for the resource instance.
     * @param config The configuration object for the resource.
     * @param schema The JSON schema for the resource's data type T (injected).
     * @param columns The array of Column definitions for T (injected).
     * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
     */
    constructor(name: string, config: C, schema?: IJsonSchemaCollection.IV3_1, columns?: Column[], validators?: TypiaValidators<T>, allowExtraFields?: boolean);
}

type ClickHousePrecision<P extends number> = {
    _clickhouse_precision?: P;
};
declare const DecimalRegex: "^-?\\d+(\\.\\d+)?$";
type ClickHouseDecimal<P extends number, S extends number> = {
    _clickhouse_precision?: P;
    _clickhouse_scale?: S;
} & Pattern<typeof DecimalRegex>;
type ClickHouseFixedStringSize<N extends number> = {
    _clickhouse_fixed_string_size?: N;
};
/**
 * FixedString(N) - Fixed-length string of exactly N bytes.
 *
 * ClickHouse stores exactly N bytes, padding shorter values with null bytes.
 * Values exceeding N bytes will throw an exception.
 *
 * Use for binary data: hashes, IP addresses, UUIDs, MAC addresses.
 *
 * @example
 * interface BinaryData {
 *   md5_hash: string & FixedString<16>;    // 16-byte MD5
 *   sha256_hash: string & FixedString<32>; // 32-byte SHA256
 * }
 */
type FixedString<N extends number> = string & ClickHouseFixedStringSize<N>;
type ClickHouseByteSize<N extends number> = {
    _clickhouse_byte_size?: N;
};
type LowCardinality = {
    _LowCardinality?: true;
};
type DateTime = Date;
type DateTime64<P extends number> = Date & ClickHousePrecision<P>;
type DateTimeString = string & tags.Format<"date-time">;
/**
 * JS Date objects cannot hold microsecond precision.
 * Use string as the runtime type to avoid losing information.
 */
type DateTime64String<P extends number> = string & tags.Format<"date-time"> & ClickHousePrecision<P>;
type Float32 = number & ClickHouseFloat<"float32">;
type Float64 = number & ClickHouseFloat<"float64">;
type Int8 = number & ClickHouseInt<"int8">;
type Int16 = number & ClickHouseInt<"int16">;
type Int32 = number & ClickHouseInt<"int32">;
type Int64 = number & ClickHouseInt<"int64">;
type UInt8 = number & ClickHouseInt<"uint8">;
type UInt16 = number & ClickHouseInt<"uint16">;
type UInt32 = number & ClickHouseInt<"uint32">;
type UInt64 = number & ClickHouseInt<"uint64">;
type Decimal<P extends number, S extends number> = string & ClickHouseDecimal<P, S>;
/**
 * Attach compression codec to a column type.
 *
 * Any valid ClickHouse codec expression is allowed. ClickHouse validates the codec at runtime.
 *
 * @template T The base data type
 * @template CodecExpr The codec expression (single codec or chain)
 *
 * @example
 * interface Metrics {
 *   // Single codec
 *   log_blob: string & ClickHouseCodec<"ZSTD(3)">;
 *
 *   // Codec chain (processed left-to-right)
 *   timestamp: Date & ClickHouseCodec<"Delta, LZ4">;
 *   temperature: number & ClickHouseCodec<"Gorilla, ZSTD">;
 *
 *   // Specialized codecs
 *   counter: number & ClickHouseCodec<"DoubleDelta">;
 *
 *   // Can combine with other annotations
 *   count: UInt64 & ClickHouseCodec<"DoubleDelta, LZ4">;
 * }
 */
type ClickHouseCodec<CodecExpr extends string> = {
    _clickhouse_codec?: CodecExpr;
};
type ClickHouseFloat<Value extends "float32" | "float64"> = tags.Type<Value extends "float32" ? "float" : "double">;
type ClickHouseInt<Value extends "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"> = Value extends "int32" | "int64" | "uint32" | "uint64" ? tags.Type<Value> : TagBase<{
    target: "number";
    kind: "type";
    value: Value;
    validate: Value extends "int8" ? "-128 <= $input && $input <= 127" : Value extends "int16" ? "-32768 <= $input && $input <= 32767" : Value extends "uint8" ? "0 <= $input && $input <= 255" : Value extends "uint16" ? "0 <= $input && $input <= 65535" : never;
    exclusive: true;
    schema: {
        type: "integer";
    };
}>;
/**
 * By default, nested objects map to the `Nested` type in clickhouse.
 * Write `nestedObject: AnotherInterfaceType & ClickHouseNamedTuple`
 * to map AnotherInterfaceType to the named tuple type.
 */
type ClickHouseNamedTuple = {
    _clickhouse_mapped_type?: "namedTuple";
};
type ClickHouseJson<maxDynamicPaths extends number | undefined = undefined, maxDynamicTypes extends number | undefined = undefined, skipPaths extends string[] = [], skipRegexes extends string[] = []> = {
    _clickhouse_mapped_type?: "JSON";
    _clickhouse_json_settings?: {
        maxDynamicPaths?: maxDynamicPaths;
        maxDynamicTypes?: maxDynamicTypes;
        skipPaths?: skipPaths;
        skipRegexes?: skipRegexes;
    };
};
type ClickHousePoint = [number, number] & {
    _clickhouse_mapped_type?: "Point";
};
type ClickHouseRing = ClickHousePoint[] & {
    _clickhouse_mapped_type?: "Ring";
};
type ClickHouseLineString = ClickHousePoint[] & {
    _clickhouse_mapped_type?: "LineString";
};
type ClickHouseMultiLineString = ClickHouseLineString[] & {
    _clickhouse_mapped_type?: "MultiLineString";
};
type ClickHousePolygon = ClickHouseRing[] & {
    _clickhouse_mapped_type?: "Polygon";
};
type ClickHouseMultiPolygon = ClickHousePolygon[] & {
    _clickhouse_mapped_type?: "MultiPolygon";
};
/**
 * typia may have trouble handling this type.
 * In which case, use {@link WithDefault} as a workaround
 *
 * @example
 * { field: number & ClickHouseDefault<"0"> }
 */
type ClickHouseDefault<SqlExpression extends string> = {
    _clickhouse_default?: SqlExpression;
};
/**
 * @example
 * {
 *   ...
 *   timestamp: Date;
 *   debugMessage: string & ClickHouseTTL<"timestamp + INTERVAL 1 WEEK">;
 * }
 */
type ClickHouseTTL<SqlExpression extends string> = {
    _clickhouse_ttl?: SqlExpression;
};
/**
 * ClickHouse MATERIALIZED column annotation.
 * The column value is computed at INSERT time and physically stored.
 * Cannot be explicitly inserted by users.
 *
 * @example
 * interface Events {
 *   eventTime: DateTime;
 *   // Extract date component - computed and stored at insert time
 *   eventDate: Date & ClickHouseMaterialized<"toDate(event_time)">;
 *
 *   userId: string;
 *   // Precompute hash for fast lookups
 *   userHash: UInt64 & ClickHouseMaterialized<"cityHash64(userId)">;
 * }
 *
 * @remarks
 * - MATERIALIZED and DEFAULT are mutually exclusive
 * - Can be combined with ClickHouseCodec for compression
 * - Changing the expression modifies the column in-place (existing values preserved)
 */
type ClickHouseMaterialized<SqlExpression extends string> = {
    _clickhouse_materialized?: SqlExpression;
};
/**
 * ClickHouse ALIAS column annotation.
 * The column value is computed on-the-fly at SELECT time and NOT physically stored.
 * Cannot be explicitly inserted by users.
 *
 * @example
 * interface Events {
 *   eventTime: DateTime;
 *   // Computed at query time, not stored on disk
 *   eventDate: Date & ClickHouseAlias<"toDate(event_time)">;
 *
 *   firstName: string;
 *   lastName: string;
 *   // Virtual computed column
 *   fullName: string & ClickHouseAlias<"concat(first_name, ' ', last_name)">;
 * }
 *
 * @remarks
 * - ALIAS, MATERIALIZED, and DEFAULT are mutually exclusive
 * - ALIAS columns are NOT stored on disk (saves storage, costs CPU at query time)
 * - Cannot be used in ORDER BY, PRIMARY KEY, or PARTITION BY
 * - Can be combined with ClickHouseCodec (though rarely useful since not stored)
 */
type ClickHouseAlias<SqlExpression extends string> = {
    _clickhouse_alias?: SqlExpression;
};
/**
 * See also {@link ClickHouseDefault}
 *
 * @example{ updated_at: WithDefault<Date, "now()"> }
 */
type WithDefault<T, _SqlExpression extends string> = T;
type IsComputed<T> = "_clickhouse_alias" extends keyof T ? true : "_clickhouse_materialized" extends keyof T ? true : false;
type HasDefault<T> = "_clickhouse_default" extends keyof T ? true : false;
/** Keys whose columns are ALIAS or MATERIALIZED — excluded from inserts entirely. */
type ComputedKeys<T> = {
    [K in keyof T]: IsComputed<T[K]> extends true ? K : never;
}[keyof T];
/** Keys whose columns carry a ClickHouseDefault expression — optional during inserts. */
type DefaultKeys<T> = {
    [K in keyof T]: HasDefault<T[K]> extends true ? K : never;
}[keyof T];
/**
 * Derive the insert-safe shape of a model:
 * - ALIAS / MATERIALIZED columns are **omitted** (ClickHouse computes them).
 * - DEFAULT columns become **optional** (ClickHouse fills them when absent).
 * - All other columns remain **required**.
 *
 * @example
 * interface Events {
 *   id: Key<string>;
 *   timestamp: Date;
 *   eventDate: Date & ClickHouseAlias<"toDate(timestamp)">;
 *   createdAt: Date & ClickHouseDefault<"now()">;
 * }
 *
 * // Insertable<Events> ≡ { id: string; timestamp: Date; createdAt?: Date }
 * const table = new OlapTable<Events>("events");
 * await table.insert([{ id: "1", timestamp: new Date() }]);
 */
type Insertable<T> = {
    [K in Exclude<keyof T, ComputedKeys<T> | DefaultKeys<T>>]: T[K];
} & {
    [K in Exclude<DefaultKeys<T>, ComputedKeys<T>>]?: T[K];
};
/**
 * ClickHouse table engine types supported by Moose.
 */
declare enum ClickHouseEngines {
    MergeTree = "MergeTree",
    ReplacingMergeTree = "ReplacingMergeTree",
    SummingMergeTree = "SummingMergeTree",
    /**
     * Stores pre-aggregated values and aggregate states that are automatically
     * merged during background compaction.
     *
     * Columns in `T` that hold aggregate data must be intersected with a tag
     * type so the compiler plugin emits the correct ClickHouse column type:
     *
     * - `& Aggregated<FnName, ArgTypes>` — produces `AggregateFunction(fn, ...types)`.
     *   Data is written via `fnState(...)` and queried with `fnMerge(...)`.
     * - `& SimpleAggregated<FnName, ArgType>` — produces `SimpleAggregateFunction(fn, type)`.
     *   Stores the merged value directly (no state/merge round-trip).
     *
     * Non-annotated columns are ordinary dimensions (ORDER BY key, etc.).
     *
     * @example
     * ```typescript
     * interface DailyStats {
     *   date: DateTime;
     *   userId: string;
     *   totalViews: number & SimpleAggregated<"sum", number>;
     *   avgRating: number & Aggregated<"avg", [number]>;
     * }
     *
     * const stats = new OlapTable<DailyStats>("daily_stats", {
     *   engine: ClickHouseEngines.AggregatingMergeTree,
     *   orderByFields: ["date", "userId"],
     * });
     * ```
     */
    AggregatingMergeTree = "AggregatingMergeTree",
    CollapsingMergeTree = "CollapsingMergeTree",
    VersionedCollapsingMergeTree = "VersionedCollapsingMergeTree",
    GraphiteMergeTree = "GraphiteMergeTree",
    S3Queue = "S3Queue",
    S3 = "S3",
    Buffer = "Buffer",
    Distributed = "Distributed",
    IcebergS3 = "IcebergS3",
    Kafka = "Kafka",
    Merge = "Merge",
    ReplicatedMergeTree = "ReplicatedMergeTree",
    ReplicatedReplacingMergeTree = "ReplicatedReplacingMergeTree",
    ReplicatedAggregatingMergeTree = "ReplicatedAggregatingMergeTree",
    ReplicatedSummingMergeTree = "ReplicatedSummingMergeTree",
    ReplicatedCollapsingMergeTree = "ReplicatedCollapsingMergeTree",
    ReplicatedVersionedCollapsingMergeTree = "ReplicatedVersionedCollapsingMergeTree"
}

/**
 * Defines how Moose manages the lifecycle of database resources when your code changes.
 *
 * This enum controls the behavior when there are differences between your code definitions
 * and the actual database schema or structure.
 */
declare enum LifeCycle {
    /**
     * Full automatic management (default behavior).
     * Moose will automatically modify database resources to match your code definitions,
     * including potentially destructive operations like dropping columns or tables.
     */
    FULLY_MANAGED = "FULLY_MANAGED",
    /**
     * Deletion-protected automatic management.
     * Moose will modify resources to match your code but will avoid destructive actions
     * such as dropping columns, or tables. Only additive changes are applied.
     */
    DELETION_PROTECTED = "DELETION_PROTECTED",
    /**
     * External management - no automatic changes.
     * Moose will not modify the database resources. You are responsible for managing
     * the schema and ensuring it matches your code definitions manually.
     */
    EXTERNALLY_MANAGED = "EXTERNALLY_MANAGED"
}

interface TableIndex {
    name: string;
    expression: string;
    type: string;
    arguments?: string[];
    granularity?: number;
}
interface TableProjection {
    name: string;
    body: string;
}
/**
 * Defines a constraint on a ClickHouse table.
 * Constraints can enforce data integrity rules or provide hints to the query optimizer.
 *
 * @example
 * ```typescript
 * constraints: [
 *   {
 *     name: "age_positive",
 *     expression: "age > 0",
 *     type: "CHECK"
 *   },
 *   {
 *     name: "valid_status",
 *     expression: "status IN ('active', 'inactive')",
 *     type: "ASSUME"
 *   }
 * ]
 * ```
 */
interface TableConstraint {
    /** The unique identifier or name of the constraint */
    name: string;
    /** The SQL or logical expression that defines the constraint condition */
    expression: string;
    /** The type of the constraint */
    type: "CHECK" | "ASSUME";
}
/**
 * Represents a failed record during insertion with error details
 */
interface FailedRecord<T> {
    /** The original record that failed to insert */
    record: T;
    /** The error message describing why the insertion failed */
    error: string;
    /** Optional: The index of this record in the original batch */
    index?: number;
}
/**
 * Result of an insert operation with detailed success/failure information
 */
interface InsertResult<T> {
    /** Number of records successfully inserted */
    successful: number;
    /** Number of records that failed to insert */
    failed: number;
    /** Total number of records processed */
    total: number;
    /** Detailed information about failed records (if record isolation was used) */
    failedRecords?: FailedRecord<T>[];
}
/**
 * Error handling strategy for insert operations
 */
type ErrorStrategy = "fail-fast" | "discard" | "isolate";
/**
 * Options for insert operations
 */
interface InsertOptions {
    /** Maximum number of bad records to tolerate before failing */
    allowErrors?: number;
    /** Maximum ratio of bad records to tolerate (0.0 to 1.0) before failing */
    allowErrorsRatio?: number;
    /** Error handling strategy */
    strategy?: ErrorStrategy;
    /** Whether to enable dead letter queue for failed records (future feature) */
    deadLetterQueue?: boolean;
    /** Whether to validate data against schema before insertion (default: true) */
    validate?: boolean;
    /** Whether to skip validation for individual records during 'isolate' strategy retries (default: false) */
    skipValidationOnRetry?: boolean;
}
/**
 * Validation result for a record with detailed error information
 */
interface ValidationError {
    /** The original record that failed validation */
    record: any;
    /** Detailed validation error message */
    error: string;
    /** Optional: The index of this record in the original batch */
    index?: number;
    /** The path to the field that failed validation */
    path?: string;
}
/**
 * Result of data validation with success/failure breakdown
 */
interface ValidationResult<T> {
    /** Records that passed validation */
    valid: T[];
    /** Records that failed validation with detailed error information */
    invalid: ValidationError[];
    /** Total number of records processed */
    total: number;
}
/**
 * S3Queue-specific table settings that can be modified with ALTER TABLE MODIFY SETTING
 * Note: Since ClickHouse 24.7, settings no longer require the 's3queue_' prefix
 */
interface S3QueueTableSettings {
    /** Processing mode: "ordered" for sequential or "unordered" for parallel processing */
    mode?: "ordered" | "unordered";
    /** What to do with files after processing: 'keep' or 'delete' */
    after_processing?: "keep" | "delete";
    /** ZooKeeper/Keeper path for coordination between replicas */
    keeper_path?: string;
    /** Number of retry attempts for failed files */
    loading_retries?: string;
    /** Number of threads for parallel processing */
    processing_threads_num?: string;
    /** Enable parallel inserts */
    parallel_inserts?: string;
    /** Enable logging to system.s3queue_log table */
    enable_logging_to_queue_log?: string;
    /** Last processed file path (for ordered mode) */
    last_processed_path?: string;
    /** Maximum number of tracked files in ZooKeeper */
    tracked_files_limit?: string;
    /** TTL for tracked files in seconds */
    tracked_file_ttl_sec?: string;
    /** Minimum polling timeout in milliseconds */
    polling_min_timeout_ms?: string;
    /** Maximum polling timeout in milliseconds */
    polling_max_timeout_ms?: string;
    /** Polling backoff in milliseconds */
    polling_backoff_ms?: string;
    /** Minimum cleanup interval in milliseconds */
    cleanup_interval_min_ms?: string;
    /** Maximum cleanup interval in milliseconds */
    cleanup_interval_max_ms?: string;
    /** Number of buckets for sharding (0 = disabled) */
    buckets?: string;
    /** Batch size for listing objects */
    list_objects_batch_size?: string;
    /** Enable hash ring filtering for distributed processing */
    enable_hash_ring_filtering?: string;
    /** Maximum files to process before committing */
    max_processed_files_before_commit?: string;
    /** Maximum rows to process before committing */
    max_processed_rows_before_commit?: string;
    /** Maximum bytes to process before committing */
    max_processed_bytes_before_commit?: string;
    /** Maximum processing time in seconds before committing */
    max_processing_time_sec_before_commit?: string;
    /** Use persistent processing nodes (available from 25.8) */
    use_persistent_processing_nodes?: string;
    /** TTL for persistent processing nodes in seconds */
    persistent_processing_nodes_ttl_seconds?: string;
    /** Additional settings */
    [key: string]: string | undefined;
}
/**
 * Base configuration shared by all table engines
 * @template T The data type of the records stored in the table.
 */
type BaseOlapConfig<T> = ({
    /**
     * Specifies the fields to use for ordering data within the ClickHouse table.
     * This is crucial for optimizing query performance.
     */
    orderByFields: (keyof T & string)[];
    orderByExpression?: undefined;
} | {
    orderByFields?: undefined;
    /**
     * An arbitrary ClickHouse SQL expression for the order by clause.
     *
     * `orderByExpression: "(id, name)"` is equivalent to `orderByFields: ["id", "name"]`
     * `orderByExpression: "tuple()"` means no sorting
     */
    orderByExpression: string;
} | {
    orderByFields?: undefined;
    orderByExpression?: undefined;
}) & {
    partitionBy?: string;
    /**
     * SAMPLE BY expression for approximate query processing.
     *
     * Examples:
     * ```typescript
     * // Single unsigned integer field
     * sampleByExpression: "userId"
     *
     * // Hash function on any field type
     * sampleByExpression: "cityHash64(id)"
     *
     * // Multiple fields with hash
     * sampleByExpression: "cityHash64(userId, timestamp)"
     * ```
     *
     * Requirements:
     * - Expression must evaluate to an unsigned integer (UInt8/16/32/64)
     * - Expression must be present in the ORDER BY clause
     * - If using hash functions, the same expression must appear in orderByExpression
     */
    sampleByExpression?: string;
    /**
     * Optional PRIMARY KEY expression.
     * When specified, this overrides the primary key inferred from Key<T> column annotations.
     *
     * This allows for:
     * - Complex primary keys using functions (e.g., "cityHash64(id)")
     * - Different column ordering in primary key vs schema definition
     * - Primary keys that differ from ORDER BY
     *
     * Example: primaryKeyExpression: "(userId, cityHash64(eventId))"
     *
     * Note: When this is set, any Key<T> annotations on columns are ignored for PRIMARY KEY generation.
     */
    primaryKeyExpression?: string;
    version?: string;
    lifeCycle?: LifeCycle;
    settings?: {
        [key: string]: string;
    };
    /**
     * Optional TTL configuration for the table.
     * e.g., "TTL timestamp + INTERVAL 90 DAY DELETE"
     *
     * Use the {@link ClickHouseTTL} type to configure column level TTL
     */
    ttl?: string;
    /** Optional secondary/data-skipping indexes */
    indexes?: TableIndex[];
    /** Optional projections for alternative data ordering within parts */
    projections?: TableProjection[];
    /**
     * Optional database name for multi-database support.
     * When not specified, uses the global ClickHouse config database.
     */
    database?: string;
    /**
     * Optional cluster name for ON CLUSTER support.
     * Use this to enable replicated tables across ClickHouse clusters.
     * The cluster must be defined in config.toml (dev environment only).
     * Example: cluster: "prod_cluster"
     */
    cluster?: string;
    /**
     * Optional seed filter applied when `moose seed clickhouse` populates a
     * local/testing database from a remote source.
     *
     * Example:
     * ```typescript
     * seedFilter: { limit: 100, where: "user_id = 10" }
     * ```
     */
    seedFilter?: {
        /** Maximum number of rows to seed for this table. */
        limit?: number;
        /** ClickHouse SQL WHERE expression to filter seeded rows. */
        where?: string;
    };
    /**
     * Optional table-level ClickHouse constraints.
     *
     * - **CHECK** — validated on INSERT.
     * - **ASSUME** — optimizer hint only (no enforcement).
     */
    constraints?: TableConstraint[];
};
/**
 * Configuration for MergeTree engine
 * @template T The data type of the records stored in the table.
 */
type MergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.MergeTree;
};
/**
 * Configuration for ReplacingMergeTree engine (deduplication)
 * @template T The data type of the records stored in the table.
 */
type ReplacingMergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.ReplacingMergeTree;
    ver?: keyof T & string;
    isDeleted?: keyof T & string;
};
/**
 * Configuration for AggregatingMergeTree engine.
 *
 * See {@link ClickHouseEngines.AggregatingMergeTree} for guidance on annotating
 * aggregate columns in `T` with `Aggregated` / `SimpleAggregated`.
 *
 * @template T The data type of the records stored in the table.
 */
type AggregatingMergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.AggregatingMergeTree;
};
/**
 * Configuration for SummingMergeTree engine
 * @template T The data type of the records stored in the table.
 */
type SummingMergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.SummingMergeTree;
    columns?: string[];
};
/**
 * Configuration for CollapsingMergeTree engine
 * @template T The data type of the records stored in the table.
 */
type CollapsingMergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.CollapsingMergeTree;
    sign: keyof T & string;
};
/**
 * Configuration for VersionedCollapsingMergeTree engine
 * @template T The data type of the records stored in the table.
 */
type VersionedCollapsingMergeTreeConfig<T> = BaseOlapConfig<T> & {
    engine: ClickHouseEngines.VersionedCollapsingMergeTree;
    sign: keyof T & string;
    ver: keyof T & string;
};
interface ReplicatedEngineProperties {
    keeperPath?: string;
    replicaName?: string;
}
/**
 * Configuration for ReplicatedMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedMergeTreeConfig<T> = Omit<MergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedMergeTree;
};
/**
 * Configuration for ReplicatedReplacingMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedReplacingMergeTreeConfig<T> = Omit<ReplacingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedReplacingMergeTree;
};
/**
 * Configuration for ReplicatedAggregatingMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedAggregatingMergeTreeConfig<T> = Omit<AggregatingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedAggregatingMergeTree;
};
/**
 * Configuration for ReplicatedSummingMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedSummingMergeTreeConfig<T> = Omit<SummingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedSummingMergeTree;
};
/**
 * Configuration for ReplicatedCollapsingMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedCollapsingMergeTreeConfig<T> = Omit<CollapsingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedCollapsingMergeTree;
};
/**
 * Configuration for ReplicatedVersionedCollapsingMergeTree engine
 * @template T The data type of the records stored in the table.
 *
 * Note: keeperPath and replicaName are optional. Omit them for ClickHouse Cloud,
 * which manages replication automatically. For self-hosted with ClickHouse Keeper,
 * provide both parameters or neither (to use server defaults).
 */
type ReplicatedVersionedCollapsingMergeTreeConfig<T> = Omit<VersionedCollapsingMergeTreeConfig<T>, "engine"> & ReplicatedEngineProperties & {
    engine: ClickHouseEngines.ReplicatedVersionedCollapsingMergeTree;
};
/**
 * Configuration for S3Queue engine - only non-alterable constructor parameters.
 * S3Queue-specific settings like 'mode', 'keeper_path', etc. should be specified
 * in the settings field, not here.
 * @template T The data type of the records stored in the table.
 */
type S3QueueConfig<T> = Omit<BaseOlapConfig<T>, "settings" | "orderByFields" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.S3Queue;
    /** S3 bucket path with wildcards (e.g., 's3://bucket/data/*.json') */
    s3Path: string;
    /** Data format (e.g., 'JSONEachRow', 'CSV', 'Parquet') */
    format: string;
    /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
    awsAccessKeyId?: string;
    /** AWS secret access key */
    awsSecretAccessKey?: string;
    /** Compression type (e.g., 'gzip', 'zstd') */
    compression?: string;
    /** Custom HTTP headers */
    headers?: {
        [key: string]: string;
    };
    /**
     * S3Queue-specific table settings that can be modified with ALTER TABLE MODIFY SETTING.
     * These settings control the behavior of the S3Queue engine.
     */
    settings?: S3QueueTableSettings;
};
/**
 * Configuration for S3 engine
 * Note: S3 engine supports ORDER BY clause, unlike S3Queue, Buffer, and Distributed engines
 * @template T The data type of the records stored in the table.
 */
type S3Config<T> = Omit<BaseOlapConfig<T>, "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.S3;
    /** S3 path (e.g., 's3://bucket/path/file.json') */
    path: string;
    /** Data format (e.g., 'JSONEachRow', 'CSV', 'Parquet') */
    format: string;
    /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
    awsAccessKeyId?: string;
    /** AWS secret access key */
    awsSecretAccessKey?: string;
    /** Compression type (e.g., 'gzip', 'zstd', 'auto') */
    compression?: string;
    /** Partition strategy (optional) */
    partitionStrategy?: string;
    /** Partition columns in data file (optional) */
    partitionColumnsInDataFile?: string;
};
/**
 * Configuration for Buffer engine
 * @template T The data type of the records stored in the table.
 */
type BufferConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.Buffer;
    /** Target database name for the destination table */
    targetDatabase: string;
    /** Target table name where data will be flushed */
    targetTable: string;
    /** Number of buffer layers (typically 16) */
    numLayers: number;
    /** Minimum time in seconds before flushing */
    minTime: number;
    /** Maximum time in seconds before flushing */
    maxTime: number;
    /** Minimum number of rows before flushing */
    minRows: number;
    /** Maximum number of rows before flushing */
    maxRows: number;
    /** Minimum bytes before flushing */
    minBytes: number;
    /** Maximum bytes before flushing */
    maxBytes: number;
    /** Optional: Flush time in seconds */
    flushTime?: number;
    /** Optional: Flush number of rows */
    flushRows?: number;
    /** Optional: Flush number of bytes */
    flushBytes?: number;
};
/**
 * Configuration for Distributed engine
 * @template T The data type of the records stored in the table.
 */
type DistributedConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.Distributed;
    /** Cluster name from the ClickHouse configuration */
    cluster: string;
    /** Database name on the cluster */
    targetDatabase: string;
    /** Table name on the cluster */
    targetTable: string;
    /** Optional: Sharding key expression for data distribution */
    shardingKey?: string;
    /** Optional: Policy name for data distribution */
    policyName?: string;
};
/** Kafka table settings. See: https://clickhouse.com/docs/engines/table-engines/integrations/kafka */
interface KafkaTableSettings {
    kafka_security_protocol?: "PLAINTEXT" | "SSL" | "SASL_PLAINTEXT" | "SASL_SSL";
    kafka_sasl_mechanism?: "GSSAPI" | "PLAIN" | "SCRAM-SHA-256" | "SCRAM-SHA-512" | "OAUTHBEARER";
    kafka_sasl_username?: string;
    kafka_sasl_password?: string;
    kafka_schema?: string;
    kafka_num_consumers?: string;
    kafka_max_block_size?: string;
    kafka_skip_broken_messages?: string;
    kafka_commit_every_batch?: string;
    kafka_client_id?: string;
    kafka_poll_timeout_ms?: string;
    kafka_poll_max_batch_size?: string;
    kafka_flush_interval_ms?: string;
    kafka_consumer_reschedule_ms?: string;
    kafka_thread_per_consumer?: string;
    kafka_handle_error_mode?: "default" | "stream";
    kafka_commit_on_select?: string;
    kafka_max_rows_per_message?: string;
    kafka_compression_codec?: string;
    kafka_compression_level?: string;
}
/** Kafka engine for streaming data from Kafka topics. Additional settings go in `settings`. */
type KafkaConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.Kafka;
    brokerList: string;
    topicList: string;
    groupName: string;
    format: string;
    settings?: KafkaTableSettings;
};
/**
 * Configuration for IcebergS3 engine - read-only Iceberg table access
 *
 * Provides direct querying of Apache Iceberg tables stored on S3.
 * Data is not copied; queries stream directly from Parquet/ORC files.
 *
 * @template T The data type of the records stored in the table.
 *
 * @example
 * ```typescript
 * const lakeEvents = new OlapTable<Event>("lake_events", {
 *   engine: ClickHouseEngines.IcebergS3,
 *   path: "s3://datalake/events/",
 *   format: "Parquet",
 *   awsAccessKeyId: mooseRuntimeEnv.get("AWS_ACCESS_KEY_ID"),
 *   awsSecretAccessKey: mooseRuntimeEnv.get("AWS_SECRET_ACCESS_KEY")
 * });
 * ```
 *
 * @remarks
 * - IcebergS3 engine is read-only
 * - Does not support ORDER BY, PARTITION BY, or SAMPLE BY clauses
 * - Queries always see the latest Iceberg snapshot (with metadata cache)
 */
type IcebergS3Config<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.IcebergS3;
    /** S3 path to Iceberg table root (e.g., 's3://bucket/warehouse/events/') */
    path: string;
    /** Data format - 'Parquet' or 'ORC' */
    format: "Parquet" | "ORC";
    /** AWS access key ID (optional, omit for NOSIGN/public buckets) */
    awsAccessKeyId?: string;
    /** AWS secret access key (optional) */
    awsSecretAccessKey?: string;
    /** Compression type (optional: 'gzip', 'zstd', 'auto') */
    compression?: string;
};
/**
 * Configuration for Merge engine - read-only view over multiple tables matching a regex pattern.
 *
 * @template T The data type of the records in the source tables.
 *
 * @example
 * ```typescript
 * const allEvents = new OlapTable<Event>("all_events", {
 *   engine: ClickHouseEngines.Merge,
 *   sourceDatabase: "currentDatabase()",
 *   tablesRegexp: "^events_\\d+$",
 * });
 * ```
 *
 * @remarks
 * - Merge engine is read-only; INSERT operations are not supported
 * - Cannot be used as a destination in IngestPipeline
 * - Does not support ORDER BY, PARTITION BY, or SAMPLE BY clauses
 */
type MergeConfig<T> = Omit<BaseOlapConfig<T>, "orderByFields" | "orderByExpression" | "partitionBy" | "sampleByExpression" | "projections"> & {
    engine: ClickHouseEngines.Merge;
    /** Database to scan for source tables (literal name, currentDatabase(), or REGEXP(...)) */
    sourceDatabase: string;
    /** Regex pattern to match table names in the source database */
    tablesRegexp: string;
};
/**
 * Legacy configuration (backward compatibility) - defaults to MergeTree engine
 * @template T The data type of the records stored in the table.
 */
type LegacyOlapConfig<T> = BaseOlapConfig<T>;
type EngineConfig<T> = MergeTreeConfig<T> | ReplacingMergeTreeConfig<T> | AggregatingMergeTreeConfig<T> | SummingMergeTreeConfig<T> | CollapsingMergeTreeConfig<T> | VersionedCollapsingMergeTreeConfig<T> | ReplicatedMergeTreeConfig<T> | ReplicatedReplacingMergeTreeConfig<T> | ReplicatedAggregatingMergeTreeConfig<T> | ReplicatedSummingMergeTreeConfig<T> | ReplicatedCollapsingMergeTreeConfig<T> | ReplicatedVersionedCollapsingMergeTreeConfig<T> | S3QueueConfig<T> | S3Config<T> | BufferConfig<T> | DistributedConfig<T> | IcebergS3Config<T> | KafkaConfig<T> | MergeConfig<T>;
/**
 * Union of all engine-specific configurations (new API)
 * @template T The data type of the records stored in the table.
 */
type OlapConfig<T> = EngineConfig<T> | LegacyOlapConfig<T>;
/**
 * Represents an OLAP (Online Analytical Processing) table, typically corresponding to a ClickHouse table.
 * Provides a typed interface for interacting with the table.
 *
 * @template T The data type of the records stored in the table. The structure of T defines the table schema.
 */
declare class OlapTable<T> extends TypedBase<T, OlapConfig<T>> {
    name: IdentifierBrandedString;
    /** @internal */
    readonly kind = "OlapTable";
    /** @internal Typia validators for Insertable<T> — used during insert validation */
    private insertValidators?;
    /** @internal Memoized ClickHouse client for reusing connections across insert calls */
    private _memoizedClient?;
    /** @internal Hash of the configuration used to create the memoized client */
    private _configHash?;
    /** @internal Cached table name to avoid repeated generation */
    private _cachedTableName?;
    /**
     * Creates a new OlapTable instance.
     * @param name The name of the table. This name is used for the underlying ClickHouse table.
     * @param config Optional configuration for the OLAP table.
     */
    constructor(name: string, config?: OlapConfig<T>);
    /** @internal **/
    constructor(name: string, config: OlapConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators?: TypiaValidators<T>, insertValidators?: TypiaValidators<Insertable<T>>);
    /** @internal Returns the versioned ClickHouse table name (e.g., "events_1_0_0") */
    generateTableName(): string;
    /**
     * Creates a fast hash of the ClickHouse configuration.
     * Uses crypto.createHash for better performance than JSON.stringify.
     *
     * @private
     */
    private createConfigHash;
    /**
     * Gets or creates a memoized ClickHouse client.
     * The client is cached and reused across multiple insert calls for better performance.
     * If the configuration changes, a new client will be created.
     *
     * @private
     */
    private getMemoizedClient;
    /**
     * Closes the memoized ClickHouse client if it exists.
     * This is useful for cleaning up connections when the table instance is no longer needed.
     * The client will be automatically recreated on the next insert call if needed.
     */
    closeClient(): Promise<void>;
    /**
     * Validates a single record using typia's comprehensive type checking.
     * This provides the most accurate validation as it uses the exact TypeScript type information.
     *
     * @param record The record to validate
     * @returns Validation result with detailed error information
     */
    validateRecord(record: unknown): {
        success: boolean;
        data?: T;
        errors?: string[];
    };
    /**
     * Type guard function using typia's is() function.
     * Provides compile-time type narrowing for TypeScript.
     *
     * @param record The record to check
     * @returns True if record matches type T, with type narrowing
     */
    isValidRecord(record: unknown): record is T;
    /**
     * Assert that a record matches type T, throwing detailed errors if not.
     * Uses typia's assert() function for the most detailed error reporting.
     *
     * @param record The record to assert
     * @returns The validated and typed record
     * @throws Detailed validation error if record doesn't match type T
     */
    assertValidRecord(record: unknown): T;
    /**
     * Validates records for insert using Insertable<T> validators when available.
     * Falls back to the full T validators if insert validators weren't generated.
     * @private
     */
    private validateInsertRecords;
    /**
     * Validates an array of records with comprehensive error reporting.
     * Uses the most appropriate validation method available (typia or basic).
     *
     * @param data Array of records to validate
     * @returns Detailed validation results
     */
    validateRecords(data: unknown[]): Promise<ValidationResult<T>>;
    /**
     * Optimized batch retry that minimizes individual insert operations.
     * Groups records into smaller batches to reduce round trips while still isolating failures.
     *
     * @private
     */
    private retryIndividualRecords;
    /**
     * Validates input parameters and strategy compatibility
     * @private
     */
    private validateInsertParameters;
    /**
     * Handles early return cases for empty data
     * @private
     */
    private handleEmptyData;
    /**
     * Performs pre-insertion validation for array data
     * @private
     */
    private performPreInsertionValidation;
    /**
     * Handles validation errors based on the specified strategy
     * @private
     */
    private handleValidationErrors;
    /**
     * Checks if validation errors exceed configured thresholds
     * @private
     */
    private checkValidationThresholds;
    /**
     * Optimized insert options preparation with better memory management
     * @private
     */
    private prepareInsertOptions;
    /**
     * Creates success result for completed insertions
     * @private
     */
    private createSuccessResult;
    /**
     * Handles insertion errors based on the specified strategy
     * @private
     */
    private handleInsertionError;
    /**
     * Handles the isolate strategy for insertion errors
     * @private
     */
    private handleIsolateStrategy;
    /**
     * Checks if insertion errors exceed configured thresholds
     * @private
     */
    private checkInsertionThresholds;
    /**
     * Recursively transforms a record to match ClickHouse's JSONEachRow requirements
     *
     * - For every Array(Nested(...)) field at any depth, each item is wrapped in its own array and recursively processed.
     * - For every Nested struct (not array), it recurses into the struct.
     * - This ensures compatibility with kafka_clickhouse_sync
     *
     * @param record The input record to transform (may be deeply nested)
     * @param columns The schema columns for this level (defaults to this.columnArray at the top level)
     * @returns The transformed record, ready for ClickHouse JSONEachRow insertion
     */
    private mapToClickhouseRecord;
    /**
     * Inserts data directly into the ClickHouse table with enhanced error handling and validation.
     * This method establishes a direct connection to ClickHouse using the project configuration
     * and inserts the provided data into the versioned table.
     *
     * PERFORMANCE OPTIMIZATIONS:
     * - Memoized client connections with fast config hashing
     * - Single-pass validation with pre-allocated arrays
     * - Batch-optimized retry strategy (batches of 10, then individual)
     * - Optimized ClickHouse settings for large datasets
     * - Reduced memory allocations and object creation
     *
     * Uses advanced typia validation when available for comprehensive type checking,
     * with fallback to basic validation for compatibility.
     *
     * The ClickHouse client is memoized and reused across multiple insert calls for better performance.
     * If the configuration changes, a new client will be automatically created.
     *
     * @param data Array of objects conforming to the table schema, or a Node.js Readable stream
     * @param options Optional configuration for error handling, validation, and insertion behavior
     * @returns Promise resolving to detailed insertion results
     * @throws {ConfigError} When configuration cannot be read or parsed
     * @throws {ClickHouseError} When insertion fails based on the error strategy
     * @throws {ValidationError} When validation fails and strategy is 'fail-fast'
     *
     * @example
     * ```typescript
     * // Create an OlapTable instance (typia validators auto-injected)
     * const userTable = new OlapTable<User>('users');
     *
     * // Insert with comprehensive typia validation
     * const result1 = await userTable.insert([
     *   { id: 1, name: 'John', email: 'john@example.com' },
     *   { id: 2, name: 'Jane', email: 'jane@example.com' }
     * ]);
     *
     * // Insert data with stream input (validation not available for streams)
     * const dataStream = new Readable({
     *   objectMode: true,
     *   read() { // Stream implementation }
     * });
     * const result2 = await userTable.insert(dataStream, { strategy: 'fail-fast' });
     *
     * // Insert with validation disabled for performance
     * const result3 = await userTable.insert(data, { validate: false });
     *
     * // Insert with error handling strategies
     * const result4 = await userTable.insert(mixedData, {
     *   strategy: 'isolate',
     *   allowErrorsRatio: 0.1,
     *   validate: true  // Use typia validation (default)
     * });
     *
     * // Optional: Clean up connection when completely done
     * await userTable.closeClient();
     * ```
     */
    insert(data: Insertable<T>[] | Readable, options?: InsertOptions): Promise<InsertResult<T>>;
}

/**
 * Options for per-query ClickHouse row policy enforcement.
 * When provided, each query activates the specified role and injects
 * custom settings (e.g., tenant ID) that row policies evaluate via getSetting().
 */
interface RowPolicyOptions {
    role: string;
    clickhouse_settings: Record<string, string>;
}
declare class QueryClient {
    client: ClickHouseClient;
    query_id_prefix: string;
    private rowPolicyOptions?;
    private readonlyMode;
    constructor(client: ClickHouseClient, query_id_prefix: string, rowPolicyOptions?: RowPolicyOptions, readonlyMode?: boolean);
    execute<T = any>(sql: Sql): Promise<ResultSet<"JSONEachRow"> & {
        __query_result_t?: T[];
    }>;
    command(sql: Sql): Promise<CommandResult>;
}

/**
 * Configuration options for creating a View.
 */
interface ViewConfig {
    /** The SQL SELECT statement or Sql object defining the view's logic. */
    selectStatement: string | Sql;
    /** Source tables/views the SELECT reads from. Used for dependency tracking during migrations. */
    baseTables: (OlapTable<any> | View)[];
    /** Optional database where the view is created. When set, the view is created as `database`.`name` in ClickHouse. */
    database?: string;
    /** Optional metadata for the view (e.g., description, source file). */
    metadata?: {
        [key: string]: any;
    };
}
/**
 * Represents a database View, defined by a SQL SELECT statement based on one or more base tables or other views.
 * Emits structured data for the Moose infrastructure system.
 */
declare class View {
    /** @internal */
    readonly kind = "View";
    /** The name of the view */
    name: string;
    /** Optional database where the view is created. When set, the view is created as `database`.`name` in ClickHouse. */
    database?: string;
    /** The SELECT SQL statement that defines the view */
    selectSql: string;
    /** Names of source tables/views that the SELECT reads from */
    sourceTables: string[];
    /** Optional metadata for the view */
    metadata: {
        [key: string]: any;
    };
    /**
     * Creates a new View instance.
     * @param name The name of the view to be created.
     * @param config Configuration for the view: select statement, base tables, optional database, and optional metadata.
     */
    constructor(name: string, config: ViewConfig);
    /**
     * @deprecated Use the config-object overload: `new View(name, { selectStatement, baseTables, metadata? })`.
     */
    constructor(name: string, selectStatement: string | Sql, baseTables: (OlapTable<any> | View)[], metadata?: {
        [key: string]: any;
    });
}

export { QueryClient as $, type Decimal as A, type Insertable as B, ClickHouseEngines as C, type DateTime as D, quoteIdentifier as E, type FixedString as F, type IdentifierBrandedString as G, type Value as H, type Int8 as I, type SqlTemplateTag as J, sql as K, LifeCycle as L, Sql as M, type NonIdentifierBrandedString as N, OlapTable as O, toStaticQuery as P, toQuery as Q, type RawValue as R, type S3QueueTableSettings as S, type TableConstraint as T, type UInt8 as U, View as V, type WithDefault as W, toQueryPreview as X, getValueFromParameter as Y, createClickhouseParameter as Z, mapToClickHouseType as _, type OlapConfig as a, TypedBase as a0, type Column as a1, type RowPolicyOptions as a2, type TypiaValidators as a3, type ViewConfig as a4, type DataType as a5, type ClickHousePoint as a6, type ClickHouseRing as a7, type ClickHouseLineString as a8, type ClickHouseMultiLineString as a9, type ClickHousePolygon as aa, type ClickHouseMultiPolygon as ab, type ClickHousePrecision as b, type ClickHouseDecimal as c, type ClickHouseByteSize as d, type ClickHouseFixedStringSize as e, type ClickHouseFloat as f, type ClickHouseInt as g, type ClickHouseJson as h, type LowCardinality as i, type ClickHouseNamedTuple as j, type ClickHouseDefault as k, type ClickHouseTTL as l, type ClickHouseMaterialized as m, type ClickHouseAlias as n, type ClickHouseCodec as o, type DateTime64 as p, type DateTimeString as q, type DateTime64String as r, type Float32 as s, type Float64 as t, type Int16 as u, type Int32 as v, type Int64 as w, type UInt16 as x, type UInt32 as y, type UInt64 as z };
