[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2. Engine

The Engine provides an interface to a financial engine with three basic financial entities: Accounts, Transactions (known as Journal Entries in accounting practice), and Splits (known as Ledger Entries). These three entities are the central data structures of the GnuCash financial data model.

In addition, the Engine provides the abstraction of Account Groups (collections of related accounts) and GNCBooks. A GNCBook abstracts both a set of related GnuCash data (financial entities plus additional information such as budgets, per-file preferences, etc.) plus a file-editing session allowing transparent support for locking and implementation with other backends such as SQL.

The Engine code contains no GUI code whatsoever and is designed to be created as a shared library for use by other programs.

2.1 Introduction  
2.2 Using and Extending the Engine API  
2.3 Globally Unique Identifiers  
2.4 Numeric Library  
2.5 Key-Value Pair Frames  
2.6 Events  
2.7 Commodities  
2.8 Commodity Tables  
2.9 Prices  
2.10 Price Databases  
2.11 Splits  
2.12 Transactions  
2.13 Accounts  
2.14 Account Groups  
2.15 GNCBooks  
2.16 Scrub  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.1 Introduction

Splits (see section 2.11 Splits), or "Ledger Entries" are the fundamental accounting units. Each Split consists of an amount (number of dollar bills, number of shares, etc.), the value of that amount expressed in a (possibly) different currency than the amount, a Memo, a pointer to the parent Transaction, a pointer to the debited Account, a reconciled flag and timestamp, an "Action" field, and a key-value frame which can store arbitrary data (see section 2.5 Key-Value Pair Frames).

Transactions (see section 2.12 Transactions) embody the notion of "double entry" accounting. A Transaction consists of a date, a description, an ID number, a list of one or more Splits, and a key-value frame. The transaction also specifies the currency with which all of the splits will be valued. When double-entry rules are enforced, the total value of the splits are zero. If there are only two splits, then the value of one must be positive, the other negative: this denotes that one account is debited, and another is credited by an equal amount. By forcing the value of the splits to always 'add up' to zero, we can gaurentee that the balances of the accounts are always correctly balanced.

The engine does not enforce double-entry accounting, but provides an API to enable user-code to find unbalanced transactions and 'repair' them so that they are in balance. See section 2.16 Scrub.

Note the sum of the values of Splits in a Transaction is always computed with respect to a currency; thus splits can be balanced even when they are in different currencies, as long as they share a common currency. This feature allows currency-trading accounts to be established.

Every Split must point to its parent Transaction, and that Transaction must in turn include that Split in the Transaction's list of Splits. A Split can belong to at most one Transaction. These relationships are enforced by the engine. The engine user cannnot accidentally destroy this relationship as long as they stick to using the API and never access internal structures directly.

Splits are grouped into Accounts (see section 2.13 Accounts) which are also known as "Ledgers" in accounting practice. Each Account consists of a list of Splits that debit that Account. To ensure consistency, if a Split points to an Account, then the Account must point to the Split, and vice-versa. A Split can belong to at most one Account. Besides merely containing a list of Splits, the Account structure also give the Account a name, a code number, description and notes fields, a key-value frame, a pointer to the commodity that is used for all splits in this account. The commodity can be the name of anything traded and tradable: a stock (e.g. "IBM", "McDonald's"), a currency (e.g. "USD", "GBP"), or anything added to the commodity table.

Accounts can be arranged in a hierarchical tree. The nodes of the tree are called "Account Groups" (see section 2.14 Account Groups). By accounting convention, the value of an Account is equal to the value of all of its Splits plus the value of all of its sub-Accounts.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.2 Using and Extending the Engine API

Engine API calls are named using a specific convention. For example, the function to access the Memo field of a Split is xaccSplitGetMemo. The prefix xacc comes first(1), followed by the name of the entity for which the API call applies (Split), followed by the action performed by the call (Get), followed by the name of the field being accessed (Memo). Future API calls should conform to this naming convention.

The formal arguments to Engine API calls always begin with the entity to which the call applies. Thus, the arguments to xaccSplitSetMemo are the Split pointer followed by the pointer to a memo string. Future API calls should also conform to this convention.

Engine API calls should be implemented to behave as gracefully as possible with unexpected input. Specifically, public API calls should gracefully handle NULL pointer arguments. User code should be able to handle NULL return values from Engine calls as well.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3 Globally Unique Identifiers

It is common for Engine structures to reference other Engine structures. For example, an Account must reference its Splits, its parent Account Group, and its child Account Group. Furthermore, other GnuCash modules may need to reference Engine structures. For example, a GUI implementation may wish to save a list of Accounts which the user has open when the application exits in order to restore that same state upon the next invocation.

One way to uniquely identify an Engine structure, at least while the program is running, is using the C pointer which points to the structure. C pointers have the advantage of speed, but also have some disadvantages:

The GUID (Globally Unique Identifier) provides a way to reference Engine structures that is more flexible than C pointers. Each Engine structure has an associated GUID which can be used to reference that structure. Engine GUIDs have the following features:

2.3.1 When to use GUIDs  
2.3.2 GUID Types  
2.3.3 How to use GUIDs  
2.3.4 GUIDs and GnuCash Entities  
2.3.5 The GUID Generator  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3.1 When to use GUIDs

Although GUIDs are very flexible, the engine structures like Accounts will probably continue to use C pointers for the forseeable future, since they are much faster (and in certain respects more convenient) than using GUIDs. In general, however, it is much safer to use GUIDs. In particular, you should consider using GUIDs if any of the following is true:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3.2 GUID Types

The GUIDs in GnuCash are typed using the enum GNCIdType. Possible values and their meanings for GUID types are:

GNC_ID_NONE
The GUID does not currently refer to a GnuCash entity, though it could refer to one in the future.

GNC_ID_NULL
The GUID does not, and never will, refer to a GnuCash entity.

GNC_ID_ACCOUNT
The GUID refers to an Account (see section 2.13 Accounts).

GNC_ID_TRANS
The GUID refers to a Transation (see section 2.12 Transactions).

GNC_ID_SPLIT
The GUID refers to a Split (see section 2.11 Splits).

Function: GNCIdType xaccGUIDType (const GUID * guid)
Return the type associated with guid.

Function: const GUID * xaccGUIDNull (void)
Return a GUID which is guaranteed to always have type GNC_ID_NULL.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3.3 How to use GUIDs

The Engine API functions which access the GUID for a specific entity return a pointer to the GUID. Note: Do not store the pointer itself! Instead, store a copy of the GUID. Storing the pointer itself would present some of the same problems as using the account pointer directly. Example:

 
{
  GUID saved_guid;
  Account *account;

  account = < something to get an Account pointer >

  saved_guid = *xaccAccountGetGUID(account);

  ...

  account = xaccAccountLookup(&saved_guid);

  ...
}

You can compare two GUIDs with the following functions.

Function: gboolean guid_equal (const GUID * guid_1, const GUID * guid_2)
Compare two guids and return TRUE if they are both non-NULL and equal.

Function: gint guid_compare (const GUID * g1, const GUID * g2)
Return the memcmp of the two GUID's.

You can encode and decode GUIDs and their string representations using the next two functions.

Function: char * guid_to_string (const GUID * guid)
Return a null-terminated string encoding of guid. String encodings of identifiers are hex numbers printed only with the characters 0 through 9 and a through f. The encoding will always be GUID_ENCODING_LENGTH characters long. The returned string should be freed when no longer needed.

Function: char * guid_to_string_buff (const GUID * guid, char * buff)
This routine does the same work as guid_to_string, except that the string is written into the memory pointed at by buff. The buffer must be at least GUID_ENCODING_LENGTH+1 characters long. This routine is handy for avoiding a malloc/free cycle. It returns a pointer to the end of what was written. (i.e. it can be used like stpcpy during string concatenation)

Function: gboolean string_to_guid (const char * string, GUID * guid)
Given a string, decode an id into guid if guid is non-NULL. The function returns TRUE if the string was a valid 32 character hexadecimal number. This function accepts both upper and lower case hex digits. If the return value is FALSE, the effect on guid is undefined.

You can allocate and deallocate space for GUIDs using standard memory routines. However, if your code is allocating and deallocating lots of GUID objects, then the next two functions should be used.

Function: GUID * xaccGUIDMalloc (void)
Return newly allocated memory for a GUID object. The memory must be freed with xaccGUIDFree. In general, this function is faster than using the standard libc allocators.

Function: void xaccGUIDFree (GUID * guid)
Free the space for a GUID that was allocated with xaccGUIDMalloc.

You can use the following two functions to aid in using GUIDS in hash tables.

Function: guint guid_hash_to_guint (gconstpointer ptr)
Return a hash value suitable for use with a GHashTable. ptr must point to a GUID.

Function: GHashTable * guid_hash_table_new (void)
Return a new GHashTable which uses GUIDs as keys.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3.4 GUIDs and GnuCash Entities

This section documents a low-level API for associating entities with GUIDs. User code and general engine code should not use this API; instead use the API documented in the sections for the specific GnuCash entities such as Accounts and Transactions.

Function: void xaccGUIDNew (GUID * guid)
Generate a new guid. This function is guaranteed to return a guid that is unique within the scope of all GnuCash entities being managed by the the current invocation of GnuCash. GnuCash routines should always use this function and not guid_new!

Function: void * xaccLookupEntity (const GUID * guid, GNCIdType entity_type)
Lookup an entity given an id and a type. If there is no entity associated with the id, or if it has a different type, NULL is returned.

Function: void xaccStoreEntity (void * entity, const GUID * guid, GNCIdType entity_type)
Store the given entity under the given id with the given type.

Function: void xaccRemoveEntity (const GUID * guid)
Remove any existing association between an entity and the given id. The entity is not changed in any way.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3.5 The GUID Generator

GUIDs are created by the GUID generator. The API for this generator is low-level and should not be used by user-code.

Function: void guid_init (void)
Initialize the GUID generator with a variety of random sources including common system files and /dev/random.

Function: void guid_init_with_salt (const void * salt, size_t salt_len)
Initialize the GUID generator with guid_init() and with the given sequence of arbitrary binary data.

Function: void guid_init_only_salt (const void * salt, size_t salt_len)
Initialize the GUID generator using only the given sequence of arbitrary binary data. This provides a way to reliably obtain a given sequence of GUIDs.

Function: void guid_new (GUID * guid)
Create a new GUID and store it in guid. This is a low-level function! GnuCash code should use xaccGUIDNew.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4 Numeric Library

=============== The documentation below for gnc_numeric is obsolete and has been superseeded by the gnc_numeric docs in the header file. =========================================

Financial quantities in GnuCash (Split quantities and values) are stored as exact quantities measured in the smallest denominational unit of the appropriate currency. For example, 100.50 US Dollars would be stored as (10050 / 100) US Dollars. GnuCash uses the gnc_numeric datatype to store financial quantities.

The gnc_numeric API provides data types and functions for manipulating exact numeric quantities. While the gnc_numeric library was developed to represent and operate on exact financial quantities in GnuCash, the library is also (hopefully) suitable for use in any application where exact numeric representation for rational numbers is needed.

A gnc_numeric value represents a number in rational form, with a 64-bit long long integer as numerator and denominator. If more precision, a higher-precision representation of irrational numbers, or a wider dynamic range is needed, a floating point format may be appropriate. There are reasonable rational approximations to common irrational constants (see section 2.4.9 Numeric Example), but the transcendental functions have not been implemented for gnc_numeric objects.

2.4.1 Standard Numeric Arguments  
2.4.2 Creating Numeric Objects  
2.4.3 Basic Arithmetic Operations  
2.4.4 Numeric Comparisons and Predicates  
2.4.5 Numeric Denominator Conversion  
2.4.6 Numeric Floating Point Conversion  
2.4.7 Numeric String Conversion  
2.4.8 Numeric Error Handling  
2.4.9 Numeric Example  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.1 Standard Numeric Arguments

=============== The documentation below for gnc_numeric is obsolete and has been superseeded by the gnc_numeric docs in the header file. =========================================

It is useful to specify a denominator in cases where it is known that the output value is of constrained precision. For example, monetary transactions must be executed in an integer number of the "smallest currency unit" of the transaction. In US Dollars, the smallest currency unit is the cent, and all monetary transactions must be done in units of cents. Therefore, any fractional cents in a computed price must be rounded away.

Most of the gnc_numeric arithmetic functions take two arguments in addition to their numeric args: denom, which is the denominator to use in the output gnc_numeric object, and how, which describes how the arithmetic result is to be converted to that denominator. This combination of output denominator and rounding policy allows the results of financial and other exact computations to be properly rounded to the appropriate units.

Valid values for denom are:

n (positive int)
Use the number n as the denominator of the output value.

GNC_DENOM_RECIPROCAL (n)
Use the value 1/n as the denominator of the output value.

GNC_DENOM_AUTO
Compute an appropriate denominator automatically. Flags in the how argument will specify how to compute the denominator.

Valid values for how are bitwise combinations of zero or one "rounding instructions" with zero or one "denominator types".

Rounding instructions control how fractional parts in the specified denominator affect the result. For example, if a computed result is "3/4" but the specified denominator for the return value is 2, should the return value be "1/2" or "2/2"?

Possible rounding instructions are:

GNC_RND_FLOOR
Round toward -infinity

GNC_RND_CEIL
Round toward +infinity

GNC_RND_TRUNC
Truncate fractions (round toward zero)

GNC_RND_PROMOTE
Promote fractions (round away from zero)

GNC_RND_ROUND
Use unbiased ("banker's") rounding. This rounds to the nearest integer, and to the nearest even integer when there are two equidistant nearest integers. This is generally the one you should use for financial quantities.

GNC_RND_ROUND_HALF_UP
Round to the nearest integer, rounding away from zero when there are two equidistant nearest integers.

GNC_RND_ROUND_HALF_DOWN
Round to the nearest integer, rounding toward zero when there are two equidistant nearest integers.

GNC_RND_NEVER
Never round at all, and signal an error if there is a fractional result in a computation.

The denominator type specifies how to compute a denominator if GNC_DENOM_AUTO is specified as the denom. Valid denominator types are:

GNC_DENOM_EXACT
Use any denominator which gives an exactly correct ratio of numerator to denominator. Use EXACT when you do not wish to lose any information in the result but also do not want to spend any time finding the "best" denominator.

GNC_DENOM_REDUCE
Reduce the result value by common factor elimination, using the smallest possible value for the denominator that keeps the correct ratio. The numerator and denominator of the result are relatively prime. This can be computationally expensive for large fractions.

GNC_DENOM_LCD
Find the least common multiple of the arguments' denominators and use that as the denominator of the result.

GNC_DENOM_FIXED
All arguments are required to have the same denominator, that denominator is to be used in the output, and an error is to be signaled if any argument has a different denominator.

GNC_DENOM_SIGFIG
Round to the number of significant figures given in the rounding instructions by the GNC_DENOM_SIGFIGS () macro.

GNC_DENOM_SIGFIGS (n)
Use a value for the denominator that will keep at least n significant figures in the result.

To use traditional rational-number operational semantics (all results are exact and are reduced to relatively-prime fractions) pass the argument GNC_DENOM_AUTO as denom and GNC_DENOM_REDUCE | GNC_RND_NEVER as how.

To enforce strict financial semantics (such that all operands must have the same denominator as each other and as the result), use GNC_DENOM_AUTO as denom and GNC_DENOM_FIXED | GNC_RND_NEVER as how.

=============== The documentation below for gnc_numeric is obsolete and has been superseeded by the gnc_numeric docs in the header file. =========================================


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.2 Creating Numeric Objects

Function: gnc_numeric gnc_numeric_create (int num, int denom)
Create a gnc_numeric object with a value of "num / denom".

Function: gnc_numeric gnc_numeric_zero ()
Create a gnc_numeric object with a value of 0.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.3 Basic Arithmetic Operations

See 2.4.1 Standard Numeric Arguments for a description of the denom and how arguments to each arithmetic function.

Function: gnc_numeric gnc_numeric_add (gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Return the sum of a and b.

Function: gnc_numeric gnc_numeric_sub (gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Return "a - b".

Function: gnc_numeric gnc_numeric_mul (gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Return the product of a and b.

Function: gnc_numeric gnc_numeric_div (gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Return "a / b".

Function: gnc_numeric gnc_numeric_neg (gnc_numeric a)
Return "-a".

Function: gnc_numeric gnc_numeric_abs (gnc_numeric a)
Return the absolute value of a.

Function: gnc_numeric gnc_numeric_add_fixed (gnc_numeric a, gnc_numeric b)
Equivalent to gnc_numeric_add on a and b with GNC_DENOM_AUTO for denom and GNC_DENOM_FIXED | GNC_RND_NEVER for how.

Function: gnc_numeric gnc_numeric_sub_fixed (gnc_numeric a, gnc_numeric b)
Equivalent to gnc_numeric_sub on a and b with GNC_DENOM_AUTO for denom and GNC_DENOM_FIXED | GNC_RND_NEVER for how.

Function: gnc_numeric gnc_numeric_add_with_error (gnc_numeric a, gnc_numeric b, gint64 denom, gint how, {gnc_numeric *} error)
The same as gnc_numeric_add, but uses error for accumulating conversion roundoff error.

Function: gnc_numeric gnc_numeric_sub_with_error (gnc_numeric a, gnc_numeric b, gint64 denom, gint how, {gnc_numeric *} error)
The same as gnc_numeric_sub, but uses error for accumulating conversion roundoff error.

Function: gnc_numeric gnc_numeric_mul_with_error (gnc_numeric a, gnc_numeric b, gint64 denom, gint how, {gnc_numeric *} error)
The same as gnc_numeric_mul, but uses error for accumulating conversion roundoff error.

Function: gnc_numeric gnc_numeric_div_with_error (gnc_numeric a, gnc_numeric b, gint64 denom, gint how, {gnc_numeric *} error)
The same as gnc_numeric_div, but uses error for accumulating conversion roundoff error.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.4 Numeric Comparisons and Predicates

Function: int gnc_numeric_zero_p (gnc_numeric a)
Returns 1 if a == 0, otherwise returns 0.

Function: int gnc_numeric_positive_p (gnc_numeric a)
Returns 1 if a > 0, otherwise returns 0.

Function: int gnc_numeric_negative_p (gnc_numeric a)
Returns 1 if a < 0, otherwise returns 0.

Function: int gnc_numeric_compare (gnc_numeric a, gnc_numeric b)
Returns +1 if a > b, -1 if b > a, 0 if a == b.

Function: int gnc_numeric_eq (gnc_numeric a, gnc_numeric b)
Returns 1 if numerator(a) == numerator(b) and denominator(a) == denominator(b), otherwise returns 0.

Function: int gnc_numeric_equal (gnc_numeric a, gnc_numeric b)
Returns 1 if the fraction represented by a is equal to the fraction represented by b, otherwise returns 0.

Function: int gnc_numeric_same (gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Convert both a and b to denom (see section 2.4.1 Standard Numeric Arguments and compare numerators of the result.

 
  For example, if a == 7/16 and b == 3/4,
  gnc_numeric_same(a, b, 2, GNC_RND_TRUNC) == 1
  because both 7/16 and 3/4 round to 1/2 under truncation. However,
  gnc_numeric_same(a, b, 2, GNC_RND_ROUND) == 0
  because 7/16 rounds to 1/2 under unbiased rounding but 3/4 rounds
  to 2/2.

=============== The documentation below for gnc_numeric is obsolete and has been superseeded by the gnc_numeric docs in the header file. =========================================


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.5 Numeric Denominator Conversion

Function: gnc_numeric gnc_numeric_convert (gnc_numeric in, gint64 denom, gint how)
Convert in to the specified denominator under standard arguments denom and how. See section 2.4.1 Standard Numeric Arguments.

Function: gnc_numeric gnc_numeric_convert_with_error (gnc_numeric in, gint64 denom, gint how, {gnc_numeric *} error)
Same as gnc_numeric_convert, but return a remainder value for accumulating conversion error.

Function: gnc_numeric gnc_numeric_reduce (gnc_numeric in)
Return in reduced by GCF reduction.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.6 Numeric Floating Point Conversion

Function: gnc_numeric double_to_gnc_numeric (double arg, gint64 denom, gint how)
Convert a floating-point number to a gnc_numeric. Both denom and how are used as in arithmetic, but GNC_DENOM_AUTO is not recognized.

Function: double gnc_numeric_to_double (gnc_numeric arg)
Convert arg to a double value.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.7 Numeric String Conversion

Function: gchar * gnc_numeric_to_string (gnc_numeric n)
Return a string representation of n. The string must be freed with g_free.

Function: const gchar * string_to_gnc_numeric (const {gchar *} str, {gnc_numeric *} n)
Read a gnc_numeric from str, skipping any leading whitespace, and returning a pointer to just past the last byte read. Return NULL on error.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.8 Numeric Error Handling

Function: int gnc_numeric_check (gnc_numeric num)
Check num for the possibility that it is an error signal rather than a proper value. Possible return codes are:

GNC_ERROR_OK
No error condition
GNC_ERROR_ARG
An improper argument was passed to a function

GNC_ERROR_OVERFLOW
An overflow occurred while calculating a result

GNC_ERROR_DENOM_DIFF
GNC_DENOM_FIXED was specified, but argument denominators differed.

GNC_ERROR_REMAINDER
GNC_RND_NEVER was specified, but the result could not be converted to the desired denominator without a remainder.

Function: gnc_numeric gnc_numeric_error (int error_code)
Create a gnc_numeric object that signals the error condition noted by error_code rather than a number.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.9 Numeric Example

=============== The documentation below for gnc_numeric is obsolete and has been superseeded by the gnc_numeric docs in the header file. =========================================

The following program finds the best gnc_numeric approximation to the `math.h' constant M_PI given a maximum denominator. For large denominators, the gnc_numeric approximation is accurate to more decimal places than will generally be needed, but in some cases this may not be good enough. For example,

 
    M_PI                   = 3.14159265358979323846
    245850922 / 78256779   = 3.14159265358979311599  (16 sig figs)
    3126535 / 995207       = 3.14159265358865047446  (12 sig figs)
    355 / 113              = 3.14159292035398252096  (7 sig figs)

 
#include <glib.h>
#include "gnc-numeric.h"
#include <math.h>

int
main(int argc, char ** argv)
{
  gnc_numeric approx, best;
  double err, best_err=1.0;
  double m_pi = M_PI;
  gint64 denom;
  gint64 max;

  sscanf(argv[1], "%Ld", &max);
  
  for (denom = 1; denom < max; denom++)
  {
    approx = double_to_gnc_numeric (m_pi, denom, GNC_RND_ROUND);
    err    = m_pi - gnc_numeric_to_double (approx);
    if (fabs (err) < fabs (best_err))
    {
      best = approx;
      best_err = err;
      printf ("%Ld / %Ld = %.30f\n", gnc_numeric_num (best),
              gnc_numeric_denom (best), gnc_numeric_to_double (best));
    }
  }
}


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5 Key-Value Pair Frames

The number and types of data items which are associated with the financial abstractions (Accounts, Transactions, and Splits) can vary widely. For example, an Account which represents a user's checking account might need to store the bank name, a telephone number, and a username for online banking purposes. Another Account representing the user's ownership of a stock might need to store information about retrieving price quotes online such as the ticker symbol and the exchange.

To meet this need for varying data storage, the GnuCash accounting entities use Key-Value Pair Frames (hereafter referred to as the datatype kvp_frame). A kvp_frame is a set of associations between character strings (keys) and kvp_value structures. A kvp_value is a union with possible types enumerated in the kvp_value_t enum which indicates the type of data stored in a kvp_value object.

2.5.1 Key-Value Policy  
2.5.2 kvp_frame  
2.5.3 kvp_value  
2.5.4 kvp_list  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.1 Key-Value Policy

This section defines the policy that programmers should follow when using key-value pairs to store information. Because of the large amount of information which can potentially be stored using this mechanism, it is important to follow these guidelines so that order will be maintained.

The following rules should be followed for using key-value pairs:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.2 kvp_frame

A kvp_frame is the datatype used to associate key strings with kvp_value objects (see section 2.5.3 kvp_value).

Function: kvp_frame* kvp_frame_new (void)
Create and initialize a new kvp_frame object and return a pointer to it.

Function: void kvp_frame_delete (kvp_frame * frame)
Free all memory associated with frame.

Function: kvp_frame* kvp_frame_copy (const kvp_frame * frame)
Return a deep copy of frame.

Function: void kvp_frame_set_slot (kvp_frame * frame, const char * key, const kvp_value * value)
Associate key with value in frame.

Function: void kvp_frame_set_slot_nc (kvp_frame * frame, const char * key, kvp_value * value)
Same as kvp_frame_set_slot, except that value is used directly, instead of being copied. This call transfers 'ownership' of value to frame.

Function: kvp_value* kvp_frame_get_slot (kvp_frame * frame, const char * key)
Return the kvp_value object associated with key in frame or return NULL if there is no association for key. The value returned is not a copy.

Function: void kvp_frame_set_slot_path (kvp_frame * frame, const kvp_value * value, const char * first_key, ...)
Associate value with the "key path" specified by the variable argument list. Each key in the path except the last denotes a sub-frame which is associated with the given key. The variable list must be terminated with NULL.

Function: void kvp_frame_set_slot_path_gslist (kvp_frame * frame, const kvp_value * value, GSList * key_path)
The same as kvp_frame_set_slot_path, except that the key path is specified using a GSList. All the keys in the list should be non-NULL.

Function: kvp_value * kvp_frame_get_slot_path (kvp_frame * frame, const char * first_key, ...)
Return the value associated with the key path, or NULL if none. The path is specified as in kvp_frame_set_slot_path.

Function: kvp_value * kvp_frame_get_slot_path_gslist (kvp_frame * frame, GSList * key_path)
Return the value associated with the key path, or NULL if none. The path is specified as in kvp_frame_set_slot_path_gslist.

Function: kvp_frame * kvp_frame_get_frame (kvp_frame * frame, ...)
Works like kvp_frame_get_slot_path, but returns the last frame in the path. All the keys should refer to frames. If the frame path does not exist, it is created.

Function: kvp_frame * kvp_frame_get_frame_gslist (kvp_frame * frame, GSList * key_path)
Works like kvp_frame_get_slot_path_gslist, but returns the last frame in the path. All the keys should refer to frames. If the frame path does not exist, it is created.

Function: kvp_frame * kvp_frame_get_frame_slash (kvp_frame * frame, const char * path)
Works like kvp_frame_get_frame, but the frame path is specified as a single string where the keys are separated by slashes; thus, for example: /this/is/a/valid/path and ///so//is////this/. Multiple slashes are compresed and a leading slash is optional. The pointers . and .. are not followed/obeyed. (This is arguably a bug that needs fixing).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.3 kvp_value

The kvp_value object stores the 'value' part of a key-value association in a kvp_frame object.

Function: void kvp_value_delete (kvp_value * value)
Free all of the memory associated with value.

Function: kvp_value* kvp_value_copy (const kvp_value * value)
Return a deep copy of value.

Function: kvp_value_t kvp_value_get_type (const kvp_value * value)
Return the type of value stored in value.

A kvp_value_t enum must have one of the following values:

KVP_TYPE_NONE
Indicates the abscence of a value in a kvp_frame.

KVP_TYPE_INT64
A gint64 value.

KVP_TYPE_FLOAT64
A double value.

KVP_TYPE_STRING
A char * value of arbitrary length.

KVP_TYPE_GUID
A GUID value. See section 2.3 Globally Unique Identifiers.

KVP_TYPE_BINARY
Arbitrary binary data.

KVP_TYPE_LIST
A kvp_list item which contains a list of kvp_value items.

KVP_TYPE_FRAME
A kvp_frame object. Thus, frames may contain other frames in a recursive manner.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.3.1 Value Constructors

The following functions create and return kvp_value objects with particular values. In the case of pointer arguments, deep copies are performed.

Function: kvp_value* kvp_value_new_int64 (gint64 value)
Function: kvp_value* kvp_value_new_float64 (double value)
Function: kvp_value* kvp_value_new_string (const char * value)
Function: kvp_value* kvp_value_new_guid (const GUID * guid)
Function: kvp_value* kvp_value_new_binary (const void * data, int datasize)
Function: kvp_value* kvp_value_new_list (const kvp_list * value)
Function: kvp_value* kvp_value_new_frame (const kvp_frame * value);


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.3.2 Value Accessors

The following functions access the value of a given kvp_value object. If the type of the object does not correspond to that named in the function, NULL, 0, or 0.0 is returned as appropriate.

Function: gint64 kvp_value_get_int64 (const kvp_value * value)
Function: double kvp_value_get_float64 (const kvp_value * value)
Function: char* kvp_value_get_string (const kvp_value * value)
Function: GUID* kvp_value_get_guid (const kvp_value * value)
Function: void* kvp_value_get_binary (const kvp_value * value, int * size_return)
Function: kvp_list* kvp_value_get_list (const kvp_value * value)
Function: kvp_frame* kvp_value_get_frame (const kvp_value * value)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.4 kvp_list

A kvp_list object abstract a list of kvp_value objects.

Function: kvp_list* kvp_list_new ()
Return a newly allocated kvp_list object.

Function: void kvp_list_delete (kvp_list * list)
Free all memory associated with list, including the kvp_value objects in list.

Function: kvp_list* kvp_list_copy (const kvp_list * list)
Return a deep copy of list.

Function: gboolean kvp_list_null_p (const kvp_list * list)
Return TRUE if list is the empty list.

Function: kvp_value* kvp_list_car (kvp_list * list)
If list is NULL or the empty list, return NULL. Otherwise, return the first kvp_value object in the list.

Function: kvp_list* kvp_list_cdr (kvp_list * list)
If list is NULL or the empty list, return NULL. Otherwise, return a kvp_list object consisting of list with the first value removed. NOTE: the returned list is not a copy!

Function: kvp_list* kvp_list_cons (kvp_value * car, kvp_list * cdr)
If either car or cdr is NULL, return NULL. Otherwise, return a kvp_list object consisting of the value of car followed by the values of cdr. This function uses 'hand-over' semantics, i.e., the arguments car and cdr are no longer the responsibility of the caller and should not be accessed after the function returns.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.6 Events

The Engine supports the concept of Events which notify external code when engine entities are created, modified, or destroyed.

User code can register event handers which are invoked for each event, giving information about the specific engine entity generating the event and the nature of the event (creation, modification, or deletion).

2.6.1 Event API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.6.1 Event API

Engine events are classified using the GNCEngineEventType bitmask which has the following predefined values:

GNC_EVENT_NONE
A null value.

GNC_EVENT_CREATE
Indicates an entity has been created.

GNC_EVENT_MODIFY
Indicates an entity has been changed in some way.

GNC_EVENT_DESTROY
Indicates an entity is being destroyed.

GNC_EVENT_ALL
The boolean OR of GNC_EVENT_CREATE, GNC_EVENT_MODIFY, and GNC_EVENT_DESTROY.

Event handlers are functions with the following type:

Data type: GNCEngineEventHandler void (*) (GUID * entity, GNCEngineEventType event_type, gpointer user_data)
A callback invoked when an engine event occurs. entity is the GUID of the entity generating the event. event_type is one of GNC_EVENT_CREATE, GNC_EVENT_MODIFY, or GNC_EVENT_DESTROY. user_data is the user data parameter supplied when the handler was registered.

Function: gint gnc_engine_register_event_handler (GNCEngineEventHandler handler, gpointer user_data)
Register a handler for engine events. The return value is an identifier used to specify this handler in other API calls.

Function: void gnc_engine_unregister_event_handler (gint handler_id)
Unregister the event handler specified by handler_id.

Function: void gnc_engine_suspend_events (void)
Suspend all engine events. This function may be called multiple times. To resume event generation, an equal number of calls to gnc_engine_resume_events must be made.

Function: void gnc_engine_resume_events (void)
Resume engine event generation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7 Commodities

A Commodity is the Engine abstraction of a tradable quantity, like a national currency or shares of a stock. A commodity object contains the following pieces of information:

A mnemonic name
The `short' name for the commodity. For national currencies this is the 3-letter ISO4217 code (USD, AUD, etc.). For stocks this is generally the exchange symbol (RHAT, IBM, etc.).

A namespace
A string identifying the context in which the mnemonic is meaninful.

A full name
The `long' name for the commodity, such as "US Dollar" or "IBM Common Stock".

A printable name
The name used to print out a string describing the commodity to a user. This name is generally long -- in some contexts it may be better to use the mnemonic instead. The printable name is determined by the namespace and mnemonic.

A unique name
A canonical name for the commodity that cannot be identical to another commodity's unique name. The unique name is determined by the namespace and mnemonic.

An exchange code
A code used to identify the commodity in its namespace context. For example, stocks have a unique code assigned to them by the exchange they are listed on.

A fraction
An integer N which specifies that 1/N is generally the smallest fraction of the commodity which can be traded. For example, most currencies are tradable in 1/100ths, so the fraction would be 100.

2.7.1 General Commodity API  
2.7.2 Commodity Getters  
2.7.3 Commodity Setters  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7.1 General Commodity API

Function: gnc_commodity * gnc_commodity_new (const char * fullname, const char * namespace, const char * mnemonic, const char * exchange_code, int fraction)
Create and return a new commodity object with the given values, or NULL if any of the values are invalid.

Function: void gnc_commodity_destroy (gnc_commodity * cm)
Destroy the given commodity and free all associated memory.

Function: gboolean gnc_commodity_equiv (const gnc_commodity * a, const gnc_commodity * b)
Return true if the two given commodities are equivalent. Two commodities are equivalent when they have the same namespace and the same mnemonic.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7.2 Commodity Getters

Function: const char * gnc_commodity_get_mnemonic (const gnc_commodity * cm)
Return the mnemonic of cm.

Function: const char * gnc_commodity_get_namespace (const gnc_commodity * cm)
Return the namespace of cm.

Function: const char * gnc_commodity_get_fullname (const gnc_commodity * cm)
Return the full name of cm.

Function: const char * gnc_commodity_get_printname (const gnc_commodity * cm)
Return the print name of cm.

Function: const char * gnc_commodity_get_exchange_code (const gnc_commodity * cm)
Return the exchange code of cm.

Function: const char * gnc_commodity_get_unique_name (const gnc_commodity * cm)
Return the unique name of cm.

Function: int gnc_commodity_get_fraction (const gnc_commodity * cm)
Return the smallest tradable fraction of cm.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.7.3 Commodity Setters

Function: void gnc_commodity_set_mnemonic (gnc_commodity * cm, const char * mnemonic)
Set the mnemonic of cm to mnemonic.

Function: void gnc_commodity_set_namespace (gnc_commodity * cm, const char * namespace)
Set the namespace of cm to namespace.

Function: void gnc_commodity_set_fullname (gnc_commodity * cm, const char * fullname)
Set the fullname of cm to fullname.

Function: void gnc_commodity_set_exchange_code (gnc_commodity * cm, const char * exchange_code)
Set the exchange code of cm to exchange_code.

Function: void gnc_commodity_set_fraction (gnc_commodity * cm, int smallest_fraction)
Set the fraction of cm to fraction.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.8 Commodity Tables

A Commodity Table holds a set of commodities and allows user code to add, remove, and access the commodities in the table.

There is a single, global Commodity Table used by the Engine.

2.8.1 General Commodity Table API  
2.8.2 Commodity Table Access API  
2.8.3 Commodity Table Modification API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.8.1 General Commodity Table API

Function: gnc_commodity_table * gnc_commodity_table_new (void)
Allocate and initialize a gnc_commodity_table. The returned table must be destroyed with gnc_commodity_table_destroy.

Function: void gnc_commodity_table_destroy (gnc_commodity_table * table)
Destroy table and all associated resources, including all Commodity objects in the table.

Function: gnc_commodity_table * gnc_engine_commodities (void)
Return the global engine commodity table.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.8.2 Commodity Table Access API

Function: gnc_commodity * gnc_commodity_table_lookup (const gnc_commodity_table * table, const char * namespace, const char * mnemonic)
Look up a commodity in table given the namespace and the mnemonic. If no such commodity exists, NULL is returned.

Function: gnc_commodity * gnc_commodity_table_find_full (const gnc_commodity_table * table, const char * namespace, const char * fullname)
Look up a commodity in table given the namespace and the full name. If no such commodity exists, NULL is returned.

Function: int gnc_commodity_table_has_namespace (const gnc_commodity_table * table, const char * namespace)
Return true if table has the namespace namespace.

Function: guint gnc_commodity_table_get_size (gnc_commodity_table * table)
Return the total number of commodities stored in table.

Function: guint gnc_commodity_table_get_number_of_namespaces (gnc_commodity_table * table)
Return the number of distinct namespaces in table.

Function: GList * gnc_commodity_table_get_namespaces (const gnc_commodity_table * table)
Return a list of the distinct namespaces in table. The list should be freed with g_list_free but the namespaces should not be freed or modified.

Function: GList * gnc_commodity_table_get_commodities (const gnc_commodity_table * table, const char * namespace)
Return a list of the commodities under namespace in table. The list should be freed with g_list_free but the commodities should not be freed.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.8.3 Commodity Table Modification API

Function: gnc_commodity * gnc_commodity_table_insert (gnc_commodity_table * table, gnc_commodity * comm)
Add commodity comm to table. If comm's namespace is not in table, the namespace will be added. This function has hand-over semantics, i.e., table assumes responsibility for comm. comm may even be destroyed by this call! The function returns the actual commodity added as a result of the call. It may not be the same object as comm, but will be equivalent to comm.

Function: void gnc_commodity_table_remove (gnc_commodity_table * table, gnc_commodity * comm)
Remove the given commodity from table. comm is not modified or destroyed.

Function: void gnc_commodity_table_add_namespace (gnc_commodity_table * table, const char * namespace)
Add namespace to table.

Function: void gnc_commodity_table_delete_namespace (gnc_commodity_table * table, const char * namespace)
Delete namespace from table including all associated commodities.

Function: void gnc_commodity_table_remove_non_iso (gnc_commodity_table * table)
Remove and destroy all commodities in table which are not in the ISO4217 namespace.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9 Prices

A Price is the Engine abstraction of an "instantaneous" price quote for a given commodity with respect to another commodity. For example, a given price might represent the value of LNUX in USD on 2001-02-03. A Price contains the following pieces of information:

A GUID
A GUID uniquely identifying the GNCPrice.

A commodity
The commodity being priced.

A currency
The denomination of the value of the item being priced.

A value
The value of the item being priced.

A time
The time the price was valid.

A source
A string describing the source of the quote. These strings will have a form like this: "Finance::Quote", "user:misc", "user:foo", etc. If the quote came from a user, as a matter of policy, you must prefix the string you give with "user:". For now, the only other reserved values are "Finance::Quote" and "old-file-import".

A type
A string describing the type of quote -- types possible right now are "bid", "ask", "last", "nav", and "unknown".

2.9.1 Price Implementation Details  
2.9.2 General Price API  
2.9.3 Price Getters  
2.9.4 Price Setters  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.1 Price Implementation Details

For the source and type fields, NULL and the empty string are considered the same, so if one of these is the empty string then it might be NULL after a file save/restore.

GNCPrices are reference counted. When you create a price or or clone one, the new price's reference count is set to 1. When you are finished with a price, call gnc_price_unref. If you hand the price pointer to some other code that needs to keep it, make sure it calls gnc_price_ref to indicate its interest in that price, and calls gnc_price_unref when it's finished with the price. For those unfamiliar with reference counting, basically each price stores an integer count which starts at 1 and is incremented every time someone calls gnc_price_ref. Conversely, the count is decremented every time someone calls gnc_price_unref. If the count ever reaches 0, the price is destroyed.

All of the getters return data that's internal to the GNCPrice, not copies, so don't free or modify these values.

All of the setters store copies of the data given, with the exception of the commodity field which just stores the pointer given. It is assumed that commodities are a global resource and are pointer unique.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.2 General Price API

Function: GNCPrice * gnc_price_create (void)
Return a newly allocated and initialized price with a reference count of 1. The price should be dereferenced with gnc_price_unref when no longer needed, but the price should not be freed by user code.

Function: GNCPrice * gnc_price_clone (GNCPrice * p)
Return a newly allocated price that's a content-wise duplicate of p. The returned clone will have a reference count of 1.

Function: void gnc_price_ref (GNCPrice * p)
Increase the reference count of p by 1.

Function: void gnc_price_unref (GNCPrice * p)
Decrease the reference coutn of p by 1. If the resulting count is 0, p will be destroyed.

Function: GNCPrice * gnc_price_lookup (const GUID * guid)
Lookup and return the price associated with guid, or NULL if there is no such price.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.3 Price Getters

Function: const GUID * gnc_price_get_guid (GNCPrice * p)
Return the GUID of p.

Function: gnc_commodity * gnc_price_get_commodity (GNCPrice * p)
Return the commodity of p.

Function: gnc_commodity * gnc_price_get_currency (GNCPrice * p)
Return the currency of p.

Function: Timespec gnc_price_get_time (GNCPrice * p)
Return the time of p.

Function: const char * gnc_price_get_source (GNCPrice * p)
Return the source of p.

Function: const char * gnc_price_get_type (GNCPrice * p)
Return the type of p.

Function: gnc_numeric gnc_price_get_value (GNCPrice * p)
Return the value of p.

Function: gint32 gnc_price_get_version (GNCPrice * p)
Return the version of p.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.4 Price Setters

Invocations of the setters should be wrapped with calls to gnc_price_begin_edit and gnc_price_commit_edit. The begin/commit calls help ensure that the local price db is synchronized with the backend.

Function: void gnc_price_begin_edit (GNCPrice * p)
Begin a sequence of changes to p.

Function: void gnc_price_commit_edit (GNCPrice * p)
End a sequence of changes to p.

Function: void gnc_price_set_commodity (GNCPrice * p, gnc_commodity * c)
Set the commodity of p to c.

Function: void gnc_price_set_currency (GNCPrice * p, gnc_commodity * c)
Set the currency of p to c.

Function: void gnc_price_set_time (GNCPrice * p, Timespec t)
Set the time of p to t.

Function: void gnc_price_set_source (GNCPrice * p, const char * source)
Set the source of p to source.

Function: void gnc_price_set_type (GNCPrice * p, const char * type)
Set the type of pto type.

Function: void gnc_price_set_value (GNCPrice * p, gnc_numeric value)
Set the value of p to value.

Function: void gnc_price_set_version (GNCPrice * p, gint32 versn)
Set the version of p to versn.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.10 Price Databases

A Price Database stores GNCPrices and allows prices to be looked up based on currency, commodity, and time.

2.10.1 Price Lists  
2.10.2 General Price Database API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.10.1 Price Lists

Price Lists are used by Price Databases to organize prices for a given commodity and currency. A Price List is a list of prices with the same commodity and currency, sorted by decreasing time (earlier prices come later in the list).

Function: gboolean gnc_price_list_insert (GList ** prices, GNCPrice * p)
Insert price p into the list prices, calling gnc_price_ref on p during the process.

Function: gboolean gnc_price_list_remove (GList ** prices, GNCPrice * p)
Remove price p from the list prices, calling gnc_price_unref on p during the process.

Function: void gnc_price_list_destroy (GList * prices)
Destroy the price list prices, calling gnc_price_unref on all the prices in the list.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.10.2 General Price Database API

Function: GNCPriceDB * gnc_pricedb_create (void)
Create and return a new price database.

Function: void gnc_pricedb_destroy (GNCPriceDB * db)
Destroy the price database db and unreference all of the prices it contains. This may not deallocate all of those prices; other code may still be holding references to them.

Function: gboolean gnc_pricedb_add_price (GNCPriceDB * db, GNCPrice * p)
Add the price p to db. This will increase the reference count of p, so user code may safely drop its reference to the price (i.e. call gnc_price_unref) if the call succeeds (returns true).

Function: gboolean gnc_pricedb_remove_price (GNCPriceDB * db, GNCPrice * p)
Removes the price p from the price database db. Returns true if successful and false otherwise.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.11 Splits

A Split is the Engine abstraction of an accounting entry in an Account Ledger. In accounting terms, a Split is a Ledger Entry. As such, it contains the following pieces of information:

A parent Account
The Account of which it is an entry.

A parent Transaction.
In accounting terms, this is the Journal Entry which this Ledger Entry is linked to.

A 'share quantity'
This is the number of 'shares' which have been debited to the parent Account. This quantity may be negative, in which case the Split represents a 'credit'. Shares are given in units of the security of the Account, unless the security field is NULL, in which case shares are given in units of the Account currency. See section 2.13 Accounts.

A 'value'
This represents the value of the shares in units of the currency of the Account. If the currency and the security are the same, or the security field is NULL, the value and share quantity must be equal.

A 'reconciled' flag
This flag represents the reconciled status of the Split. Possible reconciliation states for a Split are:

Not Reconciled
The Split has not been reconciled or cleared.

Cleared
The Split has been cleared, but not reconciled.

Reconciled
The Split has been reconciled with a statement.

Frozen
The Split has been frozen into the accounting period.

In addition to the above, Splits contain a Memo field, an Action field, and a key-value pair frame. The Memo and Action fields are for arbitrary user input. See src/engine/kvp_frame.txt for the names of keys that have already been reserved for use in the frame.

2.11.1 General Split API  
2.11.2 Split Getters  
2.11.3 Split Setters  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.11.1 General Split API

Function: Split * xaccMallocSplit (void)
Allocate, initialize, and return a new Split.

Function: void xaccSplitDestroy (Split * split)
Update split's parent Account and Transaction in a consistent manner, completely unlinking of split and freeing its memory. The goal of this routine is to perform the removal and destruction of the Split in an atomic fashion, with no chance of accidentally leaving the accounting structure out-of-balance or otherwise inconsistent.

If the deletion of the Split leaves the Transaction with no Splits, then the Transaction will be marked for deletion, but will not be deleted until the xaccTransCommitEdit() routine is called.

Function: const GUID * xaccSplitGetGUID (Split * split)
Return the GUID of split.

Function: Split * xaccSplitLookup (const GUID * guid)
Return the split associated with GUID, or NULL if there is no such split.

Function: void xaccSplitMakeStockSplit (Split * split)
Modify split to be an "official" stock-split split. Among other things, this involves clearing the value of the split to 0.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.11.2 Split Getters

Function: Account * xaccSplitGetAccount (Split * split)
Return the parent Account of split.

Function: Transaction * xaccSplitGetParent (Split * split)
Return the parent Transaction of split.

Function: gnc_numeric xaccSplitGetShareAmount (Split * split)
Return the 'share quantity' of split.

Function: gnc_numeric xaccSplitGetSharePrice (Split * split)
Return the 'share price' of split, which is the value divided by the share quantity.

Function: gnc_numeric xaccSplitGetValue (Split * split)
Return the value of split.

Function: gnc_numeric xaccSplitGetBaseValue (Split * split, const char * base_currency)
Return either the share quantity or the value of split, depending upon whether base_currency matches the security or currency of the parent Account, respectively. No other value for base_currency is legal.

Function: char xaccSplitGetReconcile (Split * split)
Return the value of the reconcile flag in split. Possible values for the flag are:

NREC
Not Reconciled

CREC
Cleared

YREC
Reconciled

FREC
Frozen

Function: void xaccSplitGetDateReconciledTS (Split * split, Timespec * ts)
Fill ts with the reconciled date of split.

Function: const char * xaccSplitGetMemo (Split * split)
Return the Memo field of split.

Function: const char * xaccSplitGetAction (Split * split)
Return the Action field of split.

Function: gnc_numeric xaccSplitGetBalance (Split * split)
Return the balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: gnc_numeric xaccSplitGetClearedBalance (Split * split)
Return the cleared balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: gnc_numeric xaccSplitGetReconciledBalance (Split * split)
Return the reconciled balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: gnc_numeric xaccSplitGetShareBalance (Split * split)
Return the share balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: gnc_numeric xaccSplitGetShareClearedBalance (Split * split)
Return the share cleared balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: gnc_numeric xaccSplitGetShareReconciledBalance (Split * split)
Return the share reconciled balance of split's parent Account up to and including split. See 2.13 Accounts for details.

Function: const char* xaccSplitGetType (Split * split)
Return split's type as a string. Currently, the possibilities are

normal
a normal split -- the default.

stock-split
a split representing a stock split. The value should be 0 and the share amount should represent the number of shares added/subtracted from the account as a result of the forward/reverse stock split.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.11.3 Split Setters

Function: void xaccSplitSetMemo (Split * split, const char * memo)
Set the memo field of split to memo.

Function: void xaccSplitSetAction (Split * split, const char * action)
Set the action field of split to memo. The action field is an arbitrary string, but is intended to be conveniently limited to a menu of selections such as "Buy", "Sell", "Interest", etc.

Function: void xaccSplitSetReconcile (Split * split, char reconciled_flag)
Set the reconciled flag of split to reconciled_flag. For the possible values and meanings of reconciled_flag, see 2.11.2 Split Getters.

Function: void xaccSplitSetDateReconciledSecs (Split * split, time_t time)
Set the reconciliation date of split to time.

Function: void xaccSplitSetDateReconciledTS (Split * split, Timespec * ts)
Set the reconciliation date of split to ts.

Function: void xaccSplitSetShareAmount (Split * split, gnc_numeric amount)
Set the share quantity of split to amount.

Function: void xaccSplitSetSharePrice (Split * split, gnc_numeric price)
Set the share price of split to price.

Function: void xaccSplitSetSharePriceAndAmount (Split * split, gnc_numeric price, gnc_numeric amount)
Set both the share price and share quantity of split. This routine is more efficent than calling xaccSplitSetShareAmount and xaccSplitSetSharePrice in succesion.

Function: void xaccSplitSetValue (Split * split, gnc_numeric value)
Adjust the share quantity of split so that split's value is equal to value.

Function: void xaccSplitSetBaseValue (Split * split, gnc_numeric value, const char * base_currency)
Set either the share quantity or value of split depending upon whether base_currency is the security or current of split's parent Account. See section 2.13 Accounts.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.12 Transactions

A Transaction is the Engine abstraction of an accounting entry in a Journal. In accounting terms, a Transaction is a Journal Entry. As such, it contains the following pieces of information:

A list of Ledger Entries, or Splits
The list of debits and credits which make up this Transaction. As in accounting, a Transaction is balanced when the sum of the debits equals the sum of the credits.

The entry date
The date the transaction was entered into GnuCash.

The post date
The date the transaction was posted. This is often the date the transaction was recorded by the bank, or the date the user initiated the transaction (i.e., wrote the check, made the ATM withdrawal).

A transaction number field
This field is intended to hold a transaction number, such as a check number or an ID assigned by a bank to an electronic transfer.

A description
A textual description of the transaction.

In addition to the above, Transactions contain a key-value pair frame.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.12.1 The Transaction Edit Cycle

The Engine supports (and, in fact, requires) a 2-phase commit/rollback cycle for modifying Transactions and their constituent Splits. A Transaction must be opened for editing using xaccTransBeginEdit() before any of the following actions may be taken.

After the desired changes have been made, they must either be committed using xaccTransCommitEdit() or rolled back using xaccTransRollbackEdit(). Rolling back a transaction will undo any changes which have been made to it or to its Splits since it was opened for editing.

2.12.2 General Transaction API  
2.12.3 Transaction Getters  
2.12.4 Transaction Setters  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.12.2 General Transaction API

Function: Transaction * xaccMallocTransaction (void)
Allocate, initialize, and return a new Transaction.

Function: void xaccTransDestroy (Transaction * {trans})
Remove all of the Splits from each of their accounts and free the memory associated with them. This routine must be followed by either an xaccTransCommitEdit() in which case the transaction memory will be freed, or by xaccTransRollbackEdit(), in which case all the original Splits are put back into place.

Function: void xaccTransAppendSplit (Transaction * trans, Split * split)
Append split to the collection of Splits in trans. If the Split is already a part of another Transaction, it will be removed from that Transaction first.

Function: void xaccTransBeginEdit (Transaction * trans)
This method must be called before any changes are made to trans or any of its component Splits. If this is not done, errors will result.

Function: void xaccTransCommitEdit (Transaction * trans)
This method indicates that the changes to trans and its Splits are complete and should be made permanent. Note this routine may result in the deletion of the transaction, if the Transaction is "empty" (has no Splits) or if xaccTransDestroy() was called on the Transaction.

Function: void xaccTransRollbackEdit (Transaction * trans)
Rejects all changes made to trans and its Splits, and sets trans back to where it was before the xaccTransBeginEdit() call. This includes restoring any deleted Splits, removing any added Splits, and undoing the effects of xaccTransDestroy(), as well as restoring share quantities, memos, descriptions, etc.

Function: gboolean xaccTransIsOpen (Transaction * trans)
Return TRUE if trans is open for editing. Otherwise, it returns FALSE.

Function: const GUID * xaccTransGetGUID (Transaction * trans)
Return the GUID of trans.

Function: Transaction * xaccTransLookup (const GUID * guid)
Return the Transaction associated with GUID, or NULL if there is no such Transaction.

Function: kvp_value * xaccTransGetSlot (Transaction * trans, const char * key)
Return the kvp_value associated with key in trans. If there is none, NULL is returned.

Function: void xaccTransSetSlot (Split * trans, const char * key, const kvp_value * value)
Associate a copy of value with key in trans.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.12.3 Transaction Getters

Function: Split * xaccTransGetSplit (Transaction * trans, int i)
Return the Ith Split of trans.

Function: GList * xaccTransGetSplitList (Transaction * trans)
Return a GList of the Splits in trans. This list is owned by trans and should not be modified in any way!

Function: const char * xaccTransGetNum (Transaction * trans)
Return the number field of trans.

Function: const char * xaccTransGetDescription (Transaction * trans)
Return the description field of trans.

Function: time_t xaccTransGetDate (Transaction * trans)
Return the post date of trans as a time_t value.

Function: long long xaccTransGetDateL (Transaction * trans)
Return the post date of trans as a long long value.

Function: void xaccTransGetDateTS (Transaction * trans, Timespec * ts)
Return the post date of trans in ts.

Function: void xaccTransGetDateEnteredTS (Transaction * trans, Timespec * ts)
Return the entry date of trans in ts.

Function: char * xaccTransGetDateStr (Transaction * trans)
Return a string representing the post date of trans, or NULL if trans is NULL. The string must be freed with free() after use.

Function: int xaccTransCountSplits (Transaction * trans)
Return the number of Splits in trans.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.12.4 Transaction Setters

Remember, before you modify a Transaction, you must open it for editing with xaccTransBeginEdit.

Function: void xaccTransSetDate (Transaction * trans, int day, int mon, int year)
Set the post date of trans with day, month, and year.

Function: void xaccTransSetDateSecs (Transaction * trans, time_t time)
Set the post date of trans using a time_t value.

Function: void xaccTransSetDateToday (Transaction * trans)
Set the post date of trans to the current time.

Function: void xaccTransSetDateTS (Transaction * trans, const Timespec * ts)
Set the post date of trans from ts.

Function: void xaccTransSetDateEnteredSecs (Transaction *trans, time_t time)
Set the entry date of trans from a time_t value.

Function: void xaccTransSetDateEnteredTS (Transaction * trans, const Timespec * ts)
Set the entry date of trans from ts.

Function: void xaccTransSetNum (Transaction * trans, const char * num)
Set the number field of trans to num.

Function: void xaccTransSetDescription (Transaction * trans, const char * desc)
Set the description field of trans to desc.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13 Accounts

An Account is the Engine abstraction of an, well, an account. Accounts contain the following pieces of information:

A list of Ledger Entries, or Splits
The list of debits and credits which apply to the Account. The sum of all debits and credits is the account balance.

A type
An integer code identifying the type of account. The Account type determines whether the Account holds shares valued in a currency or not. It is also used by the GUI and reporting system to determine how debits & credits to the Account should be treated and displayed.

A name
The name of the Account.

An account code
A string that is intended to hold a unique user-selected identifier for the account. However, uniqueness of this field is not enforced.

A description
A textual description of the Account.

A currency
The commodity that Splits in the account are valued in, i.e., the denomination of the 'value' member of Splits in the account.

A curreny SCU
The SCU is the smallest convertible unit that the currency is traded in. This value overrides the default SCU of the currency.

A security
For Accounts which may contain shares (such as stock accounts), the denomination of the 'share quantity' member of Splits in the accounts. For accounts which do not contain shares, the security is blank, and the share quantities are denominated in the Account currency.

A security SCU
Analogous to the currency SCU, but for the security.

A parent and child Account Group.
The parent and child of an Account are Account Groups (see section 2.14 Account Groups). Account Groups are used to connect Accounts together into an Account hierarchy. If the parent Account Group is not present, the Account is at the top level of the hierarchy. If the child Account Group is not present, the Account has no children.

In addition to the above, Accounts contain a key-value pair frame.

2.13.1 Account Types  
2.13.2 General Account API  
2.13.3 Account Type API  
2.13.4 Account Getters  
2.13.5 Account Tax API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13.1 Account Types

Account Types are defined by the GNCAccountType enumeration. Possible values are:

BAD_TYPE, NO_TYPE
Both of these values indicate an illegal Account type.

BANK
Denotes a savings or checking account held at a bank. Such an account is often interest bearing.

CASH
Denotes a shoe-box or pillowcase stuffed with cash. In other words, actual currency held by the user.

CREDIT
Denotes credit card accounts.

ASSET
Denotes a generic asset account.

LIABILITY
Denotes a generic liability account.

STOCK
A stock account containing stock shares.

MUTUAL
A mutual fund account containing fund shares.

CURRENCY
Denotes a currency trading account. In many ways, a currency trading account is like a stock trading account, where both quantities and prices are set. However, generally both currency and security are national currencies.

INCOME
Denotes an income account. The GnuCash financial model does not use 'categories'. Actual accounts are used instead.

EXPENSE
Denotes an expense account.

EQUITY = 10,
Denotes an equity account.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13.2 General Account API

Function: Account * xaccMallocAccount (void)
Allocate and initialize an Account. The account must be destroyed by calling xaccAccountBeginEdit followed by xaccAccountDestroy.

Function: void xaccAccountDestroy (Account * account)
Destroys account and frees all memory associated with it. This routine will also destroy the Account's children. You must call xaccAccountBeginEdit before calling this function.

Function: void xaccAccountBeginEdit (Account * account)
This routine, together with xaccAccountCommitEdit, provide a two-phase-commit wrapper for account updates much in the same way as xaccTransBeginEdit and xaccTransCommitEdit do for Transactions.

Function: void xaccAccountCommitEdit (Account * account)
The counterpart to xaccAccountBeginEdit.

Function: Account * xaccCloneAccountSimple (const Account * from)
Return a 'copy' of from that is identical in the type, name, code, description, kvp data, and currency. All other fields are the same as an account returned by xaccMallocAccount.

Function: const GUID * xaccAccountGetGUID (Account * account)
Return the globally unique id associated with account.

Function: Account * xaccAccountLookup (const GUID * guid)
Return the Account associated with guid, or NULL if there is no such Account.

Function: kvp_frame * xaccAccountGetSlots (Account * account)
Return the kvp_frame associated with account. User code may modify this kvp_frame, but must not destroy it.

Function: void xaccAccountSetSlots_nc (Account * account, kvp_frame * frame)
Set the kvp_frame associated wih account. After the call, frame is owned by account, so don't destroy it.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13.3 Account Type API

Function: const char * xaccAccountGetTypeStr (GNCAccountType type)
Return a string corresponding to the given Account type suitable for display by a GUI. The string is translated with gettext according to the current locale.

Function: char * xaccAccountTypeEnumAsString (GNCAccountType type)
Return a string corresponding to the given Account type. The string is not translated and is independent of the current locale.

Function: gboolean xaccAccountStringToType (const char * str, GNCAccountType * type)
Converts a string of the form returned by xaccAccountTypeEnumAsString to a type, return in type. Returns true if the string corresponds to an actual type.

Function: GNCAccountType xaccAccountStringToEnum (const char * str)
Similar to xaccAccountStringToEnum, but returns the type. If str does not correspond to any valid type, BAD_TYPE is returned.

Function: gboolean xaccAccountTypesCompatible (GNCAccountType parent_type, GNCAccountType child_type)
Returns TRUE if accounts of type parent_type can have child accounts of type child_type. This compatibility is not enforced by the engine, but one day it may be!


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13.4 Account Getters

Function: GNCAccountType xaccAccountGetType (Account * account)
Return the type of account.

Function: const char * xaccAccountGetName (Account * account)
Return the name of account.

Function: const char * xaccAccountGetCode (Account * account)
Return the code of account.

Function: const char * xaccAccountGetDescription (Account * account)
Return the description of account.

Function: const char * xaccAccountGetNotes (Account * account)
Return the notes of account.

Function: gnc_commodity * xaccAccountGetCurrency (Account * account)
Return the currency of account.

Function: int xaccAccountGetCurrencySCU (Account * account)
Return the SCU (smallest convertible unit) of account's currency.

Function: gnc_commodity * xaccAccountGetSecurity (Account * account)
Return the security of account. For accounts without shares, this field will be NULL.

Function: int xaccAccountGetSecuritySCU (Account * account)
Return the SCU (smallest convertible unit) of account's security.

Function: gnc_commodity * xaccAccountGetEffectiveSecurity (Account * account)
Get the `effective' security of the account. If the account has a non-NULL security field, that field will be returned. Otherwise, the currency will be returned.

Function: AccountGroup * xaccAccountGetChildren (Account * account)
Return the child group of account. The child group may be NULL, indicating account has no children.

Function: AccountGroup * xaccAccountGetParent (Account * account)
Return the parent Group of account. The parent may be NULL, indicating account is a top-level Account. However, even if the parent is not NULL, the account may still be top-level if the parent Group has no parent Account.

Function: Account * xaccAccountGetParentAccount (Account * account)
Similar to xaccAccountGetParent, but returns the parent Account of the parent Group if the parent Group exists. Otherwise, returns NULL.

Function: gnc_numeric xaccAccountGetBalance (Account * account)
Return the balance of account, which is also the balance of the last Split in account. If there are no Splits, the balance is zero. The balance is denominated in the Account currency.

Function: gnc_numeric xaccAccountGetClearedBalance (Account * account)
Return the cleared balance of account. The cleared balance is the balance of all Splits in account which are either cleared or reconciled or frozen. The cleared balance is denominated in the Account currency.

Function: gnc_numeric xaccAccountGetReconciledBalance (Account * account)
Return the reconciled balance of account. The reconciled balance is the balance of all Splits in account which are reconciled or frozen. The reconciled balance is denominated in the Account currency.

Function: gnc_numeric xaccAccountGetShareBalance (Account *account)
Return the share balance of account, which is also the share balance of the last Split in account. If there are no Splits, the balance is zero. The balance is denominated in the Account security, if the Account security exits; otherwise the share balance is denominated in the Account currency.

Function: gnc_numeric xaccAccountGetShareClearedBalance (Account * account)
Return the cleared share balance of account. The cleared share balance is the share balance of all Splits in account which are either cleared or reconciled or frozen. The cleared share balance is denominated as the share balance.

Function: gnc_numeric xaccAccountGetShareReconciledBalance (Account * account)
Return the reconciled share balance of account. The reconciled share balance is the share balance of all Splits in account which are reconciled or frozen. The reconciled sharea balance is denominated as the share balance.

Function: gnc_numeric xaccAccountGetBalanceAsOfDate (Account * account, time_t date)
Return the balance of account including all Splits whose parent Transactions have posted dates on or before date.

Function: gnc_numeric xaccAccountGetShareBalanceAsOfDate (Account * account, time_t date)
Return the share balance of account including all Splits whose parent Transactions have posted dates on or before date.

Function: GList * xaccAccountGetSplitList (Account * account)
Return a GList of the Splits in account. This list must not be modified in any way.

Function: char * xaccAccountGetFullName (Account * account, const char separator)
Returns the fully qualified name of account using the given separator character. The name must be g_freed after use. The fully qualified name of an account is the concatenation of the names of the account and all its ancestor accounts starting with the topmost account and ending with the given account. Each name is separated by the given character.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.13.5 Account Tax API

This set of API calls is related to tax information. All accounts have a tax-related boolean flag that can be set or unset. There is an additional set of API calls related to United States taxes that have `US' in the function call names. Future API calls that are specific to other countries should include the appropriate 2-letter country code in the function names.

Function: gboolean xaccAccountGetTaxRelated (Account * account)
Return the tax-related flag of account.

Function: void xaccAccountSetTaxRelated (Account * account, gboolean tax_related)
Set the tax-related flag of account.

Function: const char * xaccAccountGetTaxUSCode (Account * account)
Get the US-specific tax code associated with account, or NULL if there is none. These codes are internal to GnuCash and currently defined in `src/scm/report/txf-export.scm'.

Function: void xaccAccountSetTaxUSCode (Account * account, const char * code)
Set the US-specific tax code associated with account.

Function: const char * xaccAccountGetTaxUSPayerNameSource (Account * account)
Get the payer name source associated with account. See `src/scm/repot/taxtxf.scm' for details.

Function: void xaccAccountSetTaxUSPayerNameSource (Account * account, const char * source)
Set the payer name source associated with account.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.14 Account Groups

Account Groups are used by the Engine to connect Accounts together into an Account hierarchy. Account Groups do not correspond to any accounting concept -- they are specific to the GnuCash engine. Account Groups contain the following pieces of information:

A list of Accounts
The list Accounts in the Group.

A not-saved flag
Indicates whether any information in the hierarchy rooted at the Group needs to be saved. That includes Accounts, Splits, and Transactions.

Account Groups do not have key-value frames or GUIDs.

2.14.1 General Account Group API  
2.14.2 Account Group Account API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.14.1 General Account Group API

Function: AccountGroup * xaccMallocAccountGroup (void)
Return a newly-allocated & initialized Account Group. The Group must be freed with xaccFreeAccountGroup.

Function: void xaccFreeAccountGroup (AccountGroup * account_group)
Free the given Group and all its resources, including the Accounts.

Function: void xaccAccountGroupCommitEdit (AccountGroup * grp)
Recursively call xaccAccountCommitEdit on all child accounts and their children.

Function: void xaccGroupConcatGroup (AccountGroup * to, AccountGroup * from)
Move all accounts in from to to. After this function returns, from will have been destroyed.

Function: void xaccGroupMergeAccounts (AccountGroup * grp)
Merge all accounts in grp that have the same name and description. The semantics of this function are rather complex. Consult the implementation before use!

Function: gboolean xaccGroupNotSaved (AccountGroup * grp)
Return true if grp has changes which have not been saved.

Function: void xaccGroupMarkSaved (AccountGroup * grp)
Mark grp and all its children as saved.

Function: void xaccGroupMarkNotSaved (AccountGroup * grp)
Mark grp as not saved.

Function: void xaccGroupMarkDoFree (AccountGroup * grp)
Mark all accounts in grp as slated for destruction. This will improve the efficiency of destroying a large account hierarchy.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.14.2 Account Group Account API

Function: void xaccGroupRemoveAccount (AccountGroup * grp, Account * account)
Remove account from grp. If account is not in grp, the function will return without performing any action. In no case will account be destroyed or modified.

Function: void xaccAccountRemoveGroup (Account * acc)
Remove acc's child group. The child group is not otherwise modified or destroyed.

Function: void xaccGroupInsertAccount (AccountGroup * grp, Account * acc)
Add acc to grp. If acc is in another Group, it will be removed first.

Function: void xaccAccountInsertSubAccount (Account * parent, Account * child)
Like xaccGroupInsertAccount, but uses a parent Account instead of a parent group. If parent does not have a child Group, one will be created.

Function: int xaccGroupGetNumSubAccounts (AccountGroup * grp)
Return the total number of Accounts in the hierarchy rooted at grp.

Function: int xaccGroupGetNumAccounts (AccountGroup * grp)
Return the number of accounts in grp. This count does not include Accounts lower in the hierarchy.

Function: int xaccGroupGetDepth (AccountGroup * grp)
Returns the length of the longest tree branch in the hierarchy rooted at grp. Each link between an Account and its (non-null) children counts as one unit of length.

Function: Account * xaccGroupGetAccount (AccountGroup * group, int index)
Return the indexth Account in group, starting at zero. If index is out of range, NULL is returned.

Function: GList * xaccGroupGetSubAccounts (AccountGroup * grp)
Return a list of the Accounts, including sub-Accounts, in grp. The returned list should be freed with g_list_free when no longer needed.

Function: GList * xaccGroupGetAccountList (AccountGroup * grp)
Return a list of the immediate children of grp. The returned list should not be freed or modified in any way.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.15 GNCBooks

The GNCBook interface encapsulates all the information about a GnuCash dataset, including the methods used to read and write the dataset to datastores. This class provides several important services:

The current implementation assumes the use of files and file locks; however, the API was designed to be general enough to allow the use of generic URL's, and/or implementation on top of SQL or other database/persistant object technology.

2.15.1 GNCBook API  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.15.1 GNCBook API

Function: GNCBook * gnc_book_new (void)
Allocate, initialize, and return a new GNCBook. The new book will contain a newly allocated AccountGroup.

Function: void gnc_book_destroy (GNCBook * book)
End any editing session associated with book, and free all memory associated with it.

Function: gboolean gnc_book_begin (GNCBook * book, const char * book_id, gboolean ignore_lock, gboolean create_if_nonexistent)
Begins a new book editing sesssion. It takes as an argument the book id. The book id must be a string in the form of a URI/URL. In the current implementation, only one type of URI is supported, and that is the file URI: anything of the form file:/home/somewhere/somedir/file.xac The path part must be a valid path. The file-part must be a valid GnuCash data file. Paths may be relative or absolute. If the path is relative; that is, if the argument is file:somefile.xac then a sequence of search paths are checked for a file of this name.

The 'ignore_lock' argument, if set to TRUE, will cause this routine to ignore any file locks that it finds. If set to FALSE, then file locks will be tested and obeyed.

If the file exists, can be opened and read, and a lock can be obtained then a lock will be obtained and the function returns TRUE.

If the file/database doesn't exist, and the create_if_nonexistent flag is set to TRUE, then the database is created.

Otherwise the function returns FALSE.

Function: gboolean gnc_book_load (GNCBook * book)
Load the data associated with the book. The function returns TRUE on success.

Function: GNCBackendError gnc_book_get_error (GNCBook * book)
Obtain the reason for a failure. Standard errno values are used. Calling this routine resets the error value. This routine allows an implementation of multiple error values, e.g. in a stack, where this routine pops the top value. The current implementation has a stack that is one-deep.

Some important error values:

EINVAL
bad argument

ETXTBSY
book id is in use; it's locked by someone else

ENOSYS
unsupported URI type

ERANGE
file path too long

ENOLCK
book not open when gnc_book_save() was called.

Function: const char * gnc_book_get_error_message (GNCBook * book)
Return a string describing the reason for the current error. Calling this routine resets the error value.

Function: GNCBackendError gnc_book_pop_error (GNCBook * book)
Same as gnc_book_get_error, but the error value is reset in book.

Function: AccountGroup * gnc_book_get_group (GNCBook * book)
Return the current top-level account group.

Function: void gnc_book_set_group (GNCBook * book, AccountGroup * topgroup)
Set the topgroup to a new value.

Function: const char * gnc_book_get_file_path (GNCBook * book)
Return the fully-qualified file path for the book. That is, if a relative or partial filename was for the book, then it had to have been fully resolved to open the book. This routine returns the result of this resolution.

Function: gboolean gnc_book_save_may_clobber_data (GNCBook * book)
Return TRUE if saving the book would overwrite other information.

Function: void gnc_book_save (GNCBook * book)
Commit all changes that have been made to the book.

Function: void gnc_book_end (GNCBook * book)
Release the session lock. It will not save the account group to a file. Thus, this method acts as an "abort" or "rollback" primitive.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.16 Scrub


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by Neil Williams on June, 1 2005 using texi2html