SlideShare uma empresa Scribd logo
1 de 24
Writing MySQL
User-Defined Functions
Welcome!
●      @rolandbouman
●      roland.bouman@gmail.com
●      http://rpbouman.blogspot.com/
●   Ex-MySQL AB, Ex-Sun Microsystems
●   Currently at http://www.pentaho.com/
Different kinds of MySQL Functions
 ●   Built-in functions (and operators)
     –   Native code part of the server binaries
 ●   SQL Stored functions
     –   SQL/PSM code stored in the database
     CREATE FUNCTION lightspeed()
     RETURNS INT UNSIGNED
     BEGIN
       RETURN 299792458;
     END;



 ●   User-defined functions (UDF's)
     –   Native code stored in an external binary library
     CREATE FUNCTION lightspeed
     RETURNS INTEGER
     SONAME 'lightspeed.so';
MySQL Function Kinds Comparison
                   Built-in            UDF                 Stored routine
language           C/C++               C/C++*              SQL/PSM
execution          natively compiled   natively compiled   interpreted
performance        very good           good                not that good
user-defined       no                  yes                 yes
installation       NA                  CREATE stmt         CREATE stmt
deployment         NA                  binary library      schema object
namespace          global              global              schema
grant-able         no                  no                  yes
SQL capabilities   no                  no*                 yes
Data types         internal            internal and C/C++ SQL data types
Charset support    yes*                no                  yes
argumentlist       flexible*           flexible            fixed number & type
aggregates         yes*                yes                 no
Quick and dirty example (1/2)
●   Write C/C++ code:
char lightspeed_init(){ return 0; }
long long lightspeed(){ return 299792458; }

●   Compile to a shared library:
shell$ gcc -shared -o lightspeed.so lightspeed.c

●   Move library to plugin dir:
mysql> SHOW VARIABLES LIKE 'plugin_dir';
+---------------+------------------------------+
| Variable_name | Value                        |
+---------------+------------------------------+
| plugin_dir    | /home/mysql/mysql/lib/plugin |
+---------------+------------------------------+


shell$ mv lightspeed.so /home/mysql/mysql/lib/plugin
Quick and dirty example (2/2)
●   Register the function in MySQL
mysql> CREATE FUNCTION lightspeed
    -> RETURNS INTEGER SONAME 'lightspeed.so';

●   Verify:
mysql> SELECT * FROM mysql.func;
+------------+-----+---------------+----------+
| name       | ret | dl            | type     |
+------------+-----+---------------+----------+
| lightspeed |   2 | lightspeed.so | function |
+------------+-----+---------------+----------+
●   Run:
mysql> SELECT lightspeed();
+--------- ----+
| lightspeed() |
+--------------+
|    299792458 |
+--------------+
UDF implementation functions
●   General UDF Implementation functions
    –   Init function
    –   Row-level function
    –   De-init function

    xxx_init()




        row?            xxx()




    xxx_deinit()
UDF implementation functions
●   Aggregate UDF Implementation functions
    –   clear function
    –   add function

    xxx_init()

                                   xxx()


     start group?   xxx_clear()   xxx_add()   end group?




    xxx_deinit()
The init function
●   Signature:
    my_bool xxx_init(
       UDF_INIT *initid,
       UDF_ARGS *args,
       char *message
    );
●   Set default properties
    –   of the return value
    –   of the arguments
●   Validate arguments
●   Allocate resources
●   Signal an error
    –   Return 1 to signal an error
    –   Copy error message to *message
The de-init function
●   Signature:
    void xxx_deinit(UDF_INIT *initid);
●   De-allocate any resources
The row-level function
●   Returns the value to the caller
    –   INTEGER type (SQL: bigint):
    long long xxx(
    –
       UDF_INIT *initid,
    – UDF_ARGS *args,
       my_bool *is_null,
    – my_bool *error
    );
    –

    –   REAL type (SQL: double):
    double xxx(
      UDF_INIT *initid,
      UDF_ARGS *args,
      my_bool *is_null,
      my_bool *error
    );
The row-level function
●   Returns the value to the caller
    – STRING type (SQL: varchar,    text):
    char *xxx(
    –
       UDF_INIT *initid,
    – UDF_ARGS *args,
       char* result,
    – unsigned long length,
       my_bool *is_null,
    – my_bool *error
    );
    –

    –   DECIMAL type (SQL: decimal):
        ●   Just like STRING type
Type systems
SQL data type                               RETURNS Item_result    C type
Character strings (CHAR, VARCHAR)           STRING STRING_RESULT   char*
Text (TEXT, LONGTEXT, MEDIUMTEXT, TINYTEXT)
Binary strings (BINARY, VARBINARY)
Blob (BLOB, LONGBLOB, MEDIUMBLOB, TINYBLOB)
Temporal (DATE, TIME, DATETIME, TIMESTAMP)
Structured (ENUM, SET)
Floating point numbers (FLOAT, DOUBLE)      REAL    REAL_RESULT    double
Ints (BIGINT, MEDIUMINT, SMALLINT, TINYINT) INTEGER INT_RESULT     long long
NA                                          NA      ROW_RESULT     NA
Fixed point numbers (DECIMAL)               DECIMAL DECIMAL_RESULT char *
Data Structures
●   #include "mysql.h"
    – include dir beneath MySQL home dir

    – Actually defined in mysql_com.h
●   UDF_INIT *initid
●   UDF_ARGS *args
Data Structures: UDF_INIT
●   Passed to all UDF implementation functions
typedef struct st_udf_init {
  my_bool maybe_null;       /*   1 if function can return NULL */
  unsigned int decimals;    /*   for real functions */
  unsigned long max_length; /*   For string functions */
  char *ptr;                /*   free pointer for function data */
  my_bool const_item;       /*   1 if always returns the same value*/
  void *extension;
} UDF_INIT;

●   Conveys mainly info about return value
●   char *ptr explicitly meant to hold state:
    –   Resource allocation
●   Can always be read
●   Can be written in xxx_init()
Writing to UDF_INIT (1/3)
●   1st attempt at writing a REAL function:
char planck_init(){ return 0; }
double planck(){ return 6.62606957e-34; }

mysql> CREATE FUNCTION planck
    -> RETURNS REAL SONAME 'planck.so';

mysql> SELECT planck();
+----------+
| planck() |
+----------+
|       0. |
+----------+
●   But is planck() really 0?
Writing to UDF_INIT (2/3)
●   2nd attempt at writing a REAL function:
#include "mysql.h"

my_bool planck_init(
   UDF_INIT *initid, UDF_ARGS *args, char *msg
){
   initid->decimals = NOT_FIXED_DEC;
   return 0;
}
double planck(){return 6.62606957e-34;}

mysql> SELECT planck();
+----------------+
| planck()       |
+----------------+
| 6.62606957e-34 |
+----------------+
Writing to UDF_INIT (3/3)
●   More return value properties:
#include "mysql.h"

my_bool planck_init(
   UDF_INIT *initid, UDF_ARGS *args, char *msg
){
   initid->decimals = NOT_FIXED_DEC;
   initid->maybe_null = 0;
   initid->const_item = 1;
   return 0;
}
double planck(){return 6.62606957e-34;}
Data Structures: UDF_ARGS
●   Passed to init and row-level function
typedef struct st_udf_args
{
  unsigned int arg_count;          /*   Number of arguments          */
  enum Item_result *arg_type;      /*   Pointer to item_results      */
  char **args;                     /*   Pointer to value             */
  unsigned long *lengths;          /*   Length of string arguments   */
  char *maybe_null;                /*   1 for all maybe_null args    */
  char **attributes;               /*   Pointer to attribute name    */
  unsigned long *attribute_lengths;/*   Length of attribute          */
  void *extension;
} UDF_ARGS;

●   Conveys information about function arguments
●   Can always be read
●   Can be written in xxx_init()
Using UDF_ARGS (1/2)
●   A hello world UDF (init function):
#include "string.h"
#include "stdio.h"
#include "mysql.h"

my_bool hello_world_init(
   UDF_INIT *initid, UDF_ARGS *args, char *msg
){
   if (args->arg_count != 1) {
     memcpy(msg, "Missing message argument.", 26);
     return 1;
   }
   if (args->arg_type[0] != STRING_RESULT) {
     args->arg_type = STRING_RESULT;
   }
   return 0;
}
Using UDF_ARGS (2/2)
●   A hello world UDF (row-level function):
char *hello_world(
  UDF_INIT *initid, UDF_ARGS *args,
  char *result, unsigned long *length,
  my_bool *is_null, my_bool *error
){
  char *arg_val = args->args[0];
  char *arg_name = args->attributes[0];
  char first = arg_name[0];
  my_bool is_lit = first == ''' || first == '"';
  my_bool is_same = !strcmp(arg_value, arg_name);
  char *greeting = is_literal||is_same?"Hello":arg_name;
  *length = args->lengths[0] + strlen(greeting) + 3;
  if (*length > 255) {
    *is_null = 1;
    return NULL;
  }
  sprintf(result, "%s %s!", greeting, arg_value);
  return result;
}
The UDF Repository
●   http://www.mysqludf.org/
●   Some highlights
    –   lib_mysqludf_myxml
    –   lib_mysqludf_sys
    –   lib_mysqludf_stem
    –   lib_mysqludf_preg
●   For UDF authors:
    –   http://www.mysqludf.org/lib_mysqludf_udf/
My Latest Baby
●   https://github.com/rpbouman/mysqlv8udfs
mysql> SELECT js('
var y = parseInt(arguments[0].substr(0,4), 10),
  a = y % 19,
  b = Math.floor(y / 100),
  c = y % 100,
  d = Math.floor(b / 4),
  e = b % 4,
  f = Math.floor((b + 8) / 25),
  g = Math.floor((b - f + 1) / 3),
  h = (19 * a + b - d - g + 15) % 30,
  i = Math.floor(c / 4),
  k = c % 4,
  L = (32 + 2 * e + 2 * i - h - k) % 7,
  m = Math.floor((a + 11 * h + 22 * L) / 451),
  n = h + L - 7 * m + 114;
  y + "-" + (Math.floor(n/31)) + "-" + ((n%31)+1);'), NOW());
Recommended Reading
●   http://rpbouman.blogspot.nl/search?q=UDF

Mais conteúdo relacionado

Mais procurados

Apache Dispatch
Apache DispatchApache Dispatch
Apache DispatchFred Moyer
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Automating with ansible (part a)
Automating with ansible (part a)Automating with ansible (part a)
Automating with ansible (part a)iman darabi
 
Linux fundamental - Chap 14 shell script
Linux fundamental - Chap 14 shell scriptLinux fundamental - Chap 14 shell script
Linux fundamental - Chap 14 shell scriptKenny (netman)
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-linersdaoswald
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby appsVsevolod Romashov
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화NAVER D2
 
2005_Structures and functions of Makefile
2005_Structures and functions of Makefile2005_Structures and functions of Makefile
2005_Structures and functions of MakefileNakCheon Jung
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationrjsmelo
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPGuilherme Blanco
 

Mais procurados (20)

Apache Dispatch
Apache DispatchApache Dispatch
Apache Dispatch
 
Ruby meetup ROM
Ruby meetup ROMRuby meetup ROM
Ruby meetup ROM
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Automating with ansible (part a)
Automating with ansible (part a)Automating with ansible (part a)
Automating with ansible (part a)
 
Xmla4js
Xmla4jsXmla4js
Xmla4js
 
Lumberjack XPath 101
Lumberjack XPath 101Lumberjack XPath 101
Lumberjack XPath 101
 
Php engine
Php enginePhp engine
Php engine
 
Linux fundamental - Chap 14 shell script
Linux fundamental - Chap 14 shell scriptLinux fundamental - Chap 14 shell script
Linux fundamental - Chap 14 shell script
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-liners
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby apps
 
TRunner
TRunnerTRunner
TRunner
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화
 
Zend Expressive 3 e PSR-15
Zend Expressive 3 e PSR-15Zend Expressive 3 e PSR-15
Zend Expressive 3 e PSR-15
 
2005_Structures and functions of Makefile
2005_Structures and functions of Makefile2005_Structures and functions of Makefile
2005_Structures and functions of Makefile
 
Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 

Destaque

MySQL Built-In Functions
MySQL Built-In FunctionsMySQL Built-In Functions
MySQL Built-In FunctionsSHC
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQLUsing JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQLAnders Karlsson
 
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...Does simultaneous outsourcing of all your purchase-to-pay processes and achie...
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...sharedserviceslink.com
 
Audio recording evaluration unit 4
Audio recording evaluration unit 4Audio recording evaluration unit 4
Audio recording evaluration unit 4Sophia Gent
 
Some for all rather than more for some: A myth or an opportunity lost?
Some for all rather than more for some: A myth or an opportunity lost?Some for all rather than more for some: A myth or an opportunity lost?
Some for all rather than more for some: A myth or an opportunity lost?STEPS Centre
 
Building A Social Network Waa 1 17 07 V2 Draft
Building A Social Network   Waa   1 17 07 V2 DraftBuilding A Social Network   Waa   1 17 07 V2 Draft
Building A Social Network Waa 1 17 07 V2 DraftMarshall Sponder
 
2006增刊目录
2006增刊目录2006增刊目录
2006增刊目录guest2bb2c
 
Ignition toyota igt
Ignition toyota igtIgnition toyota igt
Ignition toyota igtToni Gim
 
Nair jure123456
Nair jure123456Nair jure123456
Nair jure123456nairjure
 
Technology In Schools What Is Changing
Technology  In  Schools  What  Is  ChangingTechnology  In  Schools  What  Is  Changing
Technology In Schools What Is ChangingYarmouth Schools
 
Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is S K "Bal" Palekar
 
Eye Catching Photos
Eye Catching PhotosEye Catching Photos
Eye Catching PhotosYee Seng Gan
 
8 habits of highly effective language learners
8 habits of highly effective language learners8 habits of highly effective language learners
8 habits of highly effective language learnersPhilip Seifi
 
GSCNC Cookie Incentives
GSCNC Cookie IncentivesGSCNC Cookie Incentives
GSCNC Cookie Incentivesddurst16
 
Xinguang Inflatable Toy Factory
Xinguang Inflatable Toy FactoryXinguang Inflatable Toy Factory
Xinguang Inflatable Toy Factoryguest47d98176
 

Destaque (20)

MySQL Built-In Functions
MySQL Built-In FunctionsMySQL Built-In Functions
MySQL Built-In Functions
 
MySQL Functions
MySQL FunctionsMySQL Functions
MySQL Functions
 
Using JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQLUsing JSON with MariaDB and MySQL
Using JSON with MariaDB and MySQL
 
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...Does simultaneous outsourcing of all your purchase-to-pay processes and achie...
Does simultaneous outsourcing of all your purchase-to-pay processes and achie...
 
Audio recording evaluration unit 4
Audio recording evaluration unit 4Audio recording evaluration unit 4
Audio recording evaluration unit 4
 
The silent way
The silent wayThe silent way
The silent way
 
Some for all rather than more for some: A myth or an opportunity lost?
Some for all rather than more for some: A myth or an opportunity lost?Some for all rather than more for some: A myth or an opportunity lost?
Some for all rather than more for some: A myth or an opportunity lost?
 
Building A Social Network Waa 1 17 07 V2 Draft
Building A Social Network   Waa   1 17 07 V2 DraftBuilding A Social Network   Waa   1 17 07 V2 Draft
Building A Social Network Waa 1 17 07 V2 Draft
 
Saim chishti books eemane abitalib2of2
Saim chishti books eemane abitalib2of2Saim chishti books eemane abitalib2of2
Saim chishti books eemane abitalib2of2
 
Saz1
Saz1Saz1
Saz1
 
2006增刊目录
2006增刊目录2006增刊目录
2006增刊目录
 
Ignition toyota igt
Ignition toyota igtIgnition toyota igt
Ignition toyota igt
 
Nair jure123456
Nair jure123456Nair jure123456
Nair jure123456
 
Technology In Schools What Is Changing
Technology  In  Schools  What  Is  ChangingTechnology  In  Schools  What  Is  Changing
Technology In Schools What Is Changing
 
Daaaaaa
DaaaaaaDaaaaaa
Daaaaaa
 
Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is Most people cannot say - even to themselves - what their "Business Model" is
Most people cannot say - even to themselves - what their "Business Model" is
 
Eye Catching Photos
Eye Catching PhotosEye Catching Photos
Eye Catching Photos
 
8 habits of highly effective language learners
8 habits of highly effective language learners8 habits of highly effective language learners
8 habits of highly effective language learners
 
GSCNC Cookie Incentives
GSCNC Cookie IncentivesGSCNC Cookie Incentives
GSCNC Cookie Incentives
 
Xinguang Inflatable Toy Factory
Xinguang Inflatable Toy FactoryXinguang Inflatable Toy Factory
Xinguang Inflatable Toy Factory
 

Semelhante a Writing MySQL UDFs

External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLAntony T Curtis
 
Extending MariaDB with user-defined functions
Extending MariaDB with user-defined functionsExtending MariaDB with user-defined functions
Extending MariaDB with user-defined functionsMariaDB plc
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensNETWAYS
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaXKernel TLV
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaPatrick Allaert
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWithTheBest
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming languageKumar Gaurav
 

Semelhante a Writing MySQL UDFs (20)

External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQL
 
Extending MariaDB with user-defined functions
Extending MariaDB with user-defined functionsExtending MariaDB with user-defined functions
Extending MariaDB with user-defined functions
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Unit 4
Unit 4Unit 4
Unit 4
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet Mens
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
8.4 Upcoming Features
8.4 Upcoming Features 8.4 Upcoming Features
8.4 Upcoming Features
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Golang
GolangGolang
Golang
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 

Mais de Roland Bouman

Beyond OData: Introducing the XML/A model for ui5
Beyond OData: Introducing the XML/A model for ui5Beyond OData: Introducing the XML/A model for ui5
Beyond OData: Introducing the XML/A model for ui5Roland Bouman
 
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)Roland Bouman
 
Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptRoland Bouman
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012Roland Bouman
 
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...Roland Bouman
 

Mais de Roland Bouman (7)

Beyond OData: Introducing the XML/A model for ui5
Beyond OData: Introducing the XML/A model for ui5Beyond OData: Introducing the XML/A model for ui5
Beyond OData: Introducing the XML/A model for ui5
 
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)
Moving and Transforming Data with Pentaho Data Integration 5.0 CE (aka Kettle)
 
Xml4js pentaho
Xml4js pentahoXml4js pentaho
Xml4js pentaho
 
Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScript
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Common schema my sql uc 2012
Common schema   my sql uc 2012Common schema   my sql uc 2012
Common schema my sql uc 2012
 
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...
Roland bouman modern_data_warehouse_architectures_data_vault_and_anchor_model...
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Writing MySQL UDFs

  • 2. Welcome! ● @rolandbouman ● roland.bouman@gmail.com ● http://rpbouman.blogspot.com/ ● Ex-MySQL AB, Ex-Sun Microsystems ● Currently at http://www.pentaho.com/
  • 3. Different kinds of MySQL Functions ● Built-in functions (and operators) – Native code part of the server binaries ● SQL Stored functions – SQL/PSM code stored in the database CREATE FUNCTION lightspeed() RETURNS INT UNSIGNED BEGIN RETURN 299792458; END; ● User-defined functions (UDF's) – Native code stored in an external binary library CREATE FUNCTION lightspeed RETURNS INTEGER SONAME 'lightspeed.so';
  • 4. MySQL Function Kinds Comparison Built-in UDF Stored routine language C/C++ C/C++* SQL/PSM execution natively compiled natively compiled interpreted performance very good good not that good user-defined no yes yes installation NA CREATE stmt CREATE stmt deployment NA binary library schema object namespace global global schema grant-able no no yes SQL capabilities no no* yes Data types internal internal and C/C++ SQL data types Charset support yes* no yes argumentlist flexible* flexible fixed number & type aggregates yes* yes no
  • 5. Quick and dirty example (1/2) ● Write C/C++ code: char lightspeed_init(){ return 0; } long long lightspeed(){ return 299792458; } ● Compile to a shared library: shell$ gcc -shared -o lightspeed.so lightspeed.c ● Move library to plugin dir: mysql> SHOW VARIABLES LIKE 'plugin_dir'; +---------------+------------------------------+ | Variable_name | Value | +---------------+------------------------------+ | plugin_dir | /home/mysql/mysql/lib/plugin | +---------------+------------------------------+ shell$ mv lightspeed.so /home/mysql/mysql/lib/plugin
  • 6. Quick and dirty example (2/2) ● Register the function in MySQL mysql> CREATE FUNCTION lightspeed -> RETURNS INTEGER SONAME 'lightspeed.so'; ● Verify: mysql> SELECT * FROM mysql.func; +------------+-----+---------------+----------+ | name | ret | dl | type | +------------+-----+---------------+----------+ | lightspeed | 2 | lightspeed.so | function | +------------+-----+---------------+----------+ ● Run: mysql> SELECT lightspeed(); +--------- ----+ | lightspeed() | +--------------+ | 299792458 | +--------------+
  • 7. UDF implementation functions ● General UDF Implementation functions – Init function – Row-level function – De-init function xxx_init() row? xxx() xxx_deinit()
  • 8. UDF implementation functions ● Aggregate UDF Implementation functions – clear function – add function xxx_init() xxx() start group? xxx_clear() xxx_add() end group? xxx_deinit()
  • 9. The init function ● Signature: my_bool xxx_init( UDF_INIT *initid, UDF_ARGS *args, char *message ); ● Set default properties – of the return value – of the arguments ● Validate arguments ● Allocate resources ● Signal an error – Return 1 to signal an error – Copy error message to *message
  • 10. The de-init function ● Signature: void xxx_deinit(UDF_INIT *initid); ● De-allocate any resources
  • 11. The row-level function ● Returns the value to the caller – INTEGER type (SQL: bigint): long long xxx( – UDF_INIT *initid, – UDF_ARGS *args, my_bool *is_null, – my_bool *error ); – – REAL type (SQL: double): double xxx( UDF_INIT *initid, UDF_ARGS *args, my_bool *is_null, my_bool *error );
  • 12. The row-level function ● Returns the value to the caller – STRING type (SQL: varchar, text): char *xxx( – UDF_INIT *initid, – UDF_ARGS *args, char* result, – unsigned long length, my_bool *is_null, – my_bool *error ); – – DECIMAL type (SQL: decimal): ● Just like STRING type
  • 13. Type systems SQL data type RETURNS Item_result C type Character strings (CHAR, VARCHAR) STRING STRING_RESULT char* Text (TEXT, LONGTEXT, MEDIUMTEXT, TINYTEXT) Binary strings (BINARY, VARBINARY) Blob (BLOB, LONGBLOB, MEDIUMBLOB, TINYBLOB) Temporal (DATE, TIME, DATETIME, TIMESTAMP) Structured (ENUM, SET) Floating point numbers (FLOAT, DOUBLE) REAL REAL_RESULT double Ints (BIGINT, MEDIUMINT, SMALLINT, TINYINT) INTEGER INT_RESULT long long NA NA ROW_RESULT NA Fixed point numbers (DECIMAL) DECIMAL DECIMAL_RESULT char *
  • 14. Data Structures ● #include "mysql.h" – include dir beneath MySQL home dir – Actually defined in mysql_com.h ● UDF_INIT *initid ● UDF_ARGS *args
  • 15. Data Structures: UDF_INIT ● Passed to all UDF implementation functions typedef struct st_udf_init { my_bool maybe_null; /* 1 if function can return NULL */ unsigned int decimals; /* for real functions */ unsigned long max_length; /* For string functions */ char *ptr; /* free pointer for function data */ my_bool const_item; /* 1 if always returns the same value*/ void *extension; } UDF_INIT; ● Conveys mainly info about return value ● char *ptr explicitly meant to hold state: – Resource allocation ● Can always be read ● Can be written in xxx_init()
  • 16. Writing to UDF_INIT (1/3) ● 1st attempt at writing a REAL function: char planck_init(){ return 0; } double planck(){ return 6.62606957e-34; } mysql> CREATE FUNCTION planck -> RETURNS REAL SONAME 'planck.so'; mysql> SELECT planck(); +----------+ | planck() | +----------+ | 0. | +----------+ ● But is planck() really 0?
  • 17. Writing to UDF_INIT (2/3) ● 2nd attempt at writing a REAL function: #include "mysql.h" my_bool planck_init( UDF_INIT *initid, UDF_ARGS *args, char *msg ){ initid->decimals = NOT_FIXED_DEC; return 0; } double planck(){return 6.62606957e-34;} mysql> SELECT planck(); +----------------+ | planck() | +----------------+ | 6.62606957e-34 | +----------------+
  • 18. Writing to UDF_INIT (3/3) ● More return value properties: #include "mysql.h" my_bool planck_init( UDF_INIT *initid, UDF_ARGS *args, char *msg ){ initid->decimals = NOT_FIXED_DEC; initid->maybe_null = 0; initid->const_item = 1; return 0; } double planck(){return 6.62606957e-34;}
  • 19. Data Structures: UDF_ARGS ● Passed to init and row-level function typedef struct st_udf_args { unsigned int arg_count; /* Number of arguments */ enum Item_result *arg_type; /* Pointer to item_results */ char **args; /* Pointer to value */ unsigned long *lengths; /* Length of string arguments */ char *maybe_null; /* 1 for all maybe_null args */ char **attributes; /* Pointer to attribute name */ unsigned long *attribute_lengths;/* Length of attribute */ void *extension; } UDF_ARGS; ● Conveys information about function arguments ● Can always be read ● Can be written in xxx_init()
  • 20. Using UDF_ARGS (1/2) ● A hello world UDF (init function): #include "string.h" #include "stdio.h" #include "mysql.h" my_bool hello_world_init( UDF_INIT *initid, UDF_ARGS *args, char *msg ){ if (args->arg_count != 1) { memcpy(msg, "Missing message argument.", 26); return 1; } if (args->arg_type[0] != STRING_RESULT) { args->arg_type = STRING_RESULT; } return 0; }
  • 21. Using UDF_ARGS (2/2) ● A hello world UDF (row-level function): char *hello_world( UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, my_bool *is_null, my_bool *error ){ char *arg_val = args->args[0]; char *arg_name = args->attributes[0]; char first = arg_name[0]; my_bool is_lit = first == ''' || first == '"'; my_bool is_same = !strcmp(arg_value, arg_name); char *greeting = is_literal||is_same?"Hello":arg_name; *length = args->lengths[0] + strlen(greeting) + 3; if (*length > 255) { *is_null = 1; return NULL; } sprintf(result, "%s %s!", greeting, arg_value); return result; }
  • 22. The UDF Repository ● http://www.mysqludf.org/ ● Some highlights – lib_mysqludf_myxml – lib_mysqludf_sys – lib_mysqludf_stem – lib_mysqludf_preg ● For UDF authors: – http://www.mysqludf.org/lib_mysqludf_udf/
  • 23. My Latest Baby ● https://github.com/rpbouman/mysqlv8udfs mysql> SELECT js(' var y = parseInt(arguments[0].substr(0,4), 10), a = y % 19, b = Math.floor(y / 100), c = y % 100, d = Math.floor(b / 4), e = b % 4, f = Math.floor((b + 8) / 25), g = Math.floor((b - f + 1) / 3), h = (19 * a + b - d - g + 15) % 30, i = Math.floor(c / 4), k = c % 4, L = (32 + 2 * e + 2 * i - h - k) % 7, m = Math.floor((a + 11 * h + 22 * L) / 451), n = h + L - 7 * m + 114; y + "-" + (Math.floor(n/31)) + "-" + ((n%31)+1);'), NOW());
  • 24. Recommended Reading ● http://rpbouman.blogspot.nl/search?q=UDF