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