github.com/safing/portbase@v0.19.5/database/doc.go (about)

     1  /*
     2  Package database provides a universal interface for interacting with the database.
     3  
     4  # A Lazy Database
     5  
     6  The database system can handle Go structs as well as serialized data by the dsd package.
     7  While data is in transit within the system, it does not know which form it currently has. Only when it reaches its destination, it must ensure that it is either of a certain type or dump it.
     8  
     9  # Record Interface
    10  
    11  The database system uses the Record interface to transparently handle all types of structs that get saved in the database. Structs include the Base struct to fulfill most parts of the Record interface.
    12  
    13  Boilerplate Code:
    14  
    15  	type Example struct {
    16  	  record.Base
    17  	  sync.Mutex
    18  
    19  	  Name  string
    20  	  Score int
    21  	}
    22  
    23  	var (
    24  	  db = database.NewInterface(nil)
    25  	)
    26  
    27  	// GetExample gets an Example from the database.
    28  	func GetExample(key string) (*Example, error) {
    29  	  r, err := db.Get(key)
    30  	  if err != nil {
    31  	    return nil, err
    32  	  }
    33  
    34  	  // unwrap
    35  	  if r.IsWrapped() {
    36  	    // only allocate a new struct, if we need it
    37  	    new := &Example{}
    38  	    err = record.Unwrap(r, new)
    39  	    if err != nil {
    40  	      return nil, err
    41  	    }
    42  	    return new, nil
    43  	  }
    44  
    45  	  // or adjust type
    46  	  new, ok := r.(*Example)
    47  	  if !ok {
    48  	    return nil, fmt.Errorf("record not of type *Example, but %T", r)
    49  	  }
    50  	  return new, nil
    51  	}
    52  
    53  	func (e *Example) Save() error {
    54  	  return db.Put(e)
    55  	}
    56  
    57  	func (e *Example) SaveAs(key string) error {
    58  	  e.SetKey(key)
    59  	  return db.PutNew(e)
    60  	}
    61  */
    62  package database