udf_example.c 32.7 KB
Newer Older
1
/* Copyright (C) 2002 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
11

bk@work.mysql.com's avatar
bk@work.mysql.com committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
** example file of UDF (user definable functions) that are dynamicly loaded
** into the standard mysqld core.
**
** The functions name, type and shared library is saved in the new system
** table 'func'.  To be able to create new functions one must have write
** privilege for the database 'mysql'.	If one starts MySQL with
** --skip-grant, then UDF initialization will also be skipped.
**
** Syntax for the new commands are:
** create function <function_name> returns {string|real|integer}
**		  soname <name_of_shared_library>
** drop function <function_name>
**
** Each defined function may have a xxxx_init function and a xxxx_deinit
** function.  The init function should alloc memory for the function
** and tell the main function about the max length of the result
** (for string functions), number of decimals (for double functions) and
** if the result may be a null value.
**
** If a function sets the 'error' argument to 1 the function will not be
** called anymore and mysqld will return NULL for all calls to this copy
** of the function.
**
** All strings arguments to functions are given as string pointer + length
** to allow handling of binary data.
** Remember that all functions must be thread safe. This means that one is not
** allowed to alloc any global or static variables that changes!
** If one needs memory one should alloc this in the init function and free
** this on the __deinit function.
**
** Note that the init and __deinit functions are only called once per
** SQL statement while the value function may be called many times
**
** Function 'metaphon' returns a metaphon string of the string argument.
** This is something like a soundex string, but it's more tuned for English.
**
** Function 'myfunc_double' returns summary of codes of all letters
** of arguments divided by summary length of all its arguments.
**
** Function 'myfunc_int' returns summary length of all its arguments.
**
58 59 60
** Function 'sequence' returns an sequence starting from a certain number.
**
** Function 'myfunc_argument_name' returns name of argument.
61
**
bk@work.mysql.com's avatar
bk@work.mysql.com committed
62 63 64
** On the end is a couple of functions that converts hostnames to ip and
** vice versa.
**
65
** A dynamicly loadable file should be compiled shared.
66
** (something like: gcc -shared -o my_func.so myfunc.cc).
bk@work.mysql.com's avatar
bk@work.mysql.com committed
67 68 69
** You can easily get all switches right by doing:
** cd sql ; make udf_example.o
** Take the compile line that make writes, remove the '-c' near the end of
70
** the line and add -shared -o udf_example.so to the end of the compile line.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
71 72
** The resulting library (udf_example.so) should be copied to some dir
** searched by ld. (/usr/lib ?)
73 74
** If you are using gcc, then you should be able to create the udf_example.so
** by simply doing 'make udf_example.so'.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
75 76 77 78 79 80 81
**
** After the library is made one must notify mysqld about the new
** functions with the commands:
**
** CREATE FUNCTION metaphon RETURNS STRING SONAME "udf_example.so";
** CREATE FUNCTION myfunc_double RETURNS REAL SONAME "udf_example.so";
** CREATE FUNCTION myfunc_int RETURNS INTEGER SONAME "udf_example.so";
82
** CREATE FUNCTION sequence RETURNS INTEGER SONAME "udf_example.so";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
83 84 85
** CREATE FUNCTION lookup RETURNS STRING SONAME "udf_example.so";
** CREATE FUNCTION reverse_lookup RETURNS STRING SONAME "udf_example.so";
** CREATE AGGREGATE FUNCTION avgcost RETURNS REAL SONAME "udf_example.so";
86
** CREATE FUNCTION myfunc_argument_name RETURNS STRING SONAME "udf_example.so";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
87 88 89 90 91 92 93 94 95 96 97 98
**
** After this the functions will work exactly like native MySQL functions.
** Functions should be created only once.
**
** The functions can be deleted by:
**
** DROP FUNCTION metaphon;
** DROP FUNCTION myfunc_double;
** DROP FUNCTION myfunc_int;
** DROP FUNCTION lookup;
** DROP FUNCTION reverse_lookup;
** DROP FUNCTION avgcost;
99
** DROP FUNCTION myfunc_argument_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
100 101 102 103 104
**
** The CREATE FUNCTION and DROP FUNCTION update the func@mysql table. All
** Active function will be reloaded on every restart of server
** (if --skip-grant-tables is not given)
**
105 106 107 108 109 110 111
** If you ge problems with undefined symbols when loading the shared
** library, you should verify that mysqld is compiled with the -rdynamic
** option.
**
** If you can't get AGGREGATES to work, check that you have the column
** 'type' in the mysql.func table.  If not, run 'mysql_fix_privilege_tables'.
**
bk@work.mysql.com's avatar
bk@work.mysql.com committed
112 113 114
*/

