Getting problems with time.Time being null in database.

xuanbao · · 1601 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am using MYSQL as a database and gorp as the ORM library. </p> <p>It&#39;s getting an error on the Updated_At column because it is null. This is how I have it written in my model: Updated_At time.Time `db: &#34;updated_at&#34;. </p> <p>The work around I&#39;m thinking about is initializing both Updated_At and Deleted_at to 0001-01-01 00:00:00 +0000 UTC. Is there a better work around?</p> <p>The error btw: </p> <p>sql: Scan error on column index 7: unsupported Scan, storing driver.Value type &lt;nil&gt; into type *time.Time</p> <hr/>**评论:**<br/><br/>tgulacsi: <pre><p>It says that use *time.Time.</p></pre>chaseroyaleee: <pre><blockquote> <p>Value type &lt;nil&gt; into type *time.Time</p> </blockquote> <p>Ohhhh. It didn&#39;t sound that explicit to me sorry haha. It&#39;s working now!</p></pre>tgulacsi: <pre><p>Yup, in reál, it is a little bit more involved: driver.Value is an empty interface, it is &#34;unpacked&#34; into the pointer given in Scan; nil needs a pointer to a pointer, thus &amp;(*time.Time).</p></pre>chaseroyaleee: <pre><p>Makes sense makes sense. Having this problem right now with posting the time. It&#39;s automatically making it 000-01-01, the 0 for time. Thinking about just changing the model from time.Time to an int instead. I&#39;ll make time to UNIX based. What do you think?</p></pre>media_guru: <pre><p>The mysql driver has a NullTime struct you can use. It has two fields: Valid (bool) and Time (time.Time)</p> <p>Time will always be set and use the default time.Time value if the column was null. If it was null, Valid will be false</p> <p>Be aware that if you use the same struct for json marshalling, that NullTime struct is gonna get marshaled as is. </p></pre>interactiv_: <pre><p>You&#39;ll get a lot of these everywhere there are potential null values and it sucks. If Go sql package was more like JDBC it would have been more manageable for any library that extends sql. So you either have to change your schema to eliminate null values, use pointers of int,string,... in your structs or use funky types provided by drivers. This is not a good API no matter what people say.</p></pre>chaseroyaleee: <pre><p>Yeah just ended up making them int64s and using Unix time because its a hassle haha</p></pre>nathj07: <pre><p>That&#39;s the empty value for time.Time. You can check it with the convenience function time.IsZero(). I&#39;ve not used mysql with Go but in PostgreSQL the lib/pq library has a NullTime type that works great on these situations.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1601 次点击  
加入收藏 微博
0 回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传