-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathodbc.c
4747 lines (4000 loc) · 118 KB
/
odbc.c
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2002-2025, University of Amsterdam,
VU University Amsterdam,
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This module is based on pl_odbc.{c,pl}, a read-only ODBC interface by
Stefano De Giorgi ([email protected]).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#define _CRT_SECURE_NO_WARNINGS 1
#include <config.h>
#ifdef _MSC_VER
#pragma warning(disable : 4996) /* deprecated function SQLSetConnectOption() */
#endif
#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#ifdef __WINDOWS__
#include <windows.h>
#endif
#define O_DEBUG 1
static int odbc_debuglevel = 0;
#ifdef O_DEBUG
#define DEBUG(level, g) if ( odbc_debuglevel >= (level) ) g
#else
#define DEBUG(level, g) ((void)0)
#endif
#include <sql.h>
#include <sqlext.h>
#include <time.h>
#include <limits.h> /* LONG_MAX, etc. */
#include <math.h>
#ifndef HAVE_SQLLEN
#define SQLLEN DWORD
#endif
#ifndef HAVE_SQLULEN
#define SQLULEN SQLUINTEGER
#endif
#ifndef SQL_COPT_SS_MARS_ENABLED
#define SQL_COPT_SS_MARS_ENABLED 1224
#endif
#ifndef SQL_MARS_ENABLED_YES
#define SQL_MARS_ENABLED_YES (SQLPOINTER)1
#endif
#ifndef WORDS_BIGENDIAN
#define ENC_SQLWCHAR ENC_UNICODE_LE
#else
#define ENC_SQLWCHAR ENC_UNICODE_BE
#endif
#ifdef __WINDOWS__
#define DEFAULT_ENCODING ENC_SQLWCHAR
#else
#define DEFAULT_ENCODING ENC_UTF8
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifndef NULL
#define NULL 0
#endif
#define MAX_NOGETDATA 1024 /* use SQLGetData() on wider columns */
#ifndef STRICT
#define STRICT
#endif
#define NameBufferLength 256
#define CVNERR -1 /* conversion error */
#if defined(_REENTRANT) && defined(O_PLMT)
#include <pthread.h>
/* FIXME: Actually use these */
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define LOCK() pthread_mutex_lock(&mutex)
#define UNLOCK() pthread_mutex_unlock(&mutex)
#if __WINDOWS__
static CRITICAL_SECTION context_mutex;
#define INIT_CONTEXT_LOCK() InitializeCriticalSection(&context_mutex)
#define LOCK_CONTEXTS() EnterCriticalSection(&context_mutex)
#define UNLOCK_CONTEXTS() LeaveCriticalSection(&context_mutex)
#else
static pthread_mutex_t context_mutex = PTHREAD_MUTEX_INITIALIZER;
#define INIT_CONTEXT_LOCK()
#define LOCK_CONTEXTS() pthread_mutex_lock(&context_mutex)
#define UNLOCK_CONTEXTS() pthread_mutex_unlock(&context_mutex)
#endif
#else /*multi-threaded*/
#define LOCK()
#define UNLOCK()
#define LOCK_CONTEXTS()
#define UNLOCK_CONTEXTS()
#define INIT_CONTEXT_LOCK()
#endif /*multi-threaded*/
#if !defined(HAVE_TIMEGM) && defined(HAVE_MKTIME) && defined(USE_UTC)
#define EMULATE_TIMEGM
static time_t timegm(struct tm *tm);
#define HAVE_TIMEGM
#endif
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Work around bug in MS SQL Server that doesn't allow for SQLGetData() on
SQLColumns(). Grrr!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#define SQL_SERVER_BUG 1
static atom_t ATOM_row; /* "row" */
static atom_t ATOM_informational; /* "informational" */
static atom_t ATOM_default; /* "default" */
static atom_t ATOM_once; /* "once" */
static atom_t ATOM_multiple; /* "multiple" */
static atom_t ATOM_commit; /* "commit" */
static atom_t ATOM_rollback; /* "rollback" */
static atom_t ATOM_atom;
static atom_t ATOM_string;
static atom_t ATOM_codes;
static atom_t ATOM_float;
static atom_t ATOM_integer;
static atom_t ATOM_time;
static atom_t ATOM_date;
static atom_t ATOM_timestamp;
static atom_t ATOM_all_types;
static atom_t ATOM_null; /* default null atom */
static atom_t ATOM_; /* "" */
static atom_t ATOM_read;
static atom_t ATOM_update;
static atom_t ATOM_dynamic;
static atom_t ATOM_forwards_only;
static atom_t ATOM_keyset_driven;
static atom_t ATOM_static;
static atom_t ATOM_auto;
static atom_t ATOM_fetch;
static atom_t ATOM_end_of_file;
static atom_t ATOM_next;
static atom_t ATOM_prior;
static atom_t ATOM_first;
static atom_t ATOM_last;
static atom_t ATOM_absolute;
static atom_t ATOM_relative;
static atom_t ATOM_bookmark;
static atom_t ATOM_strict;
static atom_t ATOM_relaxed;
static functor_t FUNCTOR_timestamp7; /* timestamp/7 */
static functor_t FUNCTOR_time3; /* time/7 */
static functor_t FUNCTOR_date3; /* date/3 */
static functor_t FUNCTOR_odbc3; /* odbc(state, code, message) */
static functor_t FUNCTOR_error2; /* error(Formal, Context) */
static functor_t FUNCTOR_type_error2; /* type_error(Term, Expected) */
static functor_t FUNCTOR_domain_error2; /* domain_error(Term, Expected) */
static functor_t FUNCTOR_existence_error2; /* existence_error(Term, Expected) */
static functor_t FUNCTOR_representation_error1; /* representation_error(What) */
static functor_t FUNCTOR_resource_error1; /* resource_error(Error) */
static functor_t FUNCTOR_permission_error3;
static functor_t FUNCTOR_odbc_statement1; /* $odbc_statement(Id) */
static functor_t FUNCTOR_odbc_connection1;
static functor_t FUNCTOR_encoding1;
static functor_t FUNCTOR_user1;
static functor_t FUNCTOR_password1;
static functor_t FUNCTOR_driver_string1;
static functor_t FUNCTOR_alias1;
static functor_t FUNCTOR_mars1;
static functor_t FUNCTOR_connection_pooling1;
static functor_t FUNCTOR_connection_pool_mode1;
static functor_t FUNCTOR_odbc_version1;
static functor_t FUNCTOR_open1;
static functor_t FUNCTOR_auto_commit1;
static functor_t FUNCTOR_types1;
static functor_t FUNCTOR_minus2;
static functor_t FUNCTOR_gt2;
static functor_t FUNCTOR_context_error3;
static functor_t FUNCTOR_data_source2;
static functor_t FUNCTOR_null1;
static functor_t FUNCTOR_source1;
static functor_t FUNCTOR_column3;
static functor_t FUNCTOR_access_mode1;
static functor_t FUNCTOR_cursor_type1;
static functor_t FUNCTOR_silent1;
static functor_t FUNCTOR_findall2; /* findall(Term, row(...)) */
static functor_t FUNCTOR_affected1;
static functor_t FUNCTOR_fetch1;
static functor_t FUNCTOR_wide_column_threshold1; /* set max_nogetdata */
#define SQL_PL_DEFAULT 0 /* don't change! */
#define SQL_PL_ATOM 1 /* return as atom */
#define SQL_PL_CODES 2 /* return as code-list */
#define SQL_PL_STRING 3 /* return as string */
#define SQL_PL_INTEGER 4 /* return as integer */
#define SQL_PL_FLOAT 5 /* return as float */
#define SQL_PL_TIME 6 /* return as time/3 structure */
#define SQL_PL_DATE 7 /* return as date/3 structure */
#define SQL_PL_TIMESTAMP 8 /* return as timestamp/7 structure */
#define PARAM_BUFSIZE (SQLLEN)sizeof(double)
typedef uintptr_t code;
typedef struct
{ SWORD cTypeID; /* C type of value */
SWORD plTypeID; /* Prolog type of value */
SWORD sqlTypeID; /* Sql type of value */
SWORD scale; /* Scale */
SQLPOINTER ptr_value; /* ptr to value */
SQLLEN length_ind; /* length/indicator of value */
SQLLEN len_value; /* length of value (as parameter) */
term_t put_data; /* data to put there */
struct
{ atom_t table; /* Table name */
atom_t column; /* column name */
} source; /* origin of the data */
char buf[PARAM_BUFSIZE]; /* Small buffer for simple cols */
} parameter;
typedef struct
{ enum
{ NULL_VAR, /* represent as variable */
NULL_ATOM, /* some atom */
NULL_FUNCTOR, /* e.g. null(_) */
NULL_RECORD /* an arbitrary term */
} nulltype;
union
{ atom_t atom; /* as atom */
functor_t functor; /* as functor */
record_t record; /* as term */
} nullvalue;
int references; /* reference count */
} nulldef; /* Prolog's representation of NULL */
typedef struct
{ int references; /* reference count */
unsigned flags; /* misc flags */
code codes[1]; /* executable code */
} findall;
typedef struct connection
{ long magic; /* magic code */
atom_t alias; /* alias name of the connection */
atom_t dsn; /* DSN name of the connection */
HDBC hdbc; /* ODBC handle */
nulldef *null; /* Prolog null value */
unsigned flags; /* general flags */
int max_qualifier_length; /* SQL_MAX_QUALIFIER_NAME_LEN */
SQLULEN max_nogetdata; /* handle as long field if larger */
IOENC encoding; /* Character encoding to use */
int rep_flag; /* REP_* for encoding */
struct connection *next; /* next in chain */
} connection;
typedef struct
{ long magic; /* magic code */
connection *connection; /* connection used */
HENV henv; /* ODBC environment */
HSTMT hstmt; /* ODBC statement handle */
RETCODE rc; /* status of last operation */
parameter *params; /* Input parameters */
parameter *result; /* Outputs (row descriptions) */
SQLSMALLINT NumCols; /* # columns */
SQLSMALLINT NumParams; /* # parameters */
functor_t db_row; /* Functor for row */
SQLINTEGER sqllen; /* length of statement (in characters) */
union
{ SQLWCHAR *w; /* as unicode */
unsigned char *a; /* as multibyte */
} sqltext; /* statement text */
int char_width; /* sizeof a character */
unsigned flags; /* general flags */
nulldef *null; /* Prolog null value */
findall *findall; /* compiled code to create result */
SQLULEN max_nogetdata; /* handle as long field if larger */
struct context *clones; /* chain of clones */
} context;
static struct
{ long statements_created; /* # created statements */
long statements_freed; /* # destroyed statements */
} statistics;
#define CON_MAGIC 0x7c42b620 /* magic code */
#define CTX_MAGIC 0x7c42b621 /* magic code */
#define CTX_FREEMAGIC 0x7c42b622 /* magic code if freed */
#define CTX_PERSISTENT 0x0001 /* persistent statement handle */
#define CTX_BOUND 0x0002 /* result-columns are bound */
#define CTX_SQLMALLOCED 0x0004 /* sqltext is malloced */
#define CTX_INUSE 0x0008 /* statement is running */
#define CTX_OWNNULL 0x0010 /* null-definition is not shared */
#define CTX_SOURCE 0x0020 /* include source of results */
#define CTX_SILENT 0x0040 /* don't produce messages */
#define CTX_PREFETCHED 0x0080 /* we have a prefetched value */
#define CTX_COLUMNS 0x0100 /* this is an SQLColumns() statement */
#define CTX_TABLES 0x0200 /* this is an SQLTables() statement */
#define CTX_GOT_QLEN 0x0400 /* got SQL_MAX_QUALIFIER_NAME_LEN */
#define CTX_NOAUTO 0x0800 /* fetch by hand */
#define CTX_PRIMARYKEY 0x1000 /* this is an SQLPrimaryKeys() statement */
#define CTX_FOREIGNKEY 0x2000 /* this is an SQLForeignKeys() statement */
#define CTX_EXECUTING 0x4000 /* Context is currently being used in SQLExecute */
#define FND_SIZE(n) ((size_t)&((findall*)NULL)->codes[n])
#define ison(s, f) ((s)->flags & (f))
#define isoff(s, f) !ison(s, f)
#define set(s, f) ((s)->flags |= (f))
#define clear(s, f) ((s)->flags &= ~(f))
static HENV henv; /* environment handle (ODBC) */
/* Prototypes */
static int pl_put_row(term_t, context *);
static int pl_put_column(context *c, int nth, term_t col);
static SWORD CvtSqlToCType(context *ctxt, SQLSMALLINT, SQLSMALLINT);
static void free_context(context *ctx);
static void close_context(context *ctx);
static void unmark_and_close_context(context *ctx);
static foreign_t odbc_set_connection(connection *cn, term_t option);
static int get_pltype(term_t t, SWORD *type);
static SWORD get_sqltype_from_atom(atom_t name, SWORD *type);
static const char *sql_type_name(SWORD type);
static const char *sql_c_type_name(SWORD type);
/*******************************
* ERRORS *
*******************************/
static int
odbc_report(HENV henv, HDBC hdbc, HSTMT hstmt, RETCODE rc)
{ SQLCHAR state[16]; /* Normally 5-character ID */
SQLINTEGER native; /* was DWORD */
SQLCHAR message[SQL_MAX_MESSAGE_LENGTH+1];
SWORD msglen;
RETCODE rce;
term_t msg = PL_new_term_ref();
switch ( (rce=SQLError(henv, hdbc, hstmt, state, &native, message,
sizeof(message), &msglen)) )
{ case SQL_NO_DATA_FOUND:
case SQL_SUCCESS_WITH_INFO:
if ( rc != SQL_ERROR )
return TRUE;
/*FALLTHROUGH*/
case SQL_SUCCESS:
{ term_t s;
if ( msglen > SQL_MAX_MESSAGE_LENGTH )
msglen = SQL_MAX_MESSAGE_LENGTH; /* TBD: get the rest? */
if ( (s = PL_new_term_ref()) &&
PL_unify_chars(s, PL_STRING|REP_MB,
(size_t)msglen, (const char*)message) &&
PL_unify_term(msg,
PL_FUNCTOR, FUNCTOR_odbc3,
PL_CHARS, state,
PL_INTEGER, (long)native,
PL_TERM, s) )
break;
return FALSE;
}
case SQL_INVALID_HANDLE:
return PL_warning("ODBC INTERNAL ERROR: Invalid handle in error");
default:
if ( rc != SQL_ERROR )
return TRUE;
}
switch(rc)
{ case SQL_SUCCESS_WITH_INFO:
{ fid_t fid = PL_open_foreign_frame();
predicate_t pred = PL_predicate("print_message", 2, "user");
term_t av;
int rc;
rc = ( (av = PL_new_term_refs(2)) &&
PL_put_atom(av+0, ATOM_informational) &&
PL_put_term(av+1, msg) &&
PL_call_predicate(NULL, PL_Q_NORMAL, pred, av)
);
PL_discard_foreign_frame(fid);
return rc;
}
case SQL_ERROR:
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_TERM, msg,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
default:
return PL_warning("Statement returned %d\n", rc);
}
}
#define TRY(ctxt, stmt, onfail) \
{ ctxt->rc = (stmt); \
if ( !report_status(ctxt) ) \
{ onfail; \
return FALSE; \
} \
}
static int
report_status(context *ctxt)
{ switch(ctxt->rc)
{ case SQL_SUCCESS:
return TRUE;
case SQL_SUCCESS_WITH_INFO:
if ( ison(ctxt, CTX_SILENT) )
return TRUE;
break;
case SQL_NO_DATA_FOUND:
return TRUE;
case SQL_INVALID_HANDLE:
return PL_warning("Invalid handle: %p", ctxt->hstmt);
}
return odbc_report(ctxt->henv, ctxt->connection->hdbc,
ctxt->hstmt, ctxt->rc);
}
static int
type_error(term_t actual, const char *expected)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_type_error2,
PL_CHARS, expected,
PL_TERM, actual,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static int
domain_error(term_t actual, const char *expected)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_domain_error2,
PL_CHARS, expected,
PL_TERM, actual,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static int
existence_error(term_t actual, const char *expected)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_existence_error2,
PL_CHARS, expected,
PL_TERM, actual,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static int
resource_error(const char *error)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_resource_error1,
PL_CHARS, error,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static int
representation_error(term_t t, const char *error)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_representation_error1,
PL_CHARS, error,
PL_TERM, t) )
return PL_raise_exception(ex);
return FALSE;
}
static int
context_error(term_t term, const char *error, const char *what)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_context_error3,
PL_TERM, term,
PL_CHARS, error,
PL_CHARS, what,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static int
permission_error(const char *op, const char *type, term_t obj)
{ term_t ex;
if ( (ex=PL_new_term_ref()) &&
PL_unify_term(ex,
PL_FUNCTOR, FUNCTOR_error2,
PL_FUNCTOR, FUNCTOR_permission_error3,
PL_CHARS, op,
PL_CHARS, type,
PL_TERM, obj,
PL_VARIABLE) )
return PL_raise_exception(ex);
return FALSE;
}
static void *
odbc_malloc(size_t bytes)
{ void *ptr = malloc(bytes);
if ( !ptr )
resource_error("memory");
return ptr;
}
static void *
odbc_realloc(void* inptr, size_t bytes)
{ void *ptr = realloc(inptr, bytes);
if ( !ptr )
{ free(inptr);
resource_error("memory");
}
return ptr;
}
/*******************************
* PRIMITIVES *
*******************************/
typedef int (*AtypeFunc)(term_t t, void *vp);
#define get_name_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_atom_chars, "atom", n)
#define get_text_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)get_text, "text", n)
#define get_atom_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_atom, "atom", n)
#define get_int_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_integer, "integer", n)
#define get_long_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_long, "integer", n)
#define get_bool_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_bool, "boolean", n)
#define get_float_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)PL_get_float, "float", n)
#define get_encoding_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)get_encoding, "encoding", n)
#define get_odbc_version_arg_ex(i, t, n) \
PL_get_typed_arg_ex(i, t, (AtypeFunc)get_odbc_version, "odbc_version", n)
/* Used for passwd and driver string. Should use Unicode/encoding
stuff for that.
*/
static int
get_text(term_t t, char **s)
{ return PL_get_chars(t, s, CVT_ATOM|CVT_STRING|CVT_LIST|REP_MB|BUF_RING);
}
typedef struct enc_name
{ char *name;
IOENC code;
atom_t a;
} enc_name;
static enc_name encodings[] =
{ { "iso_latin_1", ENC_ISO_LATIN_1 },
{ "locale", ENC_ANSI },
{ "utf8", ENC_UTF8 },
{ "unicode", ENC_SQLWCHAR },
{ NULL }
};
static int
get_encoding(term_t t, IOENC *enc)
{ atom_t a;
if ( PL_get_atom(t, &a) )
{ enc_name *en;
for(en=encodings; en->name; en++)
{ if ( !en->a )
en->a = PL_new_atom(en->name);
if ( en->a == a )
{ *enc = en->code;
return TRUE;
}
}
}
return FALSE;
}
static void
put_encoding(term_t t, IOENC enc)
{ enc_name *en;
for(en=encodings; en->name; en++)
{ if ( en->code == enc )
{ if ( !en->a )
en->a = PL_new_atom(en->name);
PL_put_atom(t, en->a);
return;
}
}
assert(0);
}
static int
enc_to_rep(IOENC enc)
{ switch(enc)
{ case ENC_ISO_LATIN_1:
return REP_ISO_LATIN_1;
case ENC_ANSI:
return REP_MB;
case ENC_UTF8:
return REP_UTF8;
case ENC_SQLWCHAR:
return 0; /* not used for wide characters */
default:
assert(0);
return 0;
}
}
static int
PL_get_typed_arg_ex(int i, term_t t, AtypeFunc func, const char *ex, void *ap)
{ term_t a = PL_new_term_ref();
if ( !PL_get_arg(i, t, a) )
return type_error(t, "compound");
if ( !(*func)(a, ap) )
return type_error(a, ex);
return TRUE;
}
#define get_int_arg(i, t, n) \
PL_get_typed_arg(i, t, (AtypeFunc)PL_get_integer, n)
static int
PL_get_typed_arg(int i, term_t t, AtypeFunc func, void *ap)
{ term_t a = PL_new_term_ref();
if ( !PL_get_arg(i, t, a) )
return FALSE;
return (*func)(a, ap);
}
static int
list_length(term_t list)
{ size_t len;
if ( PL_skip_list(list, 0, &len) == PL_LIST )
return (int)len;
type_error(list, "list");
return -1;
}
typedef struct odbc_version_name
{ char *name;
intptr_t version;
atom_t a;
} odbc_version_name;
static odbc_version_name odbc_versions[] =
{ { "2.0", SQL_OV_ODBC2 },
{ "3.0", SQL_OV_ODBC3 },
{ NULL }
};
static int
get_odbc_version(term_t t, intptr_t *ver)
{ atom_t a;
if ( PL_get_atom_ex(t, &a) )
{ odbc_version_name *v;
for(v=odbc_versions; v->name; v++)
{ if ( !v->a )
v->a = PL_new_atom(v->name);
if ( v->a == a )
{ *ver = v->version;
return TRUE;
}
}
}
return FALSE;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int formatted_string(Context, +Fmt-[Arg...])
Much like sformat, but this approach avoids avoids creating
intermediate Prolog data. Maybe we should publish pl_format()?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int
formatted_string(context *ctxt, term_t in)
{ term_t av = PL_new_term_refs(3);
static predicate_t format;
char *out = NULL;
size_t len = 0;
IOSTREAM *fd = Sopenmem(&out, &len, "w");
if ( !fd )
return FALSE; /* resource error */
if ( !format )
format = PL_predicate("format", 3, "user");
fd->encoding = ctxt->connection->encoding;
if ( !PL_unify_stream(av+0, fd) ||
!PL_get_arg(1, in, av+1) ||
!PL_get_arg(2, in, av+2) ||
!PL_call_predicate(NULL, PL_Q_PASS_EXCEPTION, format, av) )
{ Sclose(fd);
if ( out )
PL_free(out);
return FALSE;
}
Sclose(fd);
if ( ctxt->connection->encoding == ENC_SQLWCHAR )
{ ctxt->sqltext.w = (SQLWCHAR*)out;
ctxt->sqllen = (SQLINTEGER)(len/sizeof(SQLWCHAR)); /* TBD: Check range */
ctxt->char_width = sizeof(SQLWCHAR);
} else
{ ctxt->sqltext.a = (unsigned char*)out;
ctxt->sqllen = (SQLINTEGER)len; /* TBD: Check range */
ctxt->char_width = sizeof(char);
}
set(ctxt, CTX_SQLMALLOCED);
return TRUE;
}
/*******************************
* NULL VALUES *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
There are many ways one may wish to handle SQL null-values. These
functions deal with the three common ways specially and can deal with
arbitrary representations.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static nulldef *
nulldef_spec(term_t t)
{ atom_t a;
functor_t f;
nulldef *nd;
if ( !(nd=odbc_malloc(sizeof(*nd))) )
return NULL;
memset(nd, 0, sizeof(*nd));
if ( PL_get_atom(t, &a) )
{ if ( a == ATOM_null )
{ free(nd); /* TBD: not very elegant */
return NULL; /* default specifier */
}
nd->nulltype = NULL_ATOM;
nd->nullvalue.atom = a;
PL_register_atom(a); /* avoid atom-gc */
} else if ( PL_is_variable(t) )
{ nd->nulltype = NULL_VAR;
} else if ( PL_get_functor(t, &f) &&
PL_functor_arity(f) == 1 )
{ term_t a1 = PL_new_term_ref();
_PL_get_arg(1, t, a1);
if ( PL_is_variable(a1) )
{ nd->nulltype = NULL_FUNCTOR;
nd->nullvalue.functor = f;
} else
goto term;
} else
{ term:
nd->nulltype = NULL_RECORD;
nd->nullvalue.record = PL_record(t);
}
nd->references = 1;
return nd;
}
static nulldef *
clone_nulldef(nulldef *nd)
{ if ( nd )
nd->references++;
return nd;
}
static void
free_nulldef(nulldef *nd)
{ if ( nd && --nd->references == 0 )
{ switch(nd->nulltype)
{ case NULL_ATOM:
PL_unregister_atom(nd->nullvalue.atom);
break;
case NULL_RECORD:
PL_erase(nd->nullvalue.record);
break;
default:
break;
}
free(nd);
}
}
WUNUSED static int
put_sql_null(term_t t, nulldef *nd)
{ if ( nd )
{ switch(nd->nulltype)
{ case NULL_VAR:
return TRUE;
case NULL_ATOM:
return PL_put_atom(t, nd->nullvalue.atom);
case NULL_FUNCTOR:
return PL_put_functor(t, nd->nullvalue.functor);
case NULL_RECORD:
return PL_recorded(nd->nullvalue.record, t);
default:
assert(0);
return FALSE;
}
} else
return PL_put_atom(t, ATOM_null);
}
static int
is_sql_null(term_t t, nulldef *nd)
{ if ( nd )
{ switch(nd->nulltype)
{ case NULL_VAR:
return PL_is_variable(t);
case NULL_ATOM:
{ atom_t a;
return PL_get_atom(t, &a) && a == nd->nullvalue.atom;
}
case NULL_FUNCTOR:
return PL_is_functor(t, nd->nullvalue.functor);
case NULL_RECORD: /* TBD: Provide PL_unify_record */
{ term_t rec = PL_new_term_ref();
PL_recorded(nd->nullvalue.record, rec);
return PL_unify(t, rec);
}
default: /* should not happen */
assert(0);
return FALSE;
}
} else
{ atom_t a;
return PL_get_atom(t, &a) && a == ATOM_null;
}
}
/*******************************
* FINDALL(Term, row(X,...)) *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This section deals with the implementation of the statement option
findall(Template, row(Column,...)), returning a list of instances of
Template for each row.
Ideally, we should unify the row with the second argument and add the
first to the list. Unfortunately, we have to make fresh copies of the
findall/2 term for this to work, or we must protect the Template using a
record. Both approaches are slow and largely discard the purpose of the
option, which is to avoid findall/3 and its associated costs in terms of
copying and memory fragmentation.
The current implementation is incomplete. It does not allow arguments of
row(...) to be instantiated. Plain instantiation can always be avoided
using a proper SELECT statement. Potentionally useful however would be
the translation of compound terms, especially to translates
date/time/timestamp structures to a format for use by the application.
The statement is compiled into a findall statement, a set of
instructions that builds the target structure from the row returned by
the current statement.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#define MAXCODES 256
#define ROW_ARG 1024 /* way above Prolog types */
typedef struct
{ term_t row; /* the row */
term_t tmp; /* scratch term */