view src/database.c @ 5127:a9c41067dd88 ben-lisp-object

more cleanups, terminology clarification, lots of doc work -------------------- ChangeLog entries follow: -------------------- man/ChangeLog addition: 2010-03-05 Ben Wing <ben@xemacs.org> * internals/internals.texi (Introduction to Allocation): * internals/internals.texi (Integers and Characters): * internals/internals.texi (Allocation from Frob Blocks): * internals/internals.texi (lrecords): * internals/internals.texi (Low-level allocation): Rewrite section on allocation of Lisp objects to reflect the new reality. Remove references to nonexistent XSETINT and XSETCHAR. modules/ChangeLog addition: 2010-03-05 Ben Wing <ben@xemacs.org> * postgresql/postgresql.c (allocate_pgconn): * postgresql/postgresql.c (allocate_pgresult): * postgresql/postgresql.h (struct Lisp_PGconn): * postgresql/postgresql.h (struct Lisp_PGresult): * ldap/eldap.c (allocate_ldap): * ldap/eldap.h (struct Lisp_LDAP): Same changes as in src/ dir. See large log there in ChangeLog, but basically: ALLOC_LISP_OBJECT -> ALLOC_NORMAL_LISP_OBJECT LISP_OBJECT_HEADER -> NORMAL_LISP_OBJECT_HEADER ../hlo/src/ChangeLog addition: 2010-03-05 Ben Wing <ben@xemacs.org> * alloc.c: * alloc.c (old_alloc_sized_lcrecord): * alloc.c (very_old_free_lcrecord): * alloc.c (copy_lisp_object): * alloc.c (zero_sized_lisp_object): * alloc.c (zero_nonsized_lisp_object): * alloc.c (lisp_object_storage_size): * alloc.c (free_normal_lisp_object): * alloc.c (FREE_FIXED_TYPE_WHEN_NOT_IN_GC): * alloc.c (ALLOC_FROB_BLOCK_LISP_OBJECT): * alloc.c (Fcons): * alloc.c (noseeum_cons): * alloc.c (make_float): * alloc.c (make_bignum): * alloc.c (make_bignum_bg): * alloc.c (make_ratio): * alloc.c (make_ratio_bg): * alloc.c (make_ratio_rt): * alloc.c (make_bigfloat): * alloc.c (make_bigfloat_bf): * alloc.c (size_vector): * alloc.c (make_compiled_function): * alloc.c (Fmake_symbol): * alloc.c (allocate_extent): * alloc.c (allocate_event): * alloc.c (make_key_data): * alloc.c (make_button_data): * alloc.c (make_motion_data): * alloc.c (make_process_data): * alloc.c (make_timeout_data): * alloc.c (make_magic_data): * alloc.c (make_magic_eval_data): * alloc.c (make_eval_data): * alloc.c (make_misc_user_data): * alloc.c (Fmake_marker): * alloc.c (noseeum_make_marker): * alloc.c (size_string_direct_data): * alloc.c (make_uninit_string): * alloc.c (make_string_nocopy): * alloc.c (mark_lcrecord_list): * alloc.c (alloc_managed_lcrecord): * alloc.c (free_managed_lcrecord): * alloc.c (sweep_lcrecords_1): * alloc.c (malloced_storage_size): * buffer.c (allocate_buffer): * buffer.c (compute_buffer_usage): * buffer.c (DEFVAR_BUFFER_LOCAL_1): * buffer.c (nuke_all_buffer_slots): * buffer.c (common_init_complex_vars_of_buffer): * buffer.h (struct buffer_text): * buffer.h (struct buffer): * bytecode.c: * bytecode.c (make_compiled_function_args): * bytecode.c (size_compiled_function_args): * bytecode.h (struct compiled_function_args): * casetab.c (allocate_case_table): * casetab.h (struct Lisp_Case_Table): * charset.h (struct Lisp_Charset): * chartab.c (fill_char_table): * chartab.c (Fmake_char_table): * chartab.c (make_char_table_entry): * chartab.c (copy_char_table_entry): * chartab.c (Fcopy_char_table): * chartab.c (put_char_table): * chartab.h (struct Lisp_Char_Table_Entry): * chartab.h (struct Lisp_Char_Table): * console-gtk-impl.h (struct gtk_device): * console-gtk-impl.h (struct gtk_frame): * console-impl.h (struct console): * console-msw-impl.h (struct Lisp_Devmode): * console-msw-impl.h (struct mswindows_device): * console-msw-impl.h (struct msprinter_device): * console-msw-impl.h (struct mswindows_frame): * console-msw-impl.h (struct mswindows_dialog_id): * console-stream-impl.h (struct stream_console): * console-stream.c (stream_init_console): * console-tty-impl.h (struct tty_console): * console-tty-impl.h (struct tty_device): * console-tty.c (allocate_tty_console_struct): * console-x-impl.h (struct x_device): * console-x-impl.h (struct x_frame): * console.c (allocate_console): * console.c (nuke_all_console_slots): * console.c (DEFVAR_CONSOLE_LOCAL_1): * console.c (common_init_complex_vars_of_console): * data.c (make_weak_list): * data.c (make_weak_box): * data.c (make_ephemeron): * database.c: * database.c (struct Lisp_Database): * database.c (allocate_database): * database.c (finalize_database): * device-gtk.c (allocate_gtk_device_struct): * device-impl.h (struct device): * device-msw.c: * device-msw.c (mswindows_init_device): * device-msw.c (msprinter_init_device): * device-msw.c (finalize_devmode): * device-msw.c (allocate_devmode): * device-tty.c (allocate_tty_device_struct): * device-x.c (allocate_x_device_struct): * device.c: * device.c (nuke_all_device_slots): * device.c (allocate_device): * dialog-msw.c (handle_question_dialog_box): * elhash.c: * elhash.c (struct Lisp_Hash_Table): * elhash.c (finalize_hash_table): * elhash.c (make_general_lisp_hash_table): * elhash.c (Fcopy_hash_table): * elhash.h (htentry): * emacs.c (main_1): * eval.c: * eval.c (size_multiple_value): * event-stream.c (finalize_command_builder): * event-stream.c (allocate_command_builder): * event-stream.c (free_command_builder): * event-stream.c (event_stream_generate_wakeup): * event-stream.c (event_stream_resignal_wakeup): * event-stream.c (event_stream_disable_wakeup): * event-stream.c (event_stream_wakeup_pending_p): * events.h (struct Lisp_Timeout): * events.h (struct command_builder): * extents-impl.h: * extents-impl.h (struct extent_auxiliary): * extents-impl.h (struct extent_info): * extents-impl.h (set_extent_no_chase_aux_field): * extents-impl.h (set_extent_no_chase_normal_field): * extents.c: * extents.c (gap_array_marker): * extents.c (gap_array): * extents.c (extent_list_marker): * extents.c (extent_list): * extents.c (stack_of_extents): * extents.c (gap_array_make_marker): * extents.c (extent_list_make_marker): * extents.c (allocate_extent_list): * extents.c (SLOT): * extents.c (mark_extent_auxiliary): * extents.c (allocate_extent_auxiliary): * extents.c (attach_extent_auxiliary): * extents.c (size_gap_array): * extents.c (finalize_extent_info): * extents.c (allocate_extent_info): * extents.c (uninit_buffer_extents): * extents.c (allocate_soe): * extents.c (copy_extent): * extents.c (vars_of_extents): * extents.h: * faces.c (allocate_face): * faces.h (struct Lisp_Face): * faces.h (struct face_cachel): * file-coding.c: * file-coding.c (finalize_coding_system): * file-coding.c (sizeof_coding_system): * file-coding.c (Fcopy_coding_system): * file-coding.h (struct Lisp_Coding_System): * file-coding.h (MARKED_SLOT): * fns.c (size_bit_vector): * font-mgr.c: * font-mgr.c (finalize_fc_pattern): * font-mgr.c (print_fc_pattern): * font-mgr.c (Ffc_pattern_p): * font-mgr.c (Ffc_pattern_create): * font-mgr.c (Ffc_name_parse): * font-mgr.c (Ffc_name_unparse): * font-mgr.c (Ffc_pattern_duplicate): * font-mgr.c (Ffc_pattern_add): * font-mgr.c (Ffc_pattern_del): * font-mgr.c (Ffc_pattern_get): * font-mgr.c (fc_config_create_using): * font-mgr.c (fc_strlist_to_lisp_using): * font-mgr.c (fontset_to_list): * font-mgr.c (Ffc_config_p): * font-mgr.c (Ffc_config_up_to_date): * font-mgr.c (Ffc_config_build_fonts): * font-mgr.c (Ffc_config_get_cache): * font-mgr.c (Ffc_config_get_fonts): * font-mgr.c (Ffc_config_set_current): * font-mgr.c (Ffc_config_get_blanks): * font-mgr.c (Ffc_config_get_rescan_interval): * font-mgr.c (Ffc_config_set_rescan_interval): * font-mgr.c (Ffc_config_app_font_add_file): * font-mgr.c (Ffc_config_app_font_add_dir): * font-mgr.c (Ffc_config_app_font_clear): * font-mgr.c (size): * font-mgr.c (Ffc_config_substitute): * font-mgr.c (Ffc_font_render_prepare): * font-mgr.c (Ffc_font_match): * font-mgr.c (Ffc_font_sort): * font-mgr.c (finalize_fc_config): * font-mgr.c (print_fc_config): * font-mgr.h: * font-mgr.h (struct fc_pattern): * font-mgr.h (XFC_PATTERN): * font-mgr.h (struct fc_config): * font-mgr.h (XFC_CONFIG): * frame-gtk.c (allocate_gtk_frame_struct): * frame-impl.h (struct frame): * frame-msw.c (mswindows_init_frame_1): * frame-x.c (allocate_x_frame_struct): * frame.c (nuke_all_frame_slots): * frame.c (allocate_frame_core): * gc.c: * gc.c (GC_CHECK_NOT_FREE): * glyphs.c (finalize_image_instance): * glyphs.c (allocate_image_instance): * glyphs.c (Fcolorize_image_instance): * glyphs.c (allocate_glyph): * glyphs.c (unmap_subwindow_instance_cache_mapper): * glyphs.c (register_ignored_expose): * glyphs.h (struct Lisp_Image_Instance): * glyphs.h (struct Lisp_Glyph): * glyphs.h (struct glyph_cachel): * glyphs.h (struct expose_ignore): * gui.c (allocate_gui_item): * gui.h (struct Lisp_Gui_Item): * keymap.c (struct Lisp_Keymap): * keymap.c (make_keymap): * lisp.h: * lisp.h (struct Lisp_String_Direct_Data): * lisp.h (struct Lisp_String_Indirect_Data): * lisp.h (struct Lisp_Vector): * lisp.h (struct Lisp_Bit_Vector): * lisp.h (DECLARE_INLINE_LISP_BIT_VECTOR): * lisp.h (struct weak_box): * lisp.h (struct ephemeron): * lisp.h (struct weak_list): * lrecord.h: * lrecord.h (struct lrecord_implementation): * lrecord.h (MC_ALLOC_CALL_FINALIZER): * lrecord.h (struct lcrecord_list): * lstream.c (finalize_lstream): * lstream.c (sizeof_lstream): * lstream.c (Lstream_new): * lstream.c (Lstream_delete): * lstream.h (struct lstream): * marker.c: * marker.c (finalize_marker): * marker.c (compute_buffer_marker_usage): * mule-charset.c: * mule-charset.c (make_charset): * mule-charset.c (compute_charset_usage): * objects-impl.h (struct Lisp_Color_Instance): * objects-impl.h (struct Lisp_Font_Instance): * objects-tty-impl.h (struct tty_color_instance_data): * objects-tty-impl.h (struct tty_font_instance_data): * objects-tty.c (tty_initialize_color_instance): * objects-tty.c (tty_initialize_font_instance): * objects.c (finalize_color_instance): * objects.c (Fmake_color_instance): * objects.c (finalize_font_instance): * objects.c (Fmake_font_instance): * objects.c (reinit_vars_of_objects): * opaque.c: * opaque.c (sizeof_opaque): * opaque.c (make_opaque_ptr): * opaque.c (free_opaque_ptr): * opaque.h: * opaque.h (Lisp_Opaque): * opaque.h (Lisp_Opaque_Ptr): * print.c (printing_unreadable_lcrecord): * print.c (external_object_printer): * print.c (debug_p4): * process.c (finalize_process): * process.c (make_process_internal): * procimpl.h (struct Lisp_Process): * rangetab.c (Fmake_range_table): * rangetab.c (Fcopy_range_table): * rangetab.h (struct Lisp_Range_Table): * scrollbar.c: * scrollbar.c (create_scrollbar_instance): * scrollbar.c (compute_scrollbar_instance_usage): * scrollbar.h (struct scrollbar_instance): * specifier.c (finalize_specifier): * specifier.c (sizeof_specifier): * specifier.c (set_specifier_caching): * specifier.h (struct Lisp_Specifier): * specifier.h (struct specifier_caching): * symeval.h: * symeval.h (SYMBOL_VALUE_MAGIC_P): * symeval.h (DEFVAR_SYMVAL_FWD): * symsinit.h: * syntax.c (init_buffer_syntax_cache): * syntax.h (struct syntax_cache): * toolbar.c: * toolbar.c (allocate_toolbar_button): * toolbar.c (update_toolbar_button): * toolbar.h (struct toolbar_button): * tooltalk.c (struct Lisp_Tooltalk_Message): * tooltalk.c (make_tooltalk_message): * tooltalk.c (struct Lisp_Tooltalk_Pattern): * tooltalk.c (make_tooltalk_pattern): * ui-gtk.c: * ui-gtk.c (allocate_ffi_data): * ui-gtk.c (emacs_gtk_object_finalizer): * ui-gtk.c (allocate_emacs_gtk_object_data): * ui-gtk.c (allocate_emacs_gtk_boxed_data): * ui-gtk.h: * window-impl.h (struct window): * window-impl.h (struct window_mirror): * window.c (finalize_window): * window.c (allocate_window): * window.c (new_window_mirror): * window.c (mark_window_as_deleted): * window.c (make_dummy_parent): * window.c (compute_window_mirror_usage): * window.c (compute_window_usage): Overall point of this change and previous ones in this repository: (1) Introduce new, clearer terminology: everything other than int or char is a "record" object, which comes in two types: "normal objects" and "frob-block objects". Fix up all places that referred to frob-block objects as "simple", "basic", etc. (2) Provide an advertised interface for doing operations on Lisp objects, including creating new types, that is clean and consistent in its naming, uses the above-referenced terms and avoids referencing "lrecords", "old lcrecords", etc., which should hide under the surface. (3) Make the size_in_bytes and finalizer methods take a Lisp_Object rather than a void * for consistency with other methods. (4) Separate finalizer method into finalizer and disksaver, so that normal finalize methods don't have to worry about disksaving. Other specifics: (1) Renaming: LISP_OBJECT_HEADER -> NORMAL_LISP_OBJECT_HEADER ALLOC_LISP_OBJECT -> ALLOC_NORMAL_LISP_OBJECT implementation->basic_p -> implementation->frob_block_p ALLOCATE_FIXED_TYPE_AND_SET_IMPL -> ALLOC_FROB_BLOCK_LISP_OBJECT *FCCONFIG*, wrap_fcconfig -> *FC_CONFIG*, wrap_fc_config *FCPATTERN*, wrap_fcpattern -> *FC_PATTERN*, wrap_fc_pattern (the last two changes make the naming of these macros consistent with the naming of all other macros, since the objects are named fc-config and fc-pattern with a hyphen) (2) Lots of documentation fixes in lrecord.h. (3) Eliminate macros for copying, freeing, zeroing objects, getting their storage size. Instead, new functions: zero_sized_lisp_object() zero_nonsized_lisp_object() lisp_object_storage_size() free_normal_lisp_object() (copy_lisp_object() already exists) LISP_OBJECT_FROB_BLOCK_P() (actually a macro) Eliminated: free_lrecord() zero_lrecord() copy_lrecord() copy_sized_lrecord() old_copy_lcrecord() old_copy_sized_lcrecord() old_zero_lcrecord() old_zero_sized_lcrecord() LISP_OBJECT_STORAGE_SIZE() COPY_SIZED_LISP_OBJECT() COPY_SIZED_LCRECORD() COPY_LISP_OBJECT() ZERO_LISP_OBJECT() FREE_LISP_OBJECT() (4) Catch the remaining places where lrecord stuff was used directly and use the advertised interface, e.g. alloc_sized_lrecord() -> ALLOC_SIZED_LISP_OBJECT(). (5) Make certain statically-declared pseudo-objects (buffer_local_flags, console_local_flags) have their lheader initialized correctly, so things like copy_lisp_object() can work on them. Make extent_auxiliary_defaults a proper heap object Vextent_auxiliary_defaults, and make extent auxiliaries dumpable so that this object can be dumped. allocate_extent_auxiliary() now just creates the object, and attach_extent_auxiliary() creates an extent auxiliary and attaches to an extent, like the old allocate_extent_auxiliary(). (6) Create EXTENT_AUXILIARY_SLOTS macro, similar to the foo-slots.h files but in a macro instead of a file. The purpose is to avoid duplication when iterating over all the slots in an extent auxiliary. Use it. (7) In lstream.c, don't zero out object after allocation because allocation routines take care of this. (8) In marker.c, fix a mistake in computing marker overhead. (9) In print.c, clean up printing_unreadable_lcrecord(), external_object_printer() to avoid lots of ifdef NEW_GC's. (10) Separate toolbar-button allocation into a separate allocate_toolbar_button() function for use in the example code in lrecord.h.
author Ben Wing <ben@xemacs.org>
date Fri, 05 Mar 2010 04:08:17 -0600
parents b5df3737028a
children f965e31a35f0
line wrap: on
line source

/* Database access routines
   Copyright (C) 1996, William M. Perry
   Copyright (C) 2001, 2002, 2005, 2010 Ben Wing.

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: Not in FSF. */

/* Written by Bill Perry */
/* Substantially rewritten by Martin Buchholz */
/* db 2.x support added by Andreas Jaeger */
/* Mule-ized 6-22-00 Ben Wing */

#include <config.h>
#include "lisp.h"

#include "sysfile.h"
#include "buffer.h"
#include "file-coding.h"

#ifndef HAVE_DATABASE
#error HAVE_DATABASE not defined!!
#endif

#include "database.h"         /* Our include file */

#ifdef HAVE_BERKELEY_DB
/* Work around Berkeley DB's use of int types which are defined
   slightly differently in the not quite yet standard <inttypes.h>.
   See db.h for details of why we're resorting to this... */
/* glibc 2.1 doesn't have this problem with DB 2.x */
#if !(defined __GLIBC__ && __GLIBC_MINOR__ >= 1)
#ifdef HAVE_INTTYPES_H
#ifndef __BIT_TYPES_DEFINED__
#define __BIT_TYPES_DEFINED__
#endif
#include <inttypes.h>
#if !HAVE_U_INT8_T
typedef uint8_t  u_int8_t;
#endif
#if !HAVE_U_INT16_T
typedef uint16_t u_int16_t;
#endif
#if !HAVE_U_INT32_T
typedef uint32_t u_int32_t;
#endif
#ifdef WE_DONT_NEED_QUADS
#if !HAVE_U_INT64_T
typedef uint64_t u_int64_t;
#endif
#endif /* WE_DONT_NEED_QUADS */
#endif /* HAVE_INTTYPES_H */
#endif /* !(defined __GLIBC__ && __GLIBC_MINOR__ >= 1) */
/* Berkeley DB wants __STDC__ to be defined; else if does `#define const' */
#if ! defined (__STDC__) && ! defined(__cplusplus)
#define __STDC__ 0
#endif
#include DB_H_FILE              /* Berkeley db's header file */
#ifndef DB_VERSION_MAJOR
# define DB_VERSION_MAJOR 1
#endif /* DB_VERSION_MAJOR */
#ifndef DB_VERSION_MINOR
# define DB_VERSION_MINOR 0
#endif /* DB_VERSION_MINOR */
Lisp_Object Qberkeley_db;
Lisp_Object Qhash, Qbtree, Qrecno, Qunknown;
#if DB_VERSION_MAJOR > 2
Lisp_Object Qqueue;
#endif 
#endif /* HAVE_BERKELEY_DB */

#ifdef HAVE_DBM
# ifdef TRUST_NDBM_H_PROTOTYPES
#  include NDBM_H_FILE
# else /* not TRUST_NDBM_H_PROTOTYPES */

/* The prototypes in gdbm/ndbm.h currently are broken when compiling
using C++, since they are of the form `datum dbm_firstkey()', without any
args given. */

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

/* Parameters to dbm_store for simple insertion or replacement. */
#define  DBM_INSERT  0
#define  DBM_REPLACE 1

/* The data and key structure.  This structure is defined for compatibility. */
typedef struct
{
  char *dptr;
  int   dsize;
} datum;

/* The file information header. This is good enough for most applications. */
typedef struct {int dummy[10];} DBM;

int     dbm_clearerr(DBM *);
void    dbm_close(DBM *);
int     dbm_delete(DBM *, datum);
int     dbm_error(DBM *);
datum   dbm_fetch(DBM *, datum);
datum   dbm_firstkey(DBM *);
datum   dbm_nextkey(DBM *);
DBM    *dbm_open(const char *, int, mode_t);
int     dbm_store(DBM *, datum, datum, int);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

# endif /* (not) TRUST_NDBM_H_PROTOTYPES */
Lisp_Object Qdbm;
#endif /* HAVE_DBM */

Lisp_Object Vdatabase_coding_system;

Lisp_Object Qdatabasep;

typedef struct
{
  Lisp_Object (*get_subtype) (Lisp_Database *);
  Lisp_Object (*get_type) (Lisp_Database *);
  Lisp_Object (*get) (Lisp_Database *, Lisp_Object);
  int (*put) (Lisp_Database *, Lisp_Object, Lisp_Object, Lisp_Object);
  int (*rem) (Lisp_Database *, Lisp_Object);
  void (*map) (Lisp_Database *, Lisp_Object);
  void (*close) (Lisp_Database *);
  Lisp_Object (*last_error) (Lisp_Database *);
} DB_FUNCS;

struct Lisp_Database
{
  NORMAL_LISP_OBJECT_HEADER header;
  Lisp_Object fname;
  int mode;
  int access_;
  int dberrno;
  int live_p;
#ifdef HAVE_DBM
  DBM *dbm_handle;
#endif
#ifdef HAVE_BERKELEY_DB
  DB *db_handle;
#endif
  DB_FUNCS *funcs;
  Lisp_Object coding_system;
};

#define XDATABASE(x) XRECORD (x, database, Lisp_Database)
#define wrap_database(p) wrap_record (p, database)
#define DATABASEP(x) RECORDP (x, database)
#define CHECK_DATABASE(x) CHECK_RECORD (x, database)
#define CONCHECK_DATABASE(x) CONCHECK_RECORD (x, database)
#define DATABASE_LIVE_P(x) (x->live_p)

#define CHECK_LIVE_DATABASE(db) do {					\
  CHECK_DATABASE (db);							\
  if (!DATABASE_LIVE_P (XDATABASE(db)))					\
    invalid_operation ("Attempting to access closed database", db);	\
} while (0)


static Lisp_Database *
allocate_database (void)
{
  Lisp_Object obj = ALLOC_NORMAL_LISP_OBJECT (database);
  Lisp_Database *db = XDATABASE (obj);

  db->fname = Qnil;
  db->live_p = 0;
#ifdef HAVE_BERKELEY_DB
  db->db_handle = NULL;
#endif
#ifdef HAVE_DBM
  db->dbm_handle = NULL;
#endif
  db->access_ = 0;
  db->mode = 0;
  db->dberrno = 0;
  db->coding_system = Qnil;
  return db;
}

static const struct memory_description database_description[] = {
  { XD_LISP_OBJECT, offsetof (struct Lisp_Database, fname) },
  { XD_END}
};

static Lisp_Object
mark_database (Lisp_Object object)
{
  Lisp_Database *db = XDATABASE (object);
  return db->fname;
}

static void
print_database (Lisp_Object obj, Lisp_Object printcharfun,
		int UNUSED (escapeflag))
{
  Lisp_Database *db = XDATABASE (obj);

  if (print_readably)
    printing_unreadable_lcrecord (obj, 0);

  write_fmt_string_lisp (printcharfun, "#<database \"%s\" (%s/%s/",
			 3, db->fname, db->funcs->get_type (db),
			 db->funcs->get_subtype (db));

  write_fmt_string (printcharfun, "%s) ",
		    (!DATABASE_LIVE_P (db)    ? "closed"    :
		     (db->access_ & O_WRONLY) ? "writeonly" :
		     (db->access_ & O_RDWR)   ? "readwrite" : "readonly"));

  write_fmt_string_lisp (printcharfun, "coding: %s ", 1,
                         XSYMBOL_NAME (XCODING_SYSTEM_NAME
                                       (db->coding_system)));

  write_fmt_string (printcharfun, "0x%x>", db->header.uid);
}

static void
finalize_database (Lisp_Object obj)
{
  Lisp_Database *db = XDATABASE (obj);

  db->funcs->close (db);
}

DEFINE_NODUMP_LISP_OBJECT ("database", database,
			   mark_database, print_database,
			   finalize_database, 0, 0, 
			   database_description,
			   Lisp_Database);

DEFUN ("close-database", Fclose_database, 1, 1, 0, /*
Close database DATABASE.
*/
       (database))
{
  Lisp_Database *db;
  CHECK_LIVE_DATABASE (database);
  db = XDATABASE (database);
  db->funcs->close (db);
  db->live_p = 0;
  return Qnil;
}

DEFUN ("database-type", Fdatabase_type, 1, 1, 0, /*
Return the type of database DATABASE.
*/
       (database))
{
  CHECK_DATABASE (database);

  return XDATABASE (database)->funcs->get_type (XDATABASE (database));
}

DEFUN ("database-subtype", Fdatabase_subtype, 1, 1, 0, /*
Return the subtype of database DATABASE, if any.
*/
       (database))
{
  CHECK_DATABASE (database);

  return XDATABASE (database)->funcs->get_subtype (XDATABASE (database));
}

DEFUN ("database-live-p", Fdatabase_live_p, 1, 1, 0, /*
Return t if OBJECT is an active database.
*/
       (object))
{
  return DATABASEP (object) && DATABASE_LIVE_P (XDATABASE (object)) ?
    Qt : Qnil;
}

DEFUN ("database-file-name", Fdatabase_file_name, 1, 1, 0, /*
Return the filename associated with the database DATABASE.
*/
       (database))
{
  CHECK_DATABASE (database);

  return XDATABASE (database)->fname;
}

DEFUN ("databasep", Fdatabasep, 1, 1, 0, /*
Return t if OBJECT is a database.
*/
       (object))
{
  return DATABASEP (object) ? Qt : Qnil;
}

#ifdef HAVE_DBM
static void
dbm_map (Lisp_Database *db, Lisp_Object func)
{
  datum keydatum, valdatum;
  Lisp_Object key, val;

  for (keydatum = dbm_firstkey (db->dbm_handle);
       keydatum.dptr != NULL;
       keydatum = dbm_nextkey (db->dbm_handle))
    {
      valdatum = dbm_fetch (db->dbm_handle, keydatum);
      key = make_extstring ((Extbyte *) keydatum.dptr, keydatum.dsize,
			     db->coding_system);
      val = make_extstring ((Extbyte *) valdatum.dptr, valdatum.dsize,
			     db->coding_system);
      call2 (func, key, val);
    }
}

static Lisp_Object
dbm_get (Lisp_Database *db, Lisp_Object key)
{
  datum keydatum, valdatum;

  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.dptr, keydatum.dsize,
				 db->coding_system);
  valdatum = dbm_fetch (db->dbm_handle, keydatum);

  return (valdatum.dptr
	  ? make_extstring ((Extbyte *) valdatum.dptr, valdatum.dsize,
			     db->coding_system)
	  : Qnil);
}

static int
dbm_put (Lisp_Database *db,
	 Lisp_Object key, Lisp_Object val, Lisp_Object replace)
{
  datum keydatum, valdatum;

  LISP_STRING_TO_SIZED_EXTERNAL (val, valdatum.dptr, valdatum.dsize,
				 db->coding_system);
  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.dptr, keydatum.dsize,
				 db->coding_system);

  return !dbm_store (db->dbm_handle, keydatum, valdatum,
		     NILP (replace) ? DBM_INSERT : DBM_REPLACE);
}

static int
dbm_remove (Lisp_Database *db, Lisp_Object key)
{
  datum keydatum;

  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.dptr, keydatum.dsize,
				 db->coding_system);

  return dbm_delete (db->dbm_handle, keydatum);
}

static Lisp_Object
dbm_type (Lisp_Database *UNUSED (db))
{
  return Qdbm;
}

static Lisp_Object
dbm_subtype (Lisp_Database *UNUSED (db))
{
  return Qnil;
}

static Lisp_Object
dbm_lasterr (Lisp_Database *db)
{
  return lisp_strerror (db->dberrno);
}

static void
dbm_closeit (Lisp_Database *db)
{
  if (db->dbm_handle)
    {
      dbm_close (db->dbm_handle);
      db->dbm_handle = NULL;
    }
}

static DB_FUNCS ndbm_func_block =
{
  dbm_subtype,
  dbm_type,
  dbm_get,
  dbm_put,
  dbm_remove,
  dbm_map,
  dbm_closeit,
  dbm_lasterr
};
#endif /* HAVE_DBM */

#ifdef HAVE_BERKELEY_DB
static Lisp_Object
berkdb_type (Lisp_Database *UNUSED (db))
{
  return Qberkeley_db;
}

static Lisp_Object
berkdb_subtype (Lisp_Database *db)
{
  if (!db->db_handle)
    return Qnil;

  switch (db->db_handle->type)
    {
    case DB_BTREE: return Qbtree;
    case DB_HASH:  return Qhash;
    case DB_RECNO: return Qrecno;
#if DB_VERSION_MAJOR > 2
    case DB_QUEUE: return Qqueue;
#endif
    default:       return Qunknown;
    }
}

static Lisp_Object
berkdb_lasterr (Lisp_Database *db)
{
  return lisp_strerror (db->dberrno);
}

static Lisp_Object
berkdb_get (Lisp_Database *db, Lisp_Object key)
{
  DBT keydatum, valdatum;
  int status = 0;

  /* DB Version 2 requires DBT's to be zeroed before use. */
  xzero (keydatum);
  xzero (valdatum);

  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.data, keydatum.size,
				 db->coding_system);

#if DB_VERSION_MAJOR == 1
  status = db->db_handle->get (db->db_handle, &keydatum, &valdatum, 0);
#else
  status = db->db_handle->get (db->db_handle, NULL, &keydatum, &valdatum, 0);
#endif /* DB_VERSION_MAJOR */

  if (!status)
    return make_extstring ((const Extbyte *) valdatum.data, valdatum.size,
			    db->coding_system);

#if DB_VERSION_MAJOR == 1
  db->dberrno = (status == 1) ? -1 : errno;
#else
  db->dberrno = (status < 0) ? -1 : errno;
#endif /* DB_VERSION_MAJOR */

  return Qnil;
}

static int
berkdb_put (Lisp_Database *db,
	    Lisp_Object key,
	    Lisp_Object val,
	    Lisp_Object replace)
{
  DBT keydatum, valdatum;
  int status = 0;

  /* DB Version 2 requires DBT's to be zeroed before use. */
  xzero (keydatum);
  xzero (valdatum);

  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.data, keydatum.size,
				 db->coding_system);
  LISP_STRING_TO_SIZED_EXTERNAL (val, valdatum.data, valdatum.size,
				 db->coding_system);
#if DB_VERSION_MAJOR == 1
  status = db->db_handle->put (db->db_handle, &keydatum, &valdatum,
 			       NILP (replace) ? R_NOOVERWRITE : 0);
  db->dberrno = (status == 1) ? -1 : errno;
#else
  status = db->db_handle->put (db->db_handle, NULL, &keydatum, &valdatum,
			       NILP (replace) ? DB_NOOVERWRITE : 0);
  db->dberrno = (status < 0) ? -1 : errno;
#endif/* DV_VERSION_MAJOR = 2 */

  return status;
}

static int
berkdb_remove (Lisp_Database *db, Lisp_Object key)
{
  DBT keydatum;
  int status;

  /* DB Version 2 requires DBT's to be zeroed before use. */
  xzero (keydatum);

  LISP_STRING_TO_SIZED_EXTERNAL (key, keydatum.data, keydatum.size,
				 db->coding_system);

#if DB_VERSION_MAJOR == 1
  status = db->db_handle->del (db->db_handle, &keydatum, 0);
#else
  status = db->db_handle->del (db->db_handle, NULL, &keydatum, 0);
#endif /* DB_VERSION_MAJOR */

  if (!status)
    return 0;

#if DB_VERSION_MAJOR == 1
  db->dberrno = (status == 1) ? -1 : errno;
#else
  db->dberrno = (status < 0) ? -1 : errno;
#endif /* DB_VERSION_MAJOR */

  return 1;
}

