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