mysqltcl(n)
π mysqltcl π
okay so bestie, welcome to mysqltcl, manual section n β the Tcl-to-MySQL glow-up you didn't know you needed. grab a snack, this one's a long read (we're doing it in parts), but it's so worth it. π
πΈ NAME πΈ
mysqltcl β MySQL server access commands for Tcl. literally that's the whole thing, no notes. π
β¨ SYNOPSIS β¨
here's the whole squad, showing up in order, no cap:
package require Tcl 8.4
package require mysqltcl 3.0
::mysql::connect ?option value...?
::mysql::use handle database
::mysql::sel handle sql-statement ?-list|-flatlist?
::mysql::fetch handle
::mysql::exec handle sql-statement
::mysql::query handle sql-select-statement
::mysql::endquery query-handle
::mysql::map handle binding-list script
::mysql::receive handle sql-statment binding-list script
::mysql::seek handle row-index
::mysql::col handle table-name option
::mysql::col handle table-name optionkist
::mysql::col handle ?option...?
::mysql::info handle option
::mysql::baseinfo option
::mysql::ping handle
::mysql::changeuser user password ?database?
::mysql::result handle option
::mysql::state handle ?-numeric?
::mysql::close ?handle?
::mysql::insertid handle
::mysql::escape ?handle? string
::mysql::autocommit handle boolean
::mysql::commit handle
::mysql::rollback handle
::mysql::nextresult handle
::mysql::moreresult handle
::mysql::warningcount handle
::mysql::isnull value
::mysql::newnull
::mysql::setserveroption handle option
::mysql::shutdown handle
::mysql::encoding handle ?encoding?
π¦ DESCRIPTION π¦
MySQLTcl is a whole collection of Tcl commands plus a Tcl global array, and together they hand you the keys to MySQL database servers. π
fun lore drop: MySQLTcl is nothing more than a patched version of a patched version of Hakan Soderstrom's patch of Tom Poindexter's Sybtcl. it's patches all the way down, bestie, and honestly? iconic. π
Mysqltcl is a binary Tcl library (extension) written in C, and it uses the official MySQL C-API directly. Almost all the Tcl commands here correspond to MySQL C-API functions. For the full deep-dive documentation, go read the official MySQL C-API manual. π
π MYSQLTCL COMMANDS π
π ::mysql::connect ?option value...?
Connect to a MySQL server. you get back a handle, and that handle is what you pass to all the other mysqltcl commands that use this connection. π«Ά
::mysql::connect raises a Tcl error if the connection fails. no silent flops here, she will tell you.
also, ::mysql::connect reads the options from the my.cnf file, group mysqltcl, first. go check the MySQL documentation chapter "options files" if you want the details. β¨
here are all the possible connection options, no skips:
-host hostnameβ the host where the server lives. the local host is used by default.-user userβ the user whose name is used for the connection. the current Unix user-name is used by default.-password passwordβ the password for the connection. if it's not there, the connection is only possible for users who have no password on the server.-db dbβ if this option is present,dbis used as the current database, so you don't even need to callmysql::use.-port portβ the port number for the TCP/IP connection, in case it's different from the default.-socket socketβ the socket or named pipe for the connection.-encoding encodingnameβ works similar to the-encodingoption infconfigure. it also supports the special encoding namebinary. with the-binaryoption, no converting happens at all when reading or writing to/from MySQL. if the option isn't set, the system encoding (seeutf-8) is used. please test all your inputs and outputs with another program to check that everything is the way you expect it. π if thebinaryoption is not used, the system proceduresTcl_ExternalToUtfDString(writing) andTcl_ExternalToUtf(reading) get used; with thebinaryoption, the functionsTcl_GetByteArrayFromObjandTcl_NewByteArrayObjget used instead. if you want to manipulate binary data, use-encoding binary. when handling texts, set the special encoding you want to use in your database. and consider what other systems access that database and what encoding they expect β it can be useful to use-encoding utf-8, which is the standard encoding in some linux distributions and newer systems.-compress booleanβ use the compression protocol. default isfalse.-odbc booleanβ the client is an ODBC client. this changes mysqld to be more ODBC-friendly. default isfalse.-noschema booleanβ don't allow thedb_name.tbl_name.col_namesyntax. this is for ODBC. it causes the parser to generate an error if you use that syntax, which is useful for trapping bugs in some ODBC programs. this changes mysqld to be more ODBC-friendly. default isfalse.-multistatement booleanβ tell the server that the client may send multiple-row-queries (separated by;). if this flag is not set, multiple-row-queries are disabled. default isfalse.-multiresult booleanβ tell the server that the client can handle multiple-result sets from multi-queries or stored procedures. this is automatically set ifCLIENT_MULTI_STATEMENTSis set.-localfiles booleanβ enableLOAD DATA LOCALhandling. default isfalse.-foundrows booleanβ return the number of found (matched) rows, not the number of affected rows. default isfalse.-interactive booleanβ allowinteractive_timeoutseconds (instead ofwait_timeoutseconds) of inactivity before closing the connection. the client's sessionwait_timeoutvariable will be set to the value of the sessioninteractive_timeoutvariable. default isfalse.-ssl booleanβ switch to SSL after handshake. default isfalse.-sslkey stringβ is the pathname to the key file. used if-sslis true.-sslcert stringβ is the pathname to the certificate file. used if-sslis true.-sslca stringβ is the pathname to the certificate authority file. used if-sslis true.-sslcapath stringβ is the pathname to a directory that contains trusted SSL CA certificates in pem format. used if-sslis true.-sslcipher stringβ is a list of allowable ciphers to use for SSL encryption. used if-sslis true.-reconnect booleanβ default isfalse.
ποΈ ::mysql::use handle database
Associate a connected handle with a particular database. handle has to be a valid handle you previously got from ::mysql::connect. mysql::use raises a Tcl error if the handle isn't valid, or if the database name you specified couldn't be used. π
fun fact, you can use mysqltcl without specifying the database β in that case you have to use explicit schema notation to specify the table in your sql. like:
::mysql::sel $handle {select * from uni.student}
and with the connection option -noschema you can prohibit that kind of syntax. π«
π ::mysql::sel handle sql-statement ?-list|-flatlist?
Send sql-statement to the server. that's the whole move. β¨
if sql-statement is a SELECT statement and you didn't pass -list or -flatlist, the command returns the number of rows returned as the result of the query. you can then grab those rows with ::mysql::fetch and/or ::mysql::map. these resulting rows are called the pending result. π
if sql-statement is a SELECT statement and you did pass -list or -flatlist, the command returns the full list of rows returned as the result of the query, in one of two possible formats:
-listβ generates a list of lists, where each element is a row of the result.-flatlistβ generates the concatenation of all rows in a single list, which is super useful for scanning with a singleforeach.
Example, watch this slay:
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS" -list
{1 Joe} {2 Phil} {3 John}
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS" -flatlist
{1 Joe 2 Phil 3 John}
note that both list syntaxes are faster than doing something like:
% ::mysql::sel $db "SELECT ID, NAME FROM FRIENDS"
% ::mysql::map $db {id name} {lappend result $id $name}
% set $result
{1 Joe 2 Phil 3 John}
if sql-statement is a valid MySQL statement but not a SELECT statement, the command returns -1 after executing the statement β or an empty string if -list or -flatlist was specified. there is no pending result in this case.
and in any case, ::mysql::sel implicitly cancels any previous result still pending for the handle. she's a clean-slate kind of girl. π
π₯ ::mysql::fetch handle
Returns the next row from the result set as a Tcl list. mysql::fetch raises a Tcl error if there's no pending result for handle. also, mysql::fetch was formerly named mysqlnext. glow-up complete. β¨
β‘ ::mysql::exec handle sql-statement
Send sql-statement, a MySQL non-SELECT statement, to the server. the handle must be in use (through ::mysql::connect and ::mysql::use).
::mysql::exec implicitly cancels any previous result pending for the handle.
if sql-statement is actually a valid MySQL SELECT statement, the statement does get executed, but the result is discarded. no Tcl error is generated. this amounts to a (potentially costly) no-op. π so please, use the ::mysql::sel command for SELECT statements.
::mysql::exec returns the number of affected rows (DELETE, UPDATE). in the case of a multiple statement, ::mysql::exec returns a list of number of affected rows.
π§ ::mysql::query handle sql-select-statement
Send sql-select-statement to the server. π
mysql::query allows you to send multiple nested queries on one handle (without needing to build a new handle or cache results). mysql::query returns a query handle, and that query handle can be used as a handle in commands like (mysql::fetch, ::mysql::map, mysql::seek, mysql::col, mysql::result). after the result is done processing, all queries must be freed with the ::mysql::endquery query-hanlde command. π
Example:
okay bestie, we're mid-flow, no recap, just vibes and commands π
set query1 [::mysql::query $db {SELECT ID, NAME FROM FRIENDS}\]
while {[set row [::mysql::fetch $query1]]!=""} {
set id [lindex $row 0]
set query2 [::mysql::query $db "SELECT ADDRESS FROM ADDRESS WHERE FRIENDID=$ID"]
::mysql::map $query2 address { puts "address = $address" }
::mysql::endquery $query2
}
::mysql::endquery $query1
Real talk though: like, usually you wanna use sql-joins and NOT do nested queries. The SQL-sever can optimize those joined queries for you, no cap. BUT β in some apps (think GUI-Forms π) where the results hang around for a long time, the inner query isn't even known ahead of time. So nested it is, iykyk.
π
::mysql::endquery
::mysql::endqueryquery-handle β frees the result memory after a::mysql::querycommand. π§Ή
Okay this one is not optional, bestie. You must invoke ::mysql::endquery after each mysqlquery or you're gonna have memory leaks, and leaks are NOT the vibe. See the mysqlquery command for the deets.
Using ::mysql::endquery on a db-handle will also free the memory (the pending result) left behind after a ::mysql::sel command. β¨
π¦ ::mysql::map
::mysql::maphandle binding-list script β iterates a script over the rows of the pending result.
So like, ::mysql::map might consume all the rows, or only some of them β either way, any rows left over can still be grabbed later with more ::mysql::fetch or ::mysql::map commands. Nothing goes to waste. πΈ
- handle has to be a handle with a pending result from a previous
::mysql::selcommand. - binding-list has to be a list of one or more variable names.
- script has to be a Tcl script. It can be empty, but usually it's got one or more commands in it, obviously.
::mysql::map processes one row at a time from the pending result. For each row, the column values get bound to the variables in the binding list, and then the script runs. π«
Binding is strictly positional. First variable in the binding list β first column of the row, and so on down the line. The variables get created in the current context (if they don't already exist). And here's a cute trick: a variable name starting with a hyphen is not bound β it's just a placeholder chilling in the binding list. If there are more columns than variables, the extra columns are simply ignored. π
::mysql::map is basically an ordinary foreach, but make it fashion. A foreach iterates over the elements of a list; ::mysql::map iterates over the rows of a pending result. In both cases the iteration is affected by the break and continue Tcl commands. And the binding list variables keep their last values after the command has completed. πΎ
A simple example follows. Assume $db is a handle in use.
::mysql::sel $db {
select lname, fname, area, phone from friends order by lname, fname
}
::mysql::map $db {ln fn - phone} {
if {$phone == {}} continue
puts [format "%16s %-8s %s" $ln $fn $phone]
}
So what's happening: the ::mysql::sel command gets and sorts all rows from table friends. Then ::mysql::map formats and prints the result in a way that's suitable for a phone list. π For demonstration purposes one of the columns (area) is not used. The script begins by skipping over rows which have no phone number, and then the second command in the script formats and prints values from the row. Slay.
Heads up bestie: ::mysql::map raises a Tcl error if there is no pending result for handle, or if binding-list contains more variables than there are columns in the pending result. π
β ::mysql::receive
::mysql::receivehandle sql-statment binding-list script β same energy as the command mysqtclmap, but it does not need a leading::mysql::selcommand. π
The main difference is that internally it uses the MySQL client library. This command uses mysql_use_result from the C-API, which does not store the result on the client β instead it tries to receive the rows directly from the server. There's also no client cache. π«ποΈ
This command can be faster than using ::mysql::sel, and with a very big resultset it will not overload the client machine. ποΈββοΈ
But listen: the script should process the result immediately, because it can block the table (or tables) for other clients. π
If performance matters, please test all the alternatives separately. You must consider two aspects: memory consumption and performance. Both. Periodt.
π ::mysql::seek
::mysql::seekhandle row-index β moves the current position among the rows in the pending result.
This may cause ::mysql::fetch and ::mysql::map to re-read rows, or to skip over rows. π
Row index 0 is the position just before the first row in the pending result; row index 1 is the position just before the second row, and so on. You may also specify a negative row index. Row index -1 is the position just before the last row; row index -2 is the position just before the second last row, and so on. π¦
An out-of-bounds row index will cause ::mysql::seek to set the new current position either just before the first row (if the index is too negative), or just after the last row (if the index exceeds the number of rows). This is not an error condition. We're chill about it.
::mysql::seek returns the number of rows that can be read sequentially from the new current position. It raises a Tcl error if there is no pending result for handle. π€
Portability note: the functionality of ::mysql::seek is frequently absent in other Tcl extensions for SQL. That's because the MySQL C-API client library offers its own result set caching functionality that other SQL-APIs lack. That increases the performance because all rows are received at once and the query does not block the server for other clients β on the other hand, you're working on cached data, which can use a lot of memory, and it's up to date only at the moment of the query, not at the moment of fetch. π Pick your fighter.
π ::mysql::col
::mysql::colhandle table-name option::mysql::colhandle table-name optionkist::mysql::colhandle ?option...?
Returns information about the columns of a table. π
- handle must be in use.
- table-name must be the name of a table β it may be a table name, or
-currentif there is a pending result. - One or more options control what information to return. Each option must be one of the following keywords. π
nameβ Return the name of a column.typeβ Return the type of a column; one of the stringsdecimal,tiny,short,long,float,double,null,timestamp,long long,int24,date,time,date time,year,new date,enum,set,tiny blob,medium blob,long blob,blob,var string, orstring. Note that a column of typecharwill returntiny, while they are represented equally. πlengthβ Return the length of a column in bytes.tableβ Return the name of the table in which this column occurs.non_nullβ Return the string"1"if the column is non-null; otherwise"0".prim_keyβ Return the string"1"if the column is part of the primary key; otherwise"0".numericβ Return the string"1"if the column is numeric; otherwise"0".decimalsβ Return the string"1"if the column is non-null; otherwise"0".
The three forms of this command generate their result in a particular way. π§
- If a single option is present the result is a simple list of values; one for each column.
- If the options are given in the form of an option list the result is a list of lists. Each sublist corresponds to a column and contains the information specified by the options.
- If several options are given, but not in a list, the result is also a list of lists. In this case each sublist corresponds to an option and contains one value for each column.
The following is a sample interactive session containing all forms of the ::mysql::col command and their results. The last command uses the -current option. It could alternatively specify the table name explicitly. β¨
%::mysql::col $db friends name
name lname area phone
% ::mysql::col $db friends {name type length}
{fname char 12} {lname char 20} {area char 5} {phone char 12}
% ::mysql::sel $db {select * from friends}
% ::mysql::col $db -current name type length
{fname lname area phone} {char char char char} {12 20 5 12}]
π ::mysql::info
::mysql::infohandle option β returns various database information depending on the option.
The option must be one of the following keywords. π
infoβ Return a String with information about the last operation."Records: 3 Duplicates: 0 Warnings: 0"by INSERT or"Rows matched: 40 Changed: 40 Warnings: 0"by UPDATE statements (read the manual formysql_infoin the MySQL C API documentation). πdatabasesβ Return a list of all database names known to the server. The handle must be connected.dbnameβ Return the name of the database with which the handle is associated. The handle must be in use.dbname?β Return the name of the database with which the handle is associated; an empty string if the handle is connected, but not in use.hostβ Return the name of the host to which the handle is connected. The handle must be connected.hostβ Return the name of the host to which the handle is connected; an empty string if the handle is not valid.tablesβ Return a list of all table names in the database with which the handle is associated. The handle must be in use.serverversionβ Returns the version number of the server as a string.serverversionidβ Returns the version number of the server as an integer.sqlstateβ Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.'00000'means "no error." The values are specified by ANSI SQL and ODBC. Note that not all MySQL errors are yet mapped to SQLSTATE's. The value'HY000'(general error) is used for unmapped errors. π¨stateβ Returns a character string containing information similar to that provided by themysqladmin statuscommand. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables. β±οΈ
π ::mysql::baseinfo option π
Your little no-handle-needed info desk, bestie. It returns information that do not need handle β no connection, no drama, just answers.
connectparametersβ returns all supported connecting options β¨clientversionβ returns the version of the underlying MYSQL C-API library
π¦ ::mysql::ping handle π¦
Checks whether the connection to the server is working. If it has gone down, an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Returns True if the server is alive. Vibe check passed, periodt. π
πΈ ::mysql::changeuser user password ?database? πΈ
Changes the user, and causes the database specified by database to become the default (current) database on the connection specified by MySQL. In subsequent queries, this database is the default for table references that do not include an explicit database specifier.
::mysql::changeuser fails unless the connected user can be authenticated, or if he doesn't have permission to use the database. In this case the user and database are not changed.
The database parameter may be set where there is no default database.
Raises an error if the operation is not successful. No silent Ls here. π
π ::mysql::result handle option π
Returns information about the pending result. Heads up: a result is pending until canceled by a ::mysql::exec command, even if no rows remain to be read. So it's still hanging around, living its main character life. option must be one of the following keywords.
colsβ returns the number of columns in the pending result. There must be a pending result.colsβ returns the number of columns in the pending result; an empty string if no result is pending.currentβ returns the current position in the pending result; a non-negative integer. This value can be used as row-index in the::mysql::seekcommand. An error is raised if there is no pending result.current?β as above, but returns an empty string if there is no pending result.rowsβ returns the number of rows that can be read sequentially from the current position in the pending result. There must be a pending result.rowsβ returns the number of rows that can be read sequentially from the current position in the pending result; an empty string if no result is pending.
And fr fr, the way thatcolsshows up twice androwsshows up twice? That's literally how the original manpage lists them, bestie. Not me editing anything, I'm just the messenger. π
[::mysql::result $db current] + [::mysql::result $db rows] always equals the total number of rows in the pending result. Math ate that. π₯
π§ ::mysql::state handle ?-numeric? π§
Returns the state of a handle as a string, or in numeric form. There is no requirement on handle; it may be any string. The return value is one of the following strings, or the corresponding numeric value if -numeric is specified. The states form a progression where each state builds on the previous β it's giving character arc. β¨
NOT_A_HANDLE(0) β the string supplied for handle is not a mysqltcl handle at all. Not even close, babe.UNCONNECTED(1) β the string supplied for handle is one of the possible mysqltcl handles, but it is not valid to any server.CONNECTED(2) β the handle is connected to a server, but not associated with a database.IN_USE(3) β the handle is connected and associated with a database, but there is no pending result.RESULT_PENDING(4) β the handle is connected, associated with a database, and there is a pending result.
π ::mysql::close ?handle? π
Closes the server connection associated with handle, causing it to go back to the unconnected state. Closes all connections if handle is omitted. Returns an empty string.
::mysql::close raises a Tcl error if a handle is specified which is not valid.
β ::mysql::insertid handle β
Returns the auto increment id of the last INSERT statement. The receipts of your newest row. π
π ::mysql::escape ?handle? string π
Returns the content of string, with all special characters escaped, so that it is suitable for use in an SQL statement. This is simpler (faster) than using a general regexp or string map.
If handle is specified, the C-API function mysql_real_escape_string is used. This is the recommended usage, because in this case the current character set is respected. Slay, encoding-aware queen. π
π ::mysql::autocommit handle boolean π
Sets autocommit mode on if mode is 1, off if mode is 0.
π«Ά ::mysql::commit handle π«Ά
Commits the current transaction. Sign, seal, done. β¨
π ::mysql::rollback handle π
Rollback the current transaction. Not me undoing everything β it never happened bestie.
π« ::mysql::nextresult handle π«
If more query results exist, mysql::nextresult() reads the next query results and returns the status back to application. Returns -1 if no result, or the number of rows in the result set.
π ::mysql::moreresult handle π
Returns true if more results exist from the currently executed query, and the application must call mysql::result to fetch the results.
πΈ ::mysql::warningcount handle πΈ
Returns the number of warnings generated during execution of the previous SQL statement. The subtle side-eye count. π
π§ ::mysql::isnull value π§
Null handling is a known problem with Tcl, especially with DB interaction. The mysql "varchar" type has two valid blank values, NULL and an empty string. This is where the problem arises; Tcl is not able to differentiate between the two because of the way it handles strings.
Mysql has new internal Tcl type for null that string representation is stored in global array mysqltcl(nullvalue) and as default empty string. mysql::isnull can be used for safe check for null value.
Warning: mysql::isnull works only reliable if there are no type conversation on returned rows. Consider row is always Tcl list even when there are only one column in the row.
set row [::mysql::next $handle]
if {[mysql::isnull [lindex $row 1]]} {
puts "2. column of $row is null"
}
if {[mysql::isnull $row]} {
puts "this does not work, because of type conversation list to string"
}
π₯ ::mysql::newnull π₯
create new null object. It can be used to simulate returned row contents.
π ::mysql::setserveroption handle option π
there are only 2 options now: -multi_statment_on and -multi_statment_off
π ::mysql::shutdown handle π
Asks the database server to shut down. The connected user must have SHUTDOWN privileges. Big power, big responsibility. π
β¨ ::mysql::encoding handle ?encoding? β¨
Ask or change a encoding of connection. There are special encoding "binary" for binary data transfers.
π STATUS INFORMATION π
Mysqltcl creates and maintains a Tcl global array to provide status information. Its name is mysqlstatus.
Mysqlstatus elements:
codeβ a numeric conflict code set after every mysqltcl command. Zero means no conflict; non-zero means some kind of conflict. All conflicts also generate a Tcl error.
All MySQL server conflicts set mysqlstatus(code) to the numeric code of the MySQL error.
Any other conflict sets mysqlstatus(code) to -1.
commandβ the last failing mysqltcl command. Not updated for successful commands. Only the Ls get logged, basically. πmessageβ message string for the last conflict detected. The same string is returned as the result of the failing mysqltcl command. Not updated for successful commands.nullvalueβ the string to use in query results to represent the SQL null value. The empty string is used initially. You may set it to another value.
π«Ά Backward compatibility π«Ά
Up from version 3.0 all mysql commands are declared in ::mysql namespace. All names for example mysqlconnect are also aviable but deprecated. All old commands have the name pattern mysql{name} and the most of them are now mysql::{name}. The exception is mysqlnext, which was renamed to mysql::fetch.
π BUGS & POSSIBLE MISFEATURES π
Deleting any of the mysqltcl commands closes all connections. Yeah. All of them. Chaos behavior, no cap. π
π AUTHORS π
- Tobias Ritzau
- Paolo Brutti
- Artur Trzewik (mail@xdobry.de) β active maintainer
MySQLTcl is derived from a patch of msql by Hakan Soderstrom, Soderstrom Programvaruverkstad, S-12242 Enskede, Sweden. msql is derived from Sybtcl by Tom Poindexter. There are many contributors and bug reporter that are not mentioned. If you have contributed to mysqltcl and wants to be on the list contact Artur Trzewik.
and that's the whole page, bestie π«Ά this is mysqltcl(n), version 3.0 β go forth and query responsibly πβ¨
π¦ where this page comes from
- fedora 43: tcl-mysqltcl 3.052-27.fc43 Β· MIT
- fedora 43: tcl-mysqltcl 3.052-28.fc43 Β· MIT
- fedora 44: tcl-mysqltcl 3.052-28.fc44 Β· MIT
- fedora 44: tcl-mysqltcl 3.052-29.fc44 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms