### Example using all options Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Shows how to combine WithDriver, WithTables, and WithExcludedTables when creating a new import, and how to use WithSchemaPath when writing the schema. The example assumes drv and muts are defined elsewhere. ```go imp, err := entimport.NewImport( entimport.WithDriver(drv), entimport.WithTables([]string{"users", "posts"}), entimport.WithExcludedTables([]string{"audit_log"}), ) // ... err = entimport.WriteSchema(muts, entimport.WithSchemaPath("/tmp/schema")) ``` -------------------------------- ### Example: creating and registering a provider Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Shows how to create a Mux and register a provider. The provider function must match the importProvider signature; mysqlProvider is unexported. ```go m := mux.New() m.RegisterProvider(mysqlProvider, "mysql") // mysqlProvider is unexported — see note below ``` -------------------------------- ### Start Docker Compose and Run Go Tests Source: https://github.com/ariga/entimport/blob/master/internal/integration/README.md Starts the required services defined in compose/docker-compose.yaml in detached mode, then runs the Go test suite. Execute these commands from the project root. ```shell docker-compose -f compose/docker-compose.yaml up -d ``` ```shell go test ``` -------------------------------- ### Install ent codegen tool Source: https://github.com/ariga/entimport/blob/master/README.md Installs the ent codegen tool. After installation, it should be in your PATH; otherwise, you can run it with 'go run entgo.io/ent/cmd/ent '. ```shell go install entgo.io/ent/cmd/ent ``` -------------------------------- ### Build and run entimport CLI Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Run the CLI directly with go run, or install and run the binary. The -dsn flag is required and specifies the database connection. ```shell go run ariga.io/entimport/cmd/entimport -dsn "mysql://root:pass@tcp(localhost:3306)/test" ``` ```shell # or install and run the binary go install ariga.io/entimport/cmd/entimport entimport -h ``` -------------------------------- ### Example: importing schema with custom search_path Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/postgres.md Shows how to open a PostgreSQL connection with a non-default schema via search_path, create an import, generate mutations, and write the schema to ./ent/schema. Errors are wrapped with context. ```go ctx := context.Background() // search_path selects a non-default schema (see README note): drv, err := mux.Default.OpenImport("postgres://postgres:pass@localhost:5432/test?sslmode=disable&search_path=foo") if err != nil { return err } imp, err := entimport.NewImport(entimport.WithDriver(drv)) if err != nil { return err } mutations, err := imp.SchemaMutations(ctx) if err != nil { return fmt.Errorf("schema import failed: %w", err) } if err := entimport.WriteSchema(mutations, entimport.WithSchemaPath("./ent/schema")); err != nil { return fmt.Errorf("write schema: %w", err) } ``` -------------------------------- ### OpenImport usage example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Example of opening an import driver for a MySQL DSN using the default multiplexer. Logs a fatal error if the operation fails. ```go drv, err := mux.Default.OpenImport("mysql://root:pass@tcp(localhost:3306)/test") if err != nil { log.Fatalf("failed to create import driver - %v", err) } ``` -------------------------------- ### Install and run entimport Source: https://github.com/ariga/entimport/blob/master/README.md Installs and runs entimport. The command writes a valid ent schema into the specified directory (default ./ent/schema). ```shell go run ariga.io/entimport/cmd/entimport ``` -------------------------------- ### Example DSNs for mysql, postgres, and postgresql schemes Source: https://github.com/ariga/entimport/blob/master/_autodocs/configuration.md Valid DSN formats for the mux package. The mysql scheme passes the host part verbatim to sql.Open with the go-sql-driver/mysql driver. The postgres and postgresql schemes re-prepend 'postgres://' before using the lib/pq driver; the host part must not include a scheme. For postgres, the schema name is taken from the search_path query parameter, defaulting to 'public' if absent. ```text mysql://user:pass@tcp(localhost:3306)/dbname postgres://user:pass@host:port/dbname postgres://user:pass@host:port/dbname?sslmode=disable postgres://postgres:pass@localhost:5432/test?search_path=foo postgresql://user:pass@host:port/dbname ``` -------------------------------- ### WriteSchema usage example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Example of calling WriteSchema with mutations from SchemaMutations and specifying the output directory via WithSchemaPath. Logs fatal errors if schema import or writing fails. ```go mutations, err := i.SchemaMutations(ctx) if err != nil { log.Fatalf("entimport: schema import failed - %v", err) } if err := entimport.WriteSchema(mutations, entimport.WithSchemaPath("./ent/schema")); err != nil { log.Fatalf("entimport: schema writing failed - %v", err) } ``` -------------------------------- ### WriteSchema error handling example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Example of handling errors when writing to an unwritable directory, wrapping the error from schemast.Load/Print. ```go if err := entimport.WriteSchema(mutations, entimport.WithSchemaPath("/root/readonly")); err != nil { return fmt.Errorf("write schema: %w", err) // err originates from schemast.Load/Print } ``` -------------------------------- ### NewImport usage example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Shows how to create an importer with a MySQL driver and specify tables to import. It opens the driver via mux.Default.OpenImport, then calls NewImport with WithDriver and WithTables, handling errors with log.Fatalf. ```go import ( "context" "ariga.io/entimport/internal/entimport" "ariga.io/entimport/internal/mux" ) ctx := context.Background() drv, err := mux.Default.OpenImport("mysql://root:pass@tcp(localhost:3306)/test") if err != nil { log.Fatalf("entimport: failed to create import driver - %v", err) } i, err := entimport.NewImport( entimport.WithDriver(drv), entimport.WithTables([]string{"users", "user_friends"}), ) if err != nil { log.Fatalf("entimport: create importer failed: %v", err) } ``` -------------------------------- ### SchemaMutations usage example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mysql.md Shows the intended usage: open a MySQL driver, create an importer via entimport.NewImport, assert to *entimport.MySQL, call SchemaMutations, and write the schema. Requires a valid driver and handles errors. ```go ctx := context.Background() drv, err := mux.Default.OpenImport("mysql://root:pass@tcp(localhost:3306)/test") if err != nil { return err } // NewMySQL is invoked internally by NewImport for MySQL drivers. Since // ImportOptions has unexported fields, the supported construction path is: imp, err := entimport.NewImport(entimport.WithDriver(drv)) if err != nil { return err } m, ok := imp.(*entimport.MySQL) // NewImport returns the concrete *MySQL for mysql dialects if !ok { return fmt.Errorf("expected a MySQL importer, got %T", imp) } mutations, err := m.SchemaMutations(ctx) if err != nil { return fmt.Errorf("schema import failed: %w", err) } err = entimport.WriteSchema(mutations, entimport.WithSchemaPath("./ent/schema")) ``` -------------------------------- ### OpenImport error handling example Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Shows error results for an unregistered scheme and a malformed DSN. The first returns 'provider does not exist: "sqlite"' and the second returns 'failed to parse DSN: failed to parse dsn: "not-a-dsn"'. ```go drv, err := mux.Default.OpenImport("sqlite://file.db") // err: provider does not exist: "sqlite" drv, err = mux.Default.OpenImport("not-a-dsn") // err: failed to parse DSN: failed to parse dsn: "not-a-dsn" ``` -------------------------------- ### Recursive M2M relation edges example Source: https://github.com/ariga/entimport/blob/master/README.md Example of how recursive relations are handled: edge names are prefixed with 'child_' and 'parent_'. This is shown for a 'users' table with M2M relation to itself. ```go func (User) Edges() []ent.Edge { return []ent.Edge{edge.To("child_users", User.Type), edge.From("parent_users", User.Type)} } ``` -------------------------------- ### CLI error handling with exit codes Source: https://github.com/ariga/entimport/blob/master/_autodocs/errors.md CLI-level error handling: the binary converts errors to exit codes. Example shows running the CLI with an invalid DSN, producing stderr message and exit status 1. ```go // CLI-level: the binary already converts errors to exit codes. // go run ariga.io/entimport/cmd/entimport -dsn "sqlite://file.db" // stderr: entimport: failed to create import driver - provider does not exist: "sqlite" // exit status 1 ``` -------------------------------- ### Error handling for invalid schema Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mysql.md Example of handling errors from SchemaMutations, such as missing primary key. The error is wrapped from resolvePrimaryKey. ```go mutations, err := m.SchemaMutations(ctx) if err != nil { // e.g. entimport: missing primary key (table: pet) // wrapped from resolvePrimaryKey (import.go:246) return err } ``` -------------------------------- ### Initialize Go module Source: https://github.com/ariga/entimport/blob/master/README.md Sets up a Go module project, required if your project is outside GOPATH or you're not familiar with it. ```shell go mod init ``` -------------------------------- ### Basic MySQL import Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Runs entimport with a MySQL DSN, writing generated schema files to ./ent/schema/. ```shell go run arigo.io/entimport/cmd/entimport -dsn "mysql://root:pass@tcp(localhost:3306)/test" ``` -------------------------------- ### Create schema directory with ent init Source: https://github.com/ariga/entimport/blob/master/README.md Creates the /ent/schema/ directory and the file /ent/generate.go. ```shell ent init ``` -------------------------------- ### Main execution flow (entimport.go:25-57) Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Parses the -dsn and -schema-path flags, opens an import driver via mux.Default.OpenImport, creates an importer with optional table filters, generates schema mutations, and writes the schema. Exits with code 2 if -dsn is empty, and with code 1 on any failure. ```go dsn := flag.String("dsn", "", `data source name (connection information), ...`) schemaPath := flag.String("schema-path", "./ent/schema", "output path for ent schema") flag.Parse() if *dsn == "" { log.Println("entimport: data source name (dsn) must be provided") flag.Usage() os.Exit(2) } ctx := context.Background() drv, err := mux.Default.OpenImport(*dsn) if err != nil { log.Fatalf("entimport: failed to create import driver - %v", err) } i, err := entimport.NewImport( entimport.WithTables(tablesFlag), entimport.WithExcludedTables(excludeTablesFlag), entimport.WithDriver(drv), ) if err != nil { log.Fatalf("entimport: create importer failed: %v", err) } mutations, err := i.SchemaMutations(ctx) if err != nil { log.Fatalf("entimport: schema import failed - %v", err) } if err = entimport.WriteSchema(mutations, entimport.WithSchemaPath(*schemaPath)); err != nil { log.Fatalf("entimport: schema writing failed - %v", err) } ``` -------------------------------- ### Show entimport help Source: https://github.com/ariga/entimport/blob/master/README.md Displays usage information for entimport, including available flags and their defaults. ```shell entimport -h ``` -------------------------------- ### PostgreSQL import with non-public search path Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Uses a PostgreSQL DSN with sslmode=disable and search_path=foo to import from a non-public schema. ```shell go run arigo.io/entimport/cmd/entimport -dsn "postgres://postgres:pass@localhost:5432/test?sslmode=disable&search_path=foo" ``` -------------------------------- ### Default package-level multiplexer Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Package-level multiplexer instance created by New(). Its init() registers providers for schemes "mysql", "postgres", and "postgresql". ```go // internal/mux/mux.go:36 var Default = New() ``` -------------------------------- ### OpenImport method Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Opens an import driver from a full DSN. Parses the DSN on "://", looks up the scheme in registered providers, and invokes the provider with the host part. Returns an error if the DSN is malformed or the scheme is unregistered. ```go // internal/mux/mux.go:46 func (u *Mux) OpenImport(dsn string) (*ImportDriver, error) ``` -------------------------------- ### NewMySQL constructor Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mysql.md Constructor for MySQL importer. Takes *ImportOptions and returns (*MySQL, error). Currently always returns a valid instance with nil error. ```go // internal/entimport/mysql.go:30 func NewMySQL(i *ImportOptions) (*MySQL, error) ``` -------------------------------- ### NewPostgreSQL constructor Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/postgres.md Creates a new Postgres importer. Takes *ImportOptions and returns (SchemaImporter, error). Currently always returns a Postgres instance with nil error. ```go // internal/entimport/postgres.go:25 func NewPostgreSQL(i *ImportOptions) (SchemaImporter, error) ``` -------------------------------- ### Import subset of tables with -tables Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Imports only the specified tables. Per the README, join tables must be accompanied by their referenced tables. ```shell go run arigo.io/entimport/cmd/entimport -dsn "..." -tables "users,user_friends" ``` -------------------------------- ### Default Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md The package-level multiplexer. Its init() registers providers for the 'mysql', 'postgres', and 'postgresql' schemes. ```APIDOC ## Default ### Description The package-level multiplexer. Its `init()` (`provider.go:14-17`) registers providers for the `"mysql"`, `"postgres"`, and `"postgresql"` schemes. ### Method N/A (package-level variable) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Generated output structure Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Shows the directory layout produced by entimport: a generate.go file plus per-entity schema files under the schema directory. ```text . ├── generate.go └── schema └── user.go ``` -------------------------------- ### New function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Returns a new Mux with an empty provider map; use RegisterProvider or the package-level Default. ```go // internal/mux/mux.go:30 func New() *Mux ``` -------------------------------- ### Generate ent files from schemas Source: https://github.com/ariga/entimport/blob/master/README.md Generates ent files from the produced schemas. Two alternatives are shown: using 'go run' with the ent command, or using 'go generate ./ent'. ```shell go run -mod=mod entgo.io/ent/cmd/ent generate ./schema ``` ```shell # OR `ent` init: go generate ./ent ``` -------------------------------- ### SchemaMutations method signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mysql.md Implements SchemaImporter.SchemaMutations. Takes a context and returns a slice of schemast.Mutator or an error. ```go // internal/entimport/mysql.go:37 func (m *MySQL) SchemaMutations(ctx context.Context) ([]schemast.Mutator, error) ``` -------------------------------- ### Generated schema directory structure Source: https://github.com/ariga/entimport/blob/master/README.md Shows the directory structure after running entimport with the default schema path. ```text . ├── generate.go └── schema └── user.go 1 directory, 2 files ``` -------------------------------- ### Error handling — unknown provider (exit code 1) Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Running entimport with an unsupported provider (sqlite) prints an error and exits with status 1. ```shell $ entimport -dsn "sqlite://file.db" entimport: failed to create import driver - provider does not exist: "sqlite" ``` -------------------------------- ### RegisterProvider method Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Registers a provider function under one or more URL schemes. The provider is invoked with the DSN host part (scheme stripped). ```go // internal/mux/mux.go:39 func (u *Mux) RegisterProvider(p importProvider, scheme ...string) ``` -------------------------------- ### (*Mux) OpenImport Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Opens an import driver for the given DSN. Parses the DSN, looks up the scheme, and invokes the registered provider. ```APIDOC ## (*Mux) OpenImport ### Description Opens an import driver for the given DSN. Parses the DSN, looks up the scheme, and invokes the registered provider. ### Method N/A (Go method) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dsn** (`string`) - Required - Full data source name, e.g. `"mysql://root:pass@tcp(localhost:3306)/test"` or `"postgres://user:pass@localhost:5432/db"` ### Request Example ```go drv, err := mux.Default.OpenImport("mysql://root:pass@tcp(localhost:3306)/test") if err != nil { log.Fatalf("failed to create import driver - %v", err) } ``` ### Response #### Success Response Returns `(*ImportDriver, error)`. #### Response Example N/A ### Error Handling - If the DSN contains no `"://"`, returns `failed to parse dsn: ""`. - On parse failure, wraps: `failed to parse DSN: `. - If the scheme is not registered, returns `provider does not exist: ""`. #### Error Example ```go drv, err := mux.Default.OpenImport("sqlite://file.db") // err: provider does not exist: "sqlite" drv, err = mux.Default.OpenImport("not-a-dsn") // err: failed to parse DSN: failed to parse dsn: "not-a-dsn" ``` ``` -------------------------------- ### tables flag value type implementation Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Implements flag.Value for the -tables and -exclude-tables flags. Set splits on commas without trimming whitespace, so '-tables "a, b"' yields ["a", " b"]. An empty value yields [""] which is forwarded as a table name; omitting the flag keeps nil (all tables). ```go type tables []string func (t *tables) String() string { return fmt.Sprint(*t) } func (t *tables) Set(s string) error { *t = strings.Split(s, ",") return nil } ``` -------------------------------- ### Exclude tables and write to custom directory Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Excludes the audit_log table and writes generated files to /some/path/here instead of the default ./ent/schema. ```shell go run arigo.io/entimport/cmd/entimport -dsn "..." -exclude-tables "audit_log" -schema-path "/some/path/here" ``` -------------------------------- ### Error handling for unsupported dialect Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Demonstrates the error returned when the driver's dialect is not supported. It sets a contrived dialect 'oracle' and expects the error 'entimport: unsupported dialect "oracle"'. ```go drv, _ := mux.Default.OpenImport("postgres://user:pass@localhost:5432/db") drv.Dialect = "oracle" // contrived: a foreign driver i, err := entimport.NewImport(entimport.WithDriver(drv)) if err != nil { // err = entimport: unsupported dialect "oracle" return err } ``` -------------------------------- ### Import to another directory Source: https://github.com/ariga/entimport/blob/master/README.md Imports the ent schema to a specified directory using the -schema-path flag. ```shell go run ariga.io/entimport/cmd/entimport -dsn "..." -schema-path "/some/path/here" ``` -------------------------------- ### SchemaMutations method signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/postgres.md Implements SchemaImporter.SchemaMutations. Takes a context and returns a slice of schemast.Mutator or an error. Inspects the database and converts tables to Ent schema mutators. ```go // internal/entimport/postgres.go:32 func (p *Postgres) SchemaMutations(ctx context.Context) ([]schemast.Mutator, error) ``` -------------------------------- ### postgresProvider function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Signature for the internal postgresProvider function that creates an ImportDriver for PostgreSQL. It prepends the scheme, opens the database, initializes the Atlas driver, parses the URL, and sets SchemaName from the search_path query parameter (defaulting to "public"). ```go func postgresProvider(dsn string) (*ImportDriver, error) ``` -------------------------------- ### entimport usage output Source: https://github.com/ariga/entimport/blob/master/README.md Output of 'entimport -h' showing the flags: -dsn, -schema-path (default "./ent/schema"), and -tables. ```text Usage of ./entimport: -dsn string data source name (connection information), for example: "mysql://user:pass@tcp(localhost:3306)/dbname" "postgres://user:pass@host:port/dbname" -schema-path string output path for ent schema (default "./ent/schema") -tables value comma-separated list of tables to inspect (all if empty) ``` -------------------------------- ### mysqlProvider function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Signature for the internal mysqlProvider function that creates an ImportDriver for MySQL. It opens the database, initializes the Atlas driver, parses the DSN, and returns an ImportDriver with the schema name from the DSN. ```go func mysqlProvider(dsn string) (*ImportDriver, error) ``` -------------------------------- ### WithSchemaPath function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Returns an ImportOption that sets the output path for the generated Ent schema, used by WriteSchema. The path parameter is a string specifying the output directory or file path. ```go // internal/entimport/import.go:62 func WithSchemaPath(path string) ImportOption ``` -------------------------------- ### WithTables function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Returns an ImportOption that limits the import to the specified table names. An empty or nil slice means all tables are imported. The tables are passed to schema.InspectOptions{Tables}. ```go // internal/entimport/import.go:69 func WithTables(tables []string) ImportOption ``` -------------------------------- ### WithDriver function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Returns an ImportOption that sets the driver carrying the Atlas inspector, dialect, and schema name. This option is required by NewImport. ```go // internal/entimport/import.go:83 func WithDriver(drv *mux.ImportDriver) ImportOption ``` -------------------------------- ### Import MySQL schema with users table Source: https://github.com/ariga/entimport/blob/master/README.md Imports a MySQL schema with a 'users' table. The command writes a valid ent schema into the specified directory (default ./ent/schema). ```shell go run ariga.io/entimport/cmd/entimport -dsn "mysql://root:pass@tcp(localhost:3308)/test" -tables "users" ``` -------------------------------- ### Catching SchemaMutations errors by message content Source: https://github.com/ariga/entimport/blob/master/_autodocs/errors.md Library-level error handling inside the entimport module. Since no sentinel or error type is exported, detection relies on message content or wrapping. Checks for specific error messages to handle row 6 (join tables must be inspected with ref tables) and row 7 (unsupported type), then wraps other errors with %w to preserve the chain. ```go // Library-level (inside the module): inspect the failure text. mutations, err := i.SchemaMutations(ctx) if err != nil { if strings.Contains(err.Error(), "join tables must be inspected with ref tables") { // Row 6: add the join table's referenced tables to WithTables. return err } if strings.Contains(err.Error(), "unsupported type") { // Row 7: column type has no field mapping in this dialect. return err } return fmt.Errorf("entimport: schema import failed: %w", err) // preserves the chain } ``` -------------------------------- ### importProvider type alias Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Unexported alias for the provider function signature used by Mux. ```go // internal/mux/mux.go:13 importProvider func(string) (*ImportDriver, error) ``` -------------------------------- ### WriteSchema function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Signature of WriteSchema, which applies a list of schemast.Mutators and writes an Ent schema to the filesystem. Returns an error if loading, mutating, or printing fails. ```go // internal/entimport/import.go:117 func WriteSchema(mutations []schemast.Mutator, opts ...ImportOption) error ``` -------------------------------- ### Mux struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Defines the Mux type with an unexported providers map from URL scheme to an importProvider function. ```go // internal/mux/mux.go:14-19 type Mux struct { providers map[string]importProvider } ``` -------------------------------- ### (*Mux) RegisterProvider Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Registers a provider function under one or more URL schemes. The provider is invoked with the DSN host part (scheme stripped). ```APIDOC ## (*Mux) RegisterProvider ### Description Registers a provider function under one or more URL schemes. The provider is invoked with the DSN host part (scheme stripped). ### Method N/A (Go method) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **p** (`importProvider`) - Required - Provider function invoked with the DSN host part (scheme stripped) - **scheme** (`...string`) - Required - One or more URL schemes to bind the provider to (e.g. `"postgres"`, `"postgresql"`) ### Request Example N/A ### Response #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Import ent schema from Postgres database Source: https://github.com/ariga/entimport/blob/master/README.md Imports an ent schema from a Postgres database. Note: add search_path=foo if you use a non-public schema. ```shell go run ariga.io/entimport/cmd/entimport -dsn "postgres://postgres:pass@localhost:5432/test?sslmode=disable" ``` -------------------------------- ### MySQL struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the MySQL struct with an embedded *ImportOptions field. Acts as a marker/state holder around the inherited configuration. Constructor: NewMySQL(i *ImportOptions) (*MySQL, error). ```go // internal/entimport/mysql.go:25-27 type MySQL struct { *ImportOptions } ``` -------------------------------- ### Error handling for unsupported column type Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/postgres.md Shows how to handle errors from SchemaMutations, specifically for unsupported column types. The error message includes 'entimport: unsupported type' and is thrown by (*Postgres).field. ```go mutations, err := p.SchemaMutations(ctx) if err != nil { // e.g. entimport: unsupported type &{...} for column custom_type // thrown by (*Postgres).field (postgres.go:83) return err } ``` -------------------------------- ### WithDriver Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Sets the driver carrying the Atlas inspector, dialect, and schema name. Required by NewImport. ```APIDOC ## WithDriver ### Description Sets the driver carrying the Atlas inspector, dialect, and schema name. Required by NewImport. ### Function Signature ```go func WithDriver(drv *mux.ImportDriver) ImportOption ``` ### Parameters - `drv` (*mux.ImportDriver) - Required - Driver carrying the Atlas inspector, dialect, and schema name. ``` -------------------------------- ### NewImport function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Declares the NewImport function that creates a SchemaImporter for the dialect reported by the configured driver. It requires a WithDriver option and panics on a nil driver. ```go // internal/entimport/import.go:90 func NewImport(opts ...ImportOption) (SchemaImporter, error) ``` -------------------------------- ### Import ent schema from MySQL database Source: https://github.com/ariga/entimport/blob/master/README.md Imports an ent schema from a MySQL database. ```shell go run ariga.io/entimport/cmd/entimport -dsn "mysql://root:pass@tcp(localhost:3308)/test" ``` -------------------------------- ### MySQL struct Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md MySQL is a struct that embeds ImportOptions and serves as a marker/state holder. It is constructed via NewMySQL. ```APIDOC ## MySQL struct ### Description Struct embedding ImportOptions, used as a marker/state holder for MySQL imports. ### Embedded Fields - **ImportOptions** (*ImportOptions) - Inherited configuration. ### Constructor - NewMySQL(i *ImportOptions) (*MySQL, error) ``` -------------------------------- ### MySQL struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mysql.md Defines the MySQL importer struct, embedding *ImportOptions for configuration. It satisfies the SchemaImporter interface. ```go // internal/entimport/mysql.go:25 type MySQL struct { *ImportOptions } ``` -------------------------------- ### Import only specific tables Source: https://github.com/ariga/entimport/blob/master/README.md Imports only specified tables. When importing specific tables, if a table is a join table, you must also provide referenced tables. If a table is only one part of a relation, the other part won't be imported unless specified. If -tables is omitted, all tables in the current database schema are imported. ```shell go run ariga.io/entimport/cmd/entimport -dsn "..." -tables "users,user_friends" ``` -------------------------------- ### WithTables Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Limits the import to the specified table names. If empty or nil, all tables are imported. ```APIDOC ## WithTables ### Description Limits the import to the specified table names. If empty or nil, all tables are imported. ### Function Signature ```go func WithTables(tables []string) ImportOption ``` ### Parameters - `tables` ([]string) - Required - Limit import to these table names; empty/nil means all tables. ``` -------------------------------- ### WithSchemaPath Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Sets the output path for the generated Ent schema. Used by WriteSchema. ```APIDOC ## WithSchemaPath ### Description Sets the output path for the generated Ent schema. Used by WriteSchema. ### Function Signature ```go func WithSchemaPath(path string) ImportOption ``` ### Parameters - `path` (string) - Required - Output path for the generated Ent schema. ``` -------------------------------- ### ImportOptions struct Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md ImportOptions is a struct that holds configuration for the import process. All fields are unexported and set exclusively through functional options. ```APIDOC ## ImportOptions struct ### Description Configuration options for the import process. Fields are set via functional options. ### Fields - **tables** ([]string) - Set by WithTables - Table names to inspect; empty means all. - **excludedTables** ([]string) - Set by WithExcludedTables - Table names to exclude from output. - **schemaPath** (string) - Set by WithSchemaPath - Filesystem path for reading/writing the schema. - **driver** (*mux.ImportDriver) - Set by WithDriver - Driver with Atlas inspector, dialect, schema name. ### Consumed By - NewImport - WriteSchema - NewMySQL - NewPostgreSQL ``` -------------------------------- ### ImportDriver struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/mux.md Defines the ImportDriver struct with embedded io.Closer and schema.Inspector, plus Dialect and SchemaName fields. Used by NewImport and WriteSchema. ```go // internal/mux/mux.go:21-28 type ImportDriver struct { io.Closer schema.Inspector Dialect string SchemaName string } ``` -------------------------------- ### ImportOptions struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the ImportOptions struct with unexported fields for tables, excludedTables, schemaPath, and driver. Values are set exclusively through functional options like WithTables, WithExcludedTables, WithSchemaPath, and WithDriver. ```go // internal/entimport/import.go:51-56 ImportOptions struct { tables []string excludedTables []string schemaPath string driver *mux.ImportDriver } ``` -------------------------------- ### Postgres struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the Postgres struct with an embedded *ImportOptions field, same shape as MySQL. Constructor: NewPostgreSQL(i *ImportOptions) (SchemaImporter, error) — note it returns the interface. ```go // internal/entimport/postgres.go:20-22 type Postgres struct { *ImportOptions } ``` -------------------------------- ### Postgres struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/postgres.md Defines the Postgres importer type, embedding *ImportOptions. It satisfies SchemaImporter via the SchemaMutations method. ```go // internal/entimport/postgres.go:20 type Postgres struct { *ImportOptions } ``` -------------------------------- ### WriteSchema Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Applies a list of schemast.Mutators and writes an Ent schema to the filesystem. This function is used to persist the imported schema mutations to the specified schema path. ```APIDOC ## WriteSchema ### Description Applies a list of `schemast.Mutator`s and writes an Ent schema to the filesystem. This function is used to persist the imported schema mutations to the specified schema path. ### Method Function ### Signature ```go func WriteSchema(mutations []schemast.Mutator, opts ...ImportOption) error ``` ### Parameters - `mutations` ([]schemast.Mutator) - Required - Mutators produced by `SchemaMutations` (`schemast.Mutator` is `entgo.io/contrib/schemast`) - `opts` (...ImportOption) - Optional - `WithSchemaPath` controls the output directory. If omitted, `schemaPath` stays `""` ### Returns - `error` - nil on success; non-nil when `schemast.Load` fails (missing/invalid schema path), `schemast.Mutate` fails, or `Print` fails. ### Behavior Loads an existing `schemast.Context` from `i.schemaPath`, applies all mutators, then prints the result back to `i.schemaPath` with the header `schemast.Header(header)` where `header = "Code generated by entimport, DO NOT EDIT."`. > Files are **overwritten** by consecutive calls (README "Known Caveats" — real upsert is not supported). ### Examples ```go mutations, err := i.SchemaMutations(ctx) if err != nil { log.Fatalf("entimport: schema import failed - %v", err) } if err := entimport.WriteSchema(mutations, entimport.WithSchemaPath("./ent/schema")); err != nil { log.Fatalf("entimport: schema writing failed - %v", err) } ``` Error handling — output to an unwritable directory: ```go if err := entimport.WriteSchema(mutations, entimport.WithSchemaPath("/root/readonly")); err != nil { return fmt.Errorf("write schema: %w", err) // err originates from schemast.Load/Print } ``` ``` -------------------------------- ### Postgres struct Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Postgres is a struct that embeds ImportOptions and serves as a marker/state holder. It is constructed via NewPostgreSQL, which returns the SchemaImporter interface. ```APIDOC ## Postgres struct ### Description Struct embedding ImportOptions, used as a marker/state holder for Postgres imports. ### Embedded Fields - **ImportOptions** (*ImportOptions) - Inherited configuration. ### Constructor - NewPostgreSQL(i *ImportOptions) (SchemaImporter, error) ``` -------------------------------- ### WithExcludedTables function signature Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Returns an ImportOption that drops the specified table names from the inspected result. This applies after inspection; nil excludes nothing. ```go // internal/entimport/import.go:76 func WithExcludedTables(tables []string) ImportOption ``` -------------------------------- ### ImportDriver struct Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md ImportDriver wraps an io.Closer and schema.Inspector, providing Dialect and SchemaName fields. It is produced by Mux.OpenImport and consumed by WithDriver and NewImport. ```APIDOC ## ImportDriver struct ### Description Driver with Atlas inspector, dialect, and schema name. ### Fields - **Closer** (io.Closer) - Backing *sql.DB; call .Close() when done. - **Inspector** (schema.Inspector) - Atlas inspector; InspectSchema(ctx, name, opts). - **Dialect** (string) - "mysql" or "postgres". - **SchemaName** (string) - MySQL: DSN database name; Postgres: search_path or "public". ### Produced By - mux.Default.OpenImport(dsn) - (*Mux).OpenImport(dsn) ### Consumed By - WithDriver(drv *mux.ImportDriver) - NewImport (reads drv.Dialect) - Dialect SchemaMutations (reads drv.SchemaName, calls drv.InspectSchema) ``` -------------------------------- ### Error handling — missing DSN (exit code 2) Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/cli.md Running entimport without a DSN prints an error message and usage, then exits with status 2. ```shell $ entimport entimport: data source name (dsn) must be provided Usage of entimport: -dsn string data source name (connection information), ... ... # process exits with status 2 ``` -------------------------------- ### Mux struct and importProvider type definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the importProvider function type and the Mux struct used for routing DSNs to the correct provider. The providers field is an unexported map from scheme to provider. Functions include New, RegisterProvider, and OpenImport. ```go // internal/mux/mux.go:11-19 type ( // importProvider - returns an ImportDriver for a given dialect. importProvider func(string) (*ImportDriver, error) // Mux is used for routing dsn to correct provider. Mux struct { providers map[string]importProvider } ) ``` -------------------------------- ### Mux struct Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Mux is used for routing DSNs to the correct provider. It has an unexported providers map and provides methods for registration and opening imports. ```APIDOC ## Mux struct ### Description Routes DSNs to the correct provider. ### Fields - **providers** (map[string]importProvider) - Scheme to provider routing table (unexported). ### Functions - New() *Mux - (*Mux).RegisterProvider(p importProvider, scheme ...string) - (*Mux).OpenImport(dsn string) (*ImportDriver, error) ### Package Variable - Default = New() ``` -------------------------------- ### importProvider type definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Provider function stored per scheme in Mux.providers; receives the DSN host part and returns a ready *ImportDriver. ```go importProvider func(string) (*ImportDriver, error) ``` -------------------------------- ### ImportDriver struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the ImportDriver struct with embedded io.Closer and schema.Inspector, plus Dialect and SchemaName fields. Produced by mux.Default.OpenImport and (*Mux).OpenImport; consumed by WithDriver and NewImport. ```go // internal/mux/mux.go:21-28 ImportDriver struct { io.Closer schema.Inspector Dialect string SchemaName string } ``` -------------------------------- ### SchemaImporter interface definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the SchemaImporter interface with a single SchemaMutations method that imports a schema from a data source and returns schemast mutators. Implemented by *MySQL and *Postgres, and returned by NewImport and NewPostgreSQL. ```go // internal/entimport/import.go:44-48 SchemaImporter interface { // SchemaMutations imports a given schema from a data source and returns a list of schemast mutators. SchemaMutations(context.Context) ([]schemast.Mutator, error) } ``` -------------------------------- ### ImportOption func type definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines the ImportOption functional option type that mutates an ImportOptions value. Produced by WithSchemaPath, WithTables, WithExcludedTables, and WithDriver; accepted by NewImport and WriteSchema. ```go // internal/entimport/import.go:58-59 ImportOption func(*ImportOptions) ``` -------------------------------- ### WithExcludedTables Source: https://github.com/ariga/entimport/blob/master/_autodocs/api-reference/import.md Specifies table names to drop from the inspected result. Applies after inspection; nil excludes nothing. ```APIDOC ## WithExcludedTables ### Description Specifies table names to drop from the inspected result. Applies after inspection; nil excludes nothing. ### Function Signature ```go func WithExcludedTables(tables []string) ImportOption ``` ### Parameters - `tables` ([]string) - Required - Table names to drop from the inspected result. ``` -------------------------------- ### edgeDir type and constants Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines edgeDir type and constants for edge direction selection in entEdge. header is the generated-file header passed to schemast.Header. ```go const ( header = "Code generated " + "by entimport, DO NOT EDIT." to edgeDir = iota // = 0 from // = 1 ) type edgeDir int ``` -------------------------------- ### SchemaImporter interface Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md The SchemaImporter interface defines a method to import a schema from a data source and return a list of schemast mutators. It is implemented by MySQL and Postgres types and returned by NewImport and NewPostgreSQL. ```APIDOC ## SchemaImporter interface ### Description Interface for importing a schema from a data source and returning mutators to be applied by WriteSchema. ### Method SchemaMutations(context.Context) ([]schemast.Mutator, error) ### Parameters - **ctx** (context.Context) - Required - The context for the operation. ### Returns - **[]schemast.Mutator** - List of mutators to be applied. - **error** - Error if the import fails. ### Implemented By - *MySQL - *Postgres ### Returned By - NewImport - NewPostgreSQL ``` -------------------------------- ### ImportOption func type Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md ImportOption is a functional option type that mutates an ImportOptions value. It is produced by WithSchemaPath, WithTables, WithExcludedTables, and WithDriver, and accepted by NewImport and WriteSchema. ```APIDOC ## ImportOption func type ### Description Functional option that mutates an ImportOptions value. ### Signature func(*ImportOptions) ### Producers - WithSchemaPath - WithTables - WithExcludedTables - WithDriver ### Accepted By - NewImport(opts ...ImportOption) - WriteSchema(mutations []schemast.Mutator, opts ...ImportOption) ``` -------------------------------- ### relOptions struct definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Holds relation-building parameters for entEdge/upsertRelation, including uniqueness flags, recursive marker, refName, and edgeField. ```go relOptions struct { uniqueEdgeToChild bool recursive bool uniqueEdgeFromParent bool refName string edgeField string } ``` -------------------------------- ### fieldFunc type definition Source: https://github.com/ariga/entimport/blob/master/_autodocs/types.md Defines a function type that converts an Atlas schema.Column to an ent.Field. Implemented by (*MySQL).field and (*Postgres).field. ```go fieldFunc func(column *schema.Column) (f ent.Field, err error) ```