Skip to content

db.mysql #

For Linux, you need to install MySQL development package and pkg-config.

For Windows, install the installer , then copy the include and lib folders to <V install directory>\thirdparty\mysql.

Note: if you encounter weird errors (your program just exits right away, without printing any messages, even though you have println('hi') statements in your fn main()), when trying to run a program that does import db.mysql on windows, you may need to copy the .dll file: thirdparty/mysql/lib/libmysql.dll , into the folder of the executable too (it should be right next to the .exe file). This is a temporary workaround, until we have a more permanent solution, or at least more user friendly errors for that situation.

Basic Usage

import db.mysql

// Create connection
mut connection := mysql.Connection{
    username: 'root'
    dbname: 'mysql'
}
// Connect to server
connection.connect()?
// Change the default database
connection.select_db('db_users')?
// Do a query
get_users_query_result := connection.query('SELECT * FROM users')?
// Get the result as maps
for user in get_users_query_result.maps() {
    // Access the name of user
    println(user['name'])
}
// Free the query result
get_users_query_result.free()
// Close the connection if needed
connection.close()

Constants #

const (
	refresh_grant   = u32(C.REFRESH_GRANT)
	refresh_log     = u32(C.REFRESH_LOG)
	refresh_tables  = u32(C.REFRESH_TABLES)
	refresh_hosts   = u32(C.REFRESH_HOSTS)
	refresh_status  = u32(C.REFRESH_STATUS)
	refresh_threads = u32(C.REFRESH_THREADS)
	refresh_slave   = u32(C.REFRESH_SLAVE)
	refresh_master  = u32(C.REFRESH_MASTER)
)

MYSQL REFRESH FLAGS

fn debug #

fn debug(debug string)

debug - does a DBUG_PUSH with the given string.
debug() uses the Fred Fish debug library.
To use this function, you must compile the client library to support debugging.
See https://dev.mysql.com/doc/c-api/8.0/en/mysql-debug.html

fn get_client_info #

fn get_client_info() string

get_client_info - returns client version information as a string.

fn get_client_version #

fn get_client_version() u64

get_client_version - returns the client version information as an integer.

enum ConnectionFlag #

enum ConnectionFlag {
// CAN_HANDLE_EXPIRED_PASSWORDS       = C.CAN_HANDLE_EXPIRED_PASSWORDS
	client_compress = C.CLIENT_COMPRESS
	client_found_rows = C.CLIENT_FOUND_ROWS
	client_ignore_sigpipe = C.CLIENT_IGNORE_SIGPIPE
	client_ignore_space = C.CLIENT_IGNORE_SPACE
	client_interactive = C.CLIENT_INTERACTIVE
	client_local_files = C.CLIENT_LOCAL_FILES
	client_multi_results = C.CLIENT_MULTI_RESULTS
	client_multi_statements = C.CLIENT_MULTI_STATEMENTS
	client_no_schema = C.CLIENT_NO_SCHEMA
	client_odbc = C.CLIENT_ODBC
// client_optional_resultset_metadata = C.CLIENT_OPTIONAL_RESULTSET_METADATA
	client_ssl = C.CLIENT_SSL
	client_remember_options = C.CLIENT_REMEMBER_OPTIONS
}

Values for the capabilities flag bitmask used by the MySQL protocol.
See more on https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html#details

enum FieldType #

enum FieldType {
	type_decimal
	type_tiny
	type_short
	type_long
	type_float
	type_double
	type_null
	type_timestamp
	type_longlong
	type_int24
	type_date
	type_time
	type_datetime
	type_year
	type_newdate
	type_varchar
	type_bit
	type_timestamp2
	type_datetime2
	type_time2
	type_json = 245
	type_newdecimal
	type_enum
	type_set
	type_tiny_blob
	type_medium_blob
	type_long_blob
	type_blob
	type_var_string
	type_string
	type_geometry
}

FieldType is a list of all supported MYSQL field types

fn (FieldType) str #

fn (f FieldType) str() string