#ifdef STANDARD
115 116
/* STANDARD is defined, don't use any mysql functions */
#include <stdlib.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
117 118
#include <stdio.h>
#include <string.h>
119 120 121 122 123 124 125
#ifdef __WIN__
typedef unsigned __int64 ulonglong;	/* Microsofts 64 bit types */
typedef __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
126
#else
127
#include <my_global.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
128
#include <my_sys.h>
129
#if defined(MYSQL_SERVER)
130
#include <m_string.h>		/* To get strmov() */
131 132
#else
/* when compiled as standalone */
133 134
#include <string.h>
#define strmov(a,b) stpcpy(a,b)
135 136 137
#define bzero(a,b) memset(a,0,b)
#define memcpy_fixed(a,b,c) memcpy(a,b,c)
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
138 139
#endif
#include <mysql.h>
140
#include <ctype.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
141

142 143
static pthread_mutex_t LOCK_hostname;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
144 145 146 147 148 149 150 151 152 153 154
#ifdef HAVE_DLOPEN

/* These must be right or mysqld will not find the symbol! */

my_bool metaphon_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void metaphon_deinit(UDF_INIT *initid);
char *metaphon(UDF_INIT *initid, UDF_ARGS *args, char *result,
	       unsigned long *length, char *is_null, char *error);
my_bool myfunc_double_init(UDF_INIT *, UDF_ARGS *args, char *message);
double myfunc_double(UDF_INIT *initid, UDF_ARGS *args, char *is_null,
		     char *error);
155
my_bool myfunc_int_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
156 157
longlong myfunc_int(UDF_INIT *initid, UDF_ARGS *args, char *is_null,
		    char *error);
158 159
my_bool sequence_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
 void sequence_deinit(UDF_INIT *initid);
160
longlong sequence(UDF_INIT *initid, UDF_ARGS *args, char *is_null,
161
		   char *error);
162 163 164
my_bool avgcost_init( UDF_INIT* initid, UDF_ARGS* args, char* message );
void avgcost_deinit( UDF_INIT* initid );
void avgcost_reset( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error );
165
void avgcost_clear( UDF_INIT* initid, char* is_null, char *error );
166 167
void avgcost_add( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error );
double avgcost( UDF_INIT* initid, UDF_ARGS* args, char* is_null, char *error );
168 169 170
my_bool is_const_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
char *is_const(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long
               *length, char *is_null, char *error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231


/*************************************************************************
** Example of init function
** Arguments:
** initid	Points to a structure that the init function should fill.
**		This argument is given to all other functions.
**	my_bool maybe_null	1 if function can return NULL
**				Default value is 1 if any of the arguments
**				is declared maybe_null.
**	unsigned int decimals	Number of decimals.
**				Default value is max decimals in any of the
**				arguments.
**	unsigned int max_length  Length of string result.
**				The default value for integer functions is 21
**				The default value for real functions is 13+
**				default number of decimals.
**				The default value for string functions is
**				the longest string argument.
**	char *ptr;		A pointer that the function can use.
**
** args		Points to a structure which contains:
**	unsigned int arg_count		Number of arguments
**	enum Item_result *arg_type	Types for each argument.
**					Types are STRING_RESULT, REAL_RESULT
**					and INT_RESULT.
**	char **args			Pointer to constant arguments.
**					Contains 0 for not constant argument.
**	unsigned long *lengths;		max string length for each argument
**	char *maybe_null		Information of which arguments
**					may be NULL
**
** message	Error message that should be passed to the user on fail.
**		The message buffer is MYSQL_ERRMSG_SIZE big, but one should
**		try to keep the error message less than 80 bytes long!
**
** This function should return 1 if something goes wrong. In this case
** message should contain something usefull!
**************************************************************************/

#define MAXMETAPH 8

my_bool metaphon_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count != 1 || args->arg_type[0] != STRING_RESULT)
  {
    strcpy(message,"Wrong arguments to metaphon;  Use the source");
    return 1;
  }
  initid->max_length=MAXMETAPH;
  return 0;
}

/****************************************************************************
** Deinit function. This should free all resources allocated by
** this function.
** Arguments:
** initid	Return value from xxxx_init
****************************************************************************/