static void
berkdb_map (Lisp_Database *db, Lisp_Object func)
{
  DBT keydatum, valdatum;
  Lisp_Object key, val;
  DB *dbp = db->db_handle;
  int status;

  xzero (keydatum);
  xzero (valdatum);

#if DB_VERSION_MAJOR == 1
  for (status = dbp->seq (dbp, &keydatum, &valdatum, R_FIRST);
       status == 0;
       status = dbp->seq (dbp, &keydatum, &valdatum, R_NEXT))
    {
      key = make_extstring ((const Extbyte *) keydatum.data, keydatum.size,
			     db->coding_system);
      val = make_extstring ((const Extbyte *) valdatum.data, valdatum.size,
			     db->coding_system);
      call2 (func, key, val);
    }
#else
  {
    DBC *dbcp;

#if DB_VERSION_MAJOR > 2 || DB_VERSION_MINOR >=6
    status = dbp->cursor (dbp, NULL, &dbcp, 0);
#else
    status = dbp->cursor (dbp, NULL, &dbcp);
#endif
    for (status = dbcp->c_get (dbcp, &keydatum, &valdatum, DB_FIRST);
	 status == 0;
	 status = dbcp->c_get (dbcp, &keydatum, &valdatum, DB_NEXT))
      {
	key = make_extstring ((const Extbyte *) keydatum.data, keydatum.size,
			       db->coding_system);
	val = make_extstring ((const Extbyte *) valdatum.data, valdatum.size,
			       db->coding_system);
	call2 (func, key, val);
      }
    dbcp->c_close (dbcp);
  }
#endif /* DB_VERSION_MAJOR */
}

static void
berkdb_close (Lisp_Database *db)
{
  if (db->db_handle)
    {
#if DB_VERSION_MAJOR == 1
      db->db_handle->sync  (db->db_handle, 0);
      db->db_handle->close (db->db_handle);
#else
      db->db_handle->sync  (db->db_handle, 0);
      db->db_handle->close (db->db_handle, 0);
#endif /* DB_VERSION_MAJOR */
      db->db_handle = NULL;
    }
}

static DB_FUNCS berk_func_block =
{
  berkdb_subtype,
  berkdb_type,
  berkdb_get,
  berkdb_put,
  berkdb_remove,
  berkdb_map,
  berkdb_close,
  berkdb_lasterr
};
#endif /* HAVE_BERKELEY_DB */

DEFUN ("database-last-error", Fdatabase_last_error, 0, 1, 0, /*
Return the last error associated with DATABASE.
*/
       (database))
{
  if (NILP (database))
    return lisp_strerror (errno);

  CHECK_DATABASE (database);

  return XDATABASE (database)->funcs->last_error (XDATABASE (database));
}

DEFUN ("open-database", Fopen_database, 1, 6, 0, /*
Return a new database object opened on FILE.
Optional arguments TYPE and SUBTYPE specify the database type.
Optional argument ACCESS specifies the access rights, which may be any
combination of 'r' 'w' and '+', for read, write, and creation flags.
Optional argument MODE gives the permissions to use when opening FILE,
and defaults to 0755.
Optional argument CODESYS specifies the coding system used to encode/decode
data passed to/from the database, and defaults to the value of the
variable `database-coding-system'.
*/
       (file, type, subtype, access_, mode, codesys))
{
  /* This function can GC */
  int modemask;
  int accessmask = 0;
  Lisp_Database *db = NULL;
  Extbyte *filename;
  struct gcpro gcpro1, gcpro2;

  CHECK_STRING (file);
  GCPRO2 (file, access_);
  file = Fexpand_file_name (file, Qnil);
  UNGCPRO;

  LISP_PATHNAME_CONVERT_OUT (file, filename);

  if (NILP (access_))
    {
      accessmask = O_RDWR | O_CREAT;
    }
  else
    {
      Ibyte *acc;
      CHECK_STRING (access_);
      acc = XSTRING_DATA (access_);

      if (qxestrchr (acc, '+'))
	accessmask |= O_CREAT;

      {
	int rp = !!qxestrchr (acc, 'r');
	int wp = !!qxestrchr (acc, 'w');
	if (rp && wp) accessmask |= O_RDWR;
	else if (wp)  accessmask |= O_WRONLY;
	else          accessmask |= O_RDONLY;
      }
    }

  if (NILP (mode))
    {
      modemask = 0755;		/* rwxr-xr-x */
    }
  else
    {
      CHECK_INT (mode);
      modemask = XINT (mode);
    }

  if (NILP (codesys))
    codesys = Vdatabase_coding_system;

  codesys = get_coding_system_for_text_file (codesys, 0);

#ifdef HAVE_DBM
  if (NILP (type) || EQ (type, Qdbm))
    {
      DBM *dbase = dbm_open (filename, accessmask, modemask);
      if (!dbase)
	return Qnil;

      db = allocate_database ();
      db->dbm_handle = dbase;
      db->funcs = &ndbm_func_block;
      db->coding_system = codesys;
      goto db_done;
    }
#endif /* HAVE_DBM */

#ifdef HAVE_BERKELEY_DB
  if (NILP (type) || EQ (type, Qberkeley_db))
    {
      DBTYPE real_subtype;
      DB *dbase;
#if DB_VERSION_MAJOR != 1
      int status;
#endif

      if (EQ (subtype, Qhash) || NILP (subtype))
	real_subtype = DB_HASH;
      else if (EQ (subtype, Qbtree))
	real_subtype = DB_BTREE;
      else if (EQ (subtype, Qrecno))
	real_subtype = DB_RECNO;
#if DB_VERSION_MAJOR > 2
      else if (EQ (subtype, Qqueue))
	real_subtype = DB_QUEUE;
#endif
      else
	invalid_constant ("Unsupported subtype", subtype);

#if DB_VERSION_MAJOR == 1
      dbase = dbopen (filename, accessmask, modemask, real_subtype, NULL);
      if (!dbase)
	return Qnil;
#else
      /* Berkeley DB Version 2 has only the accessmask DB_CREATE and DB_RDONLY,
	 other flags shouldn't be set */
      if (NILP (access_))
	accessmask = DB_CREATE;
      else
	{
	  char *acc;
	  CHECK_STRING (access_);
	  acc = (char *) XSTRING_DATA (access_);
	  accessmask = 0;

	  if (strchr (acc, '+'))
	    accessmask |= DB_CREATE;

	  if (strchr (acc, 'r') && !strchr (acc, 'w'))
	    accessmask |= DB_RDONLY;
	}
#if DB_VERSION_MAJOR == 2
      status = db_open (filename, real_subtype, accessmask,
			modemask, NULL , NULL, &dbase);
      if (status)
	return Qnil;
#else
      status = db_create (&dbase, NULL, 0);
      if (status)
        return Qnil;
#if DB_VERSION_MAJOR < 4 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR < 1)
      status = dbase->open (dbase, filename, NULL,
                            real_subtype, accessmask, modemask);
#else /* DB_VERSION >= 4.1 */
      /* You can't use DB_AUTO_COMMIT unless you have a txn environment. */
      status = dbase->open (dbase, NULL, filename, NULL, real_subtype,
			    accessmask, modemask);
#endif /* DB_VERSION < 4.1 */
      if (status)
        {
          dbase->close (dbase, 0);
          return Qnil;
        }
#endif /* DB_VERSION_MAJOR > 2 */
      /* Normalize into system specific file modes. Only for printing */
      accessmask = accessmask & DB_RDONLY ? O_RDONLY : O_RDWR;
#endif /* DB_VERSION_MAJOR */

      db = allocate_database ();
      db->db_handle = dbase;
      db->funcs = &berk_func_block;
      db->coding_system = codesys;
      goto db_done;
    }
#endif /* HAVE_BERKELEY_DB */

  invalid_constant ("Unsupported database type", type);
  return Qnil;

 db_done:
  db->live_p = 1;
  db->fname = file;
  db->mode = modemask;
  db->access_ = accessmask;

  return wrap_database (db);
}

DEFUN ("put-database", Fput_database, 3, 4, 0, /*
Store KEY and VALUE in DATABASE.
If optional fourth arg REPLACE is non-nil,
replace any existing entry in the database.
*/
       (key, value, database, replace))
{
  CHECK_LIVE_DATABASE (database);
  CHECK_STRING (key);
  CHECK_STRING (value);
  {
    Lisp_Database *db = XDATABASE (database);
    int status = db->funcs->put (db, key, value, replace);
    return status ? Qt : Qnil;
  }
}

DEFUN ("remove-database", Fremove_database, 2, 2, 0, /*
Remove KEY from DATABASE.
*/
       (key, database))
{
  CHECK_LIVE_DATABASE (database);
  CHECK_STRING (key);
  {
    Lisp_Database *db = XDATABASE (database);
    int status = db->funcs->rem (db, key);
    return status ? Qt : Qnil;
  }
}

DEFUN ("get-database", Fget_database, 2, 3, 0, /*
Return value for KEY in DATABASE.
If there is no corresponding value, return DEFAULT (defaults to nil).
*/
       (key, database, default_))
{
  CHECK_LIVE_DATABASE (database);
  CHECK_STRING (key);
  {
    Lisp_Database *db = XDATABASE (database);
    Lisp_Object retval = db->funcs->get (db, key);
    return NILP (retval) ? default_ : retval;
  }
}

DEFUN ("map-database", Fmapdatabase, 2, 2, 0, /*
Map FUNCTION over entries in DATABASE, calling it with two args,
each key and value in the database.
*/
       (function, database))
{
  CHECK_LIVE_DATABASE (database);

  XDATABASE (database)->funcs->map (XDATABASE (database), function);

  return Qnil;
}

void
syms_of_database (void)
{
  INIT_LISP_OBJECT (database);

  DEFSYMBOL (Qdatabasep);
#ifdef HAVE_DBM
  DEFSYMBOL (Qdbm);
#endif
#ifdef HAVE_BERKELEY_DB
  DEFSYMBOL (Qberkeley_db);
  DEFSYMBOL (Qhash);
  DEFSYMBOL (Qbtree);
  DEFSYMBOL (Qrecno);
#if DB_VERSION_MAJOR > 2
  DEFSYMBOL (Qqueue);
#endif
  DEFSYMBOL (Qunknown);
#endif

  DEFSUBR (Fopen_database);
  DEFSUBR (Fdatabasep);
  DEFSUBR (Fmapdatabase);
  DEFSUBR (Fput_database);
  DEFSUBR (Fget_database);
  DEFSUBR (Fremove_database);
  DEFSUBR (Fdatabase_type);
  DEFSUBR (Fdatabase_subtype);
  DEFSUBR (Fdatabase_last_error);
  DEFSUBR (Fdatabase_live_p);
  DEFSUBR (Fdatabase_file_name);
  DEFSUBR (Fclose_database);
}

void
vars_of_database (void)
{
#ifdef HAVE_DBM
  Fprovide (Qdbm);
#endif
#ifdef HAVE_BERKELEY_DB
  Fprovide (Qberkeley_db);
#endif

  DEFVAR_LISP ("database-coding-system", &Vdatabase_coding_system /*
Default coding system used to convert data in database files.
*/ );
  Vdatabase_coding_system = Qnative;
}