File: mysql_stubs.c

package info (click to toggle)
mysql-ocaml 1.0.4-2%2Betch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 728 kB
  • ctags: 717
  • sloc: sh: 2,278; ml: 599; ansic: 531; makefile: 74; perl: 41
file content (708 lines) | stat: -rw-r--r-- 15,222 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
232
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
356
357
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
434
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
472
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/*
 * This module provides access to MySQL from Objective Caml. 
 */

 
#include <stdio.h>              /* sprintf */
#include <string.h> 
#include <stdarg.h>
 
/* OCaml runtime system */

#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/fail.h>
#include <caml/alloc.h>
#include <caml/callback.h>
#include <caml/custom.h>
#include <caml/signals.h>

/* MySQL API */

#include <mysql/mysql.h>
#include <mysql/mysqld_error.h>
#include <mysql/errmsg.h>
/* type 'a option = None | Some of 'a */

#define NONE            Val_int(0)     
#define SOME            0             

#define EXTERNAL                /* dummy to highlight fn's exported to ML */

/* Abstract types 
 *
 * dbd - data base descriptor
 *
 *      header with Abstract_tag
 *      0:      MYSQL*
 *      1:      bool    (open == true, closed == false)
 *
 * res - result returned from query/exec
 *
 *      header with Final_tag
 *      0:      finalization function for 1
 *      1:      MYSQL_RES*
 *
 */

/* macros to access C values stored inside the abstract values */
 
#define DBDmysql(x) ((MYSQL*)(Field(x,1)))
#define DBDopen(x) (Field(x,2))
#define RESval(x) (*(MYSQL_RES**)Data_custom_val(x))

static void mysqlfailwith(char *err) Noreturn;
static void mysqlfailmsg(const char *fmt, ...) Noreturn;

static void
mysqlfailwith(char *err) {
  raise_with_string(*caml_named_value("mysql error"), err);
}

static void
mysqlfailmsg(const char *fmt, ...) {
  char buf[1024];
  va_list args;

  va_start(args, fmt);
  vsnprintf(buf, sizeof buf, fmt, args);
  va_end(args);
  
  raise_with_string(*caml_named_value("mysql error"), buf);  

}

static int
int_option(value v)
{
  if (v == NONE)
    return 0;
  else
    return  Int_val(Field(v,SOME));
}


/*
 * str_option gets a char* from an ML string option value.  Returns
 * NULL for NONE.
 */

static char*
str_option(value v)
{
  if (v == NONE)
    return (char*) NULL;
  else 
    return String_val(Field(v,SOME));
}

/*
 * val_str_option creates a string option value from a char* (NONE for
 * NULL) -- dual to str_option().
 */
 
static value
val_str_option(char* s, unsigned long length)
{
  CAMLparam0();
  CAMLlocal2(res, v);

  if (!s)
    res = NONE;
  else {
    v = alloc_string(length);
    memcpy(String_val(v), s, length);
    
    res = alloc_small(1,SOME);
    Field(res,0) = v; 
  }
  CAMLreturn(res);
}

/*
 * val_some creates a (SOME v) from value v.
 */

static value
val_some(value some)
{
  CAMLparam1(some);
  CAMLlocal2(res, v);
        
  v = some;
  res = alloc_small(1,SOME);
  Field(res,0) = v;

  CAMLreturn(res);
}

/* check_dbd checks that the data base connection is still open.  The
 * open flag is reset by db_disconnect().
 */

static void
check_dbd(value dbd, char *fun)
{        
  if (!Bool_val(DBDopen(dbd))) 
    mysqlfailmsg("Mysql.%s called with closed connection", fun);
}


static void
conn_finalize(value dbd)
{
  if (Bool_val(DBDopen(dbd))) {
    caml_enter_blocking_section();
    mysql_close(DBDmysql(dbd));
    caml_leave_blocking_section();
  }
}

/* db_connect opens a data base connection and returns an abstract
 * connection object.
 */
 
EXTERNAL value
db_connect(value args)

{
  CAMLparam1(args);
  int i = 0;
  char *host      = str_option(Field(args,i++));
  char *db        = str_option(Field(args,i++));
  unsigned port   = (unsigned) int_option(Field(args,i++));
  char *pwd       = str_option(Field(args,i++));
  char *user      = str_option(Field(args,i++));
  CAMLlocal1(res);
  MYSQL *init;
  MYSQL *mysql;
        
  init = mysql_init(NULL);
  if (!init) {
    mysqlfailwith("connect failed");
  } else {
    caml_enter_blocking_section();
    mysql = mysql_real_connect(init ,host ,user
                               ,pwd ,db ,port
                               ,NULL, 0);
    caml_leave_blocking_section();
    if (!mysql) {
      mysqlfailwith(mysql_error(init));
    } else {
      res = alloc_final(3, conn_finalize, 100,1000);
      Field(res, 1) = (value)mysql;
      Field(res, 2) =  Val_true;
    }
  }
  CAMLreturn(res);
}


EXTERNAL value
db_change_user(value dbd, value args) {
  char *db        = str_option(Field(args,1));
  char *pwd       = str_option(Field(args,3));
  char *user      = str_option(Field(args,4));

  check_dbd(dbd,"change_user");

  caml_enter_blocking_section();
  if (mysql_change_user(DBDmysql(dbd), user, pwd, db)) {    
    caml_leave_blocking_section();
    mysqlfailmsg("Mysql.change_user: %s", mysql_error(DBDmysql(dbd)));
  }
  caml_leave_blocking_section();
  return Val_unit;
}

EXTERNAL value
db_list_dbs(value dbd, value pattern, value blah) {
  CAMLparam3(dbd, pattern, blah);
  CAMLlocal2(out, dbs);
  char *wild = str_option(pattern);
  int n, i;
  MYSQL_RES *res;
  MYSQL_ROW row;

  caml_enter_blocking_section();
  res = mysql_list_dbs(DBDmysql(dbd), wild);
  caml_leave_blocking_section();

  if (!res)
    CAMLreturn(NONE);

  n = mysql_num_rows(res);

  if (n == 0) {
    mysql_free_result(res);
    CAMLreturn(NONE);
  }

  dbs = alloc_tuple(n); /* Array */
  i = 0;
  while ((row = mysql_fetch_row(res)) != NULL) {
    Store_field(dbs, i, copy_string(row[0]));
    i++;
  }

  mysql_free_result(res);
  out = alloc_small(1, SOME);
  Field(out, 0) = dbs;
  CAMLreturn(out);

}

EXTERNAL value
db_select_db(value dbd, value newdb) {

  check_dbd(dbd, "select_db");
  
  caml_enter_blocking_section();
  if (mysql_select_db(DBDmysql(dbd), String_val(newdb))) {
    mysqlfailmsg("Mysql.select_db: %s", mysql_error(DBDmysql(dbd)));
    caml_leave_blocking_section();
  }
  caml_leave_blocking_section();
  return Val_unit;
}

/*
 * db_disconnect closes a db connection and marks the dbd closed.
 */

EXTERNAL value
db_disconnect(value dbd)
{
  CAMLparam1(dbd);
  check_dbd(dbd,"disconnect");
  caml_enter_blocking_section();
  mysql_close(DBDmysql(dbd));
  caml_leave_blocking_section();
  Field(dbd, 1) = Val_false;
  Field(dbd, 2) = Val_false; /* Mark closed */
  CAMLreturn(Val_unit);
}

EXTERNAL value
db_ping(value dbd)
{

  check_dbd(dbd,"ping");

  caml_enter_blocking_section();
  if (mysql_ping(DBDmysql(dbd))) {
    caml_leave_blocking_section();
    mysqlfailmsg("Mysql.ping: %s", mysql_error(DBDmysql(dbd)));
  }
  caml_leave_blocking_section();
  return Val_unit;

}

/*
 * finalize -- this is called when a data base result is garbage
 * collected -- frees memory allocated by MySQL.
 */

static void
res_finalize(value result)
{
  MYSQL_RES *res = RESval(result);
  if (res)
    mysql_free_result(res);
}


struct custom_operations res_ops = {
  "Mysql Query Results",
  res_finalize,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default
};

/*
 * db_exec -- execute a SQL query or command.  Returns a handle to
 * access the result.
 */

EXTERNAL value
db_exec(value dbd, value sql)
{
  CAMLparam2(dbd, sql);
  CAMLlocal2(res, v);
  MYSQL *mysql;
       
  check_dbd(dbd,"exec");
  mysql = DBDmysql(dbd);
        
  caml_enter_blocking_section();
  if (mysql_real_query(mysql, String_val(sql), string_length(sql))) {
    caml_leave_blocking_section();
    mysqlfailmsg("Mysql.exec: %s", mysql_error(mysql));
  } else {
    MYSQL_RES *saved;
    caml_leave_blocking_section();
    res = alloc_custom(&res_ops, sizeof(MYSQL_RES*), 1, 10);
    saved = mysql_store_result(DBDmysql(dbd));
    memcpy(Data_custom_val(res), &saved, sizeof(MYSQL_RES*));
  }

  CAMLreturn(res);
}

/* 
 * db_fetch -- fetch one result tuple, represented as array of string
 * options.  In case a value is Null, the respective value is None. 
 * Returns (Some v) in case there is such a result and None otherwise. 
 * Moves the internal result cursor to the next tuple.
 */

EXTERNAL value
db_fetch (value result)
{
  CAMLparam1(result);
  CAMLlocal2(fields, s);
  unsigned int i, n;
  unsigned long *length;  /* array of long */
  MYSQL_RES *res;
  MYSQL_ROW row;
  
  res = RESval(result);
  if (!res) 
    mysqlfailwith("Mysql.fetch: result did not return fetchable data");
  
  n = mysql_num_fields(res);
  if (n == 0)
    mysqlfailwith("Mysql.fetch: no columns");
  
  row = mysql_fetch_row(res);
  if (!row) 
    CAMLreturn(NONE);
  
  /* create Some([| f1; f2; .. ;fn |]) */
  
  length = mysql_fetch_lengths(res);      /* length[] */
  fields = alloc_tuple(n);                    /* array */
  for (i=0;i<n;i++) {
    s = val_str_option(row[i], length[i]);
    Store_field(fields, i, s);
  }
  
  CAMLreturn(val_some(fields));
}

EXTERNAL value
db_to_row(value result, value offset) {
  int64 off = Int64_val(offset);
  MYSQL_RES *res;

  res = RESval(result);
  if (!res) 
    mysqlfailwith("Mysql.to_row: result did not return fetchable data");

  if (off < 0 || off > (int64)mysql_num_rows(res)-1)
    invalid_argument("Mysql.to_row: offset out of range");

  mysql_data_seek(res, off);

  return Val_unit;
}

/*
 * db_status -- returns current status (simplistic)
 */

EXTERNAL value
db_status(value dbd)

{
  CAMLparam1(dbd);        
  check_dbd(dbd, "status");
  CAMLreturn(Val_int(mysql_errno(DBDmysql(dbd))));
}

/*
 * db_errmsg -- returns string option with last error message (None ==
 * no error)
 */

EXTERNAL value
db_errmsg(value dbd)
{
  CAMLparam1(dbd);
  CAMLlocal1(s);
  const char *msg;

  check_dbd(dbd,"errmsg");
  
  msg = mysql_error(DBDmysql(dbd));
  if (!msg || msg[0] == '\0')
    msg = (char*) NULL;
  s = val_str_option(msg, msg == (char *) NULL ? 0 : strlen(msg));
  CAMLreturn(s);
}

