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