0

0

Customized MySQL LOAD DATA LOCAL INFILE handlers with libmys_MySQL

php中文网

php中文网

发布时间:2016-06-01 13:16:35

|

1103人浏览过

|

来源于php中文网

原创

one of the lesser known (and used) mysql client api calls seems to bemysql_set_local_infile_handler()which allows to override the defaultload data local infilebehavior on the client side, allowing to import data in text form, e.g. in csv format, from other sources than actual local files. i searched for some more detailed info than the reference page in the manual for this, or some example code using this mechanism, but couldn't really find any, so this post is going to try to close this gap.

This allows for things similar to PostgreSQL'sCOPY FROM STDINmechanism in a way, there is a substantial difference between the two DMBS's approaches here: withCOPY FROM STDINan application enters a sort of push mode where text data can be sent using specific library functions the mysql client library API implements a pull model instead where the client library takes control and requests application data via specific callbacks that need to be registered up front withmysql_set_local_infile_handler()before executing aLOAD DATA INFILEquery.

Setting things up

mysql_set_local_infile_handler()expects four callback function pointers, one for initialization, one for fetching a single line of text, one for cleaning up, and an error handler. It also expects a mysql connection handle as first parameter, and a pointer to user defined per-connection data that will be passed to the init function later.

This data pointer may point to data common to all invocations of the custom handler. In the example code I'm just using it to point to a descriptive name.

Call flow

The call flow for the various infile callbacks triggered while processing aLOAD DATA INFILEquery looks like this, with the upper part being the regular case:init()being called once, thenread()repeatedly until it can't provide any more data, and finally theend()callback. The lower paths show the error handling case that is triggered byinit()returning a non-zero value, or byread()returning a negative lenght to indicate an error. In this case theerror()callback is called, followed by a call toend().

+------<------+	| |	|	|> 0	|+--------+|+--------+ |+-------+| init() |-+- == 0 -+->| read() |-+- == 0 ---------->| end() |+--------+ | +--------+ | ^+-------+		|!= 0 < 0|		| |	| +---------+ | +------------>---------+-->| error() |-+	+---------+

init()

int local_infile_init(void **instance_data, const char *filename, void *handler_data)

The init function is called first whenever aLOAD DATA LOCALquery is issued. It receives a pointer-pointer where it can store the pointer to local state data to be used for thisLOADoperation, the filename used in theLOADstatement, and the per-connection user data pointer that was passed intomysql_set_local_infile_handler()earlier.

In the example code below I'm keeping track of line numbers via the user data pointer.

read()

int local_infile_read(void *instance_data, char *buf, unsigned int buf_len)

Theread()function gets called repeatedly until no more data is available. It receives the instance data pointer you stored ininit(), a pointer to a buffer to storeINFILE data into, and the max. amount of bytes that can be put into this buffer.

You don't have to pass a complete single line of data at a time, you can pass multiple input lines, or just part of a line, you just have to make sure not to exceed the buffer size. Data passed from theread()handler will simply be transfered over to the server, and all parsing, including splitting it into lines, happens on that side.

Theread()handler shall return the number of bytes that have been put into the buffer. A value of zero indicates that all data has been read and thatread()should not be called again. A negative value indicates an error and will also terminate reading. There is no way to generate warnings here, just errors.

Kacha
Kacha

KaCha是一款革命性的AI写真工具,用AI技术将照片变成杰作!

下载

error()

int local_infile_error(void *instance_data, char *error_msg, unsigned int error_msg_len)

Theerror()handler is called after returning a non-zero value frominit()or a negative number fromread(). It receives the data pointer you've set up ininit()and a buffer pointer plus length to write an error message to. A numeric error code can be passed as the return value.

There's no direct way to set error number and error code when hitting an error ininit()orread()right away. If you need to pass on something descriptive from where the error happened to theerror()handler you have to take care of doing so using the data pointer (or via global variables).

void local_infile_end(void *instance_data)

Theend()handler is called afterread()has returned a zero length to indicate "end of data", or right after the error handler. Its sole purpose is to free any resources that you may have allocated ininit().

Summary

While local infile handlers allow for some interesting alternatives to simple client side local file imports the current implementation feels a bit complicated and not like a good fit for applications that want to avoid the SQL parsing overhead on bulk imports, but want / need to drive the process instead of passing control to the client library.

To summarize this in an itemized list:

  • Pull model works for reading data from a different stream than a simple local file, but not so much for applications that just want to avoid the SQL parsing overhead (and its synchronous nature) on importing bulk data, but are a better match for a push model like the one the PostgreSQL PQ library is using
  • No insight into theLOAD DATAstatement or the related table / column meta data apart of the file name parameter
  • No flow control in the protocol beyond what TCP provides. There's especially no way to keep the connection alive if the input stream stalls for longer thannet_read_timeout
  • Error handling: I'd personally prefer the more direct way error handling is done in the UDF (User Defined Functions) API on the server side where all callbacks that may want to report an error can do so via an extra error message buffer passed as a parameter right away, but it is probably way too late to complain about this some ten years after the fact ...

Protocol wise the PostgreSQL and MySQL implementations are not that different though, so maybe an alternative call interface similar to thePQputCopyData()/PQputCopyEnd()approach inlibpqtolibmysqlclientcould be a nice addition to support both the push and pull approaches. ( ... to be continued ...)

Example

The following example code can be compiled using

gcc `mysql_config --cflags` infile_handler.c -o infile_handler `mysql_config --libs`

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

43

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

35

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

204

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

8

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号