gorm/database.html
2017-01-16 23:35:00 +08:00

866 lines
26 KiB
HTML

<!DOCTYPE HTML>
<html lang="" >
<head>
<meta charset="UTF-8">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Database · GORM Guide</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="">
<meta name="generator" content="GitBook 3.2.2">
<link rel="stylesheet" href="gitbook/style.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-highlight/website.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-search/search.css">
<link rel="stylesheet" href="gitbook/gitbook-plugin-fontsettings/website.css">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
<link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
<link rel="next" href="database.html" />
<link rel="prev" href="./" />
</head>
<body>
<div class="book">
<div class="book-summary">
<div id="book-search-input" role="search">
<input type="text" placeholder="Type to search" />
</div>
<nav role="navigation">
<div class="book-summary">
<nav role="navigation">
<ul class="summary">
<li class="chapter " data-level="1.1" data-path="./">
<a href="./">
<b>1.1.</b>
Getting Started with GORM
</a>
</li>
<li class="chapter active" data-level="1.2" data-path="database.html">
<a href="database.html">
<b>1.2.</b>
Database
</a>
<ul class="articles">
<li class="chapter " data-level="1.2.1" data-path="database.html">
<a href="database.html#connecting-to-a-database">
<b>1.2.1.</b>
Database Connection
</a>
</li>
<li class="chapter " data-level="1.2.2" data-path="database.html">
<a href="database.html#migration">
<b>1.2.2.</b>
Migration
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.3" data-path="models.html">
<a href="models.html">
<b>1.3.</b>
Models
</a>
<ul class="articles">
<li class="chapter " data-level="1.3.1" data-path="models.html">
<a href="models.html#model-definition">
<b>1.3.1.</b>
Model Definition
</a>
</li>
<li class="chapter " data-level="1.3.2" data-path="models.html">
<a href="models.html#conventions">
<b>1.3.2.</b>
Conventions & Overriding
</a>
</li>
<li class="chapter " data-level="1.3.3" data-path="associations.html">
<a href="associations.html">
<b>1.3.3.</b>
Associations
</a>
<ul class="articles">
<li class="chapter " data-level="1.3.3.1" data-path="associations.html">
<a href="associations.html#belongs-to">
<b>1.3.3.1.</b>
Belongs To
</a>
</li>
<li class="chapter " data-level="1.3.3.2" data-path="associations.html">
<a href="associations.html#has-one">
<b>1.3.3.2.</b>
Has One
</a>
</li>
<li class="chapter " data-level="1.3.3.3" data-path="associations.html">
<a href="associations.html#has-many">
<b>1.3.3.3.</b>
Has Many
</a>
</li>
<li class="chapter " data-level="1.3.3.4" data-path="associations.html">
<a href="associations.html#many-to-many">
<b>1.3.3.4.</b>
Many To Many
</a>
</li>
<li class="chapter " data-level="1.3.3.5" data-path="associations.html">
<a href="associations.html#polymorphism">
<b>1.3.3.5.</b>
Polymorphism
</a>
</li>
<li class="chapter " data-level="1.3.3.6" data-path="associations.html">
<a href="associations.html#association-mode">
<b>1.3.3.6.</b>
Association Mode
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="chapter " data-level="1.4" data-path="crud.html">
<a href="crud.html">
<b>1.4.</b>
CRUD: Reading and Writing Data
</a>
<ul class="articles">
<li class="chapter " data-level="1.4.1" data-path="crud.html">
<a href="crud.html#create">
<b>1.4.1.</b>
Create
</a>
</li>
<li class="chapter " data-level="1.4.2" data-path="crud.html">
<a href="crud.html#query">
<b>1.4.2.</b>
Query
</a>
</li>
<li class="chapter " data-level="1.4.3" data-path="crud.html">
<a href="crud.html#preloading-eager-loading">
<b>1.4.3.</b>
Preloading (Eager Loading)
</a>
</li>
<li class="chapter " data-level="1.4.4" data-path="crud.html">
<a href="crud.html#update">
<b>1.4.4.</b>
Update
</a>
</li>
<li class="chapter " data-level="1.4.5" data-path="crud.html">
<a href="crud.html#delete">
<b>1.4.5.</b>
Delete / Soft Delete
</a>
</li>
<li class="chapter " data-level="1.4.6" data-path="crud.html">
<a href="crud.html#associations">
<b>1.4.6.</b>
Associations
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.5" data-path="callbacks.html">
<a href="callbacks.html">
<b>1.5.</b>
Callbacks
</a>
</li>
<li class="chapter " data-level="1.6" data-path="advanced.html">
<a href="advanced.html">
<b>1.6.</b>
Advanced Usage
</a>
<ul class="articles">
<li class="chapter " data-level="1.6.1" data-path="advanced.html">
<a href="advanced.html#error-handling">
<b>1.6.1.</b>
Error Handling
</a>
</li>
<li class="chapter " data-level="1.6.2" data-path="advanced.html">
<a href="advanced.html#transactions">
<b>1.6.2.</b>
Transactions
</a>
</li>
<li class="chapter " data-level="1.6.3" data-path="advanced.html">
<a href="advanced.html#sql-builder">
<b>1.6.3.</b>
Raw SQL & SQL Builder
</a>
</li>
<li class="chapter " data-level="1.6.4" data-path="advanced.html">
<a href="advanced.html#generic-database-interface-sqldb">
<b>1.6.4.</b>
Generic database interface sql.DB
</a>
</li>
<li class="chapter " data-level="1.6.5" data-path="advanced.html">
<a href="advanced.html#compose-primary-key">
<b>1.6.5.</b>
Composite Primary Key
</a>
</li>
<li class="chapter " data-level="1.6.6" data-path="advanced.html">
<a href="advanced.html#logger">
<b>1.6.6.</b>
Overriding Logger
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.7" data-path="development.html">
<a href="development.html">
<b>1.7.</b>
Development
</a>
<ul class="articles">
<li class="chapter " data-level="1.7.1" data-path="development.html">
<a href="development.html#architecture">
<b>1.7.1.</b>
Architecture
</a>
</li>
<li class="chapter " data-level="1.7.2" data-path="development.html">
<a href="development.html#write-plugins">
<b>1.7.2.</b>
Write Plugins
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="1.8" data-path="changelog.html">
<a href="changelog.html">
<b>1.8.</b>
Change Log
</a>
</li>
<li class="divider"></li>
</ul>
</nav>
</div>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<!-- Title -->
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i>
<a href="." >Database</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<div id="book-search-results">
<div class="search-noresults">
<section class="normal markdown-section">
<h1 id="database">Database</h1>
<!-- toc -->
<h2 id="connecting-to-a-database">Connecting to a database</h2>
<p>In order to connect to a database, you need to import the database&apos;s driver first. For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> _ <span class="hljs-string">&quot;github.com/go-sql-driver/mysql&quot;</span>
</code></pre>
<p>GORM has wrapped some drivers, for easier to remember the import path, so you could import the mysql driver with</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> _ <span class="hljs-string">&quot;github.com/jinzhu/gorm/dialects/mysql&quot;</span>
<span class="hljs-comment">// import _ &quot;github.com/jinzhu/gorm/dialects/postgres&quot;</span>
<span class="hljs-comment">// import _ &quot;github.com/jinzhu/gorm/dialects/sqlite&quot;</span>
<span class="hljs-comment">// import _ &quot;github.com/jinzhu/gorm/dialects/mssql&quot;</span>
</code></pre>
<h4 id="mysql">MySQL</h4>
<p><strong>NOTE:</strong> In order to handle <code>time.Time</code>, you need to include <code>parseTime</code> as a parameter. (<a href="https://github.com/go-sql-driver/mysql#parameters" target="_blank">More supported parameters</a>)</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">&quot;github.com/jinzhu/gorm&quot;</span>
_ <span class="hljs-string">&quot;github.com/jinzhu/gorm/dialects/mysql&quot;</span>
)
<span class="hljs-keyword">func</span> main() {
db, err := gorm.Open(<span class="hljs-string">&quot;mysql&quot;</span>, <span class="hljs-string">&quot;user:password@/dbname?charset=utf8&amp;parseTime=True&amp;loc=Local&quot;</span>)
<span class="hljs-keyword">defer</span> db.Close()
}
</code></pre>
<h4 id="postgresql">PostgreSQL</h4>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">&quot;github.com/jinzhu/gorm&quot;</span>
_ <span class="hljs-string">&quot;github.com/jinzhu/gorm/dialects/postgres&quot;</span>
)
<span class="hljs-keyword">func</span> main() {
db, err := gorm.Open(<span class="hljs-string">&quot;postgres&quot;</span>, <span class="hljs-string">&quot;host=myhost user=gorm dbname=gorm sslmode=disable password=mypassword&quot;</span>)
<span class="hljs-keyword">defer</span> db.Close()
}
</code></pre>
<h4 id="sqlite3">Sqlite3</h4>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">&quot;github.com/jinzhu/gorm&quot;</span>
_ <span class="hljs-string">&quot;github.com/jinzhu/gorm/dialects/sqlite&quot;</span>
)
<span class="hljs-keyword">func</span> main() {
db, err := gorm.Open(<span class="hljs-string">&quot;sqlite3&quot;</span>, <span class="hljs-string">&quot;/tmp/gorm.db&quot;</span>)
<span class="hljs-keyword">defer</span> db.Close()
}
</code></pre>
<h4 id="write-dialect-for-unsupported-databases">Write Dialect for unsupported databases</h4>
<p>GORM officially supports the above databases, but you could write a dialect for unsupported databases.</p>
<p>To write your own dialect, refer to: <a href="https://github.com/jinzhu/gorm/blob/master/dialect.go" target="_blank">https://github.com/jinzhu/gorm/blob/master/dialect.go</a></p>
<h2 id="migration">Migration</h2>
<h3 id="auto-migration">Auto Migration</h3>
<p>Automatically migrate your schema, to keep your schema update to date.</p>
<p><strong>WARNING:</strong> AutoMigrate will <strong>ONLY</strong> create tables, missing columns and missing indexes, and <strong>WON&apos;T</strong> change existing column&apos;s type or delete unused columns to protect your data.</p>
<pre><code class="lang-go">db.AutoMigrate(&amp;User{})
db.AutoMigrate(&amp;User{}, &amp;Product{}, &amp;Order{})
<span class="hljs-comment">// Add table suffix when create tables</span>
db.Set(<span class="hljs-string">&quot;gorm:table_options&quot;</span>, <span class="hljs-string">&quot;ENGINE=InnoDB&quot;</span>).AutoMigrate(&amp;User{})
</code></pre>
<h3 id="has-table">Has Table</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Check model `User`&apos;s table exists or not</span>
db.HasTable(&amp;User{})
<span class="hljs-comment">// Check table `users` exists or not</span>
db.HasTable(<span class="hljs-string">&quot;users&quot;</span>)
</code></pre>
<h3 id="create-table">Create Table</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Create table for model `User`</span>
db.CreateTable(&amp;User{})
<span class="hljs-comment">// will append &quot;ENGINE=InnoDB&quot; to the SQL statement when creating table `users`</span>
db.Set(<span class="hljs-string">&quot;gorm:table_options&quot;</span>, <span class="hljs-string">&quot;ENGINE=InnoDB&quot;</span>).CreateTable(&amp;User{})
</code></pre>
<h3 id="drop-table">Drop table</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Drop model `User`&apos;s table</span>
db.DropTable(&amp;User{})
<span class="hljs-comment">// Drop table `users</span>
db.DropTable(<span class="hljs-string">&quot;users&quot;</span>)
<span class="hljs-comment">// Drop model&apos;s `User`&apos;s table and table `products`</span>
db.DropTableIfExists(&amp;User{}, <span class="hljs-string">&quot;products&quot;</span>)
</code></pre>
<h3 id="modifycolumn">ModifyColumn</h3>
<p>Modify column&apos;s type to given value</p>
<pre><code class="lang-go"><span class="hljs-comment">// change column description&apos;s data type to `text` for model `User`</span>
db.Model(&amp;User{}).ModifyColumn(<span class="hljs-string">&quot;description&quot;</span>, <span class="hljs-string">&quot;text&quot;</span>)
</code></pre>
<h3 id="dropcolumn">DropColumn</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Drop column description from model `User`</span>
db.Model(&amp;User{}).DropColumn(<span class="hljs-string">&quot;description&quot;</span>)
</code></pre>
<h3 id="add-foreign-key">Add Foreign Key</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Add foreign key</span>
<span class="hljs-comment">// 1st param : foreignkey field</span>
<span class="hljs-comment">// 2nd param : destination table(id)</span>
<span class="hljs-comment">// 3rd param : ONDELETE</span>
<span class="hljs-comment">// 4th param : ONUPDATE</span>
db.Model(&amp;User{}).AddForeignKey(<span class="hljs-string">&quot;city_id&quot;</span>, <span class="hljs-string">&quot;cities(id)&quot;</span>, <span class="hljs-string">&quot;RESTRICT&quot;</span>, <span class="hljs-string">&quot;RESTRICT&quot;</span>)
</code></pre>
<h3 id="indexes">Indexes</h3>
<pre><code class="lang-go"><span class="hljs-comment">// Add index for columns `name` with given name `idx_user_name`</span>
db.Model(&amp;User{}).AddIndex(<span class="hljs-string">&quot;idx_user_name&quot;</span>, <span class="hljs-string">&quot;name&quot;</span>)
<span class="hljs-comment">// Add index for columns `name`, `age` with given name `idx_user_name_age`</span>
db.Model(&amp;User{}).AddIndex(<span class="hljs-string">&quot;idx_user_name_age&quot;</span>, <span class="hljs-string">&quot;name&quot;</span>, <span class="hljs-string">&quot;age&quot;</span>)
<span class="hljs-comment">// Add unique index</span>
db.Model(&amp;User{}).AddUniqueIndex(<span class="hljs-string">&quot;idx_user_name&quot;</span>, <span class="hljs-string">&quot;name&quot;</span>)
<span class="hljs-comment">// Add unique index for multiple columns</span>
db.Model(&amp;User{}).AddUniqueIndex(<span class="hljs-string">&quot;idx_user_name_age&quot;</span>, <span class="hljs-string">&quot;name&quot;</span>, <span class="hljs-string">&quot;age&quot;</span>)
<span class="hljs-comment">// Remove index</span>
db.Model(&amp;User{}).RemoveIndex(<span class="hljs-string">&quot;idx_user_name&quot;</span>)
</code></pre>
</section>
</div>
<div class="search-results">
<div class="has-results">
<h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
<ul class="search-results-list"></ul>
</div>
<div class="no-results">
<h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
</div>
</div>
</div>
</div>
</div>
</div>
<a href="./" class="navigation navigation-prev " aria-label="Previous page: Getting Started with GORM">
<i class="fa fa-angle-left"></i>
</a>
<a href="database.html#connecting-to-a-database" class="navigation navigation-next " aria-label="Next page: Database Connection">
<i class="fa fa-angle-right"></i>
</a>
</div>
<script>
var gitbook = gitbook || [];
gitbook.push(function() {
gitbook.page.hasChanged({"page":{"title":"Database","level":"1.2","depth":1,"next":{"title":"Database Connection","level":"1.2.1","depth":2,"anchor":"#connecting-to-a-database","path":"database.md","ref":"database.md#connecting-to-a-database","articles":[]},"previous":{"title":"Getting Started with GORM","level":"1.1","depth":1,"path":"README.md","ref":"README.md","articles":[]},"dir":"ltr"},"config":{"plugins":["github","edit-link"],"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"fontsettings":{"theme":"night","family":"sans","size":2},"github":{"url":"https://github.com/jinzhu/gorm"},"edit-link":{"label":"Edit This Page","base":"https://github.com/jinzhu/gorm/edit/gh-pages/documents/"},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"theme":"default","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"title":"GORM Guide","gitbook":"*"},"file":{"path":"database.md","mtime":"2017-01-16T15:30:36.000Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-01-16T15:33:01.375Z"},"basePath":".","book":{"language":""}});
});
</script>
</div>
<script src="gitbook/gitbook.js"></script>
<script src="gitbook/theme.js"></script>
<script src="gitbook/gitbook-plugin-github/plugin.js"></script>
<script src="gitbook/gitbook-plugin-edit-link/plugin.js"></script>
<script src="gitbook/gitbook-plugin-search/search-engine.js"></script>
<script src="gitbook/gitbook-plugin-search/search.js"></script>
<script src="gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
<script src="gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
<script src="gitbook/gitbook-plugin-sharing/buttons.js"></script>
<script src="gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
</body>
</html>