str returns a text representation of the field type f

fn (FieldType) get_len #

fn (f FieldType) get_len() u32

get_len returns the length in bytes, for the given field type f

struct Connection #

struct Connection {
mut:
	conn &C.MYSQL = C.mysql_init(0)
pub mut:
	host     string = '127.0.0.1'
	port     u32    = 3306
	username string
	password string
	dbname   string
	flag     ConnectionFlag
}

TODO: Documentation

fn (Connection) @select #

fn (db Connection) @select(config orm.SelectConfig, data orm.QueryData, where orm.QueryData) ![][]orm.Primitive

@select is used internally by V's ORM for processing SELECT queries

fn (Connection) affected_rows #

fn (conn &Connection) affected_rows() u64

affected_rows - return the number of rows changed/deleted/inserted by the last UPDATE, DELETE, or INSERT query.

fn (Connection) autocommit #

fn (mut conn Connection) autocommit(mode bool)

autocommit - turns on/off the auto-committing mode for the connection.
When it is on, then each query is commited right away.

fn (Connection) change_user #

fn (mut conn Connection) change_user(username string, password string, dbname string) !bool

change_user - change 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.

fn (Connection) close #

fn (mut conn Connection) close()

close - closes the connection.

fn (Connection) connect #

fn (mut conn Connection) connect() !bool

connect - create a new connection to the MySQL server.

fn (Connection) create #

fn (db Connection) create(table string, fields []orm.TableField) !

create is used internally by V's ORM for processing table creation queries (DDL)

fn (Connection) delete #

fn (db Connection) delete(table string, where orm.QueryData) !

delete is used internally by V's ORM for processing DELETE queries

fn (Connection) drop #

fn (db Connection) drop(table string) !

drop is used internally by V's ORM for processing table destroying queries (DDL)

fn (Connection) dump_debug_info #

fn (mut conn Connection) dump_debug_info() !bool

dump_debug_info - instructs the server to write debugging information to the error log. The connected user must have the SUPER privilege.

fn (Connection) escape_string #

fn (conn &Connection) escape_string(s 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.

fn (Connection) get_host_info #

fn (conn &Connection) get_host_info() string

get_host_info - returns a string describing the type of connection in use, including the server host name.

fn (Connection) get_option #

fn (conn &Connection) get_option(option_type int) !voidptr

get_option - return the value of an option, settable by set_option.
https://dev.mysql.com/doc/c-api/5.7/en/mysql-get-option.html

fn (Connection) get_server_info #

fn (conn &Connection) get_server_info() string

get_server_info - returns a string representing the MySQL server version.
For example, 8.0.24.

fn (Connection) get_server_version #

fn (conn &Connection) get_server_version() u64

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.

fn (Connection) info #

fn (conn &Connection) info() string

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

fn (Connection) init_stmt #

fn (db Connection) init_stmt(query string) Stmt

init_stmt creates a new statement, given the query

fn (Connection) insert #

fn (db Connection) insert(table string, data orm.QueryData) !

insert is used internally by V's ORM for processing INSERT queries

fn (Connection) last_id #

fn (db Connection) last_id() orm.Primitive

last_id is used internally by V's ORM for post-processing INSERT queries

fn (Connection) ping #

fn (mut conn Connection) ping() !bool

ping - pings a server connection, or tries to reconnect if the connection has gone down.

fn (Connection) query #

fn (conn Connection) query(q string) !Result

query - make an SQL query and receive the results.
query() cannot be used for statements that contain binary data; Use real_query() instead.

fn (Connection) real_query #

fn (mut conn Connection) real_query(q string) !Result

real_query - make an SQL query and receive the results.
real_query() can be used for statements containing binary data.
(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().

fn (Connection) refresh #

fn (mut conn Connection) refresh(options u32) !bool

refresh - flush the tables or caches, or resets replication server information. The connected user must have the RELOAD privilege.

fn (Connection) reset #

fn (mut conn Connection) reset() !bool

reset - resets the connection, and clear the session state.

fn (Connection) select_db #

fn (mut conn Connection) select_db(dbname string) !bool

select_db - change the default database for database queries.

fn (Connection) set_option #

fn (mut conn Connection) set_option(option_type int, val voidptr)

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().

fn (Connection) tables #

fn (conn &Connection) tables(wildcard string) ![]string

tables - returns a list of the names of the tables in the current database, that match the simple regular expression specified by the wildcard parameter.
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].

fn (Connection) update #

fn (db Connection) update(table string, data orm.QueryData, where orm.QueryData) !

update is used internally by V's ORM for processing UPDATE queries

fn (Connection) use_result #

fn (conn Connection) use_result()

use_result - reads the result of a query used after invoking mysql_real_query() or mysql_query(), for every statement that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so forth).
This reads the result of a query directly from the server 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.

