diff --git a/examples/database/mysql.v b/examples/database/mysql.v index 228c447381..6f41267398 100644 --- a/examples/database/mysql.v +++ b/examples/database/mysql.v @@ -1,14 +1,13 @@ import db.mysql fn main() { - mut conn := mysql.Connection{ + mut conn := mysql.connect( host: 'localhost' port: 3306 username: 'root' password: '' dbname: 'mysql' - } - conn.connect()! + )! res := conn.query('show tables')! for row in res.rows() { println(row.vals.join(', ')) diff --git a/examples/database/orm.v b/examples/database/orm.v index 25f284b717..800fde4801 100644 --- a/examples/database/orm.v +++ b/examples/database/orm.v @@ -102,14 +102,13 @@ fn sqlite3_array() ! { fn msql_array() ! { eprintln('------------ ${@METHOD} -----------------') - mut db := mysql.Connection{ + mut db := mysql.connect( host: mysql_host port: mysql_port username: mysql_user password: mysql_pass dbname: mysql_db - } - db.connect()! + )! defer { sql db { drop table Parent @@ -213,14 +212,13 @@ fn sqlite3() ! { fn msql() ! { eprintln('------------ ${@METHOD} -----------------') - mut conn := mysql.Connection{ + mut conn := mysql.connect( host: mysql_host port: mysql_port username: mysql_user password: mysql_pass dbname: mysql_db - } - conn.connect()! + )! defer { conn.query('DROP TABLE IF EXISTS Module') or { eprintln(err) } conn.query('DROP TABLE IF EXISTS User') or { eprintln(err) } diff --git a/vlib/db/mysql/mysql.v b/vlib/db/mysql/mysql.v index 285db74c3e..bffe49593b 100644 --- a/vlib/db/mysql/mysql.v +++ b/vlib/db/mysql/mysql.v @@ -21,7 +21,12 @@ struct SQLError { MessageError } -pub struct Connection { +pub struct DB { +mut: + conn &C.MYSQL = unsafe { nil } +} + +pub struct Config { mut: conn &C.MYSQL = C.mysql_init(0) pub mut: @@ -34,27 +39,35 @@ pub mut: } // connect attempts to establish a connection to a MySQL server. -pub fn (mut c Connection) connect() !bool { - instance := C.mysql_init(c.conn) - c.conn = C.mysql_real_connect(instance, c.host.str, c.username.str, c.password.str, - c.dbname.str, c.port, 0, c.flag) - - if isnil(c.conn) { - c.throw_mysql_error()! +pub fn connect(config Config) !DB { + mut db := DB{ + conn: C.mysql_init(0) } - return true + connection := C.mysql_real_connect(db.conn, config.host.str, config.username.str, + config.password.str, config.dbname.str, config.port, 0, config.flag) + + if isnil(connection) { + db.throw_mysql_error()! + } + + // Sets `db.conn` after checking for `null` + // because `throw_mysql_error` can't extract an error from a `null` connection, + // and `panic` will be with an empty message. + db.conn = connection + + return db } // query executes the SQL statement pointed to by the string `q`. // It cannot be used for statements that contain binary data; // Use `real_query()` instead. -pub fn (c &Connection) query(q string) !Result { - if C.mysql_query(c.conn, q.str) != 0 { - c.throw_mysql_error()! +pub fn (db &DB) query(q string) !Result { + if C.mysql_query(db.conn, q.str) != 0 { + db.throw_mysql_error()! } - result := C.mysql_store_result(c.conn) + result := C.mysql_store_result(db.conn) return Result{result} } @@ -66,8 +79,8 @@ pub fn (c &Connection) query(q string) !Result { // without storing it in a temporary table or local buffer, // mysql_use_result is faster and uses much less memory than C.mysql_store_result(). // You must mysql_free_result() after you are done with the result set. -pub fn (c &Connection) use_result() { - C.mysql_use_result(c.conn) +pub fn (db &DB) use_result() { + C.mysql_use_result(db.conn) } // real_query makes an SQL query and receive the results. @@ -75,20 +88,20 @@ pub fn (c &Connection) use_result() { // (Binary data may contain the `\0` character, which `query()` // interprets as the end of the statement string). In addition, // `real_query()` is faster than `query()`. -pub fn (mut c Connection) real_query(q string) !Result { - if C.mysql_real_query(c.conn, q.str, q.len) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) real_query(q string) !Result { + if C.mysql_real_query(db.conn, q.str, q.len) != 0 { + db.throw_mysql_error()! } - result := C.mysql_store_result(c.conn) + result := C.mysql_store_result(db.conn) return Result{result} } // select_db causes the database specified by `db` to become // the default (current) database on the connection specified by mysql. -pub fn (mut c Connection) select_db(dbname string) !bool { - if C.mysql_select_db(c.conn, dbname.str) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) select_db(dbname string) !bool { + if C.mysql_select_db(db.conn, dbname.str) != 0 { + db.throw_mysql_error()! } return true @@ -97,16 +110,16 @@ pub fn (mut c Connection) select_db(dbname string) !bool { // change_user changes the mysql user for the connection. // Passing an empty string for the `dbname` parameter, resultsg in only changing // the user and not changing the default database for the connection. -pub fn (mut c Connection) change_user(username string, password string, dbname string) !bool { +pub fn (mut db DB) change_user(username string, password string, dbname string) !bool { mut result := true if dbname != '' { - result = C.mysql_change_user(c.conn, username.str, password.str, dbname.str) + result = C.mysql_change_user(db.conn, username.str, password.str, dbname.str) } else { - result = C.mysql_change_user(c.conn, username.str, password.str, 0) + result = C.mysql_change_user(db.conn, username.str, password.str, 0) } if !result { - c.throw_mysql_error()! + db.throw_mysql_error()! } return result @@ -114,28 +127,28 @@ pub fn (mut c Connection) change_user(username string, password string, dbname s // affected_rows returns the number of rows changed, deleted, // or inserted by the last statement if it was an `UPDATE`, `DELETE`, or `INSERT`. -pub fn (c &Connection) affected_rows() u64 { - return C.mysql_affected_rows(c.conn) +pub fn (db &DB) affected_rows() u64 { + return C.mysql_affected_rows(db.conn) } // autocommit turns on/off the auto-committing mode for the connection. // When it is on, then each query is committed right away. -pub fn (mut c Connection) autocommit(mode bool) ! { - c.check_connection_is_established()! - result := C.mysql_autocommit(c.conn, mode) +pub fn (mut db DB) autocommit(mode bool) ! { + db.check_connection_is_established()! + result := C.mysql_autocommit(db.conn, mode) if result != 0 { - c.throw_mysql_error()! + db.throw_mysql_error()! } } // commit commits the current transaction. -pub fn (c &Connection) commit() ! { - c.check_connection_is_established()! - result := C.mysql_commit(c.conn) +pub fn (db &DB) commit() ! { + db.check_connection_is_established()! + result := C.mysql_commit(db.conn) if result != 0 { - c.throw_mysql_error()! + db.throw_mysql_error()! } } @@ -144,10 +157,10 @@ pub fn (c &Connection) commit() ! { // The `wildcard` parameter may contain the wildcard characters `%` or `_`. // If an empty string is passed, it will return all tables. // Calling `tables()` is similar to executing query `SHOW TABLES [LIKE wildcard]`. -pub fn (c &Connection) tables(wildcard string) ![]string { - c_mysql_result := C.mysql_list_tables(c.conn, wildcard.str) +pub fn (db &DB) tables(wildcard string) ![]string { + c_mysql_result := C.mysql_list_tables(db.conn, wildcard.str) if isnil(c_mysql_result) { - c.throw_mysql_error()! + db.throw_mysql_error()! } result := Result{c_mysql_result} @@ -163,10 +176,10 @@ pub fn (c &Connection) tables(wildcard string) ![]string { // escape_string creates a legal SQL string for use in an SQL statement. // The `s` argument is encoded to produce an escaped SQL string, // taking into account the current character set of the connection. -pub fn (c &Connection) escape_string(s string) string { +pub fn (db &DB) escape_string(s string) string { unsafe { to := malloc_noscan(2 * s.len + 1) - C.mysql_real_escape_string(c.conn, to, s.str, s.len) + C.mysql_real_escape_string(db.conn, to, s.str, s.len) return to.vstring() } } @@ -174,16 +187,16 @@ pub fn (c &Connection) escape_string(s string) string { // set_option sets extra connect options that affect the behavior of // a connection. This function may be called multiple times to set several // options. To retrieve the current values for an option, use `get_option()`. -pub fn (mut c Connection) set_option(option_type int, val voidptr) { - C.mysql_options(c.conn, option_type, val) +pub fn (mut db DB) set_option(option_type int, val voidptr) { + C.mysql_options(db.conn, option_type, val) } // get_option returns the value of an option, settable by `set_option`. // https://dev.mysql.com/doc/c-api/5.7/en/mysql-get-option.html -pub fn (c &Connection) get_option(option_type int) !voidptr { +pub fn (db &DB) get_option(option_type int) !voidptr { mysql_option := unsafe { nil } - if C.mysql_get_option(c.conn, option_type, &mysql_option) != 0 { - c.throw_mysql_error()! + if C.mysql_get_option(db.conn, option_type, &mysql_option) != 0 { + db.throw_mysql_error()! } return mysql_option @@ -191,18 +204,18 @@ pub fn (c &Connection) get_option(option_type int) !voidptr { // refresh flush the tables or caches, or resets replication server // information. The connected user must have the `RELOAD` privilege. -pub fn (mut c Connection) refresh(options u32) !bool { - if C.mysql_refresh(c.conn, options) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) refresh(options u32) !bool { + if C.mysql_refresh(db.conn, options) != 0 { + db.throw_mysql_error()! } return true } // reset resets the connection, and clear the session state. -pub fn (mut c Connection) reset() !bool { - if C.mysql_reset_connection(c.conn) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) reset() !bool { + if C.mysql_reset_connection(db.conn) != 0 { + db.throw_mysql_error()! } return true @@ -210,50 +223,50 @@ pub fn (mut c Connection) reset() !bool { // ping pings a server connection, or tries to reconnect if the connection // has gone down. -pub fn (mut c Connection) ping() !bool { - if C.mysql_ping(c.conn) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) ping() !bool { + if C.mysql_ping(db.conn) != 0 { + db.throw_mysql_error()! } return true } // close closes the connection. -pub fn (mut c Connection) close() { - C.mysql_close(c.conn) +pub fn (mut db DB) close() { + C.mysql_close(db.conn) } // info returns information about the most recently executed query. // See more on https://dev.mysql.com/doc/c-api/8.0/en/mysql-info.html -pub fn (c &Connection) info() string { - return resolve_nil_str(C.mysql_info(c.conn)) +pub fn (db &DB) info() string { + return resolve_nil_str(C.mysql_info(db.conn)) } // get_host_info returns a string describing the type of connection in use, // including the server host name. -pub fn (c &Connection) get_host_info() string { - return unsafe { C.mysql_get_host_info(c.conn).vstring() } +pub fn (db &DB) get_host_info() string { + return unsafe { C.mysql_get_host_info(db.conn).vstring() } } // get_server_info returns a string representing the MySQL server version. // For example, `8.0.24`. -pub fn (c &Connection) get_server_info() string { - return unsafe { C.mysql_get_server_info(c.conn).vstring() } +pub fn (db &DB) get_server_info() string { + return unsafe { C.mysql_get_server_info(db.conn).vstring() } } // get_server_version returns an integer, representing the MySQL server // version. The value has the format `XYYZZ` where `X` is the major version, // `YY` is the release level (or minor version), and `ZZ` is the sub-version // within the release level. For example, `8.0.24` is returned as `80024`. -pub fn (c &Connection) get_server_version() u64 { - return C.mysql_get_server_version(c.conn) +pub fn (db &DB) get_server_version() u64 { + return C.mysql_get_server_version(db.conn) } // dump_debug_info instructs the server to write debugging information // to the error log. The connected user must have the `SUPER` privilege. -pub fn (mut c Connection) dump_debug_info() !bool { - if C.mysql_dump_debug_info(c.conn) != 0 { - c.throw_mysql_error()! +pub fn (mut db DB) dump_debug_info() !bool { + if C.mysql_dump_debug_info(db.conn) != 0 { + db.throw_mysql_error()! } return true @@ -278,13 +291,13 @@ pub fn debug(debug string) { } [inline] -fn (c &Connection) throw_mysql_error() ! { - return error_with_code(get_error_msg(c.conn), get_errno(c.conn)) +fn (db &DB) throw_mysql_error() ! { + return error_with_code(get_error_msg(db.conn), get_errno(db.conn)) } [inline] -fn (c &Connection) check_connection_is_established() ! { - if isnil(c.conn) { +fn (db &DB) check_connection_is_established() ! { + if isnil(db.conn) { return error('No connection to a MySQL server, use `connect()` to connect to a database for working with it') } } diff --git a/vlib/db/mysql/mysql_orm_test.v b/vlib/db/mysql/mysql_orm_test.v index b349a971d2..1e6af4f299 100644 --- a/vlib/db/mysql/mysql_orm_test.v +++ b/vlib/db/mysql/mysql_orm_test.v @@ -36,14 +36,13 @@ struct TestDefaultAtribute { } fn test_mysql_orm() { - mut db := mysql.Connection{ + mut db := mysql.connect( host: 'localhost' port: 3306 username: 'root' password: '' dbname: 'mysql' - } - db.connect() or { panic(err) } + )! defer { db.close() } @@ -124,7 +123,6 @@ fn test_mysql_orm() { WHERE TABLE_NAME = 'TestCustomSqlType' ORDER BY ORDINAL_POSITION ") or { - println(err) panic(err) } diff --git a/vlib/db/mysql/orm.v b/vlib/db/mysql/orm.v index f585acc8d3..962c602ee1 100644 --- a/vlib/db/mysql/orm.v +++ b/vlib/db/mysql/orm.v @@ -4,7 +4,7 @@ import orm import time // @select is used internally by V's ORM for processing `SELECT ` queries. -pub fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, where orm.QueryData) ![][]orm.Primitive { +pub fn (db DB) @select(config orm.SelectConfig, data orm.QueryData, where orm.QueryData) ![][]orm.Primitive { query := orm.orm_select_gen(config, '`', false, '?', 0, where) mut result := [][]orm.Primitive{} mut stmt := db.init_stmt(query) @@ -128,7 +128,7 @@ pub fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, wher } // insert is used internally by V's ORM for processing `INSERT ` queries -pub fn (db Connection) insert(table string, data orm.QueryData) ! { +pub fn (db DB) insert(table string, data orm.QueryData) ! { mut converted_primitive_array := db.convert_query_data_to_primitives(table, data)! converted_primitive_data := orm.QueryData{ @@ -145,20 +145,20 @@ pub fn (db Connection) insert(table string, data orm.QueryData) ! { } // update is used internally by V's ORM for processing `UPDATE ` queries -pub fn (db Connection) update(table string, data orm.QueryData, where orm.QueryData) ! { +pub fn (db DB) update(table string, data orm.QueryData, where orm.QueryData) ! { query, _ := orm.orm_stmt_gen(.default, table, '`', .update, false, '?', 1, data, where) mysql_stmt_worker(db, query, data, where)! } // delete is used internally by V's ORM for processing `DELETE ` queries -pub fn (db Connection) delete(table string, where orm.QueryData) ! { +pub fn (db DB) delete(table string, where orm.QueryData) ! { query, _ := orm.orm_stmt_gen(.default, table, '`', .delete, false, '?', 1, orm.QueryData{}, where) mysql_stmt_worker(db, query, orm.QueryData{}, where)! } // last_id is used internally by V's ORM for post-processing `INSERT ` queries -pub fn (db Connection) last_id() int { +pub fn (db DB) last_id() int { query := 'SELECT last_insert_id();' id := db.query(query) or { return 0 } @@ -166,7 +166,7 @@ pub fn (db Connection) last_id() int { } // create is used internally by V's ORM for processing table creation queries (DDL) -pub fn (db Connection) create(table string, fields []orm.TableField) ! { +pub fn (db DB) create(table string, fields []orm.TableField) ! { query := orm.orm_table_gen(table, '`', true, 0, fields, mysql_type_from_v, false) or { return err } @@ -174,7 +174,7 @@ pub fn (db Connection) create(table string, fields []orm.TableField) ! { } // drop is used internally by V's ORM for processing table destroying queries (DDL) -pub fn (db Connection) drop(table string) ! { +pub fn (db DB) drop(table string) ! { query := 'DROP TABLE `${table}`;' mysql_stmt_worker(db, query, orm.QueryData{}, orm.QueryData{})! } @@ -182,7 +182,7 @@ pub fn (db Connection) drop(table string) ! { // mysql_stmt_worker executes the `query` with the provided `data` and `where` parameters // without returning the result. // This is commonly used for `INSERT`, `UPDATE`, `CREATE`, `DROP`, and `DELETE` queries. -fn mysql_stmt_worker(db Connection, query string, data orm.QueryData, where orm.QueryData) ! { +fn mysql_stmt_worker(db DB, query string, data orm.QueryData, where orm.QueryData) ! { mut stmt := db.init_stmt(query) stmt.prepare()! @@ -360,7 +360,7 @@ fn mysql_type_from_v(typ int) !string { // convert_query_data_to_primitives converts the `data` representing the `QueryData` // into an array of `Primitive`. -fn (db Connection) convert_query_data_to_primitives(table string, data orm.QueryData) ![]orm.Primitive { +fn (db DB) convert_query_data_to_primitives(table string, data orm.QueryData) ![]orm.Primitive { mut column_type_map := db.get_table_column_type_map(table)! mut converted_data := []orm.Primitive{} @@ -381,7 +381,7 @@ fn (db Connection) convert_query_data_to_primitives(table string, data orm.Query // get_table_column_type_map returns a map where the key represents the column name, // and the value represents its data type. -fn (db Connection) get_table_column_type_map(table string) !map[string]string { +fn (db DB) get_table_column_type_map(table string) !map[string]string { data_type_query := "SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${table}'" mut column_type_map := map[string]string{} results := db.query(data_type_query)! diff --git a/vlib/db/mysql/stmt.c.v b/vlib/db/mysql/stmt.c.v index b4de350121..674fb85a46 100644 --- a/vlib/db/mysql/stmt.c.v +++ b/vlib/db/mysql/stmt.c.v @@ -77,7 +77,7 @@ pub fn (s &Stmt) str() string { } // init_stmt creates a new statement, given the `query`. -pub fn (db Connection) init_stmt(query string) Stmt { +pub fn (db DB) init_stmt(query string) Stmt { return Stmt{ stmt: C.mysql_stmt_init(db.conn) query: query