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