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