• Embed Doc
  • Readcast
  • Collections
  • CommentGo Back
Download
 
Sequel:
The Database Toolkit for Ruby
Jeremy Evans
History
Originally developed by Sharon RosnerMarch 2007: 0.0.1 - First releaseJanuary 2008: 1.0 - Split into sequel, sequel_core, and sequel_model gemsFebruary 2008: 1.2 - I started using SequelMarch 2008: 1.3 - Model associations; I became developer, then maintainer of SequelApril 2008: 1.4 - Eager loading; sequel and sequel_model gems mergedApril 2008: 1.5 - Dataset graphing; much deprecation
History (2)
May 2008: 2.0 - Expression filters; deprecated method removal; massive code cleanup anddocumentation updatesJuly 2008: 2.3 - Jruby/Ruby 1.9 support; sequel_core and sequel gems mergedAugust 2008: 2.4 - Bound variable/Prepared Statements; Master/Slave database and shardingSince: Many features and bug fixes
sequel_core vs sequel_model
NOT *-core vs. *-moresequel_core:Dataset-centric, returns plain hashesBasically a ruby DSL for SQLGood for aggregate reporting, dealing with sets of objectsAlso houses the adapters, core extensions, connection pool, migrations, and some utilitiessequel_model:Object-centric, returns model objectsAn ORM built on top of sequel-coreGood for dealing with individual objectsAlso houses the string inflection methodsModel classes proxy many methods to their underlying dataset, so you get the benefits of sequel-core when using sequel-model
Database Support
13 supported adapters: ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC,
 
OpenBase, Oracle, PostgreSQL and SQLite3Some adapters support multiple databases: DataObjects, JDBCSome databases are supported by multiple adapters: MySQL, PostgreSQL, SQLitePostgreSQL adapter can use pg, postgres, or postgres-pr driver
Adding adapters
Adding additional adapters is pretty easyNeed to define:Database#connect method that returns an adapter-specific connection objectDatabase#disconnect_connection method that disconnects adapter-specific connection objectDatabase#execute method that runs SQL against the databaseDatabase#dataset method that returns a dataset subclass instance for the databaseDataset#fetch_rows method that yields hashes with symbol keysPotentially, that's itAbout 1/3 of Sequel code is in the adapters
Adding adapters (2)
However, Dataset#delete and Dataset#update should return number of rows deleted/updatedAnd Dataset#insert should return the primary key value of the row inserted (if any)Generally this is done by Database#execute or a related methodIf Sequel already supports the underlying database, just include the shared adapter codeOtherwise, you need to deal with SQL syntax issuesRunning the integration tests is a good way to check support
Sequel::Database
uri = 'postgres://user:pass@host/database'DB = Sequel.connect(uri)DB = Sequel.postgres(database, :host =>host)DB = Sequel.sqlite # Memory database
Represents a virtual database connectionUses a (not-shared) connection pool internallyMainly used to:Modify the database schemaSet defaults for datasets (e.g. quoting)Create datasetsSetup SQL loggersHandle transactionsExecute SQL directly
Sequel::Database (2)
# Set defaults for future datasetsDB.quote_identifiers = true# Create Datasets
 
dataset = DB[:attendees]# Setup SQL LoggersDB.loggers << Logger.new($stdout)# Handle transactions: block required, no way# to leave a transaction open indefinitelyDB.transaction {# Execute SQL directlyrows = DB['SELECT * FROM ...'].allDB["INSERT ..."].insertDB["DELETE ..."].deleteDB << "SET ..." }
Connection Pooling
Sequel has thread-safe connection poolingNo need for manual cleanupOnly way to get a connection is through a blockBlock ensures the connection is returned to the pool before it exitsMakes it impossible to leak connectionsConnection not checked out until final SQL string is readyConnection returned as soon as iteration of results is finishedThis allows for much better concurrency
Sequel::Dataset
Represents an SQL query, or more generally, an abstract set of rows/objectsMost methods returned modified copies, functional styleDon't need to worry about the order of methods, usuallyBuild your SQL query by chaining methods
DB[:table].limit(5, 2).order(:column4).select(:column1, :column2).filter(:column3 =>0..100).all
Fetching Rows
#each iterates over the returned rowsEnumerable is includedRows are returned as hashes with symbol keysCan set an arbitrary proc to call with the hash before yielding (how models are implemented)#all returns all rows as an array of hashesNo caching is doneIf you don't want two identical queries for the same data, store the results of #all in a variable, anduse that variable later
Dataset inserting, updating, and deleting
#insert inserts records
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...
You must be to leave a comment.
Submit
Characters: ...