Elegant way to store generic data in db?

agolangf · · 563 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Lets say I want to build a messaging platform and release a server SDK to other developers, but I want to let SDK users custom define the structure of a message itself (i.e. the fields such as title, author, date, body). I don&#39;t want to make a &#34;one-size-fits-all&#34; structure which is hardcoded into the source code.</p> <p>Golang provides great libraries to develop this kind of server, except for the db.Query() and db.QueryRow() functions which require hand crafted SQL statements and their cousin Scan() which requires the correct number of parameters.</p> <p>Could this be a good use case for the reflection package, in order to inspect the fields and generate valid SQL on the fly for an arbitrary interface{}? </p> <hr/>**评论:**<br/><br/>thequux: <pre><p>Perhaps use PostgreSQL and the <a href="http://www.postgresql.org/docs/9.4/static/datatype-json.html" rel="nofollow">jsonb</a> type? This would let you fetch results as a single column with rich structure, but still have indexed searching over json structures.</p></pre>vansterdam_city: <pre><p>Doing it your way, would you store just a PKEY id and JSON column?</p> <p>Right now I have something similar but I pulled out extra data as a SQL habit in order to index it for searches. For example a name column in order to filter a select by author. </p> <p>In your experience how good is the engine at filtering query results with clauses that use the json column?</p></pre>izuriel: <pre><p>With The jsonb type you can index fields in the JSON. No need for additional promotion. </p></pre>HectorJ: <pre><p>Just to add to that: recent versions of MySQL also support a JSON type: <a href="https://dev.mysql.com/doc/refman/5.7/en/json.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.7/en/json.html</a></p> <p>I haven&#39;t tested it yet though.</p></pre>jonbonazza: <pre><p>I would first ask yourself, &#34;Is my data relational in nature? If so, does it need to be? &#34;If not, it sounds like you&#39;d be better off forgoing the db package and using a document store (i.e MongoDB). If your data must be relational then, as mentioned, PSQL and JSONB are your best bet. RDBMS are traditionally structured by design, and PSQL is the only one that I am aware of that offers the ability to store unstructured data and query it intelligently. </p></pre>scharty: <pre><p>Yes reflection would be good.</p> <p>Or you could use a schemaless database like mongo.</p> <p>Or if you don&#39;t need to do selections of the data you could use gob and store that.</p></pre>

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

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