Database Manual · Chapter 3

Table Schema — order_history

The sample handles every demonstration with a single table, order_history. The domain is "cooking / order processing history" — each row records one drink order with its start time, end time, weight (g) and result (Done · NG · Pending).

The XDatabase\LocalDB.db included in the sample already contains this table. Its structure was made with the built-in Order History template on the Structure tab of Database Studio (the same file also holds the measure_record table of the Measure Record template). If you need the same table in a new DB, create it as described below.

Sample Table Structure

Expressed as DDL, the order_history table of the sample DB is as follows. Running it directly on the SQL tab creates the same table.

sql
CREATE TABLE IF NOT EXISTS order_history (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  order_no    TEXT    NOT NULL,
  menu_name   TEXT,
  start_time  TEXT    DEFAULT CURRENT_TIMESTAMP,
  end_time    TEXT,
  weight_g    REAL    DEFAULT 0,
  result      TEXT,
  is_error    INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_order_no    ON order_history (order_no);
CREATE INDEX IF NOT EXISTS idx_order_start ON order_history (start_time);

Column Meanings

ColumnTypeMeaning
idINTEGER PKAuto-increment identifier. The WHERE key for UPDATE / DELETE
order_noTEXT NOT NULLOrder number (O1001, O1002, …). Incremented by the Data::OrderSeq counter
menu_nameTEXTMenu name. The Add button cycles through 7 — Americano · Latte · Cappuccino · Espresso · Mocha · Green Tea · Lemonade
start_timeTEXTOrder start time. The sample script stores SYS.DateTimeString (if no value is given, the default is CURRENT_TIMESTAMP)
end_timeTEXTOrder end time. Pressing Update stores SYS.DateTimeString at that moment
weight_gREALBrewed weight (g). Update sets a fixed demo value of 250
resultTEXT"Pending" → "Done" / "NG". The script supplies the value (no default)
is_errorINTEGER0 / 1. A separate column so that the result and the error flag are kept apart

Note SQLite uses dynamic typing, so specifying just INTEGER / TEXT / REAL is enough. When moving to MSSQL, choose column types suited to that database again.

Database Studio — Creating It on the Structure Tab

Database Studio — Structure tab
Database Studio — Structure tab
  1. Open Database → Database Studio in the Solution Explorer, choose local in Connection at the top and press [Open].
  2. On the Structure tab, choose [Built-in] Order History in Template. The column and index tables are filled and order_history goes into the Table box.
  3. Choose the Apply mode at the bottom and press [Apply]. If the table does not exist, it is created after confirmation.
Apply modeWhen the table already exists
Create if not existsDoes not create it and reports that it already exists
Drop and Recreate (DELETE data!)Drops and recreates it after confirmation — all existing data is deleted
Alter (add new columns only)Adds only the missing columns after confirmation. Existing columns and data are kept (default selection)

The other functions of the Structure tab are as follows.

  • Table · Load JSON... · Save JSON... · From Current Table — table name, read / save a structure JSON file, read the structure of the current table
  • Template — built-in templates (Log Table · Alarm Table · Recipe Master · Order History · Measure Record) and user templates (*.json) in the XDatabase\Schemas\Templates\ folder. [Refresh Templates] rescans the folder.
  • Grid View (edit) / JSON Preview (read only) — edit as a table / preview as JSON
  • Columns table — Name · Type (integer · real · text · blob · numeric) · PK · Auto · NotNull · Default. [+ Add] · [- Remove] · [Up] · [Down], and [+ Add common ▼] adds a common column (id · time · created_at · updated_at · is_deleted · description) in one step.
  • Indexes table — Name · Columns · Unique. [+ Add Index] · [- Remove]
  • [Drop Table] — deletes the table after confirmation.
  • In the Tables list on the left, a single click puts the name into the Table box, and a double click loads that table's structure at once.

The structure JSON has the format below. The built-in Order History template is exactly this content, and a JSON you create and place in XDatabase\Schemas\Templates\ appears as a user template.

json
{
  "name": "order_history",
  "columns": [
    { "name": "id",         "type": "integer", "primaryKey": true, "autoIncrement": true },
    { "name": "order_no",   "type": "text",    "notNull": true },
    { "name": "menu_name",  "type": "text" },
    { "name": "start_time", "type": "text",    "default": "CURRENT_TIMESTAMP" },
    { "name": "end_time",   "type": "text" },
    { "name": "weight_g",   "type": "real",    "default": 0 },
    { "name": "result",     "type": "text" },
    { "name": "is_error",   "type": "integer", "default": 0 }
  ],
  "indexes": [
    { "name": "idx_order_no",    "columns": ["order_no"] },
    { "name": "idx_order_start", "columns": ["start_time"] }
  ]
}

An Empty Table Is Filled With 5 Rows Automatically

Data::DB_Open() checks the row count right after connecting and, if it is 0, calls DB_InsertInitialSamples() to INSERT 5 learning rows in a single transaction.

xscript
// Excerpt from Data.xms
int rowCnt = DB["local"].RunSqlScalarInt("SELECT COUNT(*) FROM order_history");
if( rowCnt == 0 )
{
   Log($"order_history is empty, insert initial 5 samples");
   DB_InsertInitialSamples();
}

The data inserted by DB_InsertInitialSamples is as follows (start_time · end_time are the time of insertion).

order_nomenu_nameweight_gresultis_error
O1001Americano250Done0
O1002Latte300Done0
O1003Cappuccino280Done0
O1004Espresso30NG1
O1005Mocha320Done0

So once the table exists, a single Open prepares the demo data as well.

After Changing the Table

  • When you add or remove columns, update the SELECT column list of DB_Refresh (Chapter 6) and the DataGrid Columns definition (Chapter 7) together.
  • The Alter apply mode only adds missing columns, so use Drop and Recreate or SQL to remove columns or change types.
  • The WHERE id = ? pattern appears in several functions, so keeping the PK name id is the safest choice.

Next Chapter

With the schema ready, check and manipulate the data directly on the SQL · Data tabs of Database Studio.

Subscribe