First cleanup, zebra_api_ext.c is epmty now
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.87 2003-03-04 23:05:30 pop Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24
25 #include <assert.h>
26 #include <stdio.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #include <direct.h>
31 #else
32 #include <unistd.h>
33 #endif
34
35 #include <yaz/diagbib1.h>
36 #include "index.h"
37 #include <charmap.h>
38 #include "zebraapi.h"
39
40 /* simple asserts to validate the most essential input args */
41 #define ASSERTZH assert(zh && zh->service)
42 #define ASSERTZHRES assert(zh && zh->service && zh->res)
43 #define ASSERTZS assert(zs)
44
45 static Res zebra_open_res (ZebraHandle zh);
46 static void zebra_close_res (ZebraHandle zh);
47
48
49 static void zebra_chdir (ZebraService zs)
50 {
51     const char *dir ;
52     ASSERTZS;
53     dir = res_get (zs->global_res, "chdir");
54     if (!dir)
55         return;
56     logf (LOG_DEBUG, "chdir %s", dir);
57 #ifdef WIN32
58     _chdir(dir);
59 #else
60     chdir (dir);
61 #endif
62 }
63
64 static void zebra_flush_reg (ZebraHandle zh)
65 {
66     ASSERTZH;
67     zh->errCode=0;
68     zebraExplain_flush (zh->reg->zei, zh);
69     
70     extract_flushWriteKeys (zh);
71     zebra_index_merge (zh);
72 }
73
74 static struct zebra_register *zebra_register_open (ZebraService zs, 
75                                                    const char *name,
76                                                    int rw, int useshadow,
77                                                    Res res,
78                                                    const char *reg_path);
79 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
80
81 ZebraHandle zebra_open (ZebraService zs)
82 {
83     ZebraHandle zh;
84     const char *default_encoding;
85     ASSERTZS;
86
87     if (!zs)
88         return 0;
89
90     zh = (ZebraHandle) xmalloc (sizeof(*zh));
91     yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
92
93     zh->service = zs;
94     zh->reg = 0;          /* no register attached yet */
95     zh->sets = 0;
96     zh->destroyed = 0;
97     zh->errCode = 0;
98     zh->errString = 0;
99     zh->res = 0; 
100
101     zh->reg_name = xstrdup ("");
102     zh->path_reg = 0;
103     zh->num_basenames = 0;
104     zh->basenames = 0;
105
106     zh->trans_no = 0;
107
108     zh->lock_normal = 0;
109     zh->lock_shadow = 0;
110
111     zh->admin_databaseName = 0;
112
113     zh->shadow_enable = 1;
114
115     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
116     zh->record_encoding = xstrdup (default_encoding);
117
118     zh->iconv_to_utf8 =
119         yaz_iconv_open ("UTF-8", default_encoding);
120     if (zh->iconv_to_utf8 == 0)
121         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
122            default_encoding);
123     zh->iconv_from_utf8 =
124         yaz_iconv_open (default_encoding, "UTF-8");
125     if (zh->iconv_to_utf8 == 0)
126         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
127            default_encoding);
128
129     zebra_mutex_cond_lock (&zs->session_lock);
130
131     zh->next = zs->sessions;
132     zs->sessions = zh;
133
134     zebra_mutex_cond_unlock (&zs->session_lock);
135
136     return zh;
137 }
138
139 ZebraService zebra_start (const char *configName)
140 {
141     Res res;
142
143     yaz_log (LOG_LOG, "zebra_start %s", configName);
144
145     if ((res = res_open (configName, 0)))
146     {
147         ZebraService zh = xmalloc (sizeof(*zh));
148
149         yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
150         
151         zh->global_res = res;
152         zh->configName = xstrdup(configName);
153         zh->sessions = 0;
154         
155         zebra_chdir (zh);
156         
157         zebra_mutex_cond_init (&zh->session_lock);
158         if (!res_get (zh->global_res, "passwd"))
159             zh->passwd_db = NULL;
160         else
161         {
162             zh->passwd_db = passwd_db_open ();
163             if (!zh->passwd_db)
164                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
165             else
166                 passwd_db_file (zh->passwd_db,
167                                 res_get (zh->global_res, "passwd"));
168         }
169         zh->path_root = res_get (zh->global_res, "root");
170         return zh;
171     }
172     return 0;
173 }
174
175 static
176 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
177                                             int rw, int useshadow, Res res,
178                                             const char *reg_path)
179 {
180     struct zebra_register *reg;
181     int record_compression = REC_COMPRESS_NONE;
182     char *recordCompression = 0;
183
184     ASSERTZS;
185     
186     reg = xmalloc (sizeof(*reg));
187
188     assert (name);
189     reg->name = xstrdup (name);
190
191     reg->seqno = 0;
192     reg->last_val = 0;
193
194     assert (res);
195
196     yaz_log (LOG_DEBUG, "zebra_register_open rw = %d useshadow=%d p=%p",
197              rw, useshadow, reg);
198
199     reg->dh = data1_createx (DATA1_FLAG_XML);
200     if (!reg->dh)
201         return 0;
202     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
203     if (!reg->bfs)
204     {
205         data1_destroy(reg->dh);
206         return 0;
207     }
208     if (useshadow)
209         bf_cache (reg->bfs, res_get (res, "shadow"));
210     data1_set_tabpath (reg->dh, res_get_def(res, "profilePath",
211                                             DEFAULT_PROFILE_PATH));
212     data1_set_tabroot (reg->dh, reg_path);
213     reg->recTypes = recTypes_init (reg->dh);
214     recTypes_default_handlers (reg->recTypes);
215
216     reg->zebra_maps = zebra_maps_open (res, reg_path);
217     reg->rank_classes = NULL;
218
219     reg->key_buf = 0;
220
221     reg->keys.buf_max = 0;
222     reg->keys.buf = 0;
223     reg->sortKeys.buf = 0;
224     reg->sortKeys.buf_max = 0;
225
226     reg->records = 0;
227     reg->dict = 0;
228     reg->sortIdx = 0;
229     reg->isams = 0;
230     reg->matchDict = 0;
231     reg->isam = 0;
232     reg->isamc = 0;
233     reg->isamd = 0;
234     reg->isamb = 0;
235     reg->zei = 0;
236     reg->matchDict = 0;
237     reg->key_file_no = 0;
238     
239     zebraRankInstall (reg, rank1_class);
240     zebraRankInstall (reg, rankzv_class);
241
242     recordCompression = res_get_def (res, "recordCompression", "none");
243     if (!strcmp (recordCompression, "none"))
244         record_compression = REC_COMPRESS_NONE;
245     if (!strcmp (recordCompression, "bzip2"))
246         record_compression = REC_COMPRESS_BZIP2;
247
248     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
249     {
250         logf (LOG_WARN, "rec_open");
251         return 0;
252     }
253     if (rw)
254     {
255         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
256     }
257     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
258     {
259         logf (LOG_WARN, "dict_open");
260         return 0;
261     }
262     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
263     {
264         logf (LOG_WARN, "sortIdx_open");
265         return 0;
266     }
267     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
268     {
269         struct ISAMS_M_s isams_m;
270         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
271                                       key_isams_m(res, &isams_m))))
272         {
273             logf (LOG_WARN, "isams_open");
274             return 0;
275         }
276     }
277     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
278     {
279         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
280                                   sizeof (struct it_key), res)))
281         {
282             logf (LOG_WARN, "is_open");
283             return 0;
284         }
285     }
286     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
287     {
288         struct ISAMC_M_s isamc_m;
289         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
290                                     rw, key_isamc_m(res, &isamc_m))))
291         {
292             logf (LOG_WARN, "isc_open");
293             return 0;
294         }
295     }
296     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
297     {
298         struct ISAMD_M_s isamd_m;
299         
300         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
301                                       rw, key_isamd_m(res, &isamd_m))))
302         {
303             logf (LOG_WARN, "isamd_open");
304             return 0;
305         }
306     }
307     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
308     {
309         struct ISAMC_M_s isamc_m;
310         
311         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
312                                        rw, key_isamc_m(res, &isamc_m), 0)))
313         {
314             logf (LOG_WARN, "isamb_open");
315             return 0;
316         }
317     }
318     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
319     {
320         struct ISAMC_M_s isamc_m;
321         
322         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
323                                        rw, key_isamc_m(res, &isamc_m), 1)))
324         {
325             logf (LOG_WARN, "isamb_open");
326             return 0;
327         }
328     }
329     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
330     {
331         struct ISAMC_M_s isamc_m;
332         
333         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
334                                        rw, key_isamc_m(res, &isamc_m), -1)))
335         {
336             logf (LOG_WARN, "isamb_open");
337             return 0;
338         }
339     }
340     reg->zei = zebraExplain_open (reg->records, reg->dh,
341                                   res, rw, reg,
342                                   explain_extract);
343     if (!reg->zei)
344     {
345         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
346         return 0;
347     }
348     reg->active = 2;
349     yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
350     return reg;
351 }
352
353 void zebra_admin_shutdown (ZebraHandle zh)
354 {
355     ASSERTZH;
356     zh->errCode=0;
357
358     zebra_mutex_cond_lock (&zh->service->session_lock);
359     zh->service->stop_flag = 1;
360     zebra_mutex_cond_unlock (&zh->service->session_lock);
361 }
362
363 void zebra_admin_start (ZebraHandle zh)
364 {
365     ZebraService zs;
366     ASSERTZH;
367     zh->errCode=0;
368     zs = zh->service;
369     zebra_mutex_cond_lock (&zs->session_lock);
370     zebra_mutex_cond_unlock (&zs->session_lock);
371 }
372
373 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
374 {
375     ASSERTZS;
376     yaz_log(LOG_DEBUG, "zebra_register_close p=%p", reg);
377     reg->stop_flag = 0;
378     zebra_chdir (zs);
379     if (reg->records)
380     {
381         zebraExplain_close (reg->zei);
382         dict_close (reg->dict);
383         if (reg->matchDict)
384             dict_close (reg->matchDict);
385         sortIdx_close (reg->sortIdx);
386         if (reg->isams)
387             isams_close (reg->isams);
388         if (reg->isam)
389             is_close (reg->isam);
390         if (reg->isamc)
391             isc_close (reg->isamc);
392         if (reg->isamd)
393             isamd_close (reg->isamd);
394         if (reg->isamb)
395             isamb_close (reg->isamb);
396         rec_close (&reg->records);
397     }
398
399     recTypes_destroy (reg->recTypes);
400     zebra_maps_close (reg->zebra_maps);
401     zebraRankDestroy (reg);
402     bfs_destroy (reg->bfs);
403     data1_destroy (reg->dh);
404
405     xfree (reg->sortKeys.buf);
406     xfree (reg->keys.buf);
407
408     xfree (reg->key_buf);
409     xfree (reg->name);
410     xfree (reg);
411 }
412
413 void zebra_stop(ZebraService zs)
414 {
415     if (!zs)
416         return ;
417     yaz_log (LOG_LOG, "zebra_stop");
418
419     while (zs->sessions)
420     {
421         zebra_close (zs->sessions);
422     }
423         
424     zebra_mutex_cond_destroy (&zs->session_lock);
425
426     if (zs->passwd_db)
427         passwd_db_close (zs->passwd_db);
428
429     res_close (zs->global_res);
430     xfree (zs->configName);
431     xfree (zs->path_root);
432     xfree (zs);
433 }
434
435 void zebra_close (ZebraHandle zh)
436 {
437     ZebraService zs;
438     struct zebra_session **sp;
439     int i;
440
441     if (!zh)
442         return;
443     ASSERTZH;
444     zh->errCode=0;
445     
446     zs = zh->service;
447     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
448     if (!zh)
449         return ;
450     resultSetDestroy (zh, -1, 0, 0);
451
452     if (zh->reg)
453         zebra_register_close (zh->service, zh->reg);
454     zebra_close_res (zh);
455
456     xfree (zh->record_encoding);
457
458     for (i = 0; i < zh->num_basenames; i++)
459         xfree (zh->basenames[i]);
460     xfree (zh->basenames);
461
462     if (zh->iconv_to_utf8 != 0)
463         yaz_iconv_close (zh->iconv_to_utf8);
464     if (zh->iconv_from_utf8 != 0)
465         yaz_iconv_close (zh->iconv_from_utf8);
466
467     xfree (zh->admin_databaseName);
468     zebra_mutex_cond_lock (&zs->session_lock);
469     zebra_lock_destroy (zh->lock_normal);
470     zebra_lock_destroy (zh->lock_shadow);
471     sp = &zs->sessions;
472     while (1)
473     {
474         assert (*sp);
475         if (*sp == zh)
476         {
477             *sp = (*sp)->next;
478             break;
479         }
480         sp = &(*sp)->next;
481     }
482     zebra_mutex_cond_unlock (&zs->session_lock);
483     xfree (zh->reg_name);
484     zh->service=0; /* more likely to trigger an assert */
485     xfree (zh);
486 }
487
488 struct map_baseinfo {
489     ZebraHandle zh;
490     NMEM mem;
491     int num_bases;
492     char **basenames;
493     int new_num_bases;
494     char **new_basenames;
495     int new_num_max;
496 };
497
498 static Res zebra_open_res (ZebraHandle zh)
499 {
500     Res res = 0;
501     char fname[512];
502     ASSERTZH;
503     zh->errCode=0;
504
505     if (zh->path_reg)
506     {
507         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
508         res = res_open (fname, zh->service->global_res);
509         if (!res)
510             res = zh->service->global_res;
511     }
512     else if (*zh->reg_name == 0)
513     {
514         res = zh->service->global_res;
515     }
516     else
517     {
518         yaz_log (LOG_WARN, "no register root specified");
519         return 0;  /* no path for register - fail! */
520     }
521     return res;
522 }
523
524 static void zebra_close_res (ZebraHandle zh)
525 {
526     ASSERTZH;
527     zh->errCode=0;
528     if (zh->res != zh->service->global_res)
529         res_close (zh->res);
530     zh->res = 0;
531 }
532
533 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
534 {
535     ASSERTZH;
536     zh->errCode=0;
537     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
538         return 0;
539     if (!zh->res)
540     {
541         assert (zh->reg == 0);
542         assert (*zh->reg_name == 0);
543     }
544     else
545     {
546         if (zh->reg)
547         {
548             resultSetInvalidate (zh);
549             zebra_register_close (zh->service, zh->reg);
550             zh->reg = 0;
551         }
552         zebra_close_res(zh);
553     }
554     xfree (zh->reg_name);
555     zh->reg_name = xstrdup (new_reg);
556
557     xfree (zh->path_reg);
558     zh->path_reg = 0;
559     if (zh->service->path_root)
560     {
561         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
562                                 strlen(zh->reg_name) + 3);
563         strcpy (zh->path_reg, zh->service->path_root);
564         if (*zh->reg_name)
565         {
566             strcat (zh->path_reg, "/");
567             strcat (zh->path_reg, zh->reg_name);
568         }
569     }
570     zh->res = zebra_open_res (zh);
571     
572     if (zh->lock_normal)
573         zebra_lock_destroy (zh->lock_normal);
574     zh->lock_normal = 0;
575
576     if (zh->lock_shadow)
577         zebra_lock_destroy (zh->lock_shadow);
578     zh->lock_shadow = 0;
579
580     if (zh->res)
581     {
582         char fname[512];
583         const char *lock_area  =res_get (zh->res, "lockDir");
584         
585         if (!lock_area && zh->path_reg)
586             res_put (zh->res, "lockDir", zh->path_reg);
587         sprintf (fname, "norm.%s.LCK", zh->reg_name);
588         zh->lock_normal =
589             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
590         
591         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
592         zh->lock_shadow =
593             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
594
595     }
596     return 1;
597 }
598
599 void map_basenames_func (void *vp, const char *name, const char *value)
600 {
601     struct map_baseinfo *p = (struct map_baseinfo *) vp;
602     int i, no;
603     char fromdb[128], todb[8][128];
604     
605     no =
606         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
607                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
608                 todb[5], todb[6], todb[7]);
609     if (no < 2)
610         return ;
611     no--;
612     for (i = 0; i<p->num_bases; i++)
613         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
614         {
615             p->basenames[i] = 0;
616             for (i = 0; i < no; i++)
617             {
618                 if (p->new_num_bases == p->new_num_max)
619                     return;
620                 p->new_basenames[(p->new_num_bases)++] = 
621                     nmem_strdup (p->mem, todb[i]);
622             }
623             return;
624         }
625 }
626
627 void map_basenames (ZebraHandle zh, ODR stream,
628                     int *num_bases, char ***basenames)
629 {
630     struct map_baseinfo info;
631     struct map_baseinfo *p = &info;
632     int i;
633     ASSERTZH;
634     zh->errCode=0;
635
636     info.zh = zh;
637     info.num_bases = *num_bases;
638     info.basenames = *basenames;
639     info.new_num_max = 128;
640     info.new_num_bases = 0;
641     info.new_basenames = (char **)
642         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
643     info.mem = stream->mem;
644
645     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
646     
647     for (i = 0; i<p->num_bases; i++)
648         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
649         {
650             p->new_basenames[(p->new_num_bases)++] = 
651                 nmem_strdup (p->mem, p->basenames[i]);
652         }
653     *num_bases = info.new_num_bases;
654     *basenames = info.new_basenames;
655     for (i = 0; i<*num_bases; i++)
656         logf (LOG_LOG, "base %s", (*basenames)[i]);
657 }
658
659 int zebra_select_database (ZebraHandle zh, const char *basename)
660 {
661     ASSERTZH;
662     zh->errCode=0;
663     return zebra_select_databases (zh, 1, &basename);
664 }
665
666 int zebra_select_databases (ZebraHandle zh, int num_bases,
667                             const char **basenames)
668 {
669     int i;
670     const char *cp;
671     int len = 0;
672     char *new_reg = 0;
673     ASSERTZH;
674     zh->errCode=0;
675     
676     if (num_bases < 1)
677     {
678         zh->errCode = 23;
679         return -1;
680     }
681     for (i = 0; i < zh->num_basenames; i++)
682         xfree (zh->basenames[i]);
683     xfree (zh->basenames);
684     
685     zh->num_basenames = num_bases;
686     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
687     for (i = 0; i < zh->num_basenames; i++)
688         zh->basenames[i] = xstrdup (basenames[i]);
689
690     cp = strrchr(basenames[0], '/');
691     if (cp)
692     {
693         len = cp - basenames[0];
694         new_reg = xmalloc (len + 1);
695         memcpy (new_reg, basenames[0], len);
696         new_reg[len] = '\0';
697     }
698     else
699         new_reg = xstrdup ("");
700     for (i = 1; i<num_bases; i++)
701     {
702         const char *cp1;
703
704         cp1 = strrchr (basenames[i], '/');
705         if (cp)
706         {
707             if (!cp1)
708             {
709                 zh->errCode = 23;
710                 return -1;
711             }
712             if (len != cp1 - basenames[i] ||
713                 memcmp (basenames[i], new_reg, len))
714             {
715                 zh->errCode = 23;
716                 return -1;
717             }
718         }
719         else
720         {
721             if (cp1)
722             {
723                 zh->errCode = 23;
724                 return -1;
725             }
726         }
727     }
728     zebra_select_register (zh, new_reg);
729     xfree (new_reg);
730     if (!zh->res)
731     {
732         zh->errCode = 109;
733         return -1;
734     }
735     if (!zh->lock_normal || !zh->lock_shadow)
736     {
737         zh->errCode = 2;
738         return -1;
739     }
740     return 0;
741 }
742
743 void zebra_search_rpn (ZebraHandle zh, ODR decode, ODR stream,
744                        Z_RPNQuery *query, const char *setname, int *hits)
745 {
746     ASSERTZH;
747     zh->errCode=0;
748     zh->hits = 0;
749     *hits = 0;
750
751     if (zebra_begin_read (zh))
752         return;
753     resultSetAddRPN (zh, decode, stream, query, 
754                      zh->num_basenames, zh->basenames, setname);
755
756     zebra_end_read (zh);
757
758     *hits = zh->hits;
759 }
760
761 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
762                              const char *setname, Z_RecordComposition *comp,
763                              oid_value input_format, int num_recs,
764                              ZebraRetrievalRecord *recs)
765 {
766     ZebraPosSet poset;
767     int i, *pos_array;
768     ASSERTZH;
769     zh->errCode=0;
770
771     if (!zh->res)
772     {
773         zh->errCode = 30;
774         zh->errString = odr_strdup (stream, setname);
775         return;
776     }
777     
778     zh->errCode = 0;
779
780     if (zebra_begin_read (zh))
781         return;
782
783     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
784     for (i = 0; i<num_recs; i++)
785         pos_array[i] = recs[i].position;
786     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
787     if (!poset)
788     {
789         logf (LOG_DEBUG, "zebraPosSetCreate error");
790         zh->errCode = 30;
791         zh->errString = nmem_strdup (stream->mem, setname);
792     }
793     else
794     {
795         for (i = 0; i<num_recs; i++)
796         {
797             if (poset[i].term)
798             {
799                 recs[i].errCode = 0;
800                 recs[i].format = VAL_SUTRS;
801                 recs[i].len = strlen(poset[i].term);
802                 recs[i].buf = poset[i].term;
803                 recs[i].base = poset[i].db;
804             }
805             else if (poset[i].sysno)
806             {
807                 recs[i].errCode =
808                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
809                                         stream, input_format, comp,
810                                         &recs[i].format, &recs[i].buf,
811                                         &recs[i].len,
812                                         &recs[i].base);
813                 recs[i].errString = NULL;
814             }
815             else
816             {
817                 char num_str[20];
818
819                 sprintf (num_str, "%d", pos_array[i]);  
820                 zh->errCode = 13;
821                 zh->errString = odr_strdup (stream, num_str);
822                 break;
823             }
824         }
825         zebraPosSetDestroy (zh, poset, num_recs);
826     }
827     zebra_end_read (zh);
828     xfree (pos_array);
829 }
830
831 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
832                  oid_value attributeset,
833                  int *position, int *num_entries, ZebraScanEntry **entries,
834                  int *is_partial)
835 {
836     ASSERTZH;
837     zh->errCode=0;
838     if (zebra_begin_read (zh))
839     {
840         *entries = 0;
841         *num_entries = 0;
842         return;
843     }
844     rpn_scan (zh, stream, zapt, attributeset,
845               zh->num_basenames, zh->basenames, position,
846               num_entries, entries, is_partial);
847     zebra_end_read (zh);
848 }
849
850 void zebra_sort (ZebraHandle zh, ODR stream,
851                  int num_input_setnames, const char **input_setnames,
852                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
853                  int *sort_status)
854 {
855     ASSERTZH;
856     zh->errCode=0;
857     if (zebra_begin_read (zh))
858         return;
859     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
860                    output_setname, sort_sequence, sort_status);
861     zebra_end_read(zh);
862 }
863
864 int zebra_deleleResultSet(ZebraHandle zh, int function,
865                           int num_setnames, char **setnames,
866                           int *statuses)
867 {
868     int i, status;
869     ASSERTZH;
870     zh->errCode=0;
871     if (zebra_begin_read(zh))
872         return Z_DeleteStatus_systemProblemAtTarget;
873     switch (function)
874     {
875     case Z_DeleteRequest_list:
876         resultSetDestroy (zh, num_setnames, setnames, statuses);
877         break;
878     case Z_DeleteRequest_all:
879         resultSetDestroy (zh, -1, 0, statuses);
880         break;
881     }
882     zebra_end_read (zh);
883     status = Z_DeleteStatus_success;
884     for (i = 0; i<num_setnames; i++)
885         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
886             status = statuses[i];
887     return status;
888 }
889
890 int zebra_errCode (ZebraHandle zh)
891 {
892     if (zh)
893         return zh->errCode;
894     return 0; 
895 }
896
897 const char *zebra_errString (ZebraHandle zh)
898 {
899     if (zh)
900         return diagbib1_str (zh->errCode);
901     return "";
902 }
903
904 char *zebra_errAdd (ZebraHandle zh)
905 {
906     if (zh)
907         return zh->errString;
908     return "";
909 }
910
911 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
912 {
913     ZebraService zs;
914     ASSERTZH;
915     zh->errCode=0;
916     zs= zh->service;
917     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
918     {
919         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
920         return 0;
921     }
922
923     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
924     return 1;
925 }
926
927 void zebra_admin_import_begin (ZebraHandle zh, const char *database,
928                                const char *record_type)
929 {
930     ASSERTZH;
931     zh->errCode=0;
932     if (zebra_select_database(zh, database))
933         return;
934     zebra_begin_trans (zh);
935     xfree (zh->admin_databaseName);
936     zh->admin_databaseName = xstrdup(database);
937 }
938
939 void zebra_admin_import_end (ZebraHandle zh)
940 {
941     ASSERTZH;
942     zh->errCode=0;
943     zebra_end_trans (zh);
944 }
945
946 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
947 {
948     int sysno;
949     int i;
950     ASSERTZH;
951     zh->errCode=0;
952     for (i = 0; i<segment->num_segmentRecords; i++)
953     {
954         Z_NamePlusRecord *npr = segment->segmentRecords[i];
955         const char *databaseName = npr->databaseName;
956
957         if (!databaseName)
958             databaseName = zh->admin_databaseName;
959         printf ("--------------%d--------------------\n", i);
960         if (npr->which == Z_NamePlusRecord_intermediateFragment)
961         {
962             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
963             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
964             {
965                 Odr_oct *oct = fragment->u.notExternallyTagged;
966                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
967                         oct->buf);
968                 
969                 sysno = 0;
970                 extract_rec_in_mem (zh, "grs.sgml",
971                                     oct->buf, oct->len,
972                                     databaseName,
973                                     0 /* delete_flag */,
974                                     0 /* test_mode */,
975                                     &sysno /* sysno */,
976                                     1 /* store_keys */,
977                                     1 /* store_data */,
978                                     0 /* match criteria */);
979             }
980         }
981     }
982 }
983
984 int zebra_admin_exchange_record (ZebraHandle zh,
985                                  const char *database,
986                                  const char *rec_buf,
987                                  size_t rec_len,
988                                  const char *recid_buf, size_t recid_len,
989                                  int action)
990 {
991     int sysno = 0;
992     char *rinfo = 0;
993     char recid_z[256];
994     ASSERTZH;
995     zh->errCode=0;
996
997     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
998         return -1;
999     memcpy (recid_z, recid_buf, recid_len);
1000     recid_z[recid_len] = 0;
1001
1002     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1003     if (rinfo)
1004     {
1005         if (action == 1)  /* fail if insert */
1006             return -1;
1007         memcpy (&sysno, rinfo+1, sizeof(sysno));
1008     }
1009     else
1010     {
1011         if (action == 2 || action == 3) /* fail if delete or update */
1012             return -1;
1013     }
1014     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
1015                         action == 3 ? 1 : 0 /* delete flag */,
1016                         0, &sysno, 1, 1, 0);
1017     if (action == 1)
1018     {
1019         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1020     }
1021     else if (action == 3)
1022     {
1023         dict_delete (zh->reg->matchDict, recid_z);
1024     }
1025     return 0;
1026 }
1027
1028 void zebra_admin_create (ZebraHandle zh, const char *database)
1029 {
1030     ZebraService zs;
1031     ASSERTZH;
1032     zh->errCode=0;
1033
1034     if (zebra_select_database (zh, database))
1035         return;
1036     zebra_begin_trans (zh);
1037
1038     zs = zh->service;
1039     /* announce database */
1040     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1041                                   /* explainDatabase */))
1042     {
1043         zh->errCode = 224;
1044         zh->errString = "database already exist";
1045     }
1046     zebra_end_trans (zh);
1047 }
1048
1049 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1050                        const char *input_str, int input_len,
1051                        char *output_str, int output_len)
1052 {
1053     WRBUF wrbuf;
1054     ASSERTZH;
1055     zh->errCode=0;
1056     if (!zh->reg->zebra_maps)
1057         return -1;
1058     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1059                           input_str, input_len);
1060     if (!wrbuf)
1061         return -2;
1062     if (wrbuf_len(wrbuf) >= output_len)
1063         return -3;
1064     if (wrbuf_len(wrbuf))
1065         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1066     output_str[wrbuf_len(wrbuf)] = '\0';
1067     return wrbuf_len(wrbuf);
1068 }
1069
1070
1071 void zebra_set_state (ZebraHandle zh, int val, int seqno)
1072 {
1073     char state_fname[256];
1074     char *fname;
1075     long p = getpid();
1076     FILE *f;
1077     ASSERTZH;
1078     zh->errCode=0;
1079
1080     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1081     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1082     f = fopen (fname, "w");
1083
1084     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1085     fprintf (f, "%c %d %ld\n", val, seqno, p);
1086     fclose (f);
1087     xfree (fname);
1088 }
1089
1090 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1091 {
1092     char state_fname[256];
1093     char *fname;
1094     FILE *f;
1095
1096     ASSERTZH;
1097     zh->errCode=0;
1098     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1099     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1100     f = fopen (fname, "r");
1101     *val = 'o';
1102     *seqno = 0;
1103
1104     if (f)
1105     {
1106         fscanf (f, "%c %d", val, seqno);
1107         fclose (f);
1108     }
1109     xfree (fname);
1110 }
1111
1112 int zebra_begin_read (ZebraHandle zh)
1113 {
1114     int dirty = 0;
1115     char val;
1116     int seqno;
1117     ASSERTZH;
1118
1119     assert (zh->res);
1120
1121     (zh->trans_no)++;
1122
1123     if (zh->trans_no != 1)
1124     {
1125         zebra_flush_reg (zh);
1126         return 0;
1127     }
1128     zh->errCode=0;
1129 #if HAVE_SYS_TIMES_H
1130     times (&zh->tms1);
1131 #endif
1132     if (!zh->res)
1133     {
1134         (zh->trans_no)--;
1135         zh->errCode = 109;
1136         return -1;
1137     }
1138     if (!zh->lock_normal || !zh->lock_shadow)
1139     {
1140         (zh->trans_no)--;
1141         zh->errCode = 2;
1142         return -1;
1143     }
1144     zebra_get_state (zh, &val, &seqno);
1145     if (val == 'd')
1146         val = 'o';
1147
1148     if (!zh->reg)
1149         dirty = 1;
1150     else if (seqno != zh->reg->seqno)
1151     {
1152         yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1153                  seqno, zh->reg->seqno);
1154         dirty = 1;
1155     }
1156     else if (zh->reg->last_val != val)
1157     {
1158         yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1159                  val, zh->reg->last_val);
1160         dirty = 1;
1161     }
1162     if (!dirty)
1163         return 0;
1164
1165     if (val == 'c')
1166         zebra_lock_r (zh->lock_shadow);
1167     else
1168         zebra_lock_r (zh->lock_normal);
1169     
1170     if (zh->reg)
1171         zebra_register_close (zh->service, zh->reg);
1172     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1173                                    0, val == 'c' ? 1 : 0,
1174                                    zh->res, zh->path_reg);
1175     if (!zh->reg)
1176     {
1177         zh->errCode = 109;
1178         return -1;
1179     }
1180     zh->reg->last_val = val;
1181     zh->reg->seqno = seqno;
1182
1183     return 0;
1184 }
1185
1186 void zebra_end_read (ZebraHandle zh)
1187 {
1188     ASSERTZH;
1189     (zh->trans_no)--;
1190
1191     if (zh->trans_no != 0)
1192         return;
1193 #if HAVE_SYS_TIMES_H
1194     times (&zh->tms2);
1195     logf (LOG_LOG, "user/system: %ld/%ld",
1196                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1197                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1198
1199 #endif
1200
1201     zebra_unlock (zh->lock_normal);
1202     zebra_unlock (zh->lock_shadow);
1203 }
1204
1205 void zebra_begin_trans (ZebraHandle zh)
1206 {
1207     int pass;
1208     int seqno = 0;
1209     char val = '?';
1210     const char *rval = 0;
1211     ASSERTZHRES;
1212
1213     assert (zh->res);
1214
1215     (zh->trans_no++);
1216     if (zh->trans_no != 1)
1217     {
1218         return;
1219     }
1220     zh->errCode=0;
1221     
1222     yaz_log (LOG_LOG, "zebra_begin_trans");
1223
1224     zh->records_inserted = 0;
1225     zh->records_updated = 0;
1226     zh->records_deleted = 0;
1227     zh->records_processed = 0;
1228
1229 #if HAVE_SYS_TIMES_H
1230     times (&zh->tms1);
1231 #endif
1232     
1233     /* lock */
1234     if (zh->shadow_enable)
1235         rval = res_get (zh->res, "shadow");
1236
1237     for (pass = 0; pass < 2; pass++)
1238     {
1239         if (rval)
1240         {
1241             zebra_lock_r (zh->lock_normal);
1242             zebra_lock_w (zh->lock_shadow);
1243         }
1244         else
1245         {
1246             zebra_lock_w (zh->lock_normal);
1247             zebra_lock_w (zh->lock_shadow);
1248         }
1249         
1250         zebra_get_state (zh, &val, &seqno);
1251         if (val == 'c')
1252         {
1253             yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1254             zebra_unlock (zh->lock_shadow);
1255             zebra_unlock (zh->lock_normal);
1256             zebra_commit (zh);
1257             continue;
1258         }
1259         else if (val == 'd')
1260         {
1261             if (rval)
1262             {
1263                 BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1264                                          zh->path_reg);
1265                 yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1266                 bf_commitClean (bfs, rval);
1267                 bfs_destroy (bfs);
1268             }
1269             else
1270             {
1271                 yaz_log (LOG_WARN, "your previous transaction didn't finish");
1272             }
1273         }
1274         break;
1275     }
1276     if (pass == 2)
1277     {
1278         yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1279         abort();
1280         return;
1281     }
1282     zebra_set_state (zh, 'd', seqno);
1283
1284     zh->reg = zebra_register_open (zh->service, zh->reg_name,
1285                                    1, rval ? 1 : 0, zh->res,
1286                                    zh->path_reg);
1287
1288     zh->reg->seqno = seqno;
1289 }
1290
1291 void zebra_end_trans (ZebraHandle zh) {
1292   ZebraTransactionStatus dummy;
1293   zebra_end_transaction(zh, &dummy);
1294 }
1295
1296 void zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1297 {
1298     char val;
1299     int seqno;
1300     const char *rval;
1301
1302     ASSERTZH;
1303
1304     status->processed = 0;
1305     status->inserted  = 0;
1306     status->updated   = 0;
1307     status->deleted   = 0;
1308     status->utime     = 0;
1309     status->stime     = 0;
1310
1311     zh->trans_no--;
1312     if (zh->trans_no != 0)
1313         return;
1314     yaz_log (LOG_LOG, "zebra_end_trans");
1315     rval = res_get (zh->res, "shadow");
1316
1317     zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1318
1319     zebra_flush_reg (zh);
1320
1321     zebra_register_close (zh->service, zh->reg);
1322     zh->reg = 0;
1323
1324     yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1325              zh->records_processed, zh->records_inserted,
1326              zh->records_updated, zh->records_deleted);
1327
1328     status->processed = zh->records_processed;
1329     status->inserted = zh->records_inserted;
1330     status->updated = zh->records_updated;
1331     status->deleted = zh->records_deleted;
1332
1333     zebra_get_state (zh, &val, &seqno);
1334     if (val != 'd')
1335     {
1336         BFiles bfs = bfs_create (rval, zh->path_reg);
1337         yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1338         bf_commitClean (bfs, rval);
1339         bfs_destroy (bfs);
1340     }
1341     if (!rval)
1342         seqno++;
1343     zebra_set_state (zh, 'o', seqno);
1344
1345     zebra_unlock (zh->lock_shadow);
1346     zebra_unlock (zh->lock_normal);
1347
1348 #if HAVE_SYS_TIMES_H
1349     times (&zh->tms2);
1350     logf (LOG_LOG, "user/system: %ld/%ld",
1351                     (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1352                     (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1353
1354     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1355     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1356 #endif
1357
1358     return;
1359 }
1360
1361 void zebra_repository_update (ZebraHandle zh)
1362 {
1363     ASSERTZH;
1364     zh->errCode=0;
1365     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1366     repositoryUpdate (zh);    
1367 }
1368
1369 void zebra_repository_delete (ZebraHandle zh)
1370 {
1371     ASSERTZH;
1372     zh->errCode=0;
1373     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1374     repositoryDelete (zh);
1375 }
1376
1377 void zebra_repository_show (ZebraHandle zh)
1378 {
1379     ASSERTZH;
1380     zh->errCode=0;
1381     repositoryShow (zh);
1382 }
1383
1384 int zebra_commit (ZebraHandle zh)
1385 {
1386     int seqno;
1387     char val;
1388     const char *rval;
1389     BFiles bfs;
1390     ASSERTZH;
1391     zh->errCode=0;
1392
1393     if (!zh->res)
1394     {
1395         zh->errCode = 109;
1396         return -1;
1397     }
1398     rval = res_get (zh->res, "shadow");    
1399     if (!rval)
1400     {
1401         logf (LOG_WARN, "Cannot perform commit");
1402         logf (LOG_WARN, "No shadow area defined");
1403         return 0;
1404     }
1405
1406     zebra_lock_w (zh->lock_normal);
1407     zebra_lock_r (zh->lock_shadow);
1408
1409     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1410
1411     zebra_get_state (zh, &val, &seqno);
1412
1413     if (rval && *rval)
1414         bf_cache (bfs, rval);
1415     if (bf_commitExists (bfs))
1416     {
1417         zebra_set_state (zh, 'c', seqno);
1418
1419         logf (LOG_LOG, "commit start");
1420         bf_commitExec (bfs);
1421 #ifndef WIN32
1422         sync ();
1423 #endif
1424         logf (LOG_LOG, "commit clean");
1425         bf_commitClean (bfs, rval);
1426         seqno++;
1427         zebra_set_state (zh, 'o', seqno);
1428     }
1429     else
1430     {
1431         logf (LOG_LOG, "nothing to commit");
1432     }
1433     bfs_destroy (bfs);
1434
1435     zebra_unlock (zh->lock_shadow);
1436     zebra_unlock (zh->lock_normal);
1437     return 0;
1438 }
1439
1440 int zebra_init (ZebraHandle zh)
1441 {
1442     const char *rval;
1443     BFiles bfs = 0;
1444     ASSERTZH;
1445     zh->errCode=0;
1446
1447     if (!zh->res)
1448     {
1449         zh->errCode = 109;
1450         return -1;
1451     }
1452     rval = res_get (zh->res, "shadow");
1453
1454     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1455                       zh->path_reg);
1456     if (rval && *rval)
1457         bf_cache (bfs, rval);
1458     
1459     bf_reset (bfs);
1460     bfs_destroy (bfs);
1461     zebra_set_state (zh, 'o', 0);
1462     return 0;
1463 }
1464
1465 int zebra_compact (ZebraHandle zh)
1466 {
1467     BFiles bfs;
1468     ASSERTZH;
1469     zh->errCode=0;
1470     if (!zh->res)
1471     {
1472         zh->errCode = 109;
1473         return -1;
1474     }
1475     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1476     inv_compact (bfs);
1477     bfs_destroy (bfs);
1478     return 0;
1479 }
1480
1481 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1482 {
1483     int sysno = 0;
1484     int olderr;
1485     ASSERTZH;
1486     zh->errCode=0;
1487     zebra_begin_trans (zh);
1488     if (zh->errCode)
1489       return 0; /* bad sysno */
1490     extract_rec_in_mem (zh, "grs.sgml",
1491                         buf, len,
1492                         "Default",  /* database */
1493                         0 /* delete_flag */,
1494                         0 /* test_mode */,
1495                         &sysno /* sysno */,
1496                         1 /* store_keys */,
1497                         1 /* store_data */,
1498                         0 /* match criteria */);
1499     olderr=zh->errCode;
1500     zebra_end_trans (zh);
1501     if (olderr)
1502       zh->errCode=olderr; 
1503     return sysno;
1504 }
1505
1506 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1507 {
1508     ASSERTZH;
1509     zh->errCode=0;
1510     memcpy (&zh->rGroup, rg, sizeof(*rg));
1511 }
1512
1513 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1514 {
1515     ASSERTZH;
1516     *code = zh->errCode;
1517     *addinfo = zh->errString;
1518 }
1519
1520 void zebra_shadow_enable (ZebraHandle zh, int value)
1521 {
1522     ASSERTZH;
1523     zh->errCode=0;
1524     zh->shadow_enable = value;
1525 }
1526
1527 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1528 {
1529     ASSERTZH;
1530     zh->errCode=0;
1531     xfree (zh->record_encoding);
1532
1533     /*
1534      * Fixme!
1535      */
1536
1537     if (zh->iconv_to_utf8 != 0)
1538         yaz_iconv_close(zh->iconv_to_utf8);
1539     if (zh->iconv_from_utf8 != 0)
1540         yaz_iconv_close(zh->iconv_from_utf8);
1541     
1542     zh->record_encoding = xstrdup (encoding);
1543     
1544     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1545     
1546     zh->iconv_to_utf8 =
1547         yaz_iconv_open ("UTF-8", encoding);
1548     if (zh->iconv_to_utf8 == 0)
1549         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1550     zh->iconv_from_utf8 =
1551         yaz_iconv_open (encoding, "UTF-8");
1552     if (zh->iconv_to_utf8 == 0)
1553         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1554
1555     return 0;
1556 }
1557
1558 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1559 {
1560     ASSERTZH;
1561     zh->errCode=0;
1562     res_put(zh->res, name, value);
1563 }
1564
1565 const char *zebra_get_resource(ZebraHandle zh,
1566                                 const char *name, const char *defaultvalue)
1567 {
1568     ASSERTZH;
1569     zh->errCode=0;
1570     return res_get_def( zh->res, name, (char *)defaultvalue);
1571 }
1572
1573 /* moved from zebra_api_ext.c by pop */
1574
1575 int zebra_trans_no (ZebraHandle zh) {
1576   return (zh->trans_no);
1577 }
1578
1579
1580
1581 int zebra_get_shadow_enable (ZebraHandle zh) {
1582   return (zh->shadow_enable);
1583 }
1584
1585 void zebra_set_shadow_enable (ZebraHandle zh, int value) {
1586   zh->shadow_enable = value;
1587 }
1588
1589 void init_recordGroup (struct recordGroup *rg) {
1590     rg->groupName = NULL;
1591     rg->databaseName = NULL;
1592     rg->path = NULL;
1593     rg->recordId = NULL;
1594     rg->recordType = NULL;
1595     rg->flagStoreData = -1;
1596     rg->flagStoreKeys = -1; 
1597     rg->flagRw = 1;
1598     rg->databaseNamePath = 0;
1599     rg->explainDatabase = 0; 
1600     rg->fileVerboseLimit = 100000; 
1601     rg->followLinks = -1;
1602
1603
1604
1605 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1606    called... and in general... Should be moved to somewhere else */
1607 void res_get_recordGroup (ZebraHandle zh,
1608                           struct recordGroup *rGroup,
1609                           const char *ext) {
1610   char gprefix[128];
1611   char ext_res[128]; 
1612     
1613   if (!rGroup->groupName || !*rGroup->groupName)
1614     *gprefix = '\0';
1615   else 
1616     sprintf (gprefix, "%s.", rGroup->groupName);
1617   
1618   /* determine file type - depending on extension */
1619   if (!rGroup->recordType) {
1620     sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1621     if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1622       sprintf (ext_res, "%srecordType", gprefix);
1623       rGroup->recordType = res_get (zh->res, ext_res);
1624     }
1625   }
1626   /* determine match criteria */
1627   if (!rGroup->recordId) { 
1628     sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1629     if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1630       sprintf (ext_res, "%srecordId", gprefix);
1631       rGroup->recordId = res_get (zh->res, ext_res);
1632     }
1633   } 
1634   
1635   /* determine database name */
1636   if (!rGroup->databaseName) {
1637     sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1638     if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1639       sprintf (ext_res, "%sdatabase", gprefix);
1640       rGroup->databaseName = res_get (zh->res, ext_res);
1641     }
1642   }
1643   if (!rGroup->databaseName)
1644     rGroup->databaseName = "Default";
1645
1646   /* determine if explain database */
1647   sprintf (ext_res, "%sexplainDatabase", gprefix);
1648   rGroup->explainDatabase =
1649     atoi (res_get_def (zh->res, ext_res, "0"));
1650
1651   /* storeData */
1652   if (rGroup->flagStoreData == -1) {
1653     const char *sval;
1654     sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1655     if (!(sval = res_get (zh->res, ext_res))) {
1656       sprintf (ext_res, "%sstoreData", gprefix);
1657       sval = res_get (zh->res, ext_res);
1658     }
1659     if (sval)
1660       rGroup->flagStoreData = atoi (sval);
1661   }
1662   if (rGroup->flagStoreData == -1)  rGroup->flagStoreData = 0;
1663
1664   /* storeKeys */
1665   if (rGroup->flagStoreKeys == -1)  {
1666     const char *sval;
1667     
1668     sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1669     sval = res_get (zh->res, ext_res);
1670     if (!sval) {
1671       sprintf (ext_res, "%sstoreKeys", gprefix);
1672       sval = res_get (zh->res, ext_res);
1673     }
1674     if (!sval)  sval = res_get (zh->res, "storeKeys");
1675     if (sval) rGroup->flagStoreKeys = atoi (sval);
1676   }
1677   if (rGroup->flagStoreKeys == -1) rGroup->flagStoreKeys = 0;
1678   
1679
1680
1681
1682 /* almost the same as zebra_records_retrieve ... but how did it work? 
1683    I mean for multiple records ??? CHECK ??? */
1684 void api_records_retrieve (ZebraHandle zh, ODR stream,
1685                            const char *setname, Z_RecordComposition *comp,
1686                            oid_value input_format, int num_recs,
1687                            ZebraRetrievalRecord *recs)
1688 {
1689     ZebraPosSet poset;
1690     int i, *pos_array;
1691
1692     if (!zh->res)
1693     {
1694         zh->errCode = 30;
1695         zh->errString = odr_strdup (stream, setname);
1696         return;
1697     }
1698     
1699     zh->errCode = 0; 
1700
1701     if (zebra_begin_read (zh))
1702         return;
1703
1704     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1705     for (i = 0; i<num_recs; i++)
1706         pos_array[i] = recs[i].position;
1707     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1708     if (!poset)
1709     {
1710         logf (LOG_DEBUG, "zebraPosSetCreate error");
1711         zh->errCode = 30;
1712         zh->errString = nmem_strdup (stream->mem, setname);
1713     }
1714     else
1715     {
1716         for (i = 0; i<num_recs; i++)
1717         {
1718             if (poset[i].term)
1719             {
1720                 recs[i].errCode = 0;
1721                 recs[i].format = VAL_SUTRS;
1722                 recs[i].len = strlen(poset[i].term);
1723                 recs[i].buf = poset[i].term;
1724                 recs[i].base = poset[i].db;
1725                 recs[i].sysno = 0;
1726             
1727             }
1728             else if (poset[i].sysno)
1729             {
1730               /* changed here ??? CHECK ??? */
1731               char *b;
1732                 recs[i].errCode =
1733                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1734                                         stream, input_format, comp,
1735                                         &recs[i].format, 
1736                                         &b,
1737                                         &recs[i].len,
1738                                         &recs[i].base);
1739                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1740                 memcpy(recs[i].buf, b, recs[i].len);
1741                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1742                 recs[i].sysno = poset[i].sysno;
1743                 recs[i].score = poset[i].score;
1744             }
1745             else
1746             {
1747                 char num_str[20];
1748
1749                 sprintf (num_str, "%d", pos_array[i]);  
1750                 zh->errCode = 13;
1751                 zh->errString = odr_strdup (stream, num_str);
1752                 break;
1753             }
1754
1755         }
1756         zebraPosSetDestroy (zh, poset, num_recs);
1757     }
1758     zebra_end_read (zh);
1759     xfree (pos_array);
1760 }
1761
1762
1763 /* ---------------------------------------------------------------------------
1764   Record insert(=update), delete 
1765
1766   If sysno is provided, then it's used to identify the reocord.
1767   If not, and match_criteria is provided, then sysno is guessed
1768   If not, and a record is provided, then sysno is got from there
1769 */
1770
1771 int zebra_update_record (ZebraHandle zh, 
1772                          struct recordGroup *rGroup,
1773                          const char *recordType,
1774                          int sysno, const char *match, const char *fname,
1775                          const char *buf, int buf_size)
1776
1777 {
1778     int res;
1779
1780     if (buf_size < 1) buf_size = strlen(buf);
1781
1782     zebra_begin_trans(zh);
1783     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1784                              0, // delete_flag 
1785                              0, // test_mode,
1786                              recordType,
1787                              &sysno,   
1788                              match, fname);     
1789     zebra_end_trans(zh); 
1790     return sysno; 
1791 }
1792
1793 int zebra_delete_record (ZebraHandle zh, 
1794                          struct recordGroup *rGroup, 
1795                          const char *recordType,
1796                          int sysno, const char *match, const char *fname,
1797                          const char *buf, int buf_size)
1798 {
1799     int res;
1800
1801     if (buf_size < 1) buf_size = strlen(buf);
1802
1803     zebra_begin_trans(zh);
1804     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1805                              1, // delete_flag
1806                              0, // test_mode, 
1807                              recordType,
1808                              &sysno,
1809                              match,fname);    
1810     zebra_end_trans(zh);
1811     return sysno;   
1812 }
1813
1814 /* ---------------------------------------------------------------------------
1815   Searching 
1816
1817   zebra_search_RPN is the same as zebra_search_rpn, except that read locking
1818   is not mandatory. (it's repeatable now, also in zebraapi.c)
1819 */
1820
1821 void zebra_search_RPN (ZebraHandle zh, ODR decode, ODR stream,
1822                        Z_RPNQuery *query, const char *setname, int *hits)
1823 {
1824     zh->hits = 0;
1825     *hits = 0;
1826
1827     if (zebra_begin_read (zh))
1828         return;
1829     resultSetAddRPN (zh, decode, stream, query, 
1830                      zh->num_basenames, zh->basenames, setname);
1831
1832     zebra_end_read (zh);
1833
1834     *hits = zh->hits;
1835 }
1836
1837 int zebra_search_PQF (ZebraHandle zh, 
1838                       ODR odr_input, ODR odr_output, 
1839                       const char *pqf_query,
1840                       const char *setname)
1841
1842 {
1843   int hits;
1844   Z_RPNQuery *query;
1845   query = p_query_rpn (odr_input, PROTO_Z3950, pqf_query);
1846
1847   if (!query) {
1848     logf (LOG_WARN, "bad query %s\n", pqf_query);
1849     odr_reset (odr_input);
1850     return(0);
1851   }
1852   zebra_search_RPN (zh, odr_input, odr_output, query, setname, &hits);
1853
1854   odr_reset (odr_input);
1855   odr_reset (odr_output);
1856   
1857   return(hits);
1858 }
1859
1860 /* ---------------------------------------------------------------------------
1861   Sort - a simplified interface, with optional read locks.
1862 */
1863 int sort (ZebraHandle zh, 
1864           ODR stream,
1865           const char *sort_spec,
1866           const char *output_setname,
1867           const char **input_setnames
1868           ) 
1869 {
1870   int num_input_setnames = 0;
1871   int sort_status = 0;
1872   Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
1873   if (!sort_sequence) {
1874     logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
1875     zh->errCode = 207;
1876     return (-1);
1877   }
1878   
1879   /* we can do this, since the perl typemap code for char** will 
1880      put a NULL at the end of list */
1881   while (input_setnames[num_input_setnames]) num_input_setnames++;
1882
1883   if (zebra_begin_read (zh))
1884     return;
1885   
1886   resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1887                  output_setname, sort_sequence, &sort_status);
1888   
1889   zebra_end_read(zh);
1890   return (sort_status);
1891 }