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