source

시간에 대해 NULL을 삽입합니다.JSON에서 디코딩된 시간

nicesource 2023. 8. 7. 22:37
반응형

시간에 대해 NULL을 삽입합니다.JSON에서 디코딩된 시간

기존 프로덕션 DB를 통해 REST 엔드포인트를 프로토타입화하고 있는데 null 가능한 datetime 열에 갇혔습니다.이미 Nullable 시간과 같은 스레드를 읽었습니다.GORM을 사용하여 MySQL에서 Time ingolang 또는 Fetching NULL datetime 값을 입력했지만 REST 끝점에 새 개체를 게시할 수 없으며 JSON의 목록에 없는 datetime-type 특성을 NULL로 MariaDB에 저장할 수 없습니다.

다음과 같은 HTTP 요청을 제출합니다.

POST /countries
{ "iso_code" : "CZ", "title" : "Czechia" }

테이블에 다음 스키마가 있습니다.

create table country
(
    iso_code   char(2)                              not null comment 'Country alpha-2 ISO code'
        primary key,
    title      varchar(255)                         null comment 'Country name',
    created_on datetime default current_timestamp() not null,
    updated_on datetime                             null on update current_timestamp()
)

이미 mysql을 사용해 보았습니다.NullTime 유형, 시간입니다.시간 유형을 포인터로 지정하고 sql:기본값:매핑의 NULL, gorm: "null" 매핑, 저는 또한 새 국가에 0을 직접 할당했습니다.저장 직전에 업데이트됨At.Save Gorm 후크 이전에는 차이가 없었습니다.

모드가 매우 명확합니다.

    type Country struct {
        IsoCode string `json:"iso_code" gorm:"primary_key" sql:"size:2"`
        Title *string `json:"title,omitempty" gorm:"null" sql:"size:255"`
        CreatedAt *time.Time `json:"created_at,omitempty" gorm:"column:created_on"`
       UpdatedAt *time.Time `json:"updated_at,omitempty" gorm:"column:updated_on;null" sql:"DEFAULT:NULL"`
    }

GORM을 사용하여 개체를 저장하는 중입니다.

func CreateCountry(country *m.Country) *m.Country {
    fmt.Println(country)

    existingCountry := GetCountry(country.IsoCode)
    if existingCountry == nil {
        err := GetDB().Create(country).Error
        // ...
    } 
    // ...
}

여기 방법에서 국가는 가치가 없습니다.UpdatedAt그렇지만Create(country)이 호출되며 정확한 값이 두 날짜/시간 열에 모두 저장됩니다.

HTTP 요청 본문에서 이렇게 읽고 있습니다.

var CreateCountry = func(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.Body)

    newCountry := &m.Country{}
    err := json.NewDecoder(r.Body).Decode(newCountry)
    // ...
}

또한 여기서 신체는 날짜/시간 속성이 0입니다.

다음과 같은 삽입 문을 생성하기 위해 무엇을 할 수 있는지 확신할 수 없습니다.

INSERT  INTO `country` (`iso_code`,
`title`,`created_on`,`updated_on`) VALUES (?,?,?,?)[KR 0xc0001f6130 null null] 

그리고 아닌

INSERT  INTO `country` (`iso_code`,
`title`,`created_on`,`updated_on`) VALUES (?,?,?,?)[KR 0xc0001f6130 2019-03-31 03:16:41.5158848 +0200 CEST m=+16.4487208
01 2019-03-31 03:16:41.5158848 +0200 CEST m=+16.448720801]

언급URL : https://stackoverflow.com/questions/55437119/insert-null-for-time-time-decoded-from-json

반응형