Skip to main content

DB

Struct DB 

Source
pub struct DB { /* private fields */ }
Expand description

In-memory representation of a decoded DB table.

Holds a complete DB table including header metadata and row data. The table data is stored as a TableInMemory which provides access to rows and columns.

§Fields

  • mysterious_byte - Boolean flag of unknown purpose (observed as 0 or 1)
  • guid - Globally Unique Identifier for this table instance
  • table - The actual table data with definition and rows

§Getters

Fields have public getters via the getset crate:

  • mysterious_byte() - Get the mysterious byte value
  • guid() - Get the table’s GUID
  • table() - Get reference to the table data

§The Mysterious Byte

The purpose of this byte is unknown, but it appears in all DB tables. Observed values are 0 or 1 (interpreted as boolean). In Warhammer 2, a value of 0 can cause crashes when tables are loaded by the game.

§GUID Handling

GUIDs are only present in some games (e.g., Warhammer series). Older games like Napoleon and Empire don’t use GUIDs, and adding them can crash those games. The encoding process respects the game’s GUID requirements.

§Example

use rpfm_lib::files::{Decodeable, db::DB, DecodeableExtraData, table::Table};
use rpfm_lib::schema::Schema;
use std::io::Cursor;

let mut extra = DecodeableExtraData::default();
extra.set_schema(Some(&schema));
extra.set_table_name(Some("units_tables"));

let mut reader = Cursor::new(table_data);
let db = DB::decode(&mut reader, &Some(extra)).unwrap();

// Access table data
let row_count = db.table().len();

Implementations§

Source§

impl DB

Source

pub fn mysterious_byte(&self) -> &bool

Boolean flag of unknown purpose (always 0 or 1).

In Warhammer 2, a value of 0 can crash the game when loading tables.

Source

pub fn guid(&self) -> &String

Globally Unique Identifier for this table instance.

Only present in newer games. Empty string for games without GUID support.

Source

pub fn table(&self) -> &TableInMemory

The table data including definition and rows.

Source§

impl DB

Source

pub fn new( definition: &Definition, definition_patch: Option<&DefinitionPatch>, table_name: &str, ) -> Self

Creates a new empty DB table with the specified definition.

Initializes a DB table with no rows but with the structure defined by the provided definition. The mysterious byte is set to true (safe default) and the GUID is empty.

§Arguments
  • definition - Schema definition specifying column types and structure
  • definition_patch - Optional patches to modify the definition
  • table_name - Name of the table (for internal tracking)
§Returns

A new empty DB table ready to have rows added.

§Example
use rpfm_lib::files::{db::DB, table::Table};
use rpfm_lib::schema::Definition;

let db = DB::new(&definition, None, "units_tables");
assert_eq!(db.table().len(), 0);
Source

pub fn read_header<R: ReadBytes>( data: &mut R, ) -> Result<(i32, bool, String, u32)>

Decodes the header section of a DB table.

Reads the header bytes to extract metadata without decoding the full table data. This is useful for inspecting table properties before committing to a full decode.

§Header Format

The header contains optional and required fields:

  1. Optional GUID Marker (0xFD 0xFE 0xFC 0xFF) + 2-byte sized UTF-16 string
  2. Optional Version Marker (0xFC 0xFD 0xFE 0xFF) + 4-byte signed integer
  3. Mysterious Byte (1 byte boolean)
  4. Entry Count (4-byte unsigned integer)
§Arguments
  • data - Reader positioned at the start of the DB table
§Returns

A tuple containing:

  • version - Table version number (0 if no version marker present)
  • mysterious_byte - Unknown boolean flag
  • guid - Table GUID (empty string if no GUID marker present)
  • entry_count - Number of rows in the table
§Errors

Returns RLibError::DecodingDBNotADBTable if:

  • The data is less than 5 bytes (minimum valid header size)
  • The data doesn’t conform to the DB header format
§Side Effects

After reading, the reader is positioned at the start of the table data section.

Source

pub fn definition(&self) -> &Definition

Returns the schema definition for this DB table.

Source

pub fn patches(&self) -> &DefinitionPatch

Returns the definition patches applied to this DB table.

Source

pub fn table_name(&self) -> &str

Returns the table name (e.g., "units_tables").

Source

pub fn table_name_without_tables(&self) -> String

Returns the table name without the "_tables" suffix.

§Panics

Panics if the table name doesn’t end with "_tables".

Source

pub fn data(&self) -> Cow<'_, [Vec<DecodedData>]>

Returns the table rows as a slice of decoded data.

