您的位置:首页 > 数据库 > MySQL

浅谈MySQL load data local infile细节 -- 从源码层面

2014-03-23 21:01 573 查看
相信大伙对mysql的load data local infile并不陌生,今天来巩固一下这里面隐藏的一些细节,对于想自己动手开发一个mysql客户端有哪些点需要注意的呢?

首先,了解一下流程:



3个点:

1、Is '<path>/<filename>' exists?对于客户端来说,在文件发送前是先检查一下文件是否存在;

2、filename前建议加上绝对路径;

3、空包,表示命令已执行完毕。

接下来,一起来学习下官方源码(版本5.5.36)是如何实现该流程?由于篇幅关系,只贴出关键部分,其他读者自行查阅源码。

首先,看看客户端的核心实现,源码在libmysql\libmysql.c的handle_local_infile函数:

my_bool handle_local_infile(MYSQL *mysql, const char *net_filename)
{
/* initialize local infile (open file, usually) */
((*options->local_infile_init)(&li_ptr, net_filename,
options->local_infile_userdata));

/* read blocks of data from local infile callback */
while ((readcount =
(*options->local_infile_read)(li_ptr, buf,
packet_length)) > 0);

/* Send empty packet to mark end of file */
(my_net_write(net, (const uchar*) "", 0))
}


接下来,看看服务端的核心实现,源码在sql\sql_load.cc的mysql_load函数:

int mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list,
List<Item> &fields_vars, List<Item> &set_fields,
List<Item> &set_values,
enum enum_duplicates handle_duplicates, bool ignore,
bool read_file_from_client)
{
net_request_file(&thd->net,ex->file_name);

// 接收客户端发过来的文件内容
while (!read_info.next_line())
;

/* ok to client sent only after binlog write and engine commit */
my_ok(thd, info.copied + info.deleted, 0L, name);
}

bool net_request_file(NET* net, const char* fname)
{
DBUG_ENTER("net_request_file");
DBUG_RETURN(net_write_command(net, 251, (uchar*) fname, strlen(fname),
(uchar*) "", 0)); // 251即上图的0xfb
}


以上就是今天要聊的小细节,希望对大家有用,祝玩得开心!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: