⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mapi.mx

📁 这个是内存数据库的客户端
💻 MX
📖 第 1 页 / 共 5 页
字号:
@' The contents of this file are subject to the MonetDB Public License@' Version 1.1 (the "License"); you may not use this file except in@' compliance with the License. You may obtain a copy of the License at@' http://monetdb.cwi.nl/Legal/MonetDBLicense-1.1.html@'@' Software distributed under the License is distributed on an "AS IS"@' basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the@' License for the specific language governing rights and limitations@' under the License.@'@' The Original Code is the MonetDB Database System.@'@' The Initial Developer of the Original Code is CWI.@' Portions created by CWI are Copyright (C) 1997-2007 CWI.@' All Rights Reserved.@f Mapi@a M.L. Kersten, K.S. Mullender@v 2.0@* The MonetDB Programming Interface@+ The Mapi LibraryThe easiest way to extend the functionality of MonetDB is to constructan independent application, which communicates with a running serverusing a database driver with a simple API and a textual protocol.  Theeffectiveness of such an approach has been demonstrated by the wideuse of database API implementations, such as Perl DBI, PHP, ODBC,...@menu* An Example::* Command Summary::* Library Synopsis::* Mapi Function Reference::@end menu@node An Example, Command Summary, The Mapi Library, The Mapi Library@- Sample MAPI ApplicationThe database driver implementation given in this document focuses ondeveloping applications in C/C++. The command collection has beenchosen to align with common practice, i.e. queries follow a prepare,execute, and fetch_row paradigm. The output is considered a regulartable. An example of a mini application below illustrates the mainoperations.@example@verbatim#include <Mapi.h>#include <stdio.h>#define die(dbh,hdl) (hdl?mapi_explain_query(hdl,stderr):		\                          dbh?mapi_explain(dbh,stderr):			\                              fprintf(stderr,"command failed\n"),	\                      exit(-1))int main(int argc, char **argv){    Mapi dbh;    MapiHdl hdl = NULL;    dbh = mapi_connect("localhost", 50000, "monetdb", "monetdb", "sql", NULL);    if (mapi_error(dbh))        die(dbh, hdl);    if ((hdl = mapi_query(dbh, "create table emp(name varchar(20), age int)")) == NULL        || mapi_error(dbh) != MOK)        die(dbh, hdl);    if (mapi_close_handle(hdl) != MOK)        die(dbh, hdl);    if ((hdl = mapi_query(dbh, "insert into emp values('John', 23)")) == NULL        || mapi_error(dbh) != MOK)        die(dbh, hdl);    mapi_close_handle(hdl);    if (mapi_error(dbh) != MOK)        die(dbh, hdl);    if ((hdl = mapi_query(dbh, "insert into emp values('Mary', 22)")) == NULL        || mapi_error(dbh) != MOK)        die(dbh, hdl);    mapi_close_handle(hdl);    if (mapi_error(dbh) != MOK)        die(dbh, hdl);    if ((hdl = mapi_query(dbh, "select * from emp")) == NULL        || mapi_error(dbh) != MOK)        die(dbh, hdl);    while (mapi_fetch_row(hdl)) {        char *nme = mapi_fetch_field(hdl, 0);        char *age = mapi_fetch_field(hdl, 1);        printf("%s is %s\n", nme, age);    }    if (mapi_error(dbh) != MOK)        die(dbh, hdl);    mapi_close_handle(hdl);    if (mapi_error(dbh) != MOK)        die(dbh, hdl);    mapi_destroy(dbh);    return 0;}@end verbatim@end exampleThe @code{mapi_connect()} operation establishes a communication channel witha running server.The query language interface is either "sql", "mil" or "xquery".Errors on the interaction can be captured using @code{mapi_error()},possibly followed by a request to dump a short error messageexplanation on a standard file location. It has been abstracted awayin a macro.Provided we can establish a connection, the interaction proceeds as inmany similar application development packages. Queries are shipped forexecution using @code{mapi_query()} and an answer table can be consumed onerow at a time. In many cases these functions suffice.The Mapi interface provides caching of rows at the client side.@code{mapi_query()} will load tuples into the cache, after which they can beread repeatedly using @code{mapi_fetch_row()} or directly accessed(@code{mapi_seek_row()}). This facility is particularly handy when small,but stable query results are repeatedly used in the client program.To ease communication between application code and the cache entries,the user can bind the C-variables both for input and output to thequery parameters, and output columns, respectively.  The queryparameters are indicated by '?' and may appear anywhere in the querytemplate.The Mapi library expects complete lines from the server as answers toquery actions. Incomplete lines leads to Mapi waiting forever on theserver. Thus formatted printing is discouraged in favor of tabularprinting as offered by the @code{table.print()} commands.The following action is needed to get a working program.Compilation of the application relies on the @emph{monetdb-config}program shipped with the distribution.It localizes the include files and library directories.Once properly installed, the application can be compiled and linked asfollows:@example@verbatimcc sample.c `monetdb-clients-config --cflags --libs` -lMapi -o sample@end verbatim@end exampleThe compilation on Windows is slightly more complicated. It requiresmore attention towards the location of the include files and libraries.@node Command Summary, Library Synopsis, An Example, The Mapi Library@- Command SummaryThe quick reference guide to the Mapi library is given below.  Moredetails on their constraints and defaults are given in the nextsection.@multitable @columnfractions 0.25 0.75@item mapi_bind()	@tab	Bind string C-variable to a field@item mapi_bind_numeric()	@tab Bind numeric C-variable to field@item mapi_bind_var()	@tab	Bind typed C-variable to a field@item mapi_cache_freeup()	@tab Forcefully shuffle fraction for cache refreshment@item mapi_cache_limit()	@tab Set the tuple cache limit@item mapi_cache_shuffle()	@tab Set shuffle fraction for cache refreshment@item mapi_clear_bindings()	@tab Clear all field bindings@item mapi_clear_params()	@tab Clear all parameter bindings@item mapi_close_handle()	@tab	Close query handle and free resources@item mapi_connect()	@tab	Connect to a Mserver @item mapi_connect_ssl()	@tab Connect to a Mserver using Secure Socket Layer (SSL)@item mapi_destroy()	@tab	Free handle resources@item mapi_disconnect()	@tab Disconnect from server@item mapi_error()	@tab	Test for error occurrence@item mapi_execute()	@tab	Execute a query@item mapi_execute_array()	@tab Execute a query using string arguments@item mapi_explain()	@tab	Display error message and context on stream@item mapi_explain_query()	@tab	Display error message and context on stream@item mapi_fetch_all_rows()	@tab	Fetch all answers from server into cache@item mapi_fetch_field()	@tab Fetch a field from the current row@item mapi_fetch_field_array()	@tab Fetch all fields from the current row@item mapi_fetch_line()	@tab	Retrieve the next line@item mapi_fetch_reset()	@tab	Set the cache reader to the beginning@item mapi_fetch_row()	@tab	Fetch row of values@item mapi_finish()	@tab	Terminate the current query@item mapi_get_dbname()	@tab	Database being served@item mapi_get_field_count()	@tab Number of fields in current row@item mapi_get_host()	@tab	Host name of server@item mapi_get_language()	@tab Query language name@item mapi_get_mapi_version()	@tab Mapi version name@item mapi_get_monet_versionId()	@tab MonetDB version identifier@item mapi_get_monet_version()	@tab MonetDB version name@item mapi_get_motd()	@tab	Get server welcome message@item mapi_get_row_count()	@tab	Number of rows in cache or -1@item mapi_get_trace()	@tab	Get trace flag@item mapi_get_user()	@tab	Current user name@item mapi_next_result()	@tab	Go to next result set@item mapi_needmore()	@tab	Return whether more data is needed@item mapi_ping()	@tab	Test server for accessibility@item mapi_prepare()	@tab	Prepare a query for execution@item mapi_prepare_array()	@tab	Prepare a query for execution using arguments@item mapi_query()	@tab	Send a query for execution@item mapi_query_array()	@tab Send a query for execution with arguments@item mapi_query_handle()	@tab	Send a query for execution@item mapi_quick_query_array()	@tab Send a query for execution with arguments@item mapi_quick_query()	@tab	Send a query for execution@item mapi_quick_response()	@tab	Quick pass response to stream@item mapi_quote()	@tab Escape characters@item mapi_reconnect()	@tab Reconnect with a clean session context@item mapi_rows_affected()	@tab Obtain number of rows changed@item mapi_seek_row()	@tab	Move row reader to specific location in cache@item mapi_setAutocommit()	@tab	Set auto-commit flag@item mapi_stream_query()	@tab Send query and prepare for reading tuple stream@item mapi_table()	@tab	Get current table name@item mapi_timeout()	@tab	Set timeout for long-running queries[TODO]@item mapi_output()	@tab	Set output format @item mapi_stream_into()	@tab	Stream document into server @item mapi_profile()	@tab	Set profile flag@item mapi_trace()	@tab	Set trace flag@item mapi_trace_log()	@tab Keep log of interaction@item mapi_virtual_result()	@tab Submit a virtual result set@item mapi_unquote()	@tab	remove escaped characters@end multitable@node Library Synopsis, Mapi Function Reference, Command Summary, The Mapi Library@- Mapi LibraryThe routines to build a MonetDB application are grouped in the libraryMonetDB Programming Interface, or shorthand Mapi.The protocol information is stored in a Mapi interface descriptor(mid).  This descriptor can be used to ship queries, which return aMapiHdl to represent the query answer.  The application can set upseveral channels with the same or a different Mserver. It is theprogrammer's responsibility not to mix the descriptors in retrievingthe results.The application may be multi-threaded as long as the user respects theindividual connections represented by the database handlers.The interface assumes a cautious user, who understands and hasexperience with the query or programming language model. It should also beclear that references returned by the API point directly into theadministrative structures of Mapi.  This means that they are validonly for a short period, mostly between successive @code{mapi_fetch_row()}commands. It also means that it the values are to retained, they haveto be copied.  A defensive programming style is advised.Upon an error, the routines @code{mapi_explain()} and @code{mapi_explain_query()}give information about the context of the failed call, including theexpression shipped and any response received.  The side-effect isclearing the error status.@- Error MessageAlmost every call can fail since the connection with the databaseserver can fail at any time.  Functions that return a handle (either@code{Mapi} or @code{MapiHdl}) may return NULL on failure, or they may return thehandle with the error flag set.  If the function returns a non-NULLhandle, always check for errors with mapi_error.Functions that return MapiMsg indicate success and failure with thefollowing codes.@multitable @columnfractions 0.15 0.7@item MOK  @tab No error @item MERROR  @tab Mapi internal error.@item MTIMEOUT  @tab Error communicating with the server.@end multitableWhen these functions return MERROR or MTIMEOUT, an explanation of theerror can be had by calling one of the functions @code{mapi_error_str()},@code{mapi_explain()}, or @code{mapi_explain_query()}.To check for error messages from the server, call @code{mapi_result_error()}.This function returns NULL if there was no error, or the error messageif there was.  A user-friendly message can be printed using@code{map_explain_result()}.  Typical usage is:@verbatimdo {    if ((error = mapi_result_error(hdl)) != NULL)        mapi_explain_result(hdl, stderr);    while ((line = mapi_fetch_line(hdl)) != NULL)        /* use output */;} while (mapi_next_result(hdl) == 1);@end verbatim@node Mapi Function Reference, The Perl Library, Library Synopsis, The Mapi Library@- Mapi Function Reference@- Connecting and Disconnecting@itemize@item Mapi mapi_connect(const char *host, int port, const char *username, const char *password, const char *lang, const char *dbname)Setup a connection with a Mserver at a @emph{host}:@emph{port} and loginwith @emph{username} and @emph{password}. If host == NULL, the localhost is accessed.  If host starts with a '/' and the system supports it,host is actually the name of a UNIX domain socket, and port is ignored.If port == 0, a default port is used.  If username == NULL,the username of the owner of the client applicationcontaining the Mapi code is used.  If password == NULL, the passwordis omitted.  The preferred query language is any of@verb{ { }sql,mil,mal,xquery @verb{ } }.  On success, the function returns apointer to a structure with administration about the connection.@item Mapi mapi_connect_ssl(const char *host, int port, const char *username, const char *password, const char *lang, const char *dbname)Setup a connection with a Mserver at a @emph{host}:@emph{port} and loginwith @emph{username} and @emph{password}. The connection is made usingthe Secure Socket Layer (SSL) and hence all data transfers to and fromthe server are encrypted. The parameters are the same as in@code{mapi_connect()}.@item MapiMsg mapi_disconnect(Mapi mid)Terminate the session described by @emph{mid}.  The only possible usesof the handle after this call is @emph{mapi_destroy()} and @code{mapi_reconnect()}.Other uses lead to failure.@item MapiMsg mapi_destroy(Mapi mid)Terminate the session described by @emph{ mid} if not already done so,and free all resources. The handle cannot be used anymore.@item MapiMsg mapi_reconnect(Mapi mid)Close the current channel (if still open) and re-establish a freshconnection. This will remove all global session variables.@item MapiMsg mapi_ping(Mapi mid)Test availability of the server. Returns zero upon success.@end itemize@- Sending Queries@itemize@item MapiHdl mapi_query(Mapi mid, const char *Command)Send the Command to the database server represented by mid.  Thisfunction returns a query handle with which the results of the querycan be retrieved.  The handle should be closed with@code{mapi_close_handle()}.  The command response is buffered forconsumption, c.f. mapi\_fetch\_row().@item MapiMsg mapi_query_handle(MapiHdl hdl, const char *Command)Send the Command to the database server represented by hdl, reusingthe handle from a previous query.  If Command is zero it takes thelast query string kept around.  The command response is buffered forconsumption, e.g. @code{mapi_fetch_row()}.@item MapiHdl mapi_query_array(Mapi mid, const char *Command, char **argv)Send the Command to the database server replacing the placeholders (?) by the string arguments presented.@item MapiHdl mapi_quick_query(Mapi mid, const char *Command, FILE *fd)Similar to @code{mapi_query()}, except that the response of the server is copiedimmediately to the file indicated.@item MapiHdl mapi_quick_query_array(Mapi mid, const char *Command, char **argv, FILE *fd)Similar to @code{mapi_query_array()}, except that the response of the serveris not analyzed, but shipped immediately to the file indicated.@item MapiHdl mapi_stream_query(Mapi mid, const char *Command, int windowsize)Send the request for processing and fetch a limited number of tuples(determined by the window size) to assess any erroneous situation.Thereafter, prepare for continual reading of tuples from the stream,until an error occurs. Each time a tuple arrives, the cache is shiftedone.@item MapiHdl mapi_prepare(Mapi mid, const char *Command)Move the query to a newly allocated query handle (which is returned).Possibly interact with the back-end to prepare the query forexecution.@item MapiMsg mapi_execute(MapiHdl hdl)Ship a previously prepared command to the backend for execution. Asingle answer is pre-fetched to detect any runtime error. MOK isreturned upon success.@item MapiMsg mapi_execute_array(MapiHdl hdl, char **argv)Similar to mapi\_execute but replacing the placeholders for the stringvalues provided.@item MapiMsg mapi_finish(MapiHdl hdl)Terminate a query.  This routine is used in the rare cases thatconsumption of the tuple stream produced should be prematurelyterminated. It is automatically called when a new query using the samequery handle is shipped to the database and when the query handle isclosed with @code{mapi_close_handle()}.@item MapiMsg mapi_virtual_result(MapiHdl hdl, int columns, const char **columnnames, const char **columntypes, const int *columnlengths, int tuplecount, const char ***tuples)Submit a table of results to the library that can then subsequently beaccessed as if it came from the server.columns is the number of columns of the result set and must be greaterthan zero.columnnames is a list of pointers to strings giving the names of theindividual columns.  Each pointer may be NULL and columnnames may beNULL if there are no names.tuplecount is the length (number of rows) of the result set.  Iftuplecount is less than zero, the number of rows is determined by a NULLpointer in the list of tuples pointers.tuples is a list of pointers to row values.  Each row value is a list ofpointers to strings giving the individual results.  If one of thesepointers is NULL it indicates a NULL/nil value.@end itemize@- Getting Results@itemize@item int mapi_get_field_count(Mapi mid)Return the number of fields in the current row.@item int mapi_get_row_count(Mapi mid)If possible, return the number of rows in the last select call.  A -1is returned if this information is not available.@item int mapi_rows_affected(MapiHdl hdl)Return the number of rows affected by a database update commandsuch as SQL's INSERT/DELETE/UPDATE statements.@item int mapi_fetch_row(MapiHdl hdl)Retrieve a row from the server.  The text retrieved is kept around in

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -