| 1 | dbx |
| 2 | [](https://goreportcard.com/report/github.com/pocketbase/dbx) |
| 3 | [](https://pkg.go.dev/github.com/pocketbase/dbx) |
| 4 | ================================================================================ |
| 5 | |
| 6 | > ⚠️ This is a maintained fork of [go-ozzo/ozzo-dbx](https://github.com/go-ozzo/ozzo-dbx) (see [#103](https://github.com/go-ozzo/ozzo-dbx/issues/103)). |
| 7 | > |
| 8 | > Currently the changes are primarily related to better SQLite support and some other minor improvements. For more details please refer to the [Releases CHANGELOG](https://github.com/pocketbase/dbx/releases). |
| 9 | |
| 10 | |
| 11 | ## Summary |
| 12 | |
| 13 | - [Description](#description) |
| 14 | - [Requirements](#requirements) |
| 15 | - [Installation](#installation) |
| 16 | - [Supported Databases](#supported-databases) |
| 17 | - [Getting Started](#getting-started) |
| 18 | - [Connecting to Database](#connecting-to-database) |
| 19 | - [Executing Queries](#executing-queries) |
| 20 | - [Binding Parameters](#binding-parameters) |
| 21 | - [Building Queries](#building-queries) |
| 22 | - [Building SELECT Queries](#building-select-queries) |
| 23 | - [Building Query Conditions](#building-query-conditions) |
| 24 | - [Building Data Manipulation Queries](#building-data-manipulation-queries) |
| 25 | - [Building Schema Manipulation Queries](#building-schema-manipulation-queries) |
| 26 | - [CRUD Operations](#crud-operations) |
| 27 | - [Create](#create) |
| 28 | - [Read](#read) |
| 29 | - [Update](#update) |
| 30 | - [Delete](#delete) |
| 31 | - [Null Handling](#null-handling) |
| 32 | - [Quoting Table and Column Names](#quoting-table-and-column-names) |
| 33 | - [Using Transactions](#using-transactions) |
| 34 | - [Logging Executed SQL Statements](#logging-executed-sql-statements) |
| 35 | - [Supporting New Databases](#supporting-new-databases) |
| 36 | |
| 37 | |
| 38 | ## Description |
| 39 | |
| 40 | `dbx` is a Go package that enhances the standard `database/sql` package by providing powerful data retrieval methods |
| 41 | as well as DB-agnostic query building capabilities. `dbx` is not an ORM. It has the following features: |
| 42 | |
| 43 | * Populating data into structs and NullString maps |
| 44 | * Named parameter binding |
| 45 | * DB-agnostic query building methods, including SELECT queries, data manipulation queries, and schema manipulation queries |
| 46 | * Inserting, updating, and deleting model structs |
| 47 | * Powerful query condition building |
| 48 | * Open architecture allowing addition of new database support or customization of existing support |
| 49 | * Logging executed SQL statements |
| 50 | * Supporting major relational databases |
| 51 | |
| 52 | For an example on how this library is used in an application, please refer to [go-rest-api](https://github.com/qiangxue/go-rest-api) which is a starter kit for building RESTful APIs in Go. |
| 53 | |
| 54 | ## Requirements |
| 55 | |
| 56 | Go 1.13 or above. |
| 57 | |
| 58 | ## Installation |
| 59 | |
| 60 | Run the following command to install the package: |
| 61 | |
| 62 | ``` |
| 63 | go get github.com/pocketbase/dbx |
| 64 | ``` |
| 65 | |
| 66 | In addition, install the specific DB driver package for the kind of database to be used. Please refer to |
| 67 | [SQL database drivers](https://github.com/golang/go/wiki/SQLDrivers) for a complete list. For example, if you are |
| 68 | using MySQL, you may install the following package: |
| 69 | |
| 70 | ```sh |
| 71 | go get github.com/go-sql-driver/mysql |
| 72 | ``` |
| 73 | |
| 74 | and import it in your main code like the following: |
| 75 | |
| 76 | ```go |
| 77 | import _ "github.com/go-sql-driver/mysql" |
| 78 | ``` |
| 79 | |
| 80 | ## Supported Databases |
| 81 | |
| 82 | The following databases are fully supported out of box: |
| 83 | |
| 84 | * SQLite |
| 85 | * MySQL |
| 86 | * PostgreSQL |
| 87 | * MS SQL Server (2012 or above) |
| 88 | * Oracle |
| 89 | |
| 90 | For other databases, the query building feature may not work as expected. You can create a custom builder to |
| 91 | solve the problem. Please see the last section for more details. |
| 92 | |
| 93 | ## Getting Started |
| 94 | |
| 95 | The following code snippet shows how you can use this package in order to access data from a MySQL database. |
| 96 | |
| 97 | ```go |
| 98 | package main |
| 99 | |
| 100 | import ( |
| 101 | "github.com/pocketbase/dbx" |
| 102 | _ "github.com/go-sql-driver/mysql" |
| 103 | ) |
| 104 | |
| 105 | func main() { |
| 106 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 107 | |
| 108 | // create a new query |
| 109 | q := db.NewQuery("SELECT id, name FROM users LIMIT 10") |
| 110 | |
| 111 | // fetch all rows into a struct array |
| 112 | var users []struct { |
| 113 | ID, Name string |
| 114 | } |
| 115 | q.All(&users) |
| 116 | |
| 117 | // fetch a single row into a struct |
| 118 | var user struct { |
| 119 | ID, Name string |
| 120 | } |
| 121 | q.One(&user) |
| 122 | |
| 123 | // fetch a single row into a string map |
| 124 | data := dbx.NullStringMap{} |
| 125 | q.One(data) |
| 126 | |
| 127 | // fetch row by row |
| 128 | rows2, _ := q.Rows() |
| 129 | for rows2.Next() { |
| 130 | rows2.ScanStruct(&user) |
| 131 | // rows.ScanMap(data) |
| 132 | // rows.Scan(&id, &name) |
| 133 | } |
| 134 | } |
| 135 | ``` |
| 136 | |
| 137 | And the following example shows how to use the query building capability of this package. |
| 138 | |
| 139 | ```go |
| 140 | package main |
| 141 | |
| 142 | import ( |
| 143 | "github.com/pocketbase/dbx" |
| 144 | _ "github.com/go-sql-driver/mysql" |
| 145 | ) |
| 146 | |
| 147 | func main() { |
| 148 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 149 | |
| 150 | // build a SELECT query |
| 151 | // SELECT `id`, `name` FROM `users` WHERE `name` LIKE '%Charles%' ORDER BY `id` |
| 152 | q := db.Select("id", "name"). |
| 153 | From("users"). |
| 154 | Where(dbx.Like("name", "Charles")). |
| 155 | OrderBy("id") |
| 156 | |
| 157 | // fetch all rows into a struct array |
| 158 | var users []struct { |
| 159 | ID, Name string |
| 160 | } |
| 161 | q.All(&users) |
| 162 | |
| 163 | // build an INSERT query |
| 164 | // INSERT INTO `users` (`name`) VALUES ('James') |
| 165 | db.Insert("users", dbx.Params{ |
| 166 | "name": "James", |
| 167 | }).Execute() |
| 168 | } |
| 169 | ``` |
| 170 | |
| 171 | ## Connecting to Database |
| 172 | |
| 173 | To connect to a database, call `dbx.Open()` in the same way as you would do with the `Open()` method in `database/sql`. |
| 174 | |
| 175 | ```go |
| 176 | db, err := dbx.Open("mysql", "user:pass@hostname/db_name") |
| 177 | ``` |
| 178 | |
| 179 | The method returns a `dbx.DB` instance which can be used to create and execute DB queries. Note that the method |
| 180 | does not really establish a connection until a query is made using the returned `dbx.DB` instance. It also |
| 181 | does not check the correctness of the data source name either. Call `dbx.MustOpen()` to make sure the data |
| 182 | source name is correct. |
| 183 | |
| 184 | ## Executing Queries |
| 185 | |
| 186 | To execute a SQL statement, first create a `dbx.Query` instance by calling `DB.NewQuery()` with the SQL statement |
| 187 | to be executed. And then call `Query.Execute()` to execute the query if the query is not meant to retrieving data. |
| 188 | For example, |
| 189 | |
| 190 | ```go |
| 191 | q := db.NewQuery("UPDATE users SET status=1 WHERE id=100") |
| 192 | result, err := q.Execute() |
| 193 | ``` |
| 194 | |
| 195 | If the SQL statement does retrieve data (e.g. a SELECT statement), one of the following methods should be called, |
| 196 | which will execute the query and populate the result into the specified variable(s). |
| 197 | |
| 198 | * `Query.All()`: populate all rows of the result into a slice of structs or `NullString` maps. |
| 199 | * `Query.One()`: populate the first row of the result into a struct or a `NullString` map. |
| 200 | * `Query.Column()`: populate the first column of the result into a slice. |
| 201 | * `Query.Row()`: populate the first row of the result into a list of variables, one for each returning column. |
| 202 | * `Query.Rows()`: returns a `dbx.Rows` instance to allow retrieving data row by row. |
| 203 | |
| 204 | For example, |
| 205 | |
| 206 | ```go |
| 207 | type User struct { |
| 208 | ID int |
| 209 | Name string |
| 210 | } |
| 211 | |
| 212 | var ( |
| 213 | users []User |
| 214 | user User |
| 215 | |
| 216 | row dbx.NullStringMap |
| 217 | |
| 218 | id int |
| 219 | name string |
| 220 | |
| 221 | err error |
| 222 | ) |
| 223 | |
| 224 | q := db.NewQuery("SELECT id, name FROM users LIMIT 10") |
| 225 | |
| 226 | // populate all rows into a User slice |
| 227 | err = q.All(&users) |
| 228 | fmt.Println(users[0].ID, users[0].Name) |
| 229 | |
| 230 | // populate the first row into a User struct |
| 231 | err = q.One(&user) |
| 232 | fmt.Println(user.ID, user.Name) |
| 233 | |
| 234 | // populate the first row into a NullString map |
| 235 | err = q.One(&row) |
| 236 | fmt.Println(row["id"], row["name"]) |
| 237 | |
| 238 | var ids []int |
| 239 | err = q.Column(&ids) |
| 240 | fmt.Println(ids) |
| 241 | |
| 242 | // populate the first row into id and name |
| 243 | err = q.Row(&id, &name) |
| 244 | |
| 245 | // populate data row by row |
| 246 | rows, _ := q.Rows() |
| 247 | for rows.Next() { |
| 248 | _ = rows.ScanMap(&row) |
| 249 | } |
| 250 | ``` |
| 251 | |
| 252 | When populating a struct, the following rules are used to determine which columns should go into which struct fields: |
| 253 | |
| 254 | * Only exported struct fields can be populated. |
| 255 | * A field receives data if its name is mapped to a column according to the field mapping function `Query.FieldMapper`. |
| 256 | The default field mapping function separates words in a field name by underscores and turns them into lower case. |
| 257 | For example, a field name `FirstName` will be mapped to the column name `first_name`, and `MyID` to `my_id`. |
| 258 | * If a field has a `db` tag, the tag value will be used as the corresponding column name. If the `db` tag is a dash `-`, |
| 259 | it means the field should NOT be populated. |
| 260 | * For anonymous fields that are of struct type, they will be expanded and their component fields will be populated |
| 261 | according to the rules described above. |
| 262 | * For named fields that are of struct type, they will also be expanded. But their component fields will be prefixed |
| 263 | with the struct names when being populated. |
| 264 | |
| 265 | An exception to the above struct expansion is that when a struct type implements `sql.Scanner` or when it is `time.Time`. |
| 266 | In this case, the field will be populated as a whole by the DB driver. Also, if a field is a pointer to some type, |
| 267 | the field will be allocated memory and populated with the query result if it is not null. |
| 268 | |
| 269 | The following example shows how fields are populated according to the rules above: |
| 270 | |
| 271 | ```go |
| 272 | type User struct { |
| 273 | id int |
| 274 | Type int `db:"-"` |
| 275 | MyName string `db:"name"` |
| 276 | Profile |
| 277 | Address Address `db:"addr"` |
| 278 | } |
| 279 | |
| 280 | type Profile struct { |
| 281 | Age int |
| 282 | } |
| 283 | |
| 284 | type Address struct { |
| 285 | City string |
| 286 | } |
| 287 | ``` |
| 288 | |
| 289 | * `User.id`: not populated because the field is not exported; |
| 290 | * `User.Type`: not populated because the `db` tag is `-`; |
| 291 | * `User.MyName`: to be populated from the `name` column, according to the `db` tag; |
| 292 | * `Profile.Age`: to be populated from the `age` column, since `Profile` is an anonymous field; |
| 293 | * `Address.City`: to be populated from the `addr.city` column, since `Address` is a named field of struct type |
| 294 | and its fields will be prefixed with `addr.` according to the `db` tag. |
| 295 | |
| 296 | Note that if a column in the result does not have a corresponding struct field, it will be ignored. Similarly, |
| 297 | if a struct field does not have a corresponding column in the result, it will not be populated. |
| 298 | |
| 299 | ## Binding Parameters |
| 300 | |
| 301 | A SQL statement is usually parameterized with dynamic values. For example, you may want to select the user record |
| 302 | according to the user ID received from the client. Parameter binding should be used in this case, and it is almost |
| 303 | always preferred to prevent from SQL injection attacks. Unlike `database/sql` which does anonymous parameter binding, |
| 304 | `dbx` uses named parameter binding. *Anonymous parameter binding is not supported*, as it will mess up with named |
| 305 | parameters. For example, |
| 306 | |
| 307 | ```go |
| 308 | q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}") |
| 309 | q.Bind(dbx.Params{"id": 100}) |
| 310 | err := q.One(&user) |
| 311 | ``` |
| 312 | |
| 313 | The above example will select the user record whose `id` is 100. The method `Query.Bind()` binds a set |
| 314 | of named parameters to a SQL statement which contains parameter placeholders in the format of `{:ParamName}`. |
| 315 | |
| 316 | If a SQL statement needs to be executed multiple times with different parameter values, it may be prepared |
| 317 | to improve the performance. For example, |
| 318 | |
| 319 | ```go |
| 320 | q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}") |
| 321 | q.Prepare() |
| 322 | defer q.Close() |
| 323 | |
| 324 | q.Bind(dbx.Params{"id": 100}) |
| 325 | err := q.One(&user) |
| 326 | |
| 327 | q.Bind(dbx.Params{"id": 200}) |
| 328 | err = q.One(&user) |
| 329 | |
| 330 | // ... |
| 331 | ``` |
| 332 | |
| 333 | |
| 334 | ## Cancelable Queries |
| 335 | |
| 336 | Queries are cancelable when they are used with `context.Context`. In particular, by calling `Query.WithContext()` you |
| 337 | can associate a context with a query and use the context to cancel the query while it is running. For example, |
| 338 | |
| 339 | ```go |
| 340 | q := db.NewQuery("SELECT id, name FROM users") |
| 341 | err := q.WithContext(ctx).All(&users) |
| 342 | ``` |
| 343 | |
| 344 | |
| 345 | ## Building Queries |
| 346 | |
| 347 | Instead of writing plain SQLs, `dbx` allows you to build SQLs programmatically, which often leads to cleaner, |
| 348 | more secure, and DB-agnostic code. You can build three types of queries: the SELECT queries, the data manipulation |
| 349 | queries, and the schema manipulation queries. |
| 350 | |
| 351 | ### Building SELECT Queries |
| 352 | |
| 353 | Building a SELECT query starts by calling `DB.Select()`. You can build different clauses of a SELECT query using |
| 354 | the corresponding query building methods. For example, |
| 355 | |
| 356 | ```go |
| 357 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 358 | err := db.Select("id", "name"). |
| 359 | From("users"). |
| 360 | Where(dbx.HashExp{"id": 100}). |
| 361 | One(&user) |
| 362 | ``` |
| 363 | |
| 364 | The above code will generate and execute the following SQL statement: |
| 365 | |
| 366 | ```sql |
| 367 | SELECT `id`, `name` FROM `users` WHERE `id`={:p0} |
| 368 | ``` |
| 369 | |
| 370 | Notice how the table and column names are properly quoted according to the currently using database type. |
| 371 | And parameter binding is used to populate the value of `p0` in the `WHERE` clause. |
| 372 | |
| 373 | Every SQL keyword has a corresponding query building method. For example, `SELECT` corresponds to `Select()`, |
| 374 | `FROM` corresponds to `From()`, `WHERE` corresponds to `Where()`, and so on. You can chain these method calls |
| 375 | together, just like you would do when writing a plain SQL. Each of these methods returns the query instance |
| 376 | (of type `dbx.SelectQuery`) that is being built. Once you finish building a query, you may call methods such as |
| 377 | `One()`, `All()` to execute the query and populate data into variables. You may also explicitly call `Build()` |
| 378 | to build the query and turn it into a `dbx.Query` instance which may allow you to get the SQL statement and do |
| 379 | other interesting work. |
| 380 | |
| 381 | |
| 382 | ### Building Query Conditions |
| 383 | |
| 384 | `dbx` supports very flexible and powerful query condition building which can be used to build SQL clauses |
| 385 | such as `WHERE`, `HAVING`, etc. For example, |
| 386 | |
| 387 | ```go |
| 388 | // id=100 |
| 389 | dbx.NewExp("id={:id}", dbx.Params{"id": 100}) |
| 390 | |
| 391 | // id=100 AND status=1 |
| 392 | dbx.HashExp{"id": 100, "status": 1} |
| 393 | |
| 394 | // status=1 OR age>30 |
| 395 | dbx.Or(dbx.HashExp{"status": 1}, dbx.NewExp("age>30")) |
| 396 | |
| 397 | // name LIKE '%admin%' AND name LIKE '%example%' |
| 398 | dbx.Like("name", "admin", "example") |
| 399 | ``` |
| 400 | |
| 401 | When building a query condition expression, its parameter values will be populated using parameter binding, which |
| 402 | prevents SQL injection from happening. Also if an expression involves column names, they will be properly quoted. |
| 403 | The following condition building functions are available: |
| 404 | |
| 405 | * `dbx.NewExp()`: creating a condition using the given expression string and binding parameters. For example, |
| 406 | `dbx.NewExp("id={:id}", dbx.Params{"id":100})` would create the expression `id=100`. |
| 407 | * `dbx.HashExp`: a map type that represents name-value pairs concatenated by `AND` operators. For example, |
| 408 | `dbx.HashExp{"id":100, "status":1}` would create `id=100 AND status=1`. |
| 409 | * `dbx.Not()`: creating a `NOT` expression by prepending `NOT` to the given expression. |
| 410 | * `dbx.And()`: creating an `AND` expression by concatenating the given expressions with the `AND` operators. |
| 411 | * `dbx.Or()`: creating an `OR` expression by concatenating the given expressions with the `OR` operators. |
| 412 | * `dbx.In()`: creating an `IN` expression for the specified column and the range of values. |
| 413 | For example, `dbx.In("age", 30, 40, 50)` would create the expression `age IN (30, 40, 50)`. |
| 414 | Note that if the value range is empty, it will generate an expression representing a false value. |
| 415 | * `dbx.NotIn()`: creating an `NOT IN` expression. This is very similar to `dbx.In()`. |
| 416 | * `dbx.Like()`: creating a `LIKE` expression for the specified column and the range of values. For example, |
| 417 | `dbx.Like("title", "golang", "framework")` would create the expression `title LIKE "%golang%" AND title LIKE "%framework%"`. |
| 418 | You can further customize a LIKE expression by calling `Escape()` and/or `Match()` functions of the resulting expression. |
| 419 | Note that if the value range is empty, it will generate an empty expression. |
| 420 | * `dbx.NotLike()`: creating a `NOT LIKE` expression. This is very similar to `dbx.Like()`. |
| 421 | * `dbx.OrLike()`: creating a `LIKE` expression but concatenating different `LIKE` sub-expressions using `OR` instead of `AND`. |
| 422 | * `dbx.OrNotLike()`: creating a `NOT LIKE` expression and concatenating different `NOT LIKE` sub-expressions using `OR` instead of `AND`. |
| 423 | * `dbx.Exists()`: creating an `EXISTS` expression by prepending `EXISTS` to the given expression. |
| 424 | * `dbx.NotExists()`: creating a `NOT EXISTS` expression by prepending `NOT EXISTS` to the given expression. |
| 425 | * `dbx.Between()`: creating a `BETWEEN` expression. For example, `dbx.Between("age", 30, 40)` would create the |
| 426 | expression `age BETWEEN 30 AND 40`. |
| 427 | * `dbx.NotBetween()`: creating a `NOT BETWEEN` expression. For example |
| 428 | |
| 429 | You may also create other convenient functions to help building query conditions, as long as the functions return |
| 430 | an object implementing the `dbx.Expression` interface. |
| 431 | |
| 432 | |
| 433 | ### Building Data Manipulation Queries |
| 434 | |
| 435 | Data manipulation queries are those changing the data in the database, such as INSERT, UPDATE, DELETE statements. |
| 436 | Such queries can be built by calling the corresponding methods of `DB`. For example, |
| 437 | |
| 438 | ```go |
| 439 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 440 | |
| 441 | // INSERT INTO `users` (`name`, `email`) VALUES ({:p0}, {:p1}) |
| 442 | err := db.Insert("users", dbx.Params{ |
| 443 | "name": "James", |
| 444 | "email": "[email protected]", |
| 445 | }).Execute() |
| 446 | |
| 447 | // UPDATE `users` SET `status`={:p0} WHERE `id`={:p1} |
| 448 | err = db.Update("users", dbx.Params{"status": 1}, dbx.HashExp{"id": 100}).Execute() |
| 449 | |
| 450 | // DELETE FROM `users` WHERE `status`={:p0} |
| 451 | err = db.Delete("users", dbx.HashExp{"status": 2}).Execute() |
| 452 | ``` |
| 453 | |
| 454 | When building data manipulation queries, remember to call `Execute()` at the end to execute the queries. |
| 455 | |
| 456 | ### Building Schema Manipulation Queries |
| 457 | |
| 458 | Schema manipulation queries are those changing the database schema, such as creating a new table, adding a new column. |
| 459 | These queries can be built by calling the corresponding methods of `DB`. For example, |
| 460 | |
| 461 | ```go |
| 462 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 463 | |
| 464 | // CREATE TABLE `users` (`id` int primary key, `name` varchar(255)) |
| 465 | q := db.CreateTable("users", map[string]string{ |
| 466 | "id": "int primary key", |
| 467 | "name": "varchar(255)", |
| 468 | }) |
| 469 | err := q.Execute() |
| 470 | ``` |
| 471 | |
| 472 | ## CRUD Operations |
| 473 | |
| 474 | Although `dbx` is not an ORM, it does provide a very convenient way to do typical CRUD (Create, Read, Update, Delete) |
| 475 | operations without the need of writing plain SQL statements. |
| 476 | |
| 477 | To use the CRUD feature, first define a struct type for a table. By default, a struct is associated with a table |
| 478 | whose name is the snake case version of the struct type name. For example, a struct named `MyCustomer` |
| 479 | corresponds to the table name `my_customer`. You may explicitly specify the table name for a struct by implementing |
| 480 | the `dbx.TableModel` interface. For example, |
| 481 | |
| 482 | ```go |
| 483 | type MyCustomer struct{} |
| 484 | |
| 485 | func (c MyCustomer) TableName() string { |
| 486 | return "customer" |
| 487 | } |
| 488 | ``` |
| 489 | |
| 490 | Note that the `TableName` method should be defined with a value receiver instead of a pointer receiver. |
| 491 | |
| 492 | If the struct has a field named `ID` or `Id`, by default the field will be treated as the primary key field. |
| 493 | If you want to use a different field as the primary key, tag it with `db:"pk"`. You may tag multiple fields |
| 494 | for composite primary keys. Note that if you also want to explicitly specify the column name for a primary key field, |
| 495 | you should use the tag format `db:"pk,col_name"`. |
| 496 | |
| 497 | You can give a common prefix or suffix to your table names by defining your own table name mapping via |
| 498 | `DB.TableMapFunc`. For example, the following code prefixes `tbl_` to all table names. |
| 499 | |
| 500 | ```go |
| 501 | db.TableMapper = func(a interface{}) string { |
| 502 | return "tbl_" + GetTableName(a) |
| 503 | } |
| 504 | ``` |
| 505 | |
| 506 | ### Create |
| 507 | |
| 508 | To create (insert) a new row using a model, call the `ModelQuery.Insert()` method. For example, |
| 509 | |
| 510 | ```go |
| 511 | type Customer struct { |
| 512 | ID int |
| 513 | Name string |
| 514 | Email string |
| 515 | Status int |
| 516 | } |
| 517 | |
| 518 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 519 | |
| 520 | customer := Customer{ |
| 521 | Name: "example", |
| 522 | Email: "[email protected]", |
| 523 | } |
| 524 | // INSERT INTO customer (name, email, status) VALUES ('example', '[email protected]', 0) |
| 525 | err := db.Model(&customer).Insert() |
| 526 | ``` |
| 527 | |
| 528 | This will insert a row using the values from *all* public fields (except the primary key field if it is empty) in the struct. |
| 529 | If a primary key field is zero (a integer zero or a nil pointer), it is assumed to be auto-incremental and |
| 530 | will be automatically filled with the last insertion ID after a successful insertion. |
| 531 | |
| 532 | You can explicitly specify the fields that should be inserted by passing the list of the field names to the `Insert()` method. |
| 533 | You can also exclude certain fields from being inserted by calling `Exclude()` before calling `Insert()`. For example, |
| 534 | |
| 535 | ```go |
| 536 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 537 | |
| 538 | // insert only Name and Email fields |
| 539 | err := db.Model(&customer).Insert("Name", "Email") |
| 540 | // insert all public fields except Status |
| 541 | err = db.Model(&customer).Exclude("Status").Insert() |
| 542 | // insert only Name |
| 543 | err = db.Model(&customer).Exclude("Status").Insert("Name", "Status") |
| 544 | ``` |
| 545 | |
| 546 | ### Read |
| 547 | |
| 548 | To read a model by a given primary key value, call `SelectQuery.Model()`. |
| 549 | |
| 550 | ```go |
| 551 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 552 | |
| 553 | var customer Customer |
| 554 | // SELECT * FROM customer WHERE id=100 |
| 555 | err := db.Select().Model(100, &customer) |
| 556 | |
| 557 | // SELECT name, email FROM customer WHERE status=1 AND id=100 |
| 558 | err = db.Select("name", "email").Where(dbx.HashExp{"status": 1}).Model(100, &customer) |
| 559 | ``` |
| 560 | |
| 561 | Note that `SelectQuery.Model()` does not support composite primary keys. You should use `SelectQuery.One()` in this case. |
| 562 | For example, |
| 563 | |
| 564 | ```go |
| 565 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 566 | |
| 567 | var orderItem OrderItem |
| 568 | |
| 569 | // SELECT * FROM order_item WHERE order_id=100 AND item_id=20 |
| 570 | err := db.Select().Where(dbx.HashExp{"order_id": 100, "item_id": 20}).One(&orderItem) |
| 571 | ``` |
| 572 | |
| 573 | In the above queries, we do not call `From()` to specify which table to select data from. This is because the select |
| 574 | query automatically sets the table according to the model struct being populated. If the struct implements `TableModel`, |
| 575 | the value returned by its `TableName()` method will be used as the table name. Otherwise, the snake case version |
| 576 | of the struct type name will be the table name. |
| 577 | |
| 578 | You may also call `SelectQuery.All()` to read a list of model structs. Similarly, you do not need to call `From()` |
| 579 | if the table name can be inferred from the model structs. |
| 580 | |
| 581 | |
| 582 | ### Update |
| 583 | |
| 584 | To update a model, call the `ModelQuery.Update()` method. Like `Insert()`, by default, the `Update()` method will |
| 585 | update *all* public fields except primary key fields of the model. You can explicitly specify which fields can |
| 586 | be updated and which cannot in the same way as described for the `Insert()` method. For example, |
| 587 | |
| 588 | ```go |
| 589 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 590 | |
| 591 | // update all public fields of customer |
| 592 | err := db.Model(&customer).Update() |
| 593 | // update only Status |
| 594 | err = db.Model(&customer).Update("Status") |
| 595 | // update all public fields except Status |
| 596 | err = db.Model(&customer).Exclude("Status").Update() |
| 597 | ``` |
| 598 | |
| 599 | Note that the `Update()` method assumes that the primary keys are immutable. It uses the primary key value of the model |
| 600 | to look for the row that should be updated. An error will be returned if a model does not have a primary key. |
| 601 | |
| 602 | |
| 603 | ### Delete |
| 604 | |
| 605 | To delete a model, call the `ModelQuery.Delete()` method. The method deletes the row using the primary key value |
| 606 | specified by the model. If the model does not have a primary key, an error will be returned. For example, |
| 607 | |
| 608 | ```go |
| 609 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 610 | |
| 611 | err := db.Model(&customer).Delete() |
| 612 | ``` |
| 613 | |
| 614 | ### Null Handling |
| 615 | |
| 616 | To represent a nullable database value, you can use a pointer type. If the pointer is nil, it means the corresponding |
| 617 | database value is null. |
| 618 | |
| 619 | Another option to represent a database null is to use `sql.NullXyz` types. For example, if a string column is nullable, |
| 620 | you may use `sql.NullString`. The `NullString.Valid` field indicates whether the value is a null or not, and |
| 621 | `NullString.String` returns the string value when it is not null. Because `sql.NulLXyz` types do not handle JSON |
| 622 | marshalling, you may use the [null package](https://github.com/guregu/null), instead. |
| 623 | |
| 624 | Below is an example of handling nulls: |
| 625 | |
| 626 | ```go |
| 627 | type Customer struct { |
| 628 | ID int |
| 629 | Email string |
| 630 | FirstName *string // use pointer to represent null |
| 631 | LastName sql.NullString // use sql.NullString to represent null |
| 632 | } |
| 633 | ``` |
| 634 | |
| 635 | ## Quoting Table and Column Names |
| 636 | |
| 637 | Databases vary in quoting table and column names. To allow writing DB-agnostic SQLs, `dbx` introduces a special |
| 638 | syntax in quoting table and column names. A word enclosed within `{{` and `}}` is treated as a table name and will |
| 639 | be quoted according to the particular DB driver. Similarly, a word enclosed within `[[` and `]]` is treated as a |
| 640 | column name and will be quoted accordingly as well. For example, when working with a MySQL database, the following |
| 641 | query will be properly quoted: |
| 642 | |
| 643 | ```go |
| 644 | // SELECT * FROM `users` WHERE `status`=1 |
| 645 | q := db.NewQuery("SELECT * FROM {{users}} WHERE [[status]]=1") |
| 646 | ``` |
| 647 | |
| 648 | Note that if a table or column name contains a prefix, it will still be properly quoted. For example, `{{public.users}}` |
| 649 | will be quoted as `"public"."users"` for PostgreSQL. |
| 650 | |
| 651 | ## Using Transactions |
| 652 | |
| 653 | You can use all aforementioned query execution and building methods with transaction. For example, |
| 654 | |
| 655 | ```go |
| 656 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 657 | |
| 658 | tx, _ := db.Begin() |
| 659 | |
| 660 | _, err1 := tx.Insert("users", dbx.Params{ |
| 661 | "name": "user1", |
| 662 | }).Execute() |
| 663 | _, err2 := tx.Insert("users", dbx.Params{ |
| 664 | "name": "user2", |
| 665 | }).Execute() |
| 666 | |
| 667 | if err1 == nil && err2 == nil { |
| 668 | tx.Commit() |
| 669 | } else { |
| 670 | tx.Rollback() |
| 671 | } |
| 672 | ``` |
| 673 | |
| 674 | You may use `DB.Transactional()` to simplify your transactional code without explicitly committing or rolling back |
| 675 | transactions. The method will start a transaction and automatically roll back the transaction if the callback |
| 676 | returns an error. Otherwise it will |
| 677 | automatically commit the transaction. |
| 678 | |
| 679 | |
| 680 | ```go |
| 681 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 682 | |
| 683 | err := db.Transactional(func(tx *dbx.Tx) error { |
| 684 | var err error |
| 685 | _, err = tx.Insert("users", dbx.Params{ |
| 686 | "name": "user1", |
| 687 | }).Execute() |
| 688 | if err != nil { |
| 689 | return err |
| 690 | } |
| 691 | _, err = tx.Insert("users", dbx.Params{ |
| 692 | "name": "user2", |
| 693 | }).Execute() |
| 694 | return err |
| 695 | }) |
| 696 | |
| 697 | fmt.Println(err) |
| 698 | ``` |
| 699 | |
| 700 | ## Logging Executed SQL Statements |
| 701 | |
| 702 | You can log and instrument DB queries by installing loggers with a DB connection. There are three kinds of loggers you |
| 703 | can install: |
| 704 | * `DB.LogFunc`: this is called each time when a SQL statement is queried or executed. The function signature is the |
| 705 | same as that of `fmt.Printf`, which makes it very easy to use. |
| 706 | * `DB.QueryLogFunc`: this is called each time when querying with a SQL statement. |
| 707 | * `DB.ExecLogFunc`: this is called when executing a SQL statement. |
| 708 | |
| 709 | The following example shows how you can make use of these loggers. |
| 710 | |
| 711 | ```go |
| 712 | package main |
| 713 | |
| 714 | import ( |
| 715 | "context" |
| 716 | "database/sql" |
| 717 | "log" |
| 718 | "time" |
| 719 | |
| 720 | "github.com/pocketbase/dbx" |
| 721 | ) |
| 722 | |
| 723 | func main() { |
| 724 | db, _ := dbx.Open("mysql", "user:pass@/example") |
| 725 | |
| 726 | // simple logging |
| 727 | db.LogFunc = log.Printf |
| 728 | |
| 729 | // or you can use the following more flexible logging |
| 730 | db.QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) { |
| 731 | log.Printf("[%.2fms] Query SQL: %v", float64(t.Milliseconds()), sql) |
| 732 | } |
| 733 | db.ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) { |
| 734 | log.Printf("[%.2fms] Execute SQL: %v", float64(t.Milliseconds()), sql) |
| 735 | } |
| 736 | // ... |
| 737 | } |
| 738 | ``` |
| 739 | |
| 740 | ## Supporting New Databases |
| 741 | |
| 742 | While `dbx` provides out-of-box query building support for most major relational databases, its open architecture |
| 743 | allows you to add support for new databases. The effort of adding support for a new database involves: |
| 744 | |
| 745 | * Create a struct that implements the `QueryBuilder` interface. You may use `BaseQueryBuilder` directly or extend it |
| 746 | via composition. |
| 747 | * Create a struct that implements the `Builder` interface. You may extend `BaseBuilder` via composition. |
| 748 | * Write an `init()` function to register the new builder in `dbx.BuilderFuncMap`. |