{"record":{"id":"b05d9cdfc4cde57c","repo":"micro/go-micro","slug":"model-postgres-create-w","errorCode":null,"errorMessage":"model/postgres: create: %w","messagePattern":"model/postgres: create: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"model/postgres/postgres.go","lineNumber":106,"sourceCode":"\t\treturn nil, model.ErrNotRegistered\n\t}\n\treturn s, nil\n}\n\nfunc (d *postgresModel) Create(ctx context.Context, v interface{}) error {\n\tschema, err := d.schema(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields := model.StructToMap(schema, v)\n\tcols, placeholders, values := buildInsert(schema, fields)\n\tquery := fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", quoteIdent(schema.Table), cols, placeholders)\n\t_, err = d.db.ExecContext(ctx, query, values...)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"duplicate key\") || strings.Contains(err.Error(), \"unique constraint\") {\n\t\t\treturn model.ErrDuplicateKey\n\t\t}\n\t\treturn fmt.Errorf(\"model/postgres: create: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc (d *postgresModel) Read(ctx context.Context, key string, v interface{}) error {\n\tschema, err := d.schema(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcols := columnList(schema)\n\tquery := fmt.Sprintf(\"SELECT %s FROM %s WHERE %s = $1\", cols, quoteIdent(schema.Table), quoteIdent(schema.Key))\n\trow := d.db.QueryRowContext(ctx, query, key)\n\tfields, err := scanRow(schema, row)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmodel.MapToStruct(schema, fields, v)\n\treturn nil","sourceCodeStart":88,"sourceCodeEnd":124,"githubUrl":"https://github.com/micro/go-micro/blob/24529f140421a11a33b6999ab7944f2021cfd69c/model/postgres/postgres.go#L88-L124","documentation":"Create executes an INSERT built from the schema and values. Duplicate-key/unique-constraint violations are translated to model.ErrDuplicateKey; any other INSERT failure is wrapped as \"model/postgres: create\" with the underlying driver error. So this error means the insert failed for a reason other than a duplicate key.","triggerScenarios":"Calling postgresModel.Create(ctx, v) when the INSERT fails due to a NOT NULL violation, type mismatch, missing column (schema/table drift), connection drop, permission denial, or invalid values (e.g. malformed JSON/UUID strings).","commonSituations":"Schema changed in the DB but the model wasn't updated (or vice versa), inserting nil into NOT NULL columns, wrong data types from unmarshaled payloads, transient network failures to Postgres.","solutions":["Unwrap the error to read the underlying Postgres message — it names the column/constraint at fault.","Align the model schema with the actual table (run migrations) so columns and types match.","Ensure required (NOT NULL) fields, including the key, are set on the struct before Create.","Check connectivity/credentials if the cause is a connection or permission error.","Handle model.ErrDuplicateKey separately if duplicates are expected business cases."],"exampleFix":"// before\nif err := store.Create(ctx, &user); err != nil {\n    return err // opaque\n}\n\n// after\nif err := store.Create(ctx, &user); err != nil {\n    if errors.Is(err, model.ErrDuplicateKey) {\n        return ErrEmailTaken\n    }\n    var pgErr *pgconn.PgError\n    if errors.As(err, &pgErr) {\n        log.Printf(\"insert failed: %s (column %s)\", pgErr.Message, pgErr.ColumnName)\n    }\n    return err\n}","handlingStrategy":"try-catch","validationCode":"// pre-validate NOT NULL and key fields before Create\nfunc insertable(v interface{}, required []string) error {\n    rv := reflect.ValueOf(v)\n    if rv.Kind() == reflect.Pointer {\n        rv = rv.Elem()\n    }\n    for _, name := range required {\n        if f := rv.FieldByName(name); !f.IsValid() || f.IsZero() {\n            return fmt.Errorf(\"field %q required before insert\", name)\n        }\n    }\n    return nil\n}","typeGuard":null,"tryCatchPattern":"if err := store.Create(ctx, &user); err != nil {\n    switch {\n    case errors.Is(err, model.ErrDuplicateKey):\n        return ErrAlreadyExists\n    default:\n        var pgErr *pgconn.PgError\n        if errors.As(err, &pgErr) {\n            log.Printf(\"create failed [%s]: %s\", pgErr.Code, pgErr.Message)\n        }\n        return fmt.Errorf(\"create: %w\", err)\n    }\n}","preventionTips":["Keep the model schema and DB migrations in sync to avoid column/type drift.","Validate required and unique fields in the service layer before Create.","Translate driver errors (pgconn.PgError) into domain errors at one boundary.","Use connection pooling with health checks to reduce transient connection failures."],"tags":["postgres","database","insert","sql"],"backgroundTag":"sql-insert-failed","analyzedSha":"24529f140421a11a33b6999ab7944f2021cfd69c","analyzedAt":"2026-09-01T02:52:24.923Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}