Ejemplo n.º 1
0
func OpenBDB(env Environment, txn Transaction, file string, database *string, dbtype DbType, flags DbFlag, mode int) (*BerkeleyDB, error) {
	cFile := C.CString(file)
	defer C.free(unsafe.Pointer(cFile))

	var cDatabase *C.char
	if database != nil {
		cDatabase = C.CString(*database)
		defer C.free(unsafe.Pointer(cDatabase))
	}

	var db *BerkeleyDB = new(BerkeleyDB)

	//The flags parameter is currently unused, and must be set to 0.
	// https://docs.oracle.com/cd/E17276_01/html/api_reference/C/dbcreate.html
	err := Err(C.db_create(&db.ptr, env.ptr, 0))
	if err != nil {
		return nil, err
	}

	err = Err(C.db_open(db.ptr, txn.ptr, cFile, cDatabase, C.DBTYPE(dbtype), C.u_int32_t(flags), C.int(mode)))
	if err != nil {
		db.Close(0)
		return nil, err
	}
	return db, ok
}
Ejemplo n.º 2
0
// Open a database in the given file and environment.
func OpenDatabase(env Environment, txn Transaction, file string, config *DatabaseConfig) (db Database, err error) {
	err = check(C.db_create(&db.ptr, env.ptr, 0))
	if err == nil {
		defer func() {
			if err != nil && db.ptr != nil {
				C.db_close(db.ptr, 0)
				db.ptr = nil
			}
		}()
	} else {
		return
	}

	var mode C.int = 0
	var flags C.u_int32_t = C.DB_THREAD
	var cfile, cpassword, cname *C.char
	var dbtype C.DBTYPE = C.DB_UNKNOWN

	if len(file) > 0 {
		cfile = C.CString(file)
		defer C.free(unsafe.Pointer(cfile))
	}

	if config != nil {
		if config.Create {
			flags |= C.DB_CREATE
		}
		if config.Mode != 0 {
			mode = C.int(config.Mode)
		}
		if len(config.Password) > 0 {
			cpassword := C.CString(config.Password)
			defer C.free(unsafe.Pointer(cpassword))
		}
		if len(config.Name) > 0 {
			cname = C.CString(config.Name)
			defer C.free(unsafe.Pointer(cname))
		}
		if config.Type != 0 {
			dbtype = C.DBTYPE(config.Type)
		}
		if config.ReadUncommitted {
			flags |= C.DB_READ_UNCOMMITTED
		}
		if config.Snapshot {
			flags |= C.DB_MULTIVERSION
		}
	}

	if cpassword != nil {
		err = check(C.db_set_encrypt(db.ptr, cpassword, 0))
		if err != nil {
			return
		}
	}

	err = check(C.db_open(db.ptr, txn.ptr, cfile, cname, dbtype, flags, mode))

	return
}