/*
 * db_escape - takes a string and escape all characters inside which
 * must be escaped inside MySQL strings.  This helps to construct SQL
 * statements easily.  Simply returns the new string including the
 * quotes. 
 */

EXTERNAL value
db_escape(value str)
{
  CAMLparam1(str);
  char *s;
  char *buf;
  int len, esclen;
  CAMLlocal1(res);
        
  s = String_val(str);
  len = string_length(str);
  buf = (char*) stat_alloc(2*len+1);
  esclen = mysql_escape_string(buf,s,len);

  res = alloc_string(esclen);
  memcpy(String_val(res), buf, esclen);
  stat_free(buf);
  
  CAMLreturn(res);
}

/*
 * db_size -- returns the size of the current result (number of rows).
 */

EXTERNAL value
db_size(value result)
{
  CAMLparam1(result);
  MYSQL_RES *res;
  int64 size;

  res = RESval(result);
  if (!res)
    size = 0;
  else
    size = (int64)(mysql_num_rows(res));
  
  CAMLreturn(copy_int64(size));
}

EXTERNAL value
db_affected(value dbd) {
  CAMLparam1(dbd);
  CAMLreturn(copy_int64(mysql_affected_rows(DBDmysql(dbd))));
}

EXTERNAL value
db_insert_id(value dbd) {
  CAMLparam1(dbd);
  CAMLreturn(copy_int64(mysql_insert_id(DBDmysql(dbd))));
}

EXTERNAL value
db_fields(value result)
{
  MYSQL_RES *res;
  long size;

  res = RESval(result);
  if (!res)
    size = 0;
  else
    size = (long)(mysql_num_fields(res));
  
  return Val_long(size);
}

EXTERNAL value
db_client_info(value unit) {
  CAMLparam1(unit);
  CAMLlocal1(info);
  info = copy_string(mysql_get_client_info());
  CAMLreturn(info);
}

EXTERNAL value
db_host_info(value dbd) {
  CAMLparam1(dbd);
  CAMLlocal1(info);
  info = copy_string(mysql_get_host_info(DBDmysql(dbd)));
  CAMLreturn(info);
}

EXTERNAL value
db_server_info(value dbd) {
  CAMLparam1(dbd);
  CAMLlocal1(info);
  info = copy_string(mysql_get_server_info(DBDmysql(dbd)));
  CAMLreturn(info);
}

EXTERNAL value
db_proto_info(value dbd) {
  long info = (long)mysql_get_proto_info(DBDmysql(dbd));
  return Val_long(info);
}


/*
 * type2dbty - maps column types to dbty values which describe the
 * column types in OCaml.
 */

#define INT_TY          0
#define FLOAT_TY        1
#define STRING_TY       2
#define SET_TY          3
#define ENUM_TY         4
#define DATETIME_TY     5
#define DATE_TY         6
#define TIME_TY         7
#define YEAR_TY         8
#define TIMESTAMP_TY    9
#define UNKNOWN_TY      10
#define INT64_TY        11
#define BLOB_TY         12
#define DECIMAL_TY			13