232
void metaphon_deinit(UDF_INIT *initid __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
{
}

/***************************************************************************
** UDF string function.
** Arguments:
** initid	Structure filled by xxx_init
** args		The same structure as to xxx_init. This structure
**		contains values for all parameters.
**		Note that the functions MUST check and convert all
**		to the type it wants!  Null values are represented by
**		a NULL pointer
** result	Possible buffer to save result. At least 255 byte long.
** length	Pointer to length of the above buffer.	In this the function
**		should save the result length
** is_null	If the result is null, one should store 1 here.
** error	If something goes fatally wrong one should store 1 here.
**
** This function should return a pointer to the result string.
** Normally this is 'result' but may also be an alloced string.
***************************************************************************/

/* Character coding array */
static char codes[26] =  {
    1,16,4,16,9,2,4,16,9,2,0,2,2,2,1,4,0,2,4,4,1,0,0,0,8,0
 /* A  B C  D E F G  H I J K L M N O P Q R S T U V W X Y Z*/
    };

/*--- Macros to access character coding array -------------*/

#define ISVOWEL(x)  (codes[(x) - 'A'] & 1)	/* AEIOU */

    /* Following letters are not changed */
#define NOCHANGE(x) (codes[(x) - 'A'] & 2)	/* FJLMNR */

    /* These form diphthongs when preceding H */
#define AFFECTH(x) (codes[(x) - 'A'] & 4)	/* CGPST */

    /* These make C and G soft */
#define MAKESOFT(x) (codes[(x) - 'A'] & 8)	/* EIY */

    /* These prevent GH from becoming F */
#define NOGHTOF(x)  (codes[(x) - 'A'] & 16)	/* BDH */


278 279 280
char *metaphon(UDF_INIT *initid __attribute__((unused)),
               UDF_ARGS *args, char *result, unsigned long *length,
               char *is_null, char *error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
281 282
{
  const char *word=args->args[0];
283 284 285 286 287 288 289 290
  const char *w_end;
  char *org_result;
  char *n, *n_start, *n_end; /* pointers to string */
  char *metaph_end;	     /* pointers to end of metaph */
  char ntrans[32];	     /* word with uppercase letters */
  int  KSflag;		     /* state flag for X to KS */

  if (!word)					/* Null argument */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
291 292 293 294
  {
    *is_null=1;
    return 0;
  }
295 296
  w_end=word+args->lengths[0];
  org_result=result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
297 298 299 300 301 302

  /*--------------------------------------------------------
   *  Copy word to internal buffer, dropping non-alphabetic
   *  characters and converting to uppercase.
   *-------------------------------------------------------*/

303
  for (n = ntrans + 1, n_end = ntrans + sizeof(ntrans)-2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
304
	word != w_end && n < n_end; word++ )
305 306
    if ( isalpha ( *word ))
      *n++ = toupper ( *word );
bk@work.mysql.com's avatar
bk@work.mysql.com committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

  if ( n == ntrans + 1 )	/* return empty string if 0 bytes */
  {
    *length=0;
    return result;
  }
  n_end = n;			/* set n_end to end of string */
  ntrans[0] = 'Z';		/* ntrans[0] should be a neutral char */
  n[0]=n[1]=0;			/* pad with nulls */
  n = ntrans + 1;		/* assign pointer to start */

  /*------------------------------------------------------------
   *  check for all prefixes:
   *		PN KN GN AE WR WH and X at start.
   *----------------------------------------------------------*/

  switch ( *n ) {
  case 'P':
  case 'K':
  case 'G':
    if ( n[1] == 'N')
      *n++ = 0;
    break;
  case 'A':
    if ( n[1] == 'E')
      *n++ = 0;
    break;
  case 'W':
    if ( n[1] == 'R' )
      *n++ = 0;
    else
      if ( *(n + 1) == 'H')
      {
	n[1] = *n;
	*n++ = 0;
      }
    break;
  case 'X':
    *n = 'S';
    break;
  }

  /*------------------------------------------------------------
   *  Now, loop step through string, stopping at end of string
   *  or when the computed metaph is MAXMETAPH characters long
   *----------------------------------------------------------*/

  KSflag = 0; /* state flag for KS translation */

356
  for (metaph_end = result + MAXMETAPH, n_start = n;
357
	n < n_end && result < metaph_end; n++ )
bk@work.mysql.com's avatar
bk@work.mysql.com committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
  {

    if ( KSflag )
    {
      KSflag = 0;
      *result++ = *n;
    }
    else
    {
      /* drop duplicates except for CC */
      if ( *( n - 1 ) == *n && *n != 'C' )
	continue;

      /* check for F J L M N R or first letter vowel */
      if ( NOCHANGE ( *n ) ||
	   ( n == n_start && ISVOWEL ( *n )))
	*result++ = *n;
      else
	switch ( *n ) {
	case 'B':	 /* check for -MB */
	  if ( n < n_end || *( n - 1 ) != 'M' )
	    *result++ = *n;
	  break;

	case 'C': /* C = X ("sh" sound) in CH and CIA */
	  /*   = S in CE CI and CY	      */
	  /*	 dropped in SCI SCE SCY       */
	  /* else K			      */
	  if ( *( n - 1 ) != 'S' ||
	       !MAKESOFT ( n[1]))
	  {
	    if ( n[1] == 'I' && n[2] == 'A' )
	      *result++ = 'X';
	    else
	      if ( MAKESOFT ( n[1]))
		*result++ = 'S';
	      else
		if ( n[1] == 'H' )
		  *result++ = (( n == n_start &&
				 !ISVOWEL ( n[2])) ||
			       *( n - 1 ) == 'S' ) ?
		    (char)'K' : (char)'X';
		else
		  *result++ = 'K';
	  }
	  break;

	case 'D':  /* J before DGE, DGI, DGY, else T */
	  *result++ =
	    ( n[1] == 'G' &&
	      MAKESOFT ( n[2])) ?
	    (char)'J' : (char)'T';
	  break;

	case 'G':   /* complicated, see table in text */
	  if (( n[1] != 'H' || ISVOWEL ( n[2]))
	      && (
		  n[1] != 'N' ||
		  (
		   (n + 1) < n_end  &&
		   (
		    n[2] != 'E' ||
		    *( n + 3 ) != 'D'
		    )
		   )
		  )
	      && (
		  *( n - 1 ) != 'D' ||
		  !MAKESOFT ( n[1])
		  )
	      )
	    *result++ =
	      ( MAKESOFT ( *( n  + 1 )) &&
		n[2] != 'G' ) ?
	      (char)'J' : (char)'K';
	  else
434
	    if ( n[1] == 'H'   &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		!NOGHTOF( *( n - 3 )) &&
		*( n - 4 ) != 'H')
	      *result++ = 'F';
	  break;

	case 'H':   /* H if before a vowel and not after */
	  /* C, G, P, S, T */

	  if ( !AFFECTH ( *( n - 1 )) &&
	       ( !ISVOWEL ( *( n - 1 )) ||
		 ISVOWEL ( n[1])))
	    *result++ = 'H';
	  break;

	case 'K':    /* K = K, except dropped after C */
	  if ( *( n - 1 ) != 'C')
	    *result++ = 'K';
	  break;

	case 'P':    /* PH = F, else P = P */
	  *result++ = *( n +  1 ) == 'H'
	    ? (char)'F' : (char)'P';
	  break;
	case 'Q':   /* Q = K (U after Q is already gone */
	  *result++ = 'K';
	  break;

	case 'S':   /* SH, SIO, SIA = X ("sh" sound) */
	  *result++ = ( n[1] == 'H' ||
			( *(n  + 1) == 'I' &&
			  ( n[2] == 'O' ||
			    n[2] == 'A')))  ?
	    (char)'X' : (char)'S';
	  break;

	case 'T':  /* TIO, TIA = X ("sh" sound) */
	  /* TH = 0, ("th" sound ) */
472
	  if ( *( n  + 1 ) == 'I' && ( n[2] == 'O'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
				      || n[2] == 'A') )
	    *result++ = 'X';
	  else
	    if ( n[1] == 'H' )
	      *result++ = '0';
	    else
	      if ( *( n + 1) != 'C' || n[2] != 'H')
		*result++ = 'T';
	  break;

	case 'V':     /* V = F */
	  *result++ = 'F';
	  break;

	case 'W':     /* only exist if a vowel follows */
	case 'Y':
	  if ( ISVOWEL ( n[1]))
	    *result++ = *n;
	  break;

	case 'X':     /* X = KS, except at start */
	  if ( n == n_start )
	    *result++ = 'S';
	  else
	  {
	    *result++ = 'K'; /* insert K, then S */
	    KSflag = 1; /* this flag will cause S to be
			   inserted on next pass thru loop */
	  }
	  break;

	case 'Z':
	  *result++ = 'S';
	  break;
	}
    }
  }
510
  *length= (unsigned long) (result - org_result);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
  return org_result;
}


/***************************************************************************
** UDF double function.
** Arguments:
** initid	Structure filled by xxx_init
** args		The same structure as to xxx_init. This structure
**		contains values for all parameters.
**		Note that the functions MUST check and convert all
**		to the type it wants!  Null values are represented by
**		a NULL pointer
** is_null	If the result is null, one should store 1 here.
** error	If something goes fatally wrong one should store 1 here.
**
** This function should return the result.
***************************************************************************/

my_bool myfunc_double_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
532 533
  uint i;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
534 535
  if (!args->arg_count)
  {
536
    strcpy(message,"myfunc_double must have at least one argument");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
537 538 539 540 541 542
    return 1;
  }
  /*
  ** As this function wants to have everything as strings, force all arguments
  ** to strings.
  */
543
  for (i=0 ; i < args->arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
544
    args->arg_type[i]=STRING_RESULT;
545 546 547
  initid->maybe_null=1;		/* The result may be null */
  initid->decimals=2;		/* We want 2 decimals in the result */
  initid->max_length=6;		/* 3 digits + . + 2 decimals */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
548 549 550 551
  return 0;
}


552 553
double myfunc_double(UDF_INIT *initid __attribute__((unused)), UDF_ARGS *args,
                     char *is_null, char *error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
554 555 556
{
  unsigned long val = 0;
  unsigned long v = 0;
557
  uint i, j;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
558

559
  for (i = 0; i < args->arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
560 561 562 563
  {
    if (args->args[i] == NULL)
      continue;
    val += args->lengths[i];
564
    for (j=args->lengths[i] ; j-- > 0 ;)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
      v += args->args[i][j];
  }
  if (val)
    return (double) v/ (double) val;
  *is_null=1;
  return 0.0;
}


/***************************************************************************
** UDF long long function.
** Arguments:
** initid	Return value from xxxx_init
** args		The same structure as to xxx_init. This structure
**		contains values for all parameters.
**		Note that the functions MUST check and convert all
**		to the type it wants!  Null values are represented by
**		a NULL pointer
** is_null	If the result is null, one should store 1 here.
** error	If something goes fatally wrong one should store 1 here.
**
** This function should return the result as a long long
***************************************************************************/

589 590
/* This function returns the sum of all arguments */

591 592 593
longlong myfunc_int(UDF_INIT *initid __attribute__((unused)), UDF_ARGS *args,
                    char *is_null __attribute__((unused)),
                    char *error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
594
{
595
  longlong val = 0;
596 597 598
  uint i;

  for (i = 0; i < args->arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
599 600 601 602
  {
    if (args->args[i] == NULL)
      continue;
    switch (args->arg_type[i]) {
603
    case STRING_RESULT:			/* Add string lengths */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
604 605
      val += args->lengths[i];
      break;
606
    case INT_RESULT:			/* Add numbers */
607
      val += *((longlong*) args->args[i]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
608
      break;
609
    case REAL_RESULT:			/* Add numers as longlong */
610
      val += (longlong) *((double*) args->args[i]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
611
      break;
612 613
    default:
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
614 615 616 617 618
    }
  }
  return val;
}

619 620 621 622
/*
  At least one of _init/_deinit is needed unless the server is started
  with --allow_suspicious_udfs.
*/
623 624 625
my_bool myfunc_int_init(UDF_INIT *initid __attribute__((unused)),
                        UDF_ARGS *args __attribute__((unused)),
                        char *message __attribute__((unused)))
626 627 628
{
  return 0;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
629

630 631 632 633 634 635 636 637 638 639 640 641 642
/*
  Simple example of how to get a sequences starting from the first argument
  or 1 if no arguments have been given
*/

my_bool sequence_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count > 1)
  {
    strmov(message,"This function takes none or 1 argument");
    return 1;
  }
  if (args->arg_count)
643
    args->arg_type[0]= INT_RESULT;		/* Force argument to int */
644 645 646 647 648 649 650

  if (!(initid->ptr=(char*) malloc(sizeof(longlong))))
  {
    strmov(message,"Couldn't allocate memory");
    return 1;
  }
  bzero(initid->ptr,sizeof(longlong));
651 652 653
  /* 
    sequence() is a non-deterministic function : it has different value 
    even if called with the same arguments.
654
  */
655
  initid->const_item=0;
656 657 658 659 660 661 662 663 664
  return 0;
}

void sequence_deinit(UDF_INIT *initid)
{
  if (initid->ptr)
    free(initid->ptr);
}

665 666 667
longlong sequence(UDF_INIT *initid __attribute__((unused)), UDF_ARGS *args,
                  char *is_null __attribute__((unused)),
                  char *error __attribute__((unused)))
668 669 670
{
  ulonglong val=0;
  if (args->arg_count)
671
    val= *((longlong*) args->args[0]);
672
  return ++*((longlong*) initid->ptr) + val;
673 674
}

675

bk@work.mysql.com's avatar
bk@work.mysql.com committed
676 677 678 679 680 681 682 683 684
/****************************************************************************
** Some functions that handles IP and hostname conversions
** The orignal function was from Zeev Suraski.
**
** CREATE FUNCTION lookup RETURNS STRING SONAME "udf_example.so";
** CREATE FUNCTION reverse_lookup RETURNS STRING SONAME "udf_example.so";
**
****************************************************************************/

685
#ifdef __WIN__
686
#include <winsock2.h>
687
#else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
688 689 690 691
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
692
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
693 694

my_bool lookup_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
695
void lookup_deinit(UDF_INIT *initid);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
696 697 698
char *lookup(UDF_INIT *initid, UDF_ARGS *args, char *result,
	     unsigned long *length, char *null_value, char *error);
my_bool reverse_lookup_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
699
void reverse_lookup_deinit(UDF_INIT *initid);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
char *reverse_lookup(UDF_INIT *initid, UDF_ARGS *args, char *result,
		     unsigned long *length, char *null_value, char *error);


/****************************************************************************
** lookup IP for an hostname.
**
** This code assumes that gethostbyname_r exists and inet_ntoa() is thread
** safe (As it is in Solaris)
****************************************************************************/


my_bool lookup_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count != 1 || args->arg_type[0] != STRING_RESULT)
  {
    strmov(message,"Wrong arguments to lookup;  Use the source");
    return 1;
  }
  initid->max_length=11;
  initid->maybe_null=1;
721
#if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_SOLARIS_STYLE_GETHOST)
722 723
  (void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
724 725 726
  return 0;
}

727
void lookup_deinit(UDF_INIT *initid __attribute__((unused)))
728
{
729
#if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_SOLARIS_STYLE_GETHOST)
730 731 732 733
  (void) pthread_mutex_destroy(&LOCK_hostname);
#endif
}

734 735 736
char *lookup(UDF_INIT *initid __attribute__((unused)), UDF_ARGS *args,
             char *result, unsigned long *res_length, char *null_value,
             char *error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
737 738
{
  uint length;
739 740 741
  char name_buff[256];
  struct hostent *hostent;
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
742
  int tmp_errno;
743 744 745 746
  char hostname_buff[2048];
  struct hostent tmp_hostent;
#endif
  struct in_addr in;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
747 748 749 750 751 752 753 754 755 756

  if (!args->args[0] || !(length=args->lengths[0]))
  {
    *null_value=1;
    return 0;
  }
  if (length >= sizeof(name_buff))
    length=sizeof(name_buff)-1;
  memcpy(name_buff,args->args[0],length);
  name_buff[length]=0;
757
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
758 759 760 761 762 763
  if (!(hostent=gethostbyname_r(name_buff,&tmp_hostent,hostname_buff,
				sizeof(hostname_buff), &tmp_errno)))
  {
    *null_value=1;
    return 0;
  }
764 765 766 767 768 769 770 771 772 773
#else
  VOID(pthread_mutex_lock(&LOCK_hostname));
  if (!(hostent= gethostbyname((char*) name_buff)))
  {
    VOID(pthread_mutex_unlock(&LOCK_hostname));
    *null_value= 1;
    return 0;
  }
  VOID(pthread_mutex_unlock(&LOCK_hostname));
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
  memcpy_fixed((char*) &in,(char*) *hostent->h_addr_list, sizeof(in.s_addr));
  *res_length= (ulong) (strmov(result, inet_ntoa(in)) - result);
  return result;
}


/****************************************************************************
** return hostname for an IP number.
** The functions can take as arguments a string "xxx.xxx.xxx.xxx" or
** four numbers.
****************************************************************************/

my_bool reverse_lookup_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count == 1)
    args->arg_type[0]= STRING_RESULT;
  else if (args->arg_count == 4)
    args->arg_type[0]=args->arg_type[1]=args->arg_type[2]=args->arg_type[3]=
      INT_RESULT;
  else
  {
    strmov(message,
	   "Wrong number of arguments to reverse_lookup;  Use the source");
    return 1;
  }
  initid->max_length=32;
  initid->maybe_null=1;
801
#if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_SOLARIS_STYLE_GETHOST)
802 803
  (void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
804 805 806
  return 0;
}

807
void reverse_lookup_deinit(UDF_INIT *initid __attribute__((unused)))
808
{
809
#if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_SOLARIS_STYLE_GETHOST)
810 811 812
  (void) pthread_mutex_destroy(&LOCK_hostname);
#endif
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
813

814 815 816
char *reverse_lookup(UDF_INIT *initid __attribute__((unused)), UDF_ARGS *args,
                     char *result, unsigned long *res_length,
                     char *null_value, char *error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
817
{
818
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
819 820
  char name_buff[256];
  struct hostent tmp_hostent;
821
  int tmp_errno;
822 823 824
#endif
  struct hostent *hp;
  unsigned long taddr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
825 826 827 828 829 830 831 832 833 834
  uint length;

  if (args->arg_count == 4)
  {
    if (!args->args[0] || !args->args[1] ||!args->args[2] ||!args->args[3])
    {
      *null_value=1;
      return 0;
    }
    sprintf(result,"%d.%d.%d.%d",
835 836 837 838
	    (int) *((longlong*) args->args[0]),
	    (int) *((longlong*) args->args[1]),
	    (int) *((longlong*) args->args[2]),
	    (int) *((longlong*) args->args[3]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
839 840
  }
  else
841 842
  {					/* string argument */
    if (!args->args[0])			/* Return NULL for NULL values */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
843 844 845 846 847 848 849 850 851 852 853
    {
      *null_value=1;
      return 0;
    }
    length=args->lengths[0];
    if (length >= (uint) *res_length-1)
      length=(uint) *res_length;
    memcpy(result,args->args[0],length);
    result[length]=0;
  }

854
  taddr = inet_addr(result);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
855 856 857 858 859
  if (taddr == (unsigned long) -1L)
  {
    *null_value=1;
    return 0;
  }
860
#if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
861 862 863 864 865 866 867
  if (!(hp=gethostbyaddr_r((char*) &taddr,sizeof(taddr), AF_INET,
			   &tmp_hostent, name_buff,sizeof(name_buff),
			   &tmp_errno)))
  {
    *null_value=1;
    return 0;
  }
868 869 870 871 872 873 874 875 876 877
#else
  VOID(pthread_mutex_lock(&LOCK_hostname));
  if (!(hp= gethostbyaddr((char*) &taddr, sizeof(taddr), AF_INET)))
  {
    VOID(pthread_mutex_unlock(&LOCK_hostname));
    *null_value= 1;
    return 0;
  }
  VOID(pthread_mutex_unlock(&LOCK_hostname));
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
  *res_length=(ulong) (strmov(result,hp->h_name) - result);
  return result;
}

/*
** Syntax for the new aggregate commands are:
** create aggregate function <function_name> returns {string|real|integer}
**		  soname <name_of_shared_library>
**
** Syntax for avgcost: avgcost( t.quantity, t.price )
**	with t.quantity=integer, t.price=double
** (this example is provided by Andreas F. Bobak <bobak@relog.ch>)
*/


struct avgcost_data
{
895 896 897
  ulonglong	count;
  longlong	totalquantity;
  double	totalprice;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
};


/*
** Average Cost Aggregate Function.
*/
my_bool
avgcost_init( UDF_INIT* initid, UDF_ARGS* args, char* message )
{
  struct avgcost_data*	data;

  if (args->arg_count != 2)
  {
    strcpy(
	   message,
	   "wrong number of arguments: AVGCOST() requires two arguments"
	   );
    return 1;
  }

918
  if ((args->arg_type[0] != INT_RESULT) || (args->arg_type[1] != REAL_RESULT) )
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932
  {
    strcpy(
	   message,
	   "wrong argument type: AVGCOST() requires an INT and a REAL"
	   );
    return 1;
  }

  /*
  **	force arguments to double.
  */
  /*args->arg_type[0]	= REAL_RESULT;
    args->arg_type[1]	= REAL_RESULT;*/

933 934 935
  initid->maybe_null	= 0;		/* The result may be null */
  initid->decimals	= 4;		/* We want 4 decimals in the result */
  initid->max_length	= 20;		/* 6 digits + . + 10 decimals */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
936

937 938 939 940 941
  if (!(data = (struct avgcost_data*) malloc(sizeof(struct avgcost_data))))
  {
    strmov(message,"Couldn't allocate memory");
    return 1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
942 943 944 945 946 947 948 949 950 951 952
  data->totalquantity	= 0;
  data->totalprice	= 0.0;

  initid->ptr = (char*)data;

  return 0;
}

void
avgcost_deinit( UDF_INIT* initid )
{
953
  free(initid->ptr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
954 955
}

956 957

/* This is only for MySQL 4.0 compability */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
958
void
959
avgcost_reset(UDF_INIT* initid, UDF_ARGS* args, char* is_null, char* message)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
960
{
961 962 963
  avgcost_clear(initid, is_null, message);
  avgcost_add(initid, args, is_null, message);
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
964

965 966 967
/* This is needed to get things to work in MySQL 4.1.1 and above */

void
968 969
avgcost_clear(UDF_INIT* initid, char* is_null __attribute__((unused)),
              char* message __attribute__((unused)))
970 971 972 973 974
{
  struct avgcost_data* data = (struct avgcost_data*)initid->ptr;
  data->totalprice=	0.0;
  data->totalquantity=	0;
  data->count=		0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
975 976 977 978
}


void
979 980 981
avgcost_add(UDF_INIT* initid, UDF_ARGS* args,
            char* is_null __attribute__((unused)),
            char* message __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
982 983 984 985
{
  if (args->args[0] && args->args[1])
  {
    struct avgcost_data* data	= (struct avgcost_data*)initid->ptr;
986 987
    longlong quantity		= *((longlong*)args->args[0]);
    longlong newquantity	= data->totalquantity + quantity;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
988 989 990 991 992 993 994 995 996 997 998 999 1000
    double price		= *((double*)args->args[1]);

    data->count++;

    if (   ((data->totalquantity >= 0) && (quantity < 0))
	   || ((data->totalquantity <  0) && (quantity > 0)) )
    {
      /*
      **	passing from + to - or from - to +
      */
      if (   ((quantity < 0) && (newquantity < 0))
	     || ((quantity > 0) && (newquantity > 0)) )
      {
1001
	data->totalprice	= price * (double)newquantity;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1002 1003 1004 1005 1006 1007 1008
      }
      /*
      **	sub q if totalq > 0
      **	add q if totalq < 0
      */
      else
      {
1009 1010
	price		  = data->totalprice / (double)data->totalquantity;
	data->totalprice  = price * (double)newquantity;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1011 1012 1013 1014 1015 1016
      }
      data->totalquantity = newquantity;
    }
    else
    {
      data->totalquantity	+= quantity;
1017
      data->totalprice		+= price * (double)quantity;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1018 1019 1020 1021 1022 1023 1024 1025 1026
    }

    if (data->totalquantity == 0)
      data->totalprice = 0.0;
  }
}


double
1027 1028
avgcost( UDF_INIT* initid, UDF_ARGS* args __attribute__((unused)),
         char* is_null, char* error __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1029 1030 1031 1032 1033 1034 1035 1036 1037
{
  struct avgcost_data* data = (struct avgcost_data*)initid->ptr;
  if (!data->count || !data->totalquantity)
  {
    *is_null = 1;
    return 0.0;
  }

  *is_null = 0;
1038
  return data->totalprice/(double)data->totalquantity;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1039 1040
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
my_bool myfunc_argument_name_init(UDF_INIT *initid, UDF_ARGS *args,
				  char *message);
char *myfunc_argument_name(UDF_INIT *initid, UDF_ARGS *args, char *result,
			   unsigned long *length, char *null_value,
			   char *error);

my_bool myfunc_argument_name_init(UDF_INIT *initid, UDF_ARGS *args,
				  char *message)
{
  if (args->arg_count != 1)
  {
    strmov(message,"myfunc_argument_name_init accepts only one argument");
    return 1;
  }
  initid->max_length= args->attribute_lengths[0];
  initid->maybe_null= 1;
  initid->const_item= 1;
  return 0;
}

1061 1062 1063 1064
char *myfunc_argument_name(UDF_INIT *initid __attribute__((unused)),
                           UDF_ARGS *args, char *result,
                           unsigned long *length, char *null_value,
                           char *error __attribute__((unused)))
1065 1066 1067 1068 1069 1070
{
  if (!args->attributes[0])
  {
    null_value= 0;
    return 0;
  }
1071
  (*length)--; /* space for ending \0 (for debugging purposes) */
1072 1073 1074 1075 1076 1077 1078
  if (*length > args->attribute_lengths[0])
    *length= args->attribute_lengths[0];
  memcpy(result, args->attributes[0], *length);
  result[*length]= 0;
  return result;
}

1079 1080 1081 1082 1083 1084 1085 1086 1087


my_bool is_const_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count != 1)
  {
    strmov(message, "IS_CONST accepts only one argument");
    return 1;
  }
1088
  initid->ptr= (char*)((args->args[0] != NULL) ? 1UL : 0);
1089 1090 1091
  return 0;
}

1092 1093 1094
char * is_const(UDF_INIT *initid, UDF_ARGS *args __attribute__((unused)),
                char *result, unsigned long *length,
                char *is_null, char *error __attribute__((unused)))
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
{
  if (initid->ptr != 0) {
    sprintf(result, "const");
  } else {
    sprintf(result, "not const");
  }
  *is_null= 0;
  *length= strlen(result);
  return result;
}


1107

1108 1109 1110 1111
my_bool check_const_len_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if (args->arg_count != 1)
  {
1112
    strmov(message, "CHECK_CONST_LEN accepts only one argument");
1113 1114 1115 1116
    return 1;
  }
  if (args->args[0] == 0)
  {
1117
    initid->ptr= (char*)"Not constant";
1118 1119 1120
  }
  else if(strlen(args->args[0]) == args->lengths[0])
  {
1121
    initid->ptr= (char*)"Correct length";
1122 1123 1124
  }
  else
  {
1125
    initid->ptr= (char*)"Wrong length";
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
  }
  initid->max_length = 100;
  return 0;
}

char * check_const_len(UDF_INIT *initid, UDF_ARGS *args __attribute__((unused)),
                char *result, unsigned long *length,
                char *is_null, char *error __attribute__((unused)))
{
  strmov(result, initid->ptr);
  *length= strlen(result);
  *is_null= 0;
  return result;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1142
#endif /* HAVE_DLOPEN */