github.com/System-Glitch/goyave/v2@v2.10.3-0.20200819142921-51011e75d504/docs_src/src/guide/basics/database.md (about)

     1  ---
     2  meta:
     3    - name: "og:title"
     4      content: "Database - Goyave"
     5    - name: "twitter:title"
     6      content: "Database - Goyave"
     7    - name: "title"
     8      content: "Database - Goyave"
     9  ---
    10  
    11  # Database
    12  
    13  [[toc]]
    14  
    15  ## Introduction
    16  
    17  Most web applications use a database. In this section, we are going to see how Goyave applications can query a database, using the awesome [Gorm ORM](https://gorm.io/).
    18  
    19  Database connections are managed by the framework and are long-lived. When the server shuts down, the database connections are closed automatically. So you don't have to worry about creating, closing or refreshing database connections in your application.
    20  
    21  All functions below require the `database` and the `gorm` packages to be imported.
    22  
    23  ``` go
    24  import (
    25    "github.com/System-Glitch/goyave/v2/database"
    26    "github.com/jinzhu/gorm"
    27  )
    28  ```
    29  
    30  ## Configuration
    31  
    32  Very few code is required to get started with databases. There are some [configuration](../configuration.html#database-category) options that you need to change though:
    33  - `database.connection`
    34  - `database.host`
    35  - `database.port`
    36  - `database.name`
    37  - `database.username`
    38  - `database.password`
    39  - `database.options`
    40  - `database.maxOpenConnection`
    41  - `database.maxIdleConnection`
    42  - `database.maxLifetime`
    43  
    44  ::: tip
    45  `database.options` represents the additional connection options. For example, when using MySQL, you should use the `parseTime=true` option so `time.Time` can be handled correctly. Available options differ from one driver to another and can be found in their respective documentation.
    46  :::
    47  
    48  ### Drivers
    49  
    50  The framework supports the following sql drivers:
    51  - `none` (*Disable database features*)
    52  - `mysql`
    53  - `postgres`
    54  - `sqlite3`
    55  - `mssql`
    56  
    57  Change the `database.connection` config entry to the desired driver.
    58  
    59  In order to be able connect to the database, Gorm needs a database driver to be imported. Add the following import to your `kernel.go`:
    60  ``` go
    61  import _ "github.com/jinzhu/gorm/dialects/mysql"
    62  // import _ "github.com/jinzhu/gorm/dialects/postgres"
    63  // import _ "github.com/jinzhu/gorm/dialects/sqlite"
    64  // import _ "github.com/jinzhu/gorm/dialects/mssql"
    65  ```
    66  
    67  ::: tip
    68  For SQLite, only the `database.name` config entry is required.
    69  :::
    70  
    71  ## Getting a database connection
    72  
    73  #### database.GetConnection
    74  
    75  Returns the global database connection pool. Creates a new connection pool if no connection is available.
    76  
    77  The connections will be closed automatically on server shutdown so you don't need to call `Close()` when you're done with the database.
    78  
    79  
    80  | Parameters | Return     |
    81  |------------|------------|
    82  |            | `*gorm.DB` |
    83  
    84  **Example:**
    85  ``` go
    86  db := database.GetConnection()
    87  db.First(&user)
    88  ```
    89  
    90  ::: tip
    91  Learn how to use the CRUD interface and the query builder in the [Gorm documentation](https://gorm.io/docs/index.html).
    92  :::
    93  
    94  #### database.Close
    95  
    96  If you want to manually close the database connection, you can do it using `Close()`. New connections can be re-opened using `GetConnection()` as usual. This function does nothing if the database connection is already closed or has never been created.
    97  
    98  | Parameters | Return |
    99  |------------|--------|
   100  |            | `void` |
   101  
   102  **Example:**
   103  ``` go
   104  database.Close()
   105  ```
   106  
   107  ## Models
   108  
   109  A model is a structure reflecting a database table structure. An instance of a model is a single database record. Each model is defined in its own file inside the `database/model` directory.
   110  
   111  ### Defining a model
   112  
   113  Models are usually just normal Golang structs, basic Go types, or pointers of them. `sql.Scanner` and `driver.Valuer` interfaces are also supported.
   114  
   115  ```go
   116  func init() {
   117      database.RegisterModel(&User{})
   118  }
   119  
   120  type User struct {
   121      gorm.Model
   122      Name         string
   123      Age          sql.NullInt64
   124      Birthday     *time.Time
   125      Email        string  `gorm:"type:varchar(100);unique_index"`
   126      Role         string  `gorm:"size:255"` // set field size to 255
   127      MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null
   128      Num          int     `gorm:"AUTO_INCREMENT"` // set num to auto incrementable
   129      Address      string  `gorm:"index:addr"` // create index with name `addr` for address
   130      IgnoreMe     int     `gorm:"-"` // ignore this field
   131  }
   132  ```
   133  
   134  ::: tip
   135  All models should be **registered** in an `init()` function inside their model file. To ensure the `init()` functions are executed before the server starts, import the `models` package in your `kernel.go`.
   136  
   137  ``` go
   138  import _ "database/model"
   139  ```
   140  :::
   141  
   142  Learn more about model declaration in the [Gorm documentation](https://gorm.io/docs/models.html).
   143  
   144  #### database.RegisterModel
   145  
   146  Registers a model for auto-migration.
   147  
   148  | Parameters          | Return |
   149  |---------------------|--------|
   150  | `model interface{}` | `void` |
   151  
   152  #### database.GetRegisteredModels
   153  
   154  Get the registered models. The returned slice is a copy of the original, so it cannot be modified.
   155  
   156  | Parameters | Return          |
   157  |------------|-----------------|
   158  |            | `[]interface{}` |
   159  
   160  #### database.ClearRegisteredModels
   161  
   162  Unregister all models.
   163  
   164  | Parameters | Return |
   165  |------------|--------|
   166  |            | `void` |
   167  
   168  ### Hidden fields
   169  
   170  <p><Badge text="Since v2.9.0"/></p>
   171  
   172  Sometimes you may wish to exclude some fields from your model's JSON form, such as passwords. To do so, you can add the `model:"hide"` tag to the field you want to hide.
   173  
   174  ``` go
   175  type User struct {
   176      Username string
   177      Password string `model:"hide" json:",omitempty"`
   178  }
   179  ```
   180  
   181  When a struct is sent as a response through `response.JSON()`, all its fields (including promoted fields) tagged with `model:"hide"` will be set to their zero value. Add the `json:",omitempty"` tag to entirely remove the field from the resulting JSON string.
   182  
   183  You can also filter hidden fields by passing a struct to [`helper.RemoveHiddenFields()`](../advanced/helpers.html#helper-removehiddenfields).
   184  
   185  ### Automatic migrations
   186  
   187  If the `database.autoMigrate` config option is set to true, all registered models will be automatically migrated when the server starts.
   188  
   189  ::: warning
   190  Automatic migrations **only create** tables, missing columns and missing indexes. They **wont't change** existing column’s type or delete unused columns.
   191  :::
   192  
   193  If you would like to know more about migrations using Gorm, read their [documentation](https://gorm.io/docs/migration.html).