static value
type2dbty (int type)
{
  static struct {int mysql; value caml;} map[] = {
    {FIELD_TYPE_DECIMAL     , Val_long(DECIMAL_TY)},
    {FIELD_TYPE_TINY        , Val_long(INT_TY)},
    {FIELD_TYPE_SHORT       , Val_long(INT_TY)},
    {FIELD_TYPE_LONG        , Val_long(INT_TY)},
    {FIELD_TYPE_FLOAT       , Val_long(FLOAT_TY)},
    {FIELD_TYPE_DOUBLE      , Val_long(FLOAT_TY)},
    {FIELD_TYPE_NULL        , Val_long(STRING_TY)},
    {FIELD_TYPE_TIMESTAMP   , Val_long(TIMESTAMP_TY)},
    {FIELD_TYPE_LONGLONG    , Val_long(INT64_TY)},
    {FIELD_TYPE_INT24       , Val_long(INT_TY)},
    {FIELD_TYPE_DATE        , Val_long(DATE_TY)},
    {FIELD_TYPE_TIME        , Val_long(TIME_TY)},
    {FIELD_TYPE_DATETIME    , Val_long(DATETIME_TY)},
    {FIELD_TYPE_YEAR        , Val_long(YEAR_TY)},
    {FIELD_TYPE_NEWDATE     , Val_long(UNKNOWN_TY)},
    {FIELD_TYPE_ENUM        , Val_long(ENUM_TY)},
    {FIELD_TYPE_SET         , Val_long(SET_TY)},
    {FIELD_TYPE_TINY_BLOB   , Val_long(BLOB_TY)},
    {FIELD_TYPE_MEDIUM_BLOB , Val_long(BLOB_TY)},
    {FIELD_TYPE_LONG_BLOB   , Val_long(BLOB_TY)},
    {FIELD_TYPE_BLOB        , Val_long(BLOB_TY)},
    {FIELD_TYPE_VAR_STRING  , Val_long(STRING_TY)},
    {FIELD_TYPE_STRING      , Val_long(STRING_TY)},
    {-1 /*default*/         , Val_long(UNKNOWN_TY)}
  };
  int i;
  
  /* in principle using bsearch() would be better -- but how can
   * we know that the left side of the map is properly sorted? 
   */

  for (i=0; map[i].mysql != -1 && map[i].mysql != type; i++)
    /* empty */ ;
  
  return map[i].caml;
}

value 
make_field(MYSQL_FIELD *f) {
  CAMLparam0();
  CAMLlocal5(out, data, name, table, def);

  name = copy_string(f->name);

  if (f->table)
    table = val_str_option(f->table, strlen(f->table));
  else
    table = NONE;

  if (f->def)
    def = val_str_option(f->def, strlen(f->def));
  else
    def = NONE;

  data = alloc_small(7, 0);
  Field(data, 0) = name;
  Field(data, 1) = table;
  Field(data, 2) = def;
  Field(data, 3) = type2dbty(f->type);
  Field(data, 4) = Val_long(f->max_length);
  Field(data, 5) = Val_long(f->flags);
  Field(data, 6) = Val_long(f->decimals);

  CAMLreturn(data);
}
     
EXTERNAL value
db_fetch_field(value result) {
  CAMLparam1(result);
  CAMLlocal2(field, out);
  MYSQL_FIELD *f;
  MYSQL_RES *res = RESval(result);

  if (!res)
    CAMLreturn(NONE);

  f = mysql_fetch_field(res);
  if (!f)
    CAMLreturn(NONE);

  field = make_field(f);
  out = alloc_small(1, SOME);
  Field(out, SOME) = field;
  CAMLreturn(out);
}

EXTERNAL value
db_fetch_field_dir(value result, value pos) {
  CAMLparam2(result, pos);
  CAMLlocal2(field, out);
  MYSQL_FIELD *f;
  MYSQL_RES *res = RESval(result);

  if (!res)
    CAMLreturn(NONE);

  f = mysql_fetch_field_direct(res, Long_val(pos));
  if (!f)
    CAMLreturn(NONE);

  field = make_field(f);
  out = alloc_small(1, SOME);
  Field(out, SOME) = field;
  CAMLreturn(out);
}


EXTERNAL value
db_fetch_fields(value result) {
  CAMLparam1(result);
  CAMLlocal2(fields, out);
  MYSQL_RES *res = RESval(result);
  MYSQL_FIELD *f;
  int i, n;

  n = mysql_num_fields(res);

  if (n == 0)
    CAMLreturn(NONE);

  f = mysql_fetch_fields(res);

  fields = alloc_tuple(n);

  for (i = 0; i < n; i++) {
    Store_field(fields, i, make_field(f+i));
  }

  out = alloc_small(1, SOME);
  Field(out, 0) = fields;
  CAMLreturn(out);
}