| 1 | module mysql |
| 2 | |
| 3 | import sync |
| 4 | |
| 5 | // Values for the capabilities flag bitmask used by the MySQL protocol. |
| 6 | // See more on https://dev.mysql.com/doc/dev/mysql-server/latest/group__group__cs__capabilities__flags.html#details |
| 7 | @[flag] |
| 8 | pub enum ConnectionFlag { |
| 9 | client_long_password // (1 << 0) Use the improved version of Old Password Authentication |
| 10 | client_found_rows // (1 << 1) Send found rows instead of affected rows in EOF_Packet |
| 11 | client_long_flag // (1 << 2) Get all column flags |
| 12 | client_connect_with_db // (1 << 3) Database (schema) name can be specified on connect in Handshake Response Packet |
| 13 | client_no_schema // (1 << 4) DEPRECATED: Don't allow database.table.column |
| 14 | client_compress // (1 << 5) Compression protocol supported |
| 15 | client_odbc // (1 << 6) Special handling of ODBC behavior |
| 16 | client_local_files // (1 << 7) Can use LOAD DATA LOCAL |
| 17 | client_ignore_space // (1 << 8) Ignore spaces before '(' |
| 18 | client_protocol_41 // (1 << 9) New 4.1 protocol |
| 19 | client_interactive // (1 << 10) This is an interactive client |
| 20 | client_ssl // (1 << 11) Use SSL encryption for the session |
| 21 | client_ignore_sigpipe // (1 << 12) Client only flag |
| 22 | client_transactions // (1 << 13) Client knows about transactions |
| 23 | client_reserved // (1 << 14) DEPRECATED: Old flag for 4.1 protocol |
| 24 | client_reserved2 // (1 << 15) DEPRECATED: Old flag for 4.1 authentication \ CLIENT_SECURE_CONNECTION |
| 25 | client_multi_statements // (1 << 16) Enable/disable multi-stmt support |
| 26 | client_multi_results // (1 << 17) Enable/disable multi-results |
| 27 | client_ps_multi_results // (1 << 18) Multi-results and OUT parameters in PS-protocol |
| 28 | client_plugin_auth // (1 << 19) Client supports plugin authentication |
| 29 | client_connect_attrs // (1 << 20) Client supports connection attributes |
| 30 | client_plugin_auth_lenenc_client_data // (1 << 21) Enable authentication response packet to be larger than 255 bytes |
| 31 | client_can_handle_expired_passwords // (1 << 22) Don't close the connection for a user account with expired password |
| 32 | client_session_track // (1 << 23) Capable of handling server state change information |
| 33 | client_deprecate_eof // (1 << 24) Client no longer needs EOF_Packet and will use OK_Packet instead |
| 34 | client_optional_resultset_metadata // (1 << 25) The client can handle optional metadata information in the resultset |
| 35 | client_zstd_compression_algorithm // (1 << 26) Compression protocol extended to support zstd compression method |
| 36 | client_query_attributes // (1 << 27) Support optional extension for query parameters into the COM_QUERY and COM_STMT_EXECUTE packets |
| 37 | multi_factor_authentication // (1 << 28) Support Multi factor authentication |
| 38 | client_capability_extension // (1 << 29) This flag will be reserved to extend the 32bit capabilities structure to 64bits |
| 39 | client_ssl_verify_server_cert // (1 << 30) Verify server certificate |
| 40 | client_remember_options // (1 << 31) Don't reset the options after an unsuccessful connect |
| 41 | } |
| 42 | |
| 43 | pub enum MySQLTransactionLevel { |
| 44 | read_uncommitted |
| 45 | read_committed |
| 46 | repeatable_read |
| 47 | serializable |
| 48 | } |
| 49 | |
| 50 | struct SQLError { |
| 51 | MessageError |
| 52 | } |
| 53 | |
| 54 | const mysql_no_connection_error_message = 'No connection to a MySQL server, use `connect()` to connect to a database for working with it' |
| 55 | const mysql_thread_init_error_message = 'db.mysql: failed to initialize MySQL thread state' |
| 56 | |
| 57 | struct ConnectionState { |
| 58 | mut: |
| 59 | conn &C.MYSQL = unsafe { nil } |
| 60 | mutex &sync.Mutex = sync.new_mutex() |
| 61 | } |
| 62 | |
| 63 | struct MySQLThreadGuard { |
| 64 | mut: |
| 65 | active bool |
| 66 | } |
| 67 | |
| 68 | struct MySQLConnectionGuard { |
| 69 | mut: |
| 70 | conn &C.MYSQL = unsafe { nil } |
| 71 | state &ConnectionState = unsafe { nil } |
| 72 | thread MySQLThreadGuard |
| 73 | } |
| 74 | |
| 75 | pub struct DB { |
| 76 | mut: |
| 77 | conn &C.MYSQL = unsafe { nil } |
| 78 | state &ConnectionState = unsafe { nil } |
| 79 | } |
| 80 | |
| 81 | @[params] |
| 82 | pub struct Config { |
| 83 | pub mut: |
| 84 | host string = '127.0.0.1' |
| 85 | port u32 = 3306 |
| 86 | user string |
| 87 | username string |
| 88 | password string |
| 89 | dbname string |
| 90 | flag ConnectionFlag |
| 91 | |
| 92 | // SSL params, only valid when set .client_ssl |
| 93 | ssl_key string |
| 94 | ssl_cert string |
| 95 | ssl_ca string |
| 96 | ssl_capath string |
| 97 | ssl_cipher string |
| 98 | } |
| 99 | |
| 100 | // connection_user returns the configured username, accepting both `user` and `username`. |
| 101 | pub fn (config Config) connection_user() !string { |
| 102 | if config.user != '' && config.username != '' && config.user != config.username { |
| 103 | return error('db.mysql: Config.user and Config.username must match when both are set') |
| 104 | } |
| 105 | if config.username != '' { |
| 106 | return config.username |
| 107 | } |
| 108 | return config.user |
| 109 | } |
| 110 | |
| 111 | // val returns the value at `index`. |
| 112 | pub fn (row Row) val(index int) string { |
| 113 | return row.vals[index] |
| 114 | } |
| 115 | |
| 116 | // values returns all row values. |
| 117 | pub fn (row Row) values() []string { |
| 118 | return row.vals.clone() |
| 119 | } |
| 120 | |
| 121 | // connect attempts to establish a connection to a MySQL server. |
| 122 | pub fn connect(config Config) !DB { |
| 123 | mut db := DB{ |
| 124 | conn: C.mysql_init(0) |
| 125 | } |
| 126 | username := config.connection_user()! |
| 127 | |
| 128 | if config.flag.has(.client_ssl) { |
| 129 | if config.ssl_key.len > 0 { |
| 130 | db.set_option(C.MYSQL_OPT_SSL_KEY, config.ssl_key.str) |
| 131 | } |
| 132 | if config.ssl_cert.len > 0 { |
| 133 | db.set_option(C.MYSQL_OPT_SSL_CERT, config.ssl_cert.str) |
| 134 | } |
| 135 | if config.ssl_ca.len > 0 { |
| 136 | db.set_option(C.MYSQL_OPT_SSL_CA, config.ssl_ca.str) |
| 137 | } |
| 138 | if config.ssl_capath.len > 0 { |
| 139 | db.set_option(C.MYSQL_OPT_SSL_CAPATH, config.ssl_capath.str) |
| 140 | } |
| 141 | if config.ssl_cipher.len > 0 { |
| 142 | db.set_option(C.MYSQL_OPT_SSL_CIPHER, config.ssl_cipher.str) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | connection := C.mysql_real_connect(db.conn, config.host.str, username.str, config.password.str, |
| 147 | config.dbname.str, config.port, 0, config.flag) |
| 148 | |
| 149 | if isnil(connection) { |
| 150 | db.throw_mysql_error()! |
| 151 | } |
| 152 | |
| 153 | // Sets `db.conn` after checking for `null` |
| 154 | // because `throw_mysql_error` can't extract an error from a `null` connection, |
| 155 | // and `panic` will be with an empty message. |
| 156 | db.conn = connection |
| 157 | db.state = &ConnectionState{ |
| 158 | conn: connection |
| 159 | } |
| 160 | |
| 161 | return db |
| 162 | } |
| 163 | |
| 164 | // query executes the SQL statement pointed to by the string `q`. |
| 165 | // It cannot be used for statements that contain binary data; |
| 166 | // Use `real_query()` instead. |
| 167 | pub fn (db &DB) query(q string) !Result { |
| 168 | mut guard := db.acquire_connection_guard()! |
| 169 | defer { |
| 170 | guard.release() |
| 171 | } |
| 172 | if C.mysql_query(guard.conn, charptr(q.str)) != 0 { |
| 173 | throw_mysql_error_for_conn(guard.conn)! |
| 174 | } |
| 175 | |
| 176 | result := C.mysql_store_result(guard.conn) |
| 177 | return Result{result} |
| 178 | } |
| 179 | |
| 180 | // use_result reads the result of a query |
| 181 | // used after invoking mysql_real_query() or mysql_query(), |
| 182 | // for every statement that successfully produces a result set |
| 183 | // (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so forth). |
| 184 | // This reads the result of a query directly from the server |
| 185 | // without storing it in a temporary table or local buffer, |
| 186 | // mysql_use_result is faster and uses much less memory than C.mysql_store_result(). |
| 187 | // You must mysql_free_result() after you are done with the result set. |
| 188 | pub fn (db &DB) use_result() { |
| 189 | mut guard := db.acquire_connection_guard() or { return } |
| 190 | defer { |
| 191 | guard.release() |
| 192 | } |
| 193 | C.mysql_use_result(guard.conn) |
| 194 | } |
| 195 | |
| 196 | // real_query makes an SQL query and receive the results. |
| 197 | // `real_query()` can be used for statements containing binary data. |
| 198 | // (Binary data may contain the `\0` character, which `query()` |
| 199 | // interprets as the end of the statement string). In addition, |
| 200 | // `real_query()` is faster than `query()`. |
| 201 | pub fn (mut db DB) real_query(q string) !Result { |
| 202 | mut guard := db.acquire_connection_guard()! |
| 203 | defer { |
| 204 | guard.release() |
| 205 | } |
| 206 | if C.mysql_real_query(guard.conn, q.str, q.len) != 0 { |
| 207 | throw_mysql_error_for_conn(guard.conn)! |
| 208 | } |
| 209 | |
| 210 | result := C.mysql_store_result(guard.conn) |
| 211 | return Result{result} |
| 212 | } |
| 213 | |
| 214 | // select_db causes the database specified by `db` to become |
| 215 | // the default (current) database on the connection specified by mysql. |
| 216 | pub fn (mut db DB) select_db(dbname string) !bool { |
| 217 | mut guard := db.acquire_connection_guard()! |
| 218 | defer { |
| 219 | guard.release() |
| 220 | } |
| 221 | if C.mysql_select_db(guard.conn, dbname.str) != 0 { |
| 222 | throw_mysql_error_for_conn(guard.conn)! |
| 223 | } |
| 224 | |
| 225 | return true |
| 226 | } |
| 227 | |
| 228 | // change_user changes the mysql user for the connection. |
| 229 | // Passing an empty string for the `dbname` parameter, resultsg in only changing |
| 230 | // the user and not changing the default database for the connection. |
| 231 | pub fn (mut db DB) change_user(username string, password string, dbname string) !bool { |
| 232 | mut guard := db.acquire_connection_guard()! |
| 233 | defer { |
| 234 | guard.release() |
| 235 | } |
| 236 | mut result := true |
| 237 | |
| 238 | if dbname != '' { |
| 239 | result = C.mysql_change_user(guard.conn, username.str, password.str, dbname.str) |
| 240 | } else { |
| 241 | result = C.mysql_change_user(guard.conn, username.str, password.str, 0) |
| 242 | } |
| 243 | if !result { |
| 244 | throw_mysql_error_for_conn(guard.conn)! |
| 245 | } |
| 246 | |
| 247 | return result |
| 248 | } |
| 249 | |
| 250 | // affected_rows returns the number of rows changed, deleted, |
| 251 | // or inserted by the last statement if it was an `UPDATE`, `DELETE`, or `INSERT`. |
| 252 | pub fn (db &DB) affected_rows() u64 { |
| 253 | mut guard := db.acquire_connection_guard() or { return 0 } |
| 254 | defer { |
| 255 | guard.release() |
| 256 | } |
| 257 | return C.mysql_affected_rows(guard.conn) |
| 258 | } |
| 259 | |
| 260 | // autocommit turns on/off the auto-committing mode for the connection. |
| 261 | // When it is on, then each query is committed right away. |
| 262 | pub fn (mut db DB) autocommit(mode bool) ! { |
| 263 | mut guard := db.acquire_connection_guard()! |
| 264 | defer { |
| 265 | guard.release() |
| 266 | } |
| 267 | result := C.mysql_autocommit(guard.conn, mode) |
| 268 | |
| 269 | if result != 0 { |
| 270 | throw_mysql_error_for_conn(guard.conn)! |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // commit commits the current transaction. |
| 275 | pub fn (db &DB) commit() ! { |
| 276 | mut guard := db.acquire_connection_guard()! |
| 277 | defer { |
| 278 | guard.release() |
| 279 | } |
| 280 | result := C.mysql_commit(guard.conn) |
| 281 | |
| 282 | if result != 0 { |
| 283 | throw_mysql_error_for_conn(guard.conn)! |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | @[params] |
| 288 | pub struct MySQLTransactionParam { |
| 289 | transaction_level MySQLTransactionLevel = .repeatable_read |
| 290 | } |
| 291 | |
| 292 | // begin begins a new transaction. |
| 293 | pub fn (db &DB) begin(param MySQLTransactionParam) ! { |
| 294 | db.check_connection_is_established()! |
| 295 | db.set_transaction_level(param.transaction_level)! |
| 296 | result := db.exec_none('START TRANSACTION') |
| 297 | if result != 0 { |
| 298 | db.throw_mysql_error()! |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // set_transaction_level set level for the transaction |
| 303 | pub fn (db &DB) set_transaction_level(level MySQLTransactionLevel) ! { |
| 304 | db.check_connection_is_established()! |
| 305 | mut sql_stmt := 'SET TRANSACTION ISOLATION LEVEL ' |
| 306 | match level { |
| 307 | .read_uncommitted { sql_stmt += 'READ UNCOMMITTED' } |
| 308 | .read_committed { sql_stmt += 'READ COMMITTED' } |
| 309 | .repeatable_read { sql_stmt += 'REPEATABLE READ' } |
| 310 | .serializable { sql_stmt += 'SERIALIZABLE' } |
| 311 | } |
| 312 | |
| 313 | result := db.exec_none(sql_stmt) |
| 314 | if result != 0 { |
| 315 | db.throw_mysql_error()! |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // rollback rollbacks the current transaction. |
| 320 | pub fn (db &DB) rollback() ! { |
| 321 | mut guard := db.acquire_connection_guard()! |
| 322 | defer { |
| 323 | guard.release() |
| 324 | } |
| 325 | result := C.mysql_rollback(guard.conn) |
| 326 | |
| 327 | if result != 0 { |
| 328 | throw_mysql_error_for_conn(guard.conn)! |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | // rollback_to rollbacks to a specified savepoint. |
| 333 | pub fn (db &DB) rollback_to(savepoint string) ! { |
| 334 | if !savepoint.is_identifier() { |
| 335 | return error('savepoint should be a identifier string') |
| 336 | } |
| 337 | db.check_connection_is_established()! |
| 338 | result := db.exec_none('ROLLBACK TO SAVEPOINT ${savepoint}') |
| 339 | if result != 0 { |
| 340 | db.throw_mysql_error()! |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // savepoint create a new savepoint. |
| 345 | pub fn (db &DB) savepoint(savepoint string) ! { |
| 346 | if !savepoint.is_identifier() { |
| 347 | return error('savepoint should be a identifier string') |
| 348 | } |
| 349 | db.check_connection_is_established()! |
| 350 | result := db.exec_none('SAVEPOINT ${savepoint}') |
| 351 | if result != 0 { |
| 352 | db.throw_mysql_error()! |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | // release_savepoint releases a specified savepoint. |
| 357 | pub fn (db &DB) release_savepoint(savepoint string) ! { |
| 358 | if !savepoint.is_identifier() { |
| 359 | return error('savepoint should be a identifier string') |
| 360 | } |
| 361 | db.check_connection_is_established()! |
| 362 | result := db.exec_none('RELEASE SAVEPOINT ${savepoint}') |
| 363 | if result != 0 { |
| 364 | db.throw_mysql_error()! |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | // tables returns a list of the names of the tables in the current database, |
| 369 | // that match the simple regular expression specified by the `wildcard` parameter. |
| 370 | // The `wildcard` parameter may contain the wildcard characters `%` or `_`. |
| 371 | // If an empty string is passed, it will return all tables. |
| 372 | // Calling `tables()` is similar to executing query `SHOW TABLES [LIKE wildcard]`. |
| 373 | pub fn (db &DB) tables(wildcard string) ![]string { |
| 374 | mut guard := db.acquire_connection_guard()! |
| 375 | defer { |
| 376 | guard.release() |
| 377 | } |
| 378 | c_mysql_result := C.mysql_list_tables(guard.conn, wildcard.str) |
| 379 | if isnil(c_mysql_result) { |
| 380 | throw_mysql_error_for_conn(guard.conn)! |
| 381 | } |
| 382 | |
| 383 | result := Result{c_mysql_result} |
| 384 | mut tables := []string{} |
| 385 | |
| 386 | for row in result.rows() { |
| 387 | tables << row.vals[0] |
| 388 | } |
| 389 | |
| 390 | return tables |
| 391 | } |
| 392 | |
| 393 | // escape_string creates a legal SQL string for use in an SQL statement. |
| 394 | // The `s` argument is encoded to produce an escaped SQL string, |
| 395 | // taking into account the current character set of the connection. |
| 396 | pub fn (db &DB) escape_string(s string) string { |
| 397 | conn := db.current_conn() |
| 398 | if isnil(conn) { |
| 399 | return '' |
| 400 | } |
| 401 | mut thread_guard := mysql_thread_guard() or { return '' } |
| 402 | defer { |
| 403 | thread_guard.release() |
| 404 | } |
| 405 | unsafe { |
| 406 | to := malloc_noscan(2 * s.len + 1) |
| 407 | C.mysql_real_escape_string(conn, to, s.str, s.len) |
| 408 | return to.vstring() |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | // set_option sets extra connect options that affect the behavior of |
| 413 | // a connection. This function may be called multiple times to set several |
| 414 | // options. To retrieve the current values for an option, use `get_option()`. |
| 415 | pub fn (mut db DB) set_option(option_type int, val voidptr) { |
| 416 | conn := db.current_conn() |
| 417 | if isnil(conn) { |
| 418 | return |
| 419 | } |
| 420 | mut thread_guard := mysql_thread_guard() or { return } |
| 421 | defer { |
| 422 | thread_guard.release() |
| 423 | } |
| 424 | C.mysql_options(conn, option_type, val) |
| 425 | } |
| 426 | |
| 427 | // get_option returns the value of an option, settable by `set_option`. |
| 428 | // https://dev.mysql.com/doc/c-api/5.7/en/mysql-get-option.html |
| 429 | pub fn (db &DB) get_option(option_type int) !voidptr { |
| 430 | mut guard := db.acquire_connection_guard()! |
| 431 | defer { |
| 432 | guard.release() |
| 433 | } |
| 434 | mysql_option := unsafe { nil } |
| 435 | if C.mysql_get_option(guard.conn, option_type, &mysql_option) != 0 { |
| 436 | throw_mysql_error_for_conn(guard.conn)! |
| 437 | } |
| 438 | |
| 439 | return mysql_option |
| 440 | } |
| 441 | |
| 442 | // refresh flush the tables or caches, or resets replication server |
| 443 | // information. The connected user must have the `RELOAD` privilege. |
| 444 | pub fn (mut db DB) refresh(options u32) !bool { |
| 445 | mut guard := db.acquire_connection_guard()! |
| 446 | defer { |
| 447 | guard.release() |
| 448 | } |
| 449 | if C.mysql_refresh(guard.conn, options) != 0 { |
| 450 | throw_mysql_error_for_conn(guard.conn)! |
| 451 | } |
| 452 | |
| 453 | return true |
| 454 | } |
| 455 | |
| 456 | // reset resets the connection, and clear the session state. |
| 457 | pub fn (mut db DB) reset() ! { |
| 458 | mut guard := db.acquire_connection_guard()! |
| 459 | defer { |
| 460 | guard.release() |
| 461 | } |
| 462 | if C.mysql_reset_connection(guard.conn) != 0 { |
| 463 | throw_mysql_error_for_conn(guard.conn)! |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | // ping pings a server connection, or tries to reconnect if the connection |
| 468 | // has gone down. |
| 469 | pub fn (mut db DB) ping() !bool { |
| 470 | mut guard := db.acquire_connection_guard()! |
| 471 | defer { |
| 472 | guard.release() |
| 473 | } |
| 474 | if C.mysql_ping(guard.conn) != 0 { |
| 475 | throw_mysql_error_for_conn(guard.conn)! |
| 476 | } |
| 477 | |
| 478 | return true |
| 479 | } |
| 480 | |
| 481 | // validate pings a server connection, or tries to reconnect if the connection |
| 482 | // has gone down. |
| 483 | pub fn (mut db DB) validate() !bool { |
| 484 | return db.ping()! |
| 485 | } |
| 486 | |
| 487 | // close closes the connection. |
| 488 | pub fn (mut db DB) close() ! { |
| 489 | if isnil(db.state) { |
| 490 | if isnil(db.conn) { |
| 491 | return |
| 492 | } |
| 493 | mut thread_guard := mysql_thread_guard()! |
| 494 | defer { |
| 495 | thread_guard.release() |
| 496 | } |
| 497 | C.mysql_close(db.conn) |
| 498 | db.conn = unsafe { nil } |
| 499 | return |
| 500 | } |
| 501 | db.state.mutex.@lock() |
| 502 | defer { |
| 503 | db.state.mutex.unlock() |
| 504 | } |
| 505 | if isnil(db.state.conn) { |
| 506 | db.conn = unsafe { nil } |
| 507 | return |
| 508 | } |
| 509 | mut thread_guard := mysql_thread_guard()! |
| 510 | defer { |
| 511 | thread_guard.release() |
| 512 | } |
| 513 | C.mysql_close(db.state.conn) |
| 514 | db.state.conn = unsafe { nil } |
| 515 | db.conn = unsafe { nil } |
| 516 | } |
| 517 | |
| 518 | // info returns information about the most recently executed query. |
| 519 | // See more on https://dev.mysql.com/doc/c-api/8.0/en/mysql-info.html |
| 520 | pub fn (db &DB) info() string { |
| 521 | mut guard := db.acquire_connection_guard() or { return '' } |
| 522 | defer { |
| 523 | guard.release() |
| 524 | } |
| 525 | return resolve_nil_str(C.mysql_info(guard.conn)) |
| 526 | } |
| 527 | |
| 528 | // get_host_info returns a string describing the type of connection in use, |
| 529 | // including the server host name. |
| 530 | pub fn (db &DB) get_host_info() string { |
| 531 | mut guard := db.acquire_connection_guard() or { return '' } |
| 532 | defer { |
| 533 | guard.release() |
| 534 | } |
| 535 | return unsafe { C.mysql_get_host_info(guard.conn).vstring() } |
| 536 | } |
| 537 | |
| 538 | // get_server_info returns a string representing the MySQL server version. |
| 539 | // For example, `8.0.24`. |
| 540 | pub fn (db &DB) get_server_info() string { |
| 541 | mut guard := db.acquire_connection_guard() or { return '' } |
| 542 | defer { |
| 543 | guard.release() |
| 544 | } |
| 545 | return unsafe { C.mysql_get_server_info(guard.conn).vstring() } |
| 546 | } |
| 547 | |
| 548 | // get_server_version returns an integer, representing the MySQL server |
| 549 | // version. The value has the format `XYYZZ` where `X` is the major version, |
| 550 | // `YY` is the release level (or minor version), and `ZZ` is the sub-version |
| 551 | // within the release level. For example, `8.0.24` is returned as `80024`. |
| 552 | pub fn (db &DB) get_server_version() u64 { |
| 553 | mut guard := db.acquire_connection_guard() or { return 0 } |
| 554 | defer { |
| 555 | guard.release() |
| 556 | } |
| 557 | return C.mysql_get_server_version(guard.conn) |
| 558 | } |
| 559 | |
| 560 | // dump_debug_info instructs the server to write debugging information |
| 561 | // to the error log. The connected user must have the `SUPER` privilege. |
| 562 | pub fn (mut db DB) dump_debug_info() !bool { |
| 563 | mut guard := db.acquire_connection_guard()! |
| 564 | defer { |
| 565 | guard.release() |
| 566 | } |
| 567 | if C.mysql_dump_debug_info(guard.conn) != 0 { |
| 568 | throw_mysql_error_for_conn(guard.conn)! |
| 569 | } |
| 570 | |
| 571 | return true |
| 572 | } |
| 573 | |
| 574 | // get_client_info returns client version information as a string. |
| 575 | pub fn get_client_info() string { |
| 576 | return unsafe { C.mysql_get_client_info().vstring() } |
| 577 | } |
| 578 | |
| 579 | // get_client_version returns the client version information as an integer. |
| 580 | pub fn get_client_version() u64 { |
| 581 | return C.mysql_get_client_version() |
| 582 | } |
| 583 | |
| 584 | // debug does a `DBUG_PUSH` with the given string. |
| 585 | // `debug()` uses the Fred Fish debug library. |
| 586 | // To use this function, you must compile the client library to support debugging. |
| 587 | // See https://dev.mysql.com/doc/c-api/8.0/en/mysql-debug.html |
| 588 | pub fn debug(debug string) { |
| 589 | C.mysql_debug(debug.str) |
| 590 | } |
| 591 | |
| 592 | // exec executes the `query` on the given `db`, and returns an array of all the results, or an error on failure |
| 593 | pub fn (db &DB) exec(query string) ![]Row { |
| 594 | mut guard := db.acquire_connection_guard()! |
| 595 | defer { |
| 596 | guard.release() |
| 597 | } |
| 598 | if C.mysql_query(guard.conn, query.str) != 0 { |
| 599 | throw_mysql_error_for_conn(guard.conn)! |
| 600 | } |
| 601 | |
| 602 | result := C.mysql_store_result(guard.conn) |
| 603 | if result == unsafe { nil } { |
| 604 | return []Row{} |
| 605 | } else { |
| 606 | return Result{result}.rows() |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | // exec_one executes the `query` on the given `db`, and returns either the first row from the result, if the query was successful, or an error |
| 611 | pub fn (db &DB) exec_one(query string) !Row { |
| 612 | mut guard := db.acquire_connection_guard()! |
| 613 | defer { |
| 614 | guard.release() |
| 615 | } |
| 616 | if C.mysql_query(guard.conn, query.str) != 0 { |
| 617 | throw_mysql_error_for_conn(guard.conn)! |
| 618 | } |
| 619 | |
| 620 | result := C.mysql_store_result(guard.conn) |
| 621 | |
| 622 | if result == unsafe { nil } { |
| 623 | throw_mysql_error_for_conn(guard.conn)! |
| 624 | } |
| 625 | row_vals := C.mysql_fetch_row(result) |
| 626 | num_cols := C.mysql_num_fields(result) |
| 627 | |
| 628 | if row_vals == unsafe { nil } { |
| 629 | return Row{} |
| 630 | } |
| 631 | |
| 632 | mut row := Row{} |
| 633 | for i in 0 .. num_cols { |
| 634 | if unsafe { row_vals[i] == nil } { |
| 635 | row.vals << '' |
| 636 | } else { |
| 637 | row.vals << mystring(unsafe { &u8(row_vals[i]) }) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | return row |
| 642 | } |
| 643 | |
| 644 | // exec_none executes the `query` on the given `db`, and returns the integer MySQL result code |
| 645 | // Use it, in case you don't expect any row results, but still want a result code. |
| 646 | // e.g. for queries like these: INSERT INTO ... VALUES (...) |
| 647 | pub fn (db &DB) exec_none(query string) int { |
| 648 | mut guard := db.acquire_connection_guard() or { return 1 } |
| 649 | defer { |
| 650 | guard.release() |
| 651 | } |
| 652 | C.mysql_query(guard.conn, query.str) |
| 653 | |
| 654 | return get_errno(guard.conn) |
| 655 | } |
| 656 | |
| 657 | // exec_param_many executes the `query` with parameters provided as `?`'s in the query |
| 658 | // It returns either the full result set, or an error on failure |
| 659 | pub fn (db &DB) exec_param_many(query string, params []string) ![]Row { |
| 660 | stmt := db.prepare(query)! |
| 661 | defer { |
| 662 | stmt.close() |
| 663 | } |
| 664 | rows := stmt.execute(params)! |
| 665 | return rows |
| 666 | } |
| 667 | |
| 668 | // exec_param executes the `query` with one parameter provided as an `?` in the query |
| 669 | // It returns either the full result set, or an error on failure |
| 670 | pub fn (db &DB) exec_param(query string, param string) ![]Row { |
| 671 | return db.exec_param_many(query, [param])! |
| 672 | } |
| 673 | |
| 674 | // exec_param2 executes the `query` with two parameters provided as `?` placeholders. |
| 675 | pub fn (db &DB) exec_param2(query string, param string, param2 string) ![]Row { |
| 676 | return db.exec_param_many(query, [param, param2])! |
| 677 | } |
| 678 | |
| 679 | // A StmtHandle is created through prepare, it will be bound |
| 680 | // to one DB connection and will become unusable if the connection |
| 681 | // is closed |
| 682 | pub struct StmtHandle { |
| 683 | stmt &C.MYSQL_STMT = &C.MYSQL_STMT(unsafe { nil }) |
| 684 | db DB |
| 685 | } |
| 686 | |
| 687 | // prepare takes in a query string, returning a StmtHandle |
| 688 | // that can then be used to execute the query as many times |
| 689 | // as needed, which must be closed manually by the user |
| 690 | // Placeholders are represented by `?` |
| 691 | pub fn (db &DB) prepare(query string) !StmtHandle { |
| 692 | mut guard := db.acquire_connection_guard()! |
| 693 | defer { |
| 694 | guard.release() |
| 695 | } |
| 696 | stmt := C.mysql_stmt_init(guard.conn) |
| 697 | if stmt == unsafe { nil } { |
| 698 | throw_mysql_error_for_conn(guard.conn)! |
| 699 | } |
| 700 | |
| 701 | mut code := C.mysql_stmt_prepare(stmt, query.str, query.len) |
| 702 | if code != 0 { |
| 703 | throw_mysql_stmt_error(stmt)! |
| 704 | } |
| 705 | |
| 706 | return StmtHandle{ |
| 707 | stmt: stmt |
| 708 | db: DB{ |
| 709 | conn: db.current_conn() |
| 710 | state: db.state |
| 711 | } |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | // execute takes in an array of params that will be bound to the statement, |
| 716 | // followed by it's execution |
| 717 | // Returns an array of Rows, which will be empty if nothing is returned |
| 718 | // from the query, or possibly an error value |
| 719 | pub fn (stmt &StmtHandle) execute(params []string) ![]Row { |
| 720 | mut guard := stmt.db.acquire_connection_guard()! |
| 721 | defer { |
| 722 | guard.release() |
| 723 | } |
| 724 | mut bind_params := []C.MYSQL_BIND{} |
| 725 | for param in params { |
| 726 | bind := C.MYSQL_BIND{ |
| 727 | buffer_type: mysql_type_string |
| 728 | buffer: param.str |
| 729 | buffer_length: u32(param.len) |
| 730 | length: 0 |
| 731 | is_null: 0 |
| 732 | } |
| 733 | bind_params << bind |
| 734 | } |
| 735 | |
| 736 | mut response := C.mysql_stmt_bind_param(stmt.stmt, unsafe { &C.MYSQL_BIND(bind_params.data) }) |
| 737 | if response == true { |
| 738 | throw_mysql_stmt_error(stmt.stmt)! |
| 739 | } |
| 740 | |
| 741 | mut code := C.mysql_stmt_execute(stmt.stmt) |
| 742 | if code != 0 { |
| 743 | throw_mysql_stmt_error(stmt.stmt)! |
| 744 | } |
| 745 | |
| 746 | query_metadata := C.mysql_stmt_result_metadata(stmt.stmt) |
| 747 | // If the query returns no metadata we have no data to return |
| 748 | // This happens in insert queries |
| 749 | if query_metadata == unsafe { nil } { |
| 750 | return []Row{} |
| 751 | } |
| 752 | num_cols := C.mysql_num_fields(query_metadata) |
| 753 | mut length := []u32{len: num_cols} |
| 754 | mut is_null := []bool{len: num_cols} |
| 755 | |
| 756 | mut binds := []C.MYSQL_BIND{} |
| 757 | for i in 0 .. num_cols { |
| 758 | bind := C.MYSQL_BIND{ |
| 759 | buffer_type: mysql_type_string |
| 760 | buffer: 0 |
| 761 | buffer_length: 0 |
| 762 | length: unsafe { &length[i] } |
| 763 | is_null: unsafe { &is_null[i] } |
| 764 | } |
| 765 | binds << bind |
| 766 | } |
| 767 | |
| 768 | mut rows := []Row{} |
| 769 | response = C.mysql_stmt_bind_result(stmt.stmt, unsafe { &C.MYSQL_BIND(binds.data) }) |
| 770 | for { |
| 771 | code = C.mysql_stmt_fetch(stmt.stmt) |
| 772 | if code == mysql_no_data { |
| 773 | break |
| 774 | } |
| 775 | lengths := length[0..num_cols].clone() |
| 776 | mut row := Row{} |
| 777 | for i in 0 .. num_cols { |
| 778 | l := lengths[i] |
| 779 | data := unsafe { malloc(l) } |
| 780 | binds[i].buffer = data |
| 781 | binds[i].buffer_length = l |
| 782 | code = C.mysql_stmt_fetch_column(stmt.stmt, unsafe { &binds[i] }, i, 0) |
| 783 | if *(binds[i].is_null) { |
| 784 | row.vals << '' |
| 785 | } else { |
| 786 | row.vals << unsafe { data.vstring() } |
| 787 | } |
| 788 | } |
| 789 | rows << row |
| 790 | } |
| 791 | return rows |
| 792 | } |
| 793 | |
| 794 | // close acts on a StmtHandle to close the mysql Stmt |
| 795 | // meaning it is no longer available for use |
| 796 | pub fn (stmt &StmtHandle) close() { |
| 797 | mut thread_guard := mysql_thread_guard() or { return } |
| 798 | defer { |
| 799 | thread_guard.release() |
| 800 | } |
| 801 | C.mysql_stmt_close(stmt.stmt) |
| 802 | } |
| 803 | |
| 804 | @[inline] |
| 805 | fn (db &DB) throw_mysql_error() ! { |
| 806 | conn := db.current_conn() |
| 807 | if isnil(conn) { |
| 808 | return error(mysql_no_connection_error_message) |
| 809 | } |
| 810 | return error_with_code(get_error_msg(conn), get_errno(conn)) |
| 811 | } |
| 812 | |
| 813 | @[inline] |
| 814 | fn throw_mysql_stmt_error(stmt &C.MYSQL_STMT) ! { |
| 815 | return error_with_code(get_stmt_error_msg(stmt), get_stmt_errno(stmt)) |
| 816 | } |
| 817 | |
| 818 | @[inline] |
| 819 | fn throw_mysql_error_for_conn(conn &C.MYSQL) ! { |
| 820 | return error_with_code(get_error_msg(conn), get_errno(conn)) |
| 821 | } |
| 822 | |
| 823 | @[inline] |
| 824 | fn mysql_thread_guard() !MySQLThreadGuard { |
| 825 | if C.mysql_thread_init() { |
| 826 | return error(mysql_thread_init_error_message) |
| 827 | } |
| 828 | return MySQLThreadGuard{ |
| 829 | active: true |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | @[inline] |
| 834 | fn (mut guard MySQLThreadGuard) release() { |
| 835 | if guard.active { |
| 836 | C.mysql_thread_end() |
| 837 | guard.active = false |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | @[inline] |
| 842 | fn (db &DB) current_conn() &C.MYSQL { |
| 843 | if !isnil(db.state) { |
| 844 | return db.state.conn |
| 845 | } |
| 846 | return db.conn |
| 847 | } |
| 848 | |
| 849 | fn (db &DB) acquire_connection_guard() !MySQLConnectionGuard { |
| 850 | if !isnil(db.state) { |
| 851 | db.state.mutex.@lock() |
| 852 | conn := db.state.conn |
| 853 | if isnil(conn) { |
| 854 | db.state.mutex.unlock() |
| 855 | return error(mysql_no_connection_error_message) |
| 856 | } |
| 857 | mut thread_guard := mysql_thread_guard() or { |
| 858 | db.state.mutex.unlock() |
| 859 | return err |
| 860 | } |
| 861 | return MySQLConnectionGuard{ |
| 862 | conn: conn |
| 863 | state: db.state |
| 864 | thread: thread_guard |
| 865 | } |
| 866 | } |
| 867 | if isnil(db.conn) { |
| 868 | return error(mysql_no_connection_error_message) |
| 869 | } |
| 870 | mut thread_guard := mysql_thread_guard()! |
| 871 | return MySQLConnectionGuard{ |
| 872 | conn: db.conn |
| 873 | thread: thread_guard |
| 874 | } |
| 875 | } |
| 876 | |
| 877 | @[inline] |
| 878 | fn (mut guard MySQLConnectionGuard) release() { |
| 879 | guard.thread.release() |
| 880 | if !isnil(guard.state) { |
| 881 | guard.state.mutex.unlock() |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | @[inline] |
| 886 | fn (db &DB) check_connection_is_established() ! { |
| 887 | if isnil(db.current_conn()) { |
| 888 | return error(mysql_no_connection_error_message) |
| 889 | } |
| 890 | } |
| 891 | |