struct Field #

struct Field {
	name             string
	org_name         string
	table            string
	org_table        string
	db               string
	catalog          string
	def              string
	length           int
	max_length       int
	name_length      u32
	org_name_length  u32
	table_length     u32
	org_table_length u32
	db_length        u32
	catalog_length   u32
	def_length       u32
	flags            u32
	decimals         u32
	charsetnr        u32
	type_            FieldType
}

fn (Field) str #

fn (f Field) str() string

str - serializes the field

struct Result #

struct Result {
	result &C.MYSQL_RES = unsafe { nil }
}

fn (Result) fetch_row #

fn (r Result) fetch_row() &&u8

fetch_row - fetches the next row from a result.

fn (Result) n_rows #

fn (r Result) n_rows() u64

n_rows - returns the number of rows from a result.

fn (Result) n_fields #

fn (r Result) n_fields() int

n_fields - returns the number of columns from a result.

fn (Result) rows #

fn (r Result) rows() []Row

rows - returns array of rows, each containing an array of values, one for each column.

fn (Result) maps #

fn (r Result) maps() []map[string]string

maps - returns an array of maps, each containing a set of field name: field value pairs.

fn (Result) fields #

fn (r Result) fields() []Field

fields - returns an array of fields/columns.
The definitions apply primarily for columns of results, such as those produced by SELECT statements.

fn (Result) free #

unsafe
fn (r &Result) free()

free - frees the memory used by a result

struct Row #

struct Row {
pub mut:
	vals []string
}

struct Stmt #

struct Stmt {
	stmt  &C.MYSQL_STMT = &C.MYSQL_STMT(0)
	query string
mut:
	binds []C.MYSQL_BIND
	res   []C.MYSQL_BIND
}

fn (Stmt) str #

fn (s &Stmt) str() string

str returns a text representation of the given mysql statement s

fn (Stmt) prepare #

fn (stmt Stmt) prepare() !

prepare a statement for execution

fn (Stmt) bind_params #

fn (stmt Stmt) bind_params() !

bind_params binds all the parameters in stmt

fn (Stmt) execute #

fn (stmt Stmt) execute() !int

execute executes the given stmt and waits for the result

fn (Stmt) next #

fn (stmt Stmt) next() !int

next retrieves the next available result from the execution of stmt

fn (Stmt) gen_metadata #

fn (stmt Stmt) gen_metadata() &C.MYSQL_RES

gen_metadata executes mysql_stmt_result_metadata over the given stmt It requires that the statement has produced a result set, since the metadata will be for that result set.
See https://dev.mysql.com/doc/c-api/5.7/en/mysql-stmt-result-metadata.html

fn (Stmt) fetch_fields #

fn (stmt Stmt) fetch_fields(res &C.MYSQL_RES) &C.MYSQL_FIELD

fetch_fields retrieves the fields from the metadata result of the execution of stmt.
See https://dev.mysql.com/doc/c-api/5.7/en/mysql-fetch-fields.html See also Result.n_fields for the size of the returned C array.

fn (Stmt) fetch_stmt #

fn (stmt Stmt) fetch_stmt() !int

