SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
Advanced O/R Mapping with Glorp
Alan Knight (knight@acm.org)
Cincom Systems of Canada
Metaphor/Motivating Example
Ruby on Rails/ActiveRecord
Reading Database Schema
» Some interesting mapping issues
Creating Mappings Dynamically
» Conventions/Grammar
APIs
» Querying
» Globals, Singletons, Transactions
Schema Evolution
Web Integration
Ruby on Rails
“Opinionated software”
Rails
Go really fast, but only in one direction
Reaction against J2EE/.NET
“Greenfield” projects
Ruby-Based
Smalltalk-like, scripting language
Some very Smalltalkish “tricks” in rails
ActiveRecord pattern for persistence
Architecture: Glorp and ActiveRecord
Metadata vs. convention-driven
Glorp: Explicit metadata
Tables
Classes
Descriptors/Mappings
ActiveRecord
Strict naming conventions
Aware of language forms
Hints at the class level
Code Generation (mostly for web)
Brokers
Glorp
Single broker (session)
» Responsible for object identity
» Manages automatic writes
Multiple clients use multiple sessions
Independent of other frameworks
ActiveRecord
Classes as brokers
» No object identity
» Single global session
Explicit writes
Tightly integrated with web framework
Domain Model
Glorp
No metadata in domain classes
Premium on flexibility, ability to optimize
Expect existing classes, schema
ActiveRecord
Premium on simplicity
Minimal metadata, but on domain classes
May not even be a domain model
» Use ActiveRecord directly
» Instance variables as properties
Goal
Can we provide some of the benefits,
but without losing our advantages
“Hyperactive Records”
Automatic persistence
Convention-driven
But be less restrictive
Use a bit more information (constraints)
Allow a graceful transition
Issue: Reading Schema
Before we can automate, we need to
read the database schema.
A nicely recursive problem
DatabaseTable
•name
•constraints
•fields DatabaseField
•name
•isPrimaryKey
•type
•nullable
ForeignKeyConstraint
•name
•sourceFields
•targetFields
INFORMATION_SCHEMA
Mapping DatabaseField
DatabaseField
•name
•isPrimaryKey
•type
•nullable
table := self tableNamed: 'columns'.
(aDescriptor newMapping: DirectMapping)
from: 'name'
to: (table fieldNamed: 'column_name').
COLUMNS
•TABLE_NAME
•COLUMN_NAME
•DATA_TYPE
•IS_NULLABLE
Mapping #isPrimaryKey
ST: a boolean value
DB: primary key constraints are entities
Columns used in a constraint are listed in
key_column_usage
For a field, do any primary key constraints
exist that make use of it
Mapping a two-level join to a boolean
Mapping #isPrimaryKey
(aDescriptor newMapping: DirectMapping)
from: #isPrimaryKey
to: [:each |
each primaryKeyConstraints notEmpty].
Direct mapping, but to an expression
“each” is the field we’re referring to
primaryKeyConstraints is another
relationship
notEmpty is a subselect operation
Subselects
In queries, several “collection” operations
that turn into different kinds of subselects
isEmpty/notEmpty
select:
anySatisfy:/noneSatisfy:
sqlCount (also aggregation)
read: Customer
where: [:each |
(each orders select: [:order |
order amount > 1000])
sqlCount > 5].
Reading Schema Summary
sourceFields and targetFields worse
Information_schema variations, limits
Works for Oracle, Postgresql, MySQL
No changes at all to the domain model
But easier because read-only
Several pseudoVariables
Good motivation for automatic
mapping
Back to ActiveRecord
Glorp metadata
defined in DescriptorSystem
Methods for tables, classes, mapping
E.g. #descriptorForCustomer:
Lists allTables, allClasses
ActiveRecord DescriptorSystem
All subclasses of ActiveRecord
Read allTables from the database
For each class name, find table name
Find link tables from constraints or hints
For each inst var/field name, figure out
the mapping
Naming convention
Database constraints
Aside: Inflector
Ruby on Rails class
Knows basic grammar forms (English)
Knows class/inst var/field/table naming
and capitalization
Person class -> PEOPLE table
OVERDUE_ORDER_ID -> overdueOrder
Big ball of regular expressions
Aside: Hints
Ruby on Rails uses class data to tell it
how to create relationships that are
ambiguous
hasMany, hasAndBelongsToMany
tableNames (added)
Aside: Class Generation
Generate a package
Class for each database table
Filtered
Empty descriptor system with root
class
Incremental Setup
We want to do as little work as
necessary
How to “tweak” an automatically
generated mapping
#mappingNamed:do:
self mappingNamed: #bankCode do:
[:mapping | mapping type: Integer].
Rails Migrations
Define tables in Ruby code
Multiple versions, ordered by naming
convention
First version full
Subsequent versions define how to
upgrade and downgrade
In the database, store a version
number for the schema
Run the instructions in sequence
Smalltalk Migrations
We have full metadata definition of
tables
Keep multiple classes
Subclasses?
Modify the schema to conform to the
newest
Prototype level
No upgrading instructions, can lose data
Jumps directly from one to the other
Web Integration
Equivalent to automatic web forms
MagritteGlorp (Ramon Leon)
Extend Magritte with additional
information about relationship types
Generate Glorp descriptors based on
Magritte metadata
Web Integration
GlorpActiveRecordMagritteSupport
Magritte metadata based on Glorp
Assume Magritte editor based on data
type
Glorp metadata based on database
References
GLORP
http://www.glorp.org
http://glorp.sourceforge.net
Ruby on Rails
http://www.rubyonrails.org/
Lots of other links
The End
Subselects
In SQL terms, a nested query
Many different uses
tend to make the brain hurt
Glorp provides various shortcuts for
specific Smalltalk semantics, plus a
general mechanism
sometimes also make the brain hurt
still settling on semantics, naming
Subselect Example
e.g.
… where: [:each | each members
anySatisfy: [:eachMember | eachMember
name like: 'Alan%']].
SELECT <project fields>
FROM PROJECT t1
WHERE EXISTS (
SELECT <whatever> FROM MEMBER s1t1 WHERE
s1t1.proj_id = t1.id)
Aggregating
Two forms of aggregating
At the query level
aQuery retrieve: [:each | each value sum]
Puts an aggregate into the fields of the SQL
SELECT ... SUM(t1.value)
Within a where clause
where: [:each | (each value sqlSum) > 10]
Creates a subselect of that aggregate
SELECT ... WHERE (SELECT
SUM(s1t1.value) FROM ... WHERE ...)
> 10
min, max, average, count, etc.
Still More Aggregating
Also within a where clause
expression count: [:x | x attribute]
or more generally
expression
count: [:x | x attribute]
where: [:x | x something = 5].
More awkward than
expression sqlCount
Not really more powerful
General Aggregations
General facility
read: GlorpCustomer
where: [:each | each
(each
aggregate: each accounts
as: #countStar
where: [:acct | acct price > 1000]])
= 1].
Really awkward
More general
Only requires the underlying function to
exist
Select:
count:where: suggests a more
Smalltalk-like form
where: [:each |
(each users select: [:eachUser |
eachUser name like: 'A%])
sqlCount > 3].
Or we could apply other operations
e.g. anySatisfy: to the filtered
collection.
Fully General Subselects
A subselect is represented by a query.
aCustomer accounts
anySatisfyExists: [:eachAccount |
eachAccount in:
(Query
read: GlorpBankAccount
where: [:acct |
acct balance < 100])]].
Very general, but awkward
Often putting queries into block temps,
setting retrieve: clauses, etc.
Correlated Subselects
Are the internal selects effectively constants,
or do they refer back to things in outer
queries
Slower in database, but more powerful
read: StorePackage where: [:each |
| q |
q := Query read: StorePackage
where: [:eachPkg |
eachPkg name = each name].
q retrieve: [:x | x primaryKey max].
each username = 'aknight' & (each primaryKey
= q)].
OK, No More Subselects
Yes, these are complicated
Sometimes you need them
The tests are a good resource for code
fragments to copy from
Or just experiment until you get SQL
(and results) you want

Más contenido relacionado

La actualidad más candente

Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
Mazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml ToolsMazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml ToolsCardinaleWay Mazda
 
Lesson 02 Introduction to XAML
Lesson 02 Introduction to XAMLLesson 02 Introduction to XAML
Lesson 02 Introduction to XAMLQuang Nguyễn Bá
 
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...confluent
 
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D..."Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...Vadym Kazulkin
 
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...Flink Forward
 
Predictable reactive state management - ngrx
Predictable reactive state management - ngrxPredictable reactive state management - ngrx
Predictable reactive state management - ngrxIlia Idakiev
 
It's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda ArchitectureIt's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda ArchitectureYaroslav Tkachenko
 
Apache Beam @ GCPUG.TW Flink.TW 20161006
Apache Beam @ GCPUG.TW Flink.TW 20161006Apache Beam @ GCPUG.TW Flink.TW 20161006
Apache Beam @ GCPUG.TW Flink.TW 20161006Randy Huang
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONSyed Moosa Kaleem
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operatorsVivek Kumar
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling WebStackAcademy
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 

La actualidad más candente (20)

Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Ruby loves DDD
Ruby loves DDDRuby loves DDD
Ruby loves DDD
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Mazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml ToolsMazda Use of Third Generation Xml Tools
Mazda Use of Third Generation Xml Tools
 
Lesson 02 Introduction to XAML
Lesson 02 Introduction to XAMLLesson 02 Introduction to XAML
Lesson 02 Introduction to XAML
 
Gourmet Service Object
Gourmet Service ObjectGourmet Service Object
Gourmet Service Object
 
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...
Kafka Summit NYC 2017 - Building Advanced Streaming Applications using the La...
 
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D..."Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...
"Production-ready Serverless Java Applications in 3 weeks" at AWS Community D...
 
Ajax
AjaxAjax
Ajax
 
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
Flink Forward Berlin 2017: Boris Lublinsky, Stavros Kontopoulos - Introducing...
 
Predictable reactive state management - ngrx
Predictable reactive state management - ngrxPredictable reactive state management - ngrx
Predictable reactive state management - ngrx
 
Ajax
AjaxAjax
Ajax
 
JS - Basics
JS - BasicsJS - Basics
JS - Basics
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
It's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda ArchitectureIt's Time To Stop Using Lambda Architecture
It's Time To Stop Using Lambda Architecture
 
Apache Beam @ GCPUG.TW Flink.TW 20161006
Apache Beam @ GCPUG.TW Flink.TW 20161006Apache Beam @ GCPUG.TW Flink.TW 20161006
Apache Beam @ GCPUG.TW Flink.TW 20161006
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 

Similar a Advanced O/R Mapping with Glorp

Object- Relational Persistence in Smalltalk
Object- Relational Persistence in SmalltalkObject- Relational Persistence in Smalltalk
Object- Relational Persistence in SmalltalkESUG
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolFrom Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolESUG
 
AWS Webcast - Build high-scale applications with Amazon DynamoDB
AWS Webcast - Build high-scale applications with Amazon DynamoDBAWS Webcast - Build high-scale applications with Amazon DynamoDB
AWS Webcast - Build high-scale applications with Amazon DynamoDBAmazon Web Services
 
Shaping serverless architecture with domain driven design patterns - py web-il
Shaping serverless architecture with domain driven design patterns - py web-ilShaping serverless architecture with domain driven design patterns - py web-il
Shaping serverless architecture with domain driven design patterns - py web-ilAsher Sterkin
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservicesMohammed Shaban
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSAlberto Paro
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsScala Italy
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
Advanced web application architecture Way2Web
Advanced web application architecture Way2WebAdvanced web application architecture Way2Web
Advanced web application architecture Way2WebMatthias Noback
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Spark Summit
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 

Similar a Advanced O/R Mapping with Glorp (20)

Object- Relational Persistence in Smalltalk
Object- Relational Persistence in SmalltalkObject- Relational Persistence in Smalltalk
Object- Relational Persistence in Smalltalk
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolFrom Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
 
AWS Webcast - Build high-scale applications with Amazon DynamoDB
AWS Webcast - Build high-scale applications with Amazon DynamoDBAWS Webcast - Build high-scale applications with Amazon DynamoDB
AWS Webcast - Build high-scale applications with Amazon DynamoDB
 
Shaping serverless architecture with domain driven design patterns - py web-il
Shaping serverless architecture with domain driven design patterns - py web-ilShaping serverless architecture with domain driven design patterns - py web-il
Shaping serverless architecture with domain driven design patterns - py web-il
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservices
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Lift Framework
Lift FrameworkLift Framework
Lift Framework
 
Advanced web application architecture Way2Web
Advanced web application architecture Way2WebAdvanced web application architecture Way2Web
Advanced web application architecture Way2Web
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
[2015/2016] Backbone JS
[2015/2016] Backbone JS[2015/2016] Backbone JS
[2015/2016] Backbone JS
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Grails
GrailsGrails
Grails
 
Grails
GrailsGrails
Grails
 

Más de ESUG

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingESUG
 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in PharoESUG
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapESUG
 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoESUG
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...ESUG
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsESUG
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6ESUG
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationESUG
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingESUG
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesESUG
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportESUG
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsESUG
 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector TuningESUG
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseESUG
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FutureESUG
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the DebuggerESUG
 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing ScoreESUG
 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptESUG
 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocESUG
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsESUG
 

Más de ESUG (20)

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in Pharo
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in Pharo
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector Tuning
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing Score
 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design Mooc
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
 

Último

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Último (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

Advanced O/R Mapping with Glorp

  • 1. Advanced O/R Mapping with Glorp Alan Knight (knight@acm.org) Cincom Systems of Canada
  • 2. Metaphor/Motivating Example Ruby on Rails/ActiveRecord Reading Database Schema » Some interesting mapping issues Creating Mappings Dynamically » Conventions/Grammar APIs » Querying » Globals, Singletons, Transactions Schema Evolution Web Integration
  • 3. Ruby on Rails “Opinionated software” Rails Go really fast, but only in one direction Reaction against J2EE/.NET “Greenfield” projects Ruby-Based Smalltalk-like, scripting language Some very Smalltalkish “tricks” in rails ActiveRecord pattern for persistence
  • 4. Architecture: Glorp and ActiveRecord Metadata vs. convention-driven Glorp: Explicit metadata Tables Classes Descriptors/Mappings ActiveRecord Strict naming conventions Aware of language forms Hints at the class level Code Generation (mostly for web)
  • 5. Brokers Glorp Single broker (session) » Responsible for object identity » Manages automatic writes Multiple clients use multiple sessions Independent of other frameworks ActiveRecord Classes as brokers » No object identity » Single global session Explicit writes Tightly integrated with web framework
  • 6. Domain Model Glorp No metadata in domain classes Premium on flexibility, ability to optimize Expect existing classes, schema ActiveRecord Premium on simplicity Minimal metadata, but on domain classes May not even be a domain model » Use ActiveRecord directly » Instance variables as properties
  • 7. Goal Can we provide some of the benefits, but without losing our advantages “Hyperactive Records” Automatic persistence Convention-driven But be less restrictive Use a bit more information (constraints) Allow a graceful transition
  • 8. Issue: Reading Schema Before we can automate, we need to read the database schema. A nicely recursive problem DatabaseTable •name •constraints •fields DatabaseField •name •isPrimaryKey •type •nullable ForeignKeyConstraint •name •sourceFields •targetFields
  • 10. Mapping DatabaseField DatabaseField •name •isPrimaryKey •type •nullable table := self tableNamed: 'columns'. (aDescriptor newMapping: DirectMapping) from: 'name' to: (table fieldNamed: 'column_name'). COLUMNS •TABLE_NAME •COLUMN_NAME •DATA_TYPE •IS_NULLABLE
  • 11. Mapping #isPrimaryKey ST: a boolean value DB: primary key constraints are entities Columns used in a constraint are listed in key_column_usage For a field, do any primary key constraints exist that make use of it Mapping a two-level join to a boolean
  • 12. Mapping #isPrimaryKey (aDescriptor newMapping: DirectMapping) from: #isPrimaryKey to: [:each | each primaryKeyConstraints notEmpty]. Direct mapping, but to an expression “each” is the field we’re referring to primaryKeyConstraints is another relationship notEmpty is a subselect operation
  • 13. Subselects In queries, several “collection” operations that turn into different kinds of subselects isEmpty/notEmpty select: anySatisfy:/noneSatisfy: sqlCount (also aggregation) read: Customer where: [:each | (each orders select: [:order | order amount > 1000]) sqlCount > 5].
  • 14. Reading Schema Summary sourceFields and targetFields worse Information_schema variations, limits Works for Oracle, Postgresql, MySQL No changes at all to the domain model But easier because read-only Several pseudoVariables Good motivation for automatic mapping
  • 15. Back to ActiveRecord Glorp metadata defined in DescriptorSystem Methods for tables, classes, mapping E.g. #descriptorForCustomer: Lists allTables, allClasses
  • 16. ActiveRecord DescriptorSystem All subclasses of ActiveRecord Read allTables from the database For each class name, find table name Find link tables from constraints or hints For each inst var/field name, figure out the mapping Naming convention Database constraints
  • 17. Aside: Inflector Ruby on Rails class Knows basic grammar forms (English) Knows class/inst var/field/table naming and capitalization Person class -> PEOPLE table OVERDUE_ORDER_ID -> overdueOrder Big ball of regular expressions
  • 18. Aside: Hints Ruby on Rails uses class data to tell it how to create relationships that are ambiguous hasMany, hasAndBelongsToMany tableNames (added)
  • 19. Aside: Class Generation Generate a package Class for each database table Filtered Empty descriptor system with root class
  • 20. Incremental Setup We want to do as little work as necessary How to “tweak” an automatically generated mapping #mappingNamed:do: self mappingNamed: #bankCode do: [:mapping | mapping type: Integer].
  • 21. Rails Migrations Define tables in Ruby code Multiple versions, ordered by naming convention First version full Subsequent versions define how to upgrade and downgrade In the database, store a version number for the schema Run the instructions in sequence
  • 22. Smalltalk Migrations We have full metadata definition of tables Keep multiple classes Subclasses? Modify the schema to conform to the newest Prototype level No upgrading instructions, can lose data Jumps directly from one to the other
  • 23. Web Integration Equivalent to automatic web forms MagritteGlorp (Ramon Leon) Extend Magritte with additional information about relationship types Generate Glorp descriptors based on Magritte metadata
  • 24. Web Integration GlorpActiveRecordMagritteSupport Magritte metadata based on Glorp Assume Magritte editor based on data type Glorp metadata based on database
  • 27. Subselects In SQL terms, a nested query Many different uses tend to make the brain hurt Glorp provides various shortcuts for specific Smalltalk semantics, plus a general mechanism sometimes also make the brain hurt still settling on semantics, naming
  • 28. Subselect Example e.g. … where: [:each | each members anySatisfy: [:eachMember | eachMember name like: 'Alan%']]. SELECT <project fields> FROM PROJECT t1 WHERE EXISTS ( SELECT <whatever> FROM MEMBER s1t1 WHERE s1t1.proj_id = t1.id)
  • 29. Aggregating Two forms of aggregating At the query level aQuery retrieve: [:each | each value sum] Puts an aggregate into the fields of the SQL SELECT ... SUM(t1.value) Within a where clause where: [:each | (each value sqlSum) > 10] Creates a subselect of that aggregate SELECT ... WHERE (SELECT SUM(s1t1.value) FROM ... WHERE ...) > 10 min, max, average, count, etc.
  • 30. Still More Aggregating Also within a where clause expression count: [:x | x attribute] or more generally expression count: [:x | x attribute] where: [:x | x something = 5]. More awkward than expression sqlCount Not really more powerful
  • 31. General Aggregations General facility read: GlorpCustomer where: [:each | each (each aggregate: each accounts as: #countStar where: [:acct | acct price > 1000]]) = 1]. Really awkward More general Only requires the underlying function to exist
  • 32. Select: count:where: suggests a more Smalltalk-like form where: [:each | (each users select: [:eachUser | eachUser name like: 'A%]) sqlCount > 3]. Or we could apply other operations e.g. anySatisfy: to the filtered collection.
  • 33. Fully General Subselects A subselect is represented by a query. aCustomer accounts anySatisfyExists: [:eachAccount | eachAccount in: (Query read: GlorpBankAccount where: [:acct | acct balance < 100])]]. Very general, but awkward Often putting queries into block temps, setting retrieve: clauses, etc.
  • 34. Correlated Subselects Are the internal selects effectively constants, or do they refer back to things in outer queries Slower in database, but more powerful read: StorePackage where: [:each | | q | q := Query read: StorePackage where: [:eachPkg | eachPkg name = each name]. q retrieve: [:x | x primaryKey max]. each username = 'aknight' & (each primaryKey = q)].
  • 35. OK, No More Subselects Yes, these are complicated Sometimes you need them The tests are a good resource for code fragments to copy from Or just experiment until you get SQL (and results) you want