Write a Groovy script that interacts with a SQL database using DataSet, treating tables…
- User
Write a Groovy script that interacts with a SQL database using
DataSet, treating tables as pseudo-objects for queries. Assistant
Write a Groovy script that interacts with a SQL database using DataSet, treating tables as pseudo-objects for queries.
The user wants a Groovy script that demonstrates how to interact with a SQL database using the groovy.sql.DataSet class.
The key feature of DataSet is that it treats database tables as if they were collections of Groovy objects, allowing for a more fluent, object-oriented syntax for queries (pseudo-objects).
Key Requirements:
groovy.sql.DataSet (which implies using groovy.sql.Sql as well).DataSet abstraction.row.name instead of row['name']), etc.Steps to Create the Script:
Dependencies:
@Grab annotation to download the dependency automatically.Setup:
groovy.sql.Sql.groovy.sql.DataSet.Initialization:
Sql instance.Employees with id, name, age, salary).insert is fine here, though DataSet can add rows too, standard SQL is often clearer for setup).Demonstrating DataSet:
DataSet from the Sql object pointing to the Employees table.findAll (or similar) method with a closure. Inside the closure, access properties using dot notation (e.g., it.age > 30).collect to transform results.Code Structure:
try-with-resources (or Groovy's equivalent with block) to handle the connection closing, although for a script, it might just run and exit. It's better to be safe/clean.Refining the Example:
DataSet.Drafting the Code (Mental or Scratchpad):
@Grab('com.h2database:h2:1.4.200')
import groovy.sql.*
// Connect
def sql = Sql.newInstance("jdbc:h2:mem:test", "sa", "", "org.h2.Driver")
// Setup
sql.execute '''
create table users (
id int primary key,
name varchar(255),
age int
)
'''
sql.execute "insert into users values (1, 'Alice', 30)"
sql.execute "insert into users values (2, 'Bob', 24)"
// The DataSet part
def users = sql.dataSet('users') // or sql.dataSet(UserClass)
// Querying like a collection
// Find users older than 25
def olderUsers = users.findAll { it.age > 25 }
// Print
olderUsers.each { println it.name }
Adding specific "Pseudo-object" nuances:
DataSet is actually a bit special. When you do ds.findAll { it.age > 25 }, Groovy actually generates SQL under the hood if possible, or fetches rows. Wait, checking documentation...DataSet extends GroovyObject. It behaves like a list.rows(), I get a list. If I iterate directly on the DataSet, it executes the query.DataSet creates a view where rows are objects.Detailed DataSet Capabilities to Show:
sql.dataSet("TableName")each { ... }findAll { ... } (This triggers a SQL query with a WHERE clause if the closure is "AST transformable", otherwise it filters in memory. For the sake of a clear example, simple closures are best).add(row) to insert using an object/map.Finalizing the Script Content:
People table.DataSet.add().findAll.it.name).Reviewing constraints: "interacts with a SQL database using DataSet".
DataSet object.Output formatting: Provide the code block and a brief explanation of what's happening.
(Self-Correction during drafting):
One thing about DataSet in older Groovy versions vs newer: The abstraction is handy but sometimes tricky with complex queries.
I will focus on the "Pseudo-object" aspect: accessing columns as properties (row.columnName) and using closures for logic.
Let's write the actual code.
@Grab(group='com.h2database', module='h2', version='2.1.214')
import groovy.sql.Sql
import groovy.sql.DataSet
// Setup H2 in-memory DB
def sql = Sql.newInstance("jdbc:h2:mem:testdb", "sa", "", "org.h2.Driver")
// 1. Initialize Schema
sql.execute """
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
role VARCHAR(50),
salary INT
)
"""
// 2. The DataSet way of inserting (treating rows as objects)
def employees = sql.dataSet('employees')
employees.add(id: 1, name: "Alice", role: "Dev", salary: 90000)
employees.add(id: 2, name: "Bob", role: "Manager", salary: 120000)
employees.add(id: 3, name: "Charlie", role: "Dev", salary: 95000)
// 3. Querying using DataSet (Pseudo-object behavior)
println "--- High Earners (Salary > 100k) ---"
// The closure passed to 'rows' or 'each' uses the 'where' clause logic if possible,
// but here we demonstrate the object-access style.
def highEarners = employees.findAll { it.salary > 100000 }
highEarners.each { row ->
println "Name: ${row.name}, Salary: ${row.salary}"
}
// 4. Complex Filtering
println "\n--- Developers ---"
// We can chain methods similar to Streams/Collections
employees.findAll { it.role == 'Dev' }
.sort { it.salary }
.each { println "${it.name} earns ${it.salary}" }
// Clean up
sql.close()
Refinement on DataSet behavior: DataSet implements GroovyObject and behaves like a list.
findAll on a DataSet returns a DataSet (a view).
Wait, standard findAll in Groovy returns a list.
Groovy Sql.DataSet behaves slightly differently. It creates a sub-dataset or executes the query depending on how you use it.
Actually, looking at the specific groovy.sql.DataSet API:
When you call each or rows, it executes.
If you use view(closure), it creates a sub-dataset.
The prompt asks to treat tables as pseudo-objects.
I will ensure the example shows:
This looks solid. I'll add comments explaining the "magic" (Groovy's GroovyResultSet which allows property access on result set columns).
Here is a complete, runnable Groovy script.
This script uses H2, an in-memory SQL database, so you do not need to install a database server to run it. It demonstrates how to use groovy.sql.DataSet to treat database tables as collection-like objects, allowing you to query rows using property notation (e.g., row.name) instead of standard String indices.
@Grab(group='com.h2database', module='h2', version='2.1.214')
import groovy.sql.Sql
import groovy.sql.DataSet
// 1. Connect to an in-memory H2 database
// 'testDB' is the name, DB_CLOSE_DELAY=-1 keeps it alive in memory
def sql = Sql.newInstance("jdbc:h2:mem:testDB;DB_CLOSE_DELAY=-1", "org.h2.Driver")
println "--- Setting up Schema ---"
// 2. Create a sample table
sql.execute '''
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
department VARCHAR(50),
salary INT
)
'''
// 3. Insert data using standard SQL
sql.execute "INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", ['Alice', 'Engineering', 90000]
sql.execute "INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", ['Bob', 'Marketing', 70000]
sql.execute "INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", ['Charlie', 'Engineering', 120000]
sql.execute "INSERT INTO employees (name, department, salary) VALUES (?, ?, ?)", ['Diana', 'HR', 60000]
println "--- Dataset Operations ---"
// 4. Create a DataSet
// This creates a 'pseudo-object' representing the table.
// We can now perform Groovy collection operations (each, find, etc.) on it.
DataSet employees = sql.dataSet('employees')
// EXAMPLE 1: Iterating (Implicit SQL Generation)
// Calling .each on a DataSet generates a "SELECT * FROM employees" query behind the scenes.
// Note how we access columns as properties: it.name, it.salary.
println "\nAll Employees:"
employees.each { row ->
println "ID: $row.id, Name: $row.name, Dept: $row.department"
}
// EXAMPLE 2: Filtering (Pseudo-Object Querying)
// We can use Groovy's 'findAll' closure.
// If the closure is simple, DataSet attempts to translate it into a WHERE clause.
// Otherwise, it streams rows and filters in memory.
println "\nEngineering Employees (Filtered):"
employees.findAll { it.department == 'Engineering' }.each { row ->
println "- $row.name earns \$$row.salary"
}
// EXAMPLE 3: Adding rows using the DataSet
// The DataSet acts as a proxy to the table.
println "\nAdding a new employee via DataSet..."
employees.add(
name: 'Eve',
department: 'Engineering',
salary: 95000
)
// Verify the addition
def eve = employees.find { it.name == 'Eve' }
println "Found new employee: ${eve?.name} in ${eve?.department}"
// EXAMPLE 4: Complex Query / Projection
// We can treat the rows as POGOs (Plain Old Groovy Objects) for calculations.
println "\nSalary Analysis:"
def highEarners = employees.findAll { it.salary > 80000 }
def totalSalary = highEarners.collect { it.salary }.sum()
println "High earners (>80k): ${highEarners.collect { it.name }.join(', ')}"
println "Total salary of high earners: \$$totalSalary"
// Clean up
sql.close()
sql.dataSet('table_name'): This wraps the table in a Groovy object. Unlike standard JDBC where you deal with Strings and ResultSets, the DataSet acts like a persistent Collection.row.name): Inside the closures (.each, .find), the row object is a GroovyResultSet. It intercepts property calls, allowing you to write row.salary instead of row.getInt("salary") or row['salary']..each, .find, .collect, and .sum directly on the database table representation..add(Map): The DataSet allows you to insert new records by passing a Map where keys match column names, generating the INSERT statement dynamically.