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