Source

pub fn data_mut(&mut self) -> &mut Vec<Vec<DecodedData>>

Returns a mutable reference to the table rows.

Ensure modifications maintain valid structure matching the definition.

Source

pub fn set_data(&mut self, data: &[Vec<DecodedData>]) -> Result<()>

Replaces all table data with the provided rows.

§Errors

Returns an error if rows don’t match the table definition structure.

Source

pub fn new_row(&self) -> Vec<DecodedData>

Creates a new row with default values from the table definition.

Source

pub fn column_position_by_name(&self, column_name: &str) -> Option<usize>

Returns the column index for a given column name, or None if not found.

Source

pub fn len(&self) -> usize

Returns the number of rows in the table.

Source

pub fn is_empty(&self) -> bool

Returns true if the table has no rows.

Source

pub fn set_definition(&mut self, new_definition: &Definition)

Replaces the table definition and migrates existing data to match.

Use this to update tables to a newer schema version. Data is converted between compatible types where possible.

Source

pub fn update(&mut self, new_definition: &Definition)

Alias for set_definition.

Source

pub fn cascade_edition( pack: &mut Pack, schema: &Schema, table_name: &str, field: &Field, definition: &Definition, value_before: &str, value_after: &str, ) -> Vec<ContainerPath>

Performs a cascade update of a value across all referencing tables in a Pack.

When a key field value is changed, this function finds all tables that reference that field and updates them accordingly. It also updates corresponding Loc entries if the edited field affects localisation keys.

§Arguments
  • pack - The Pack to search and update.
  • schema - Schema containing table definitions and reference information.
  • table_name - Name of the source table (e.g., "units_tables").
  • field - The field being edited.
  • definition - Definition of the source table.
  • value_before - Original value being replaced.
  • value_after - New value to set.
§Returns

List of paths where references were found and updated.

Source

pub fn merge(sources: &[&Self]) -> Result<Self>

Merges multiple DB tables into a single new table.

Combines all rows from the source tables. The first table’s definition and patches are used for the merged result. All source tables are converted to match this definition before merging.

§Errors

Returns an error if:

  • Tables have different names (can’t merge units_tables with buildings_tables)
  • Fewer than 2 tables are provided
Source

pub fn tsv_import( records: StringRecordsIter<'_, File>, field_order: &HashMap<u32, String>, schema: &Schema, table_name: &str, table_version: i32, ) -> Result<Self>

Imports a DB table from TSV (tab-separated values) format.

§Arguments
  • records - CSV reader iterator over TSV records.
  • field_order - Mapping of column positions to field names.
  • schema - Schema containing the table definition.
  • table_name - Name of the table (e.g., "units_tables").
  • table_version - Version of the table definition to use.
§Errors

Returns an error if no matching definition is found in the schema.

Source

pub fn tsv_export( &self, writer: &mut Writer<File>, table_path: &str, keys_first: bool, ) -> Result<()>

Exports the DB table to TSV (tab-separated values) format.

§Arguments
  • writer - CSV writer for the output file.
  • table_path - Path used in the TSV metadata header.
  • keys_first - If true, key columns are written before non-key columns.
Source

pub fn altered(&self) -> bool

Returns true if data was modified during decoding (e.g., invalid values corrected).

Source

pub fn generate_twad_key_deletes_keys(&self, keys: &mut HashSet<String>)

Generates combined primary keys to populate the twad_key_deletes table.

Different tables use different key concatenation rules. This function handles the table-specific key format for each known table type.

Trait Implementations§

Source§

impl Clone for DB

Source§

fn clone(&self) -> DB

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DB

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Decodeable for DB

Source§

fn decode<R: ReadBytes>( data: &mut R, extra_data: &Option<DecodeableExtraData<'_>>, ) -> Result<Self>

Decodes binary data into the implementing type. Read more
Source§

impl<'de> Deserialize<'de> for DB

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Encodeable for DB

Source§

fn encode<W: WriteBytes>( &mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData<'_>>, ) -> Result<()>

Encodes the implementing type into binary data. Read more
Source§

impl From<TableInMemory> for DB

Implementation to create a DB from a Table.

Source§

fn from(table: TableInMemory) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for DB

Source§

fn eq(&self, other: &DB) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for DB

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for DB

Auto Trait Implementations§

§

impl Freeze for DB

§

impl RefUnwindSafe for DB

§

impl Send for DB

§

impl Sync for DB

§

impl Unpin for DB

§

impl UnsafeUnpin for DB

§

impl UnwindSafe for DB

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,