@mariiodegen/seed-db 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import type { InitCommandOptions } from "../types";
2
+ export declare const STARTER_CONFIG_CONTENT = "// seed.config.ts\nimport type { SeedConfig } from \"./src/config/types\";\n\nexport default {\n databaseUrl: process.env.DATABASE_URL,\n defaultRows: 10,\n schema: \"public\",\n nullRate: 0.1,\n tables: {\n // Example custom table rule:\n // users: {\n // rows: 50,\n // columns: {\n // role: \"member\",\n // },\n // },\n },\n} satisfies SeedConfig;\n";
3
+ export declare const STARTER_ENV_CONTENT = "# Local PostgreSQL connection string\nDATABASE_URL=\"postgres://seed:seed@localhost:5433/seed\"\n";
4
+ export declare function initCommand(options?: InitCommandOptions, targetDir?: string): Promise<{
5
+ configPath: string;
6
+ envPath: string;
7
+ }>;
@@ -0,0 +1,4 @@
1
+ import type { Schema } from "../introspect/types";
2
+ import type { InspectCommandOptions } from "../types";
3
+ export declare function formatSchemaText(schema: Schema): string;
4
+ export declare function inspectCommand(options: InspectCommandOptions): Promise<Schema>;
@@ -0,0 +1,3 @@
1
+ import type { ExecutionResult } from "../execute/types";
2
+ import type { RunCommandOptions } from "../types";
3
+ export declare function runCommand(options: RunCommandOptions): Promise<ExecutionResult>;
@@ -0,0 +1,15 @@
1
+ import type { SeedConfig } from "./types";
2
+ /**
3
+ * Type-safe configuration helper for seed.config.ts
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { defineSeedConfig } from "@mariiodegen/seed-db";
8
+ *
9
+ * export default defineSeedConfig({
10
+ * defaultRows: 25,
11
+ * seed: 42,
12
+ * });
13
+ * ```
14
+ */
15
+ export declare function defineSeedConfig(config: SeedConfig): SeedConfig;
@@ -0,0 +1,4 @@
1
+ export * from "./types";
2
+ export * from "./validate";
3
+ export * from "./merge";
4
+ export * from "./load";
@@ -0,0 +1,5 @@
1
+ import type { GlobalOptions } from "../types";
2
+ import type { ResolvedConfig, SeedConfig } from "./types";
3
+ export declare const DEFAULT_CONFIG_PATH = "./seed.config.ts";
4
+ export declare function loadConfigFile(configPath?: string, isCustomPath?: boolean): Promise<SeedConfig>;
5
+ export declare function loadAndResolveConfig(flags?: Partial<GlobalOptions>): Promise<ResolvedConfig>;
@@ -0,0 +1,15 @@
1
+ import type { RunCommandOptions } from "../types";
2
+ import type { SeedConfig, ResolvedConfig } from "./types";
3
+ export interface MergeInputs {
4
+ flags?: Partial<RunCommandOptions>;
5
+ fileConfig?: SeedConfig;
6
+ env?: Record<string, string | undefined>;
7
+ }
8
+ export declare const DEFAULT_CONFIG: {
9
+ schema: string;
10
+ defaultRows: number;
11
+ nullRate: number;
12
+ format: "text";
13
+ verbose: boolean;
14
+ };
15
+ export declare function mergeConfig(inputs?: MergeInputs): ResolvedConfig;
@@ -0,0 +1,45 @@
1
+ export interface ColumnRuleContext {
2
+ faker: unknown;
3
+ }
4
+ export type ColumnRule = string | number | boolean | null | {
5
+ oneOf: Array<string | number | boolean>;
6
+ weights?: number[];
7
+ } | {
8
+ int: {
9
+ min: number;
10
+ max: number;
11
+ };
12
+ } | {
13
+ float: {
14
+ min: number;
15
+ max: number;
16
+ precision?: number;
17
+ };
18
+ } | {
19
+ faker: string;
20
+ } | ((ctx: ColumnRuleContext) => unknown);
21
+ export interface TableConfig {
22
+ ignore?: boolean;
23
+ rows?: number;
24
+ columns?: Record<string, ColumnRule>;
25
+ }
26
+ export interface SeedConfig {
27
+ databaseUrl?: string;
28
+ schema?: string;
29
+ defaultRows?: number;
30
+ seed?: number;
31
+ nullRate?: number;
32
+ allowedHosts?: string[];
33
+ tables?: Record<string, TableConfig>;
34
+ }
35
+ export interface ResolvedConfig {
36
+ databaseUrl?: string;
37
+ schema: string;
38
+ defaultRows: number;
39
+ seed?: number;
40
+ nullRate: number;
41
+ allowedHosts: string[];
42
+ tables: Record<string, TableConfig>;
43
+ format: "text" | "json";
44
+ verbose: boolean;
45
+ }
@@ -0,0 +1,2 @@
1
+ import type { ResolvedConfig } from "./types";
2
+ export declare function validateConfig(config: ResolvedConfig): void;
@@ -0,0 +1,17 @@
1
+ export type ExitCode = 1 | 2 | 3;
2
+ export interface SeedErrorOptions {
3
+ code: string;
4
+ where: string;
5
+ cause: string;
6
+ fix: string;
7
+ exit: ExitCode;
8
+ }
9
+ export declare class SeedError extends Error {
10
+ readonly code: string;
11
+ readonly where: string;
12
+ readonly cause: string;
13
+ readonly fix: string;
14
+ readonly exit: ExitCode;
15
+ constructor(opts: SeedErrorOptions);
16
+ }
17
+ export declare function formatError(err: SeedError, format: "text" | "json"): string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Calculates the maximum safe batch size for a table given its column count.
3
+ * PostgreSQL bind parameters ($1, $2, ...) are indexed by an unsigned 16-bit integer,
4
+ * capping individual query parameters at 65,535.
5
+ *
6
+ * Formula: min(1000, floor(65000 / columnCount))
7
+ */
8
+ export declare function calculateBatchSize(columnCount: number): number;
9
+ /**
10
+ * Splits an array of items into chunks of up to batchSize.
11
+ */
12
+ export declare function chunkRows<T>(items: T[], batchSize: number): T[][];
@@ -0,0 +1,15 @@
1
+ import type { Faker } from "@faker-js/faker";
2
+ import type { Schema } from "../introspect/types";
3
+ import type { ResolvedConfig } from "../config/types";
4
+ import type { TableOrderResult } from "../graph/types";
5
+ import type { ExecutionResult } from "./types";
6
+ export interface DryRunOptions {
7
+ schema: Schema;
8
+ config: ResolvedConfig;
9
+ orderResult: TableOrderResult;
10
+ faker: Faker;
11
+ }
12
+ /**
13
+ * Simulates the execution pipeline and prints the exact SQL statements without writing to any database.
14
+ */
15
+ export declare function executeDryRun(options: DryRunOptions): ExecutionResult;
@@ -0,0 +1,18 @@
1
+ import type { Faker } from "@faker-js/faker";
2
+ import type { Schema } from "../introspect/types";
3
+ import type { ResolvedConfig } from "../config/types";
4
+ import type { TableOrderResult } from "../graph/types";
5
+ import type { ExecutionResult } from "./types";
6
+ export interface FileModeOptions {
7
+ outFile: string;
8
+ startId?: number;
9
+ schema: Schema;
10
+ config: ResolvedConfig;
11
+ orderResult: TableOrderResult;
12
+ faker: Faker;
13
+ }
14
+ /**
15
+ * Generates a standalone PostgreSQL SQL script with client-assigned primary keys,
16
+ * deferred FK patch pass, and sequence synchronization.
17
+ */
18
+ export declare function executeFileMode(options: FileModeOptions): ExecutionResult;
@@ -0,0 +1,2 @@
1
+ import type { ExecutionResult } from "./types";
2
+ export declare function formatExecutionText(result: ExecutionResult): string;
@@ -0,0 +1,16 @@
1
+ export interface HostInfo {
2
+ host: string;
3
+ database: string;
4
+ }
5
+ /**
6
+ * Extracts host and database name from a connection URL, with safe fallbacks.
7
+ */
8
+ export declare function extractHostInfo(databaseUrl: string): HostInfo;
9
+ /**
10
+ * Determines whether the specified host is considered local/safe without confirmation.
11
+ */
12
+ export declare function isLocalHost(host: string, allowedHosts?: string[]): boolean;
13
+ /**
14
+ * Ensures user is warned and confirms before seeding any non-local/production database.
15
+ */
16
+ export declare function assertProductionSafety(databaseUrl: string, allowedHosts?: string[], yesFlag?: boolean): Promise<void>;
@@ -0,0 +1,18 @@
1
+ import type { Faker } from "@faker-js/faker";
2
+ import type { Schema } from "../introspect/types";
3
+ import type { ResolvedConfig } from "../config/types";
4
+ import type { TableOrderResult } from "../graph/types";
5
+ import type { ExecutionResult } from "./types";
6
+ export interface LiveExecutionOptions {
7
+ databaseUrl: string;
8
+ schema: Schema;
9
+ config: ResolvedConfig;
10
+ orderResult: TableOrderResult;
11
+ faker: Faker;
12
+ check?: boolean;
13
+ verbose?: boolean;
14
+ }
15
+ /**
16
+ * Executes database seeding inside a single transaction with automatic rollback on error.
17
+ */
18
+ export declare function executeLive(options: LiveExecutionOptions): Promise<ExecutionResult>;
@@ -0,0 +1,31 @@
1
+ export declare function escapeSqlValue(value: unknown): string;
2
+ export declare function escapeIdentifier(ident: string): string;
3
+ export interface InsertSqlOptions {
4
+ tableName: string;
5
+ schema?: string;
6
+ columns: string[];
7
+ rows: Record<string, unknown>[];
8
+ hasIdentityAlways?: boolean;
9
+ }
10
+ /**
11
+ * Formats a multi-row INSERT statement with optional OVERRIDING SYSTEM VALUE for identity columns.
12
+ */
13
+ export declare function formatInsertSql(options: InsertSqlOptions): string;
14
+ export interface UpdateSqlOptions {
15
+ tableName: string;
16
+ schema?: string;
17
+ pkColumns: string[];
18
+ fkColumn: string;
19
+ patches: Array<{
20
+ pkValues: Record<string, unknown>;
21
+ fkValue: unknown;
22
+ }>;
23
+ }
24
+ /**
25
+ * Formats deferred FK patch pass UPDATE statements.
26
+ */
27
+ export declare function formatUpdateSql(options: UpdateSqlOptions): string[];
28
+ /**
29
+ * Formats sequence synchronization statement so auto-incrementing serials continue seamlessly.
30
+ */
31
+ export declare function formatSequenceSyncSql(tableName: string, pkColumn: string, schema?: string): string;
@@ -0,0 +1,18 @@
1
+ import type { DeferredForeignKey } from "../graph/types";
2
+ export type ExecutionMode = "live" | "dry-run" | "check" | "file";
3
+ export interface TableExecutionStats {
4
+ table: string;
5
+ rowsInserted: number;
6
+ batches: number;
7
+ deferredPatched: number;
8
+ }
9
+ export interface ExecutionResult {
10
+ mode: ExecutionMode;
11
+ success: boolean;
12
+ totalRows: number;
13
+ tables: TableExecutionStats[];
14
+ deferredFks: DeferredForeignKey[];
15
+ durationMs: number;
16
+ rolledBack?: boolean;
17
+ outFile?: string;
18
+ }
@@ -0,0 +1,17 @@
1
+ import { Faker } from "@faker-js/faker";
2
+ import type { Schema, Table } from "../introspect/types";
3
+ import type { ResolvedConfig } from "../config/types";
4
+ import type { DeferredForeignKey } from "../graph/types";
5
+ import type { KeyPool, TablePlan } from "./types";
6
+ /**
7
+ * Builds the execution plan for a single table, mapping every column to its resolution source.
8
+ */
9
+ export declare function buildTablePlan(table: Table, schema: Schema, config: ResolvedConfig, deferredFks: DeferredForeignKey[]): TablePlan;
10
+ /**
11
+ * Generates relationally consistent fake rows for a table using its TablePlan.
12
+ */
13
+ export declare function generateTableRows(table: Table, plan: TablePlan, schema: Schema, config: ResolvedConfig, keyPools: Map<string, KeyPool>, faker: Faker): Record<string, unknown>[];
14
+ /**
15
+ * Creates an instance of Faker seeded deterministically.
16
+ */
17
+ export declare function createSeededFaker(seed?: number): Faker;
@@ -0,0 +1,13 @@
1
+ import type { Column } from "../introspect/types";
2
+ import type { GenContext } from "./types";
3
+ export interface SemanticRule {
4
+ name: string;
5
+ label: string;
6
+ match: (name: string, col: Column) => boolean;
7
+ generate: (ctx: GenContext, col: Column) => unknown;
8
+ }
9
+ export declare const SEMANTIC_RULES: SemanticRule[];
10
+ /**
11
+ * Finds a matching semantic rule for a column, if one exists and matches type safety guards.
12
+ */
13
+ export declare function findSemanticRule(col: Column): SemanticRule | null;
@@ -0,0 +1,10 @@
1
+ import type { Column, Schema } from "../introspect/types";
2
+ import type { GenContext } from "./types";
3
+ /**
4
+ * Returns a generator function for a standard PostgreSQL data type, or null if unsupported.
5
+ */
6
+ export declare function getTypeGenerator(col: Column, schema: Schema): ((ctx: GenContext) => unknown) | null;
7
+ /**
8
+ * Returns a human-readable generator label for planning/inspect output.
9
+ */
10
+ export declare function getTypeLabel(col: Column, schema: Schema): string;
@@ -0,0 +1,42 @@
1
+ import type { Faker } from "@faker-js/faker";
2
+ import type { DeferredForeignKey } from "../graph/types";
3
+ export type ColumnSource = "skip" | "config" | "fk" | "semantic" | "type";
4
+ export interface ColumnPlan {
5
+ column: string;
6
+ source: ColumnSource;
7
+ generator: string;
8
+ }
9
+ export interface TablePlan {
10
+ table: string;
11
+ rowCount: number;
12
+ ignored: boolean;
13
+ columns: ColumnPlan[];
14
+ deferred: DeferredForeignKey[];
15
+ }
16
+ export interface KeyPool {
17
+ table: string;
18
+ keyColumns: string[];
19
+ keys: unknown[][];
20
+ }
21
+ export interface GenContext {
22
+ faker: Faker;
23
+ index: number;
24
+ row: Record<string, unknown>;
25
+ }
26
+ export type ColumnRule = string | number | boolean | null | {
27
+ oneOf: Array<string | number | boolean>;
28
+ weights?: number[];
29
+ } | {
30
+ int: {
31
+ min: number;
32
+ max: number;
33
+ };
34
+ } | {
35
+ float: {
36
+ min: number;
37
+ max: number;
38
+ precision?: number;
39
+ };
40
+ } | {
41
+ faker: string;
42
+ } | ((ctx: GenContext) => unknown);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Finds a directed cycle among the provided nodes.
3
+ * An edge from U to V means "table U depends on table V (V must precede U)".
4
+ *
5
+ * @param nodes List of node names (e.g. table names)
6
+ * @param getNeighbors Function returning outgoing neighbor nodes (e.g. parent tables)
7
+ * @returns Array representing the cycle (e.g. ["teams", "players", "teams"]) or null if acyclic.
8
+ */
9
+ export declare function findCycle(nodes: string[], getNeighbors: (node: string) => string[]): string[] | null;
@@ -0,0 +1,17 @@
1
+ import type { Schema } from "../introspect/types";
2
+ import type { TableOrderResult } from "./types";
3
+ /**
4
+ * Calculates the topological insertion order for database tables based on their foreign keys.
5
+ *
6
+ * Algorithm:
7
+ * 1. Filter to tables in the requested run set (defaulting to all tables in schema).
8
+ * 2. Extract self-referencing foreign keys (e.g. employees.manager_id) and mark them deferred.
9
+ * 3. Execute Kahn's algorithm:
10
+ * - In-degree = count of distinct uninserted parent tables in the run set.
11
+ * - When multiple tables have in-degree 0, pick alphabetically for deterministic repeatability.
12
+ * 4. If a cycle stalls the resolution:
13
+ * - Trace the cycle using DFS.
14
+ * - If any foreign key in the cycle is nullable, break the cycle by deferring that FK.
15
+ * - If all foreign keys in the cycle are NOT NULL, halt with E_CIRCULAR_DEPENDENCY (exit 3).
16
+ */
17
+ export declare function orderTables(schema: Schema, runTables?: string[]): TableOrderResult;
@@ -0,0 +1,10 @@
1
+ import type { ForeignKey } from "../introspect/types";
2
+ export interface DeferredForeignKey {
3
+ table: string;
4
+ fk: ForeignKey;
5
+ reason: "self-reference" | "cycle";
6
+ }
7
+ export interface TableOrderResult {
8
+ order: string[];
9
+ deferredFks: DeferredForeignKey[];
10
+ }
@@ -0,0 +1,5 @@
1
+ export type { SeedConfig, TableConfig, ColumnRule, ColumnRuleContext, ResolvedConfig, } from "./config/types";
2
+ export { defineSeedConfig } from "./config/define";
3
+ export { SeedError, formatError } from "./errors";
4
+ export { createProgram, isJsonRequested } from "./cli";
5
+ export { main } from "./main";