fetch_stmt fetches the next row in the result set. It returns the status of the execution of mysql_stmt_fetch .
See https://dev.mysql.com/doc/c-api/5.7/en/mysql-stmt-fetch.html

fn (Stmt) close #

fn (stmt Stmt) close() !

close disposes the prepared stmt. The statement becomes invalid, and should not be used anymore after this call.
If the current statement has pending or unread results, this method cancels them too.
See https://dev.mysql.com/doc/c-api/5.7/en/mysql-stmt-close.html

fn (Stmt) error #

fn (stmt Stmt) error(code int) IError

error returns a proper V error with a human readable description, given the error code returned by MySQL

fn (Stmt) bind_bool #

fn (mut stmt Stmt) bind_bool(b &bool)

bind_bool binds a single boolean value to the statement stmt

fn (Stmt) bind_byte #

fn (mut stmt Stmt) bind_byte(b &byte)

bind_byte binds a single byte value to the statement stmt

fn (Stmt) bind_u8 #

fn (mut stmt Stmt) bind_u8(b &u8)

bind_u8 binds a single u8 value to the statement stmt

fn (Stmt) bind_i8 #

fn (mut stmt Stmt) bind_i8(b &i8)

bind_i8 binds a single i8 value to the statement stmt

fn (Stmt) bind_i16 #

fn (mut stmt Stmt) bind_i16(b &i16)

bind_i16 binds a single i16 value to the statement stmt

fn (Stmt) bind_u16 #

fn (mut stmt Stmt) bind_u16(b &u16)

bind_u16 binds a single u16 value to the statement stmt

fn (Stmt) bind_int #

fn (mut stmt Stmt) bind_int(b &int)

bind_int binds a single int value to the statement stmt

fn (Stmt) bind_u32 #

fn (mut stmt Stmt) bind_u32(b &u32)

bind_u32 binds a single u32 value to the statement stmt

fn (Stmt) bind_i64 #

fn (mut stmt Stmt) bind_i64(b &i64)

bind_i64 binds a single i64 value to the statement stmt

fn (Stmt) bind_u64 #

fn (mut stmt Stmt) bind_u64(b &u64)

bind_u64 binds a single u64 value to the statement stmt

fn (Stmt) bind_f32 #

fn (mut stmt Stmt) bind_f32(b &f32)

bind_f32 binds a single f32 value to the statement stmt

fn (Stmt) bind_f64 #

fn (mut stmt Stmt) bind_f64(b &f64)

bind_f64 binds a single f64 value to the statement stmt

fn (Stmt) bind_text #

fn (mut stmt Stmt) bind_text(b string)

bind_text binds a single string value to the statement stmt

fn (Stmt) bind #

fn (mut stmt Stmt) bind(typ int, buffer voidptr, buf_len u32)

bind binds a single value pointed by buffer, to the statement stmt. The buffer length must be passed as well in buf_len.
Note: it is more convenient to use one of the other bind_XYZ methods.

fn (Stmt) bind_res #

fn (mut stmt Stmt) bind_res(fields &C.MYSQL_FIELD, dataptr []&u8, lens []u32, num_fields int)

bind_res will store one result in the statement stmt

fn (Stmt) bind_result_buffer #

fn (mut stmt Stmt) bind_result_buffer() !

bind_result_buffer binds one result value, by calling mysql_stmt_bind_result .
See https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-bind-result.html

fn (Stmt) store_result #

fn (mut stmt Stmt) store_result() !

store_result will buffer the complete result set from the execution of stmt on the client side.
Note: result sets are produced by calling mysql_stmt_execute() to executed prepared statements for SQL statements such as SELECT, SHOW, DESCRIBE, and EXPLAIN.
By default, result sets for successfully executed prepared statements are not buffered on the client, and mysql_stmt_fetch() fetches them one at a time from the server.
Note 2: call store_result, after binding data buffers with bind_result_buffer, and before calling fetch_stmt to fetch rows.
See https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-store-result.html