db.tables and conn:merge
...
what are db.tables
and conn:merge
. how are VDBs used.
A call to conn:merge{}
will either insert new rows in a database table or update existing rows. This depends on how the VDB was configured, see Key Fields and Examples.
...
In addition to executing SQL statements directly, Iguana offers another method for writing to databases using a Database Schema File (*.vdb), db.tables{}
and the conn:merge{}
function.
This method allows you to easily map data to multiple rows in a single Lua table and then perform a bulk insert or update without writing complex and long SQL statements. Data INSERTs and UPDATEs are simplified as it automatically handles the logic for determining whether to insert new rows or update existing ones, depending on the configuration of key columns in the VDB.
If key columns are defined, Iguana performs a SELECT
...
query to check if a row with matching key values exists. If a matching row
...
is found, an UPDATE operation is performed
...
; otherwise, an INSERT is performed.
...
separate page on bulk inserts?
Bulk insert is an optional
bulk_insert
boolean flag forconn:merge{}
that can be used with Microsoft SQL Server and MySQL. It ignores the key columns defined in the VMD files and always does an INSERT using the bulk insert syntax. If your table has a large number of rows, this can improve performance.Note: Bulk insert does inserts only, if you need to do updates you must handle these separately. You will get an error if you try to merge a duplicate record.
db:merge does not support spaces in column names
...
If no key columns are defined, new rows are always inserted. This is useful when you don’t want to overwrite existing data.
We see a great example of this in the introductory article: Understanding Databases in Iguana.
...
Expand | ||
---|---|---|
| ||
A VDB acts as an intermediary table mirroring your database table structure. It is used to define how data is structured and how it maps to actual database columns. SeeCreating a VDB for building this simple Patients table inside report.vdb. In this case, we have not defined any keys for the database table - seeKey Fields and Examples.
|
Expand | |||||
---|---|---|---|---|---|
| |||||
Now we can use the
|
Expand | |||||
---|---|---|---|---|---|
| |||||
A call to
With some databases, you can also perform a Bulk Insert on Merge. |
Expand | |||||
---|---|---|---|---|---|
| |||||
The merge process all happens within a single database transaction. If it fails, the transaction is rolled back and nothing is altered in the database. This behavior can be optionally turned off if you pass in Just like with
|