{"id":13400156,"url":"https://github.com/jeremyevans/sequel","last_synced_at":"2025-09-09T21:11:55.205Z","repository":{"id":388437,"uuid":"5954","full_name":"jeremyevans/sequel","owner":"jeremyevans","description":"Sequel: The Database Toolkit for Ruby","archived":false,"fork":false,"pushed_at":"2025-05-03T06:05:53.000Z","size":60084,"stargazers_count":5028,"open_issues_count":0,"forks_count":1075,"subscribers_count":112,"default_branch":"master","last_synced_at":"2025-05-05T10:08:02.574Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://sequel.jeremyevans.net","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jeremyevans.png","metadata":{"files":{"readme":"README.rdoc","changelog":"CHANGELOG","contributing":"CONTRIBUTING","funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2008-03-31T05:41:15.000Z","updated_at":"2025-05-03T20:16:49.000Z","dependencies_parsed_at":"2023-07-05T14:45:35.979Z","dependency_job_id":"a99db688-9d0d-4997-80fa-8341b107a14b","html_url":"https://github.com/jeremyevans/sequel","commit_stats":{"total_commits":8198,"total_committers":404,"mean_commits":"20.292079207920793","dds":0.202732373749695,"last_synced_commit":"6a7f9158adfc49d0099e7ef7b5a6a6bbb7c0ea4b"},"previous_names":[],"tags_count":222,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremyevans%2Fsequel","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremyevans%2Fsequel/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremyevans%2Fsequel/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremyevans%2Fsequel/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jeremyevans","download_url":"https://codeload.github.com/jeremyevans/sequel/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252531465,"owners_count":21763290,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T19:00:49.047Z","updated_at":"2025-05-05T16:06:15.643Z","avatar_url":"https://github.com/jeremyevans.png","language":"Ruby","readme":"== Sequel: The Database Toolkit for Ruby\n\nSequel is a simple, flexible, and powerful SQL database access\ntoolkit for Ruby.\n\n* Sequel provides thread safety, connection pooling and a concise\n  DSL for constructing SQL queries and table schemas.\n* Sequel includes a comprehensive ORM layer for mapping\n  records to Ruby objects and handling associated records.\n* Sequel supports advanced database features such as prepared\n  statements, bound variables, savepoints, two-phase commit,\n  transaction isolation, primary/replica configurations, and\n  database sharding.\n* Sequel currently has adapters for ADO, Amalgalite, \n  IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle,\n  PostgreSQL, SQLAnywhere, SQLite3, TinyTDS, and Trilogy.\n\n== Resources\n\nWebsite :: https://sequel.jeremyevans.net\nRDoc Documentation :: https://sequel.jeremyevans.net/rdoc\nSource Code :: https://github.com/jeremyevans/sequel\nBug tracking (GitHub Issues) :: https://github.com/jeremyevans/sequel/issues\nDiscussion Forum (GitHub Discussions) :: https://github.com/jeremyevans/sequel/discussions\nArchived Discussion Forum (sequel-talk Google Group) :: https://www.mail-archive.com/sequel-talk@googlegroups.com/\n\nIf you have questions about how to use Sequel, please ask on\nGitHub Discussions.\nOnly use the the bug tracker to report\nbugs in Sequel, not to ask for help on using Sequel.\n\nTo check out the source code:\n  \n  git clone git://github.com/jeremyevans/sequel.git\n  \n=== Contact\n\nIf you have any comments or suggestions please post to the Google group.\n\n== Installation\n\n  gem install sequel\n  \n== A Short Example\n\n  require 'sequel'\n  \n  DB = Sequel.sqlite # memory database, requires sqlite3\n  \n  DB.create_table :items do\n    primary_key :id\n    String :name\n    Float :price\n  end\n  \n  items = DB[:items] # Create a dataset\n  \n  # Populate the table\n  items.insert(name: 'abc', price: rand * 100)\n  items.insert(name: 'def', price: rand * 100)\n  items.insert(name: 'ghi', price: rand * 100)\n  \n  # Print out the number of records\n  puts \"Item count: #{items.count}\"\n  \n  # Print out the average price\n  puts \"The average price is: #{items.avg(:price)}\"\n\n== The Sequel Console\n\nSequel includes an IRB console for quick access to databases (usually referred to as \u003ctt\u003ebin/sequel\u003c/tt\u003e). You can use it like this:\n\n  sequel sqlite://test.db # test.db in current directory\n\nYou get an IRB session with the Sequel::Database object stored in DB.\n\nIn addition to providing an IRB shell (the default behavior), bin/sequel also has support for migrating databases, dumping schema migrations, and copying databases.  See the {bin/sequel guide}[rdoc-ref:doc/bin_sequel.rdoc] for more details.\n\n== An Introduction\n\nSequel is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.\n\nSequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.\n\nFor example, the following one-liner returns the average GDP for countries in the middle east region:\n\n  DB[:countries].where(region: 'Middle East').avg(:GDP)\n  \nWhich is equivalent to:\n\n  SELECT avg(GDP) FROM countries WHERE region = 'Middle East'\n\nSince datasets retrieve records only when needed, they can be stored and later reused. Records are fetched as hashes, and are accessed using an +Enumerable+ interface:\n\n  middle_east = DB[:countries].where(region: 'Middle East')\n  middle_east.order(:name).each{|r| puts r[:name]}\n  \nSequel also offers convenience methods for extracting data from Datasets, such as an extended +map+ method:\n\n  middle_east.map(:name) # =\u003e ['Egypt', 'Turkey', 'Israel', ...]\n  middle_east.map([:id, :name]) # =\u003e [[1, 'Egypt'], [3, 'Turkey'], [2, 'Israel'], ...]\n  \nOr getting results as a hash via +as_hash+, with one column as key and another as value:\n\n  middle_east.as_hash(:name, :area) # =\u003e {'Israel' =\u003e 20000, 'Turkey' =\u003e 120000, ...}\n\n== Getting Started\n\n=== Connecting to a database\n\nTo connect to a database you simply provide \u003ctt\u003eSequel.connect\u003c/tt\u003e with a URL:\n\n  require 'sequel'\n  DB = Sequel.connect('sqlite://blog.db') # requires sqlite3\n  \nThe connection URL can also include such stuff as the user name, password, and port:\n\n  DB = Sequel.connect('postgres://user:password@host:port/database_name') # requires pg\n\nYou can also specify optional parameters, such as the connection pool size, or loggers for logging SQL queries:\n\n  DB = Sequel.connect(\"postgres://user:password@host:port/database_name\",\n    max_connections: 10, logger: Logger.new('log/db.log'))\n\nIt is also possible to use a hash instead of a connection URL, but make sure to include the :adapter option in this case:\n\n  DB = Sequel.connect(adapter: :postgres, user: 'user', password: 'password', host: 'host', port: port,\n    database: 'database_name', max_connections: 10, logger: Logger.new('log/db.log'))\n\nYou can specify a block to connect, which will disconnect from the database after it completes:\n\n  Sequel.connect('postgres://user:password@host:port/database_name'){|db| db[:posts].delete}\n\n=== The DB convention\n\nThroughout Sequel's documentation, you will see the +DB+ constant used to refer to the Sequel::Database instance you create.\nThis reflects the recommendation that for an app with a single Sequel::Database instance, the Sequel convention is to store\nthe instance in the +DB+ constant.  This is just a convention, it's not required, but it is recommended.\n\nNote that some frameworks that use Sequel may create the Sequel::Database instance for you, and you might not know\nhow to access it.  In most cases, you can access the Sequel::Database instance through \u003ctt\u003eSequel::Model.db\u003c/tt\u003e.\n\n=== Arbitrary SQL queries\n\nYou can execute arbitrary SQL code using \u003ctt\u003eDatabase#run\u003c/tt\u003e:\n\n  DB.run(\"create table t (a text, b text)\")\n  DB.run(\"insert into t values ('a', 'b')\")\n\nYou can also create datasets based on raw SQL:\n\n  dataset = DB['select id from items']\n  dataset.count # will return the number of records in the result set\n  dataset.map(:id) # will return an array containing all values of the id column in the result set\n\nYou can also fetch records with raw SQL through the dataset:\n\n  DB['select * from items'].each do |row|\n    p row\n  end\n\nYou can use placeholders in your SQL string as well:\n\n  name = 'Jim'\n  DB['select * from items where name = ?', name].each do |row|\n    p row\n  end\n\n=== Getting Dataset Instances\n\nDatasets are the primary way records are retrieved and manipulated.  They are generally created via the \u003ctt\u003eDatabase#from\u003c/tt\u003e or \u003ctt\u003eDatabase#[]\u003c/tt\u003e methods:\n\n  posts = DB.from(:posts)\n  posts = DB[:posts] # same\n\nDatasets will only fetch records when you tell them to. They can be manipulated to filter records, change ordering, join tables, etc.  Datasets are always frozen, and they are safe to use by multiple threads concurrently.\n\n=== Retrieving Records\n\nYou can retrieve all records by using the +all+ method:\n\n  posts.all\n  # SELECT * FROM posts\n\nThe +all+ method returns an array of hashes, where each hash corresponds to a record.\n\nYou can also iterate through records one at a time using +each+:\n\n  posts.each{|row| p row}\n\nOr perform more advanced stuff:\n\n  names_and_dates = posts.map([:name, :date])\n  old_posts, recent_posts = posts.partition{|r| r[:date] \u003c Date.today - 7}\n  \nYou can also retrieve the first record in a dataset:\n\n  posts.order(:id).first\n  # SELECT * FROM posts ORDER BY id LIMIT 1\n  \nNote that you can get the first record in a dataset even if it isn't ordered:\n\n  posts.first\n  # SELECT * FROM posts LIMIT 1\n  \nIf the dataset is ordered, you can also ask for the last record:\n\n  posts.order(:stamp).last\n  # SELECT * FROM posts ORDER BY stamp DESC LIMIT 1\n  \nYou can also provide a filter when asking for a single record:\n\n  posts.first(id: 1)\n  # SELECT * FROM posts WHERE id = 1 LIMIT 1\n  \nOr retrieve a single value for a specific record:\n\n  posts.where(id: 1).get(:name)\n  # SELECT name FROM posts WHERE id = 1 LIMIT 1\n  \n=== Filtering Records\n\nThe most common way to filter records is to provide a hash of values to match to +where+:\n\n  my_posts = posts.where(category: 'ruby', author: 'david')\n  # WHERE ((category = 'ruby') AND (author = 'david'))\n  \nYou can also specify ranges:\n\n  my_posts = posts.where(stamp: (Date.today - 14)..(Date.today - 7))\n  # WHERE ((stamp \u003e= '2010-06-30') AND (stamp \u003c= '2010-07-07'))\n  \nOr arrays of values:\n\n  my_posts = posts.where(category: ['ruby', 'postgres', 'linux'])\n  # WHERE (category IN ('ruby', 'postgres', 'linux'))\n  \nBy passing a block to where, you can use expressions (this is fairly \"magical\"):\n  \n  my_posts = posts.where{stamp \u003e Date.today \u003c\u003c 1}\n  # WHERE (stamp \u003e '2010-06-14')\n  my_posts = posts.where{stamp =~ Date.today}\n  # WHERE (stamp = '2010-07-14')\n  \nIf you want to wrap the objects yourself, you can use expressions without the \"magic\":\n  \n  my_posts = posts.where(Sequel[:stamp] \u003e Date.today \u003c\u003c 1)\n  # WHERE (stamp \u003e '2010-06-14')\n  my_posts = posts.where(Sequel[:stamp] =~ Date.today)\n  # WHERE (stamp = '2010-07-14')\n  \nSome databases such as PostgreSQL and MySQL also support filtering via Regexps:\n\n  my_posts = posts.where(category: /ruby/i)\n  # WHERE (category ~* 'ruby')\n  \nYou can also use an inverse filter via +exclude+:\n\n  my_posts = posts.exclude(category: ['ruby', 'postgres', 'linux'])\n  # WHERE (category NOT IN ('ruby', 'postgres', 'linux'))\n\nBut note that this does a full inversion of the filter:\n\n  my_posts = posts.exclude(category: ['ruby', 'postgres', 'linux'], id: 1)\n  # WHERE ((category NOT IN ('ruby', 'postgres', 'linux')) OR (id != 1))\n\nIf at any point you want to use a custom SQL fragment for part of a query,\nyou can do so via +Sequel.lit+:\n\n  posts.where(Sequel.lit('stamp IS NOT NULL'))\n  # WHERE (stamp IS NOT NULL)\n\nYou can safely interpolate parameters into the custom SQL fragment by\nproviding them as additional arguments:\n\n  author_name = 'JKR'\n  posts.where(Sequel.lit('(stamp \u003c ?) AND (author != ?)', Date.today - 3, author_name))\n  # WHERE ((stamp \u003c '2010-07-11') AND (author != 'JKR'))\n\nDatasets can also be used as subqueries:\n\n  DB[:items].where(Sequel[:price] \u003e DB[:items].select{avg(price) + 100})\n  # WHERE (price \u003e (SELECT avg(price) + 100 FROM items))\n\nAfter filtering, you can retrieve the matching records by using any of the retrieval methods:\n\n  my_posts.each{|row| p row}\n  \nSee the {Dataset Filtering}[rdoc-ref:doc/dataset_filtering.rdoc] file for more details.\n\n=== Security\n\nDesigning apps with security in mind is a best practice.\nPlease read the {Security Guide}[rdoc-ref:doc/security.rdoc] for details on security\nissues that you should be aware of when using Sequel.\n\n=== Summarizing Records\n\nCounting records is easy using +count+:\n\n  posts.where(Sequel.like(:category, '%ruby%')).count\n  # SELECT COUNT(*) FROM posts WHERE (category LIKE '%ruby%' ESCAPE '\\')\n\nAnd you can also query maximum/minimum values via +max+ and +min+:\n\n  max = DB[:history].max(:value)\n  # SELECT max(value) FROM history\n  \n  min = DB[:history].min(:value)\n  # SELECT min(value) FROM history\n  \nOr calculate a sum or average via +sum+ and +avg+:\n\n  sum = DB[:items].sum(:price)\n  # SELECT sum(price) FROM items\n  avg = DB[:items].avg(:price)\n  # SELECT avg(price) FROM items\n  \n=== Ordering Records\n\nOrdering datasets is simple using +order+:\n\n  posts.order(:stamp)\n  # ORDER BY stamp\n  posts.order(:stamp, :name)\n  # ORDER BY stamp, name\n\n+order+ always overrides the existing order:\n\n  posts.order(:stamp).order(:name)\n  # ORDER BY name\n\nIf you would like to add to the existing order, use +order_append+ or +order_prepend+:\n\n  posts.order(:stamp).order_append(:name)\n  # ORDER BY stamp, name\n  posts.order(:stamp).order_prepend(:name)\n  # ORDER BY name, stamp\n  \nYou can also specify descending order:\n\n  posts.reverse_order(:stamp)\n  # ORDER BY stamp DESC\n  posts.order(Sequel.desc(:stamp))\n  # ORDER BY stamp DESC\n\n=== Core Extensions\n\nNote the use of \u003ctt\u003eSequel.desc(:stamp)\u003c/tt\u003e in the above example.  Much of Sequel's DSL uses this style, calling methods on the Sequel module that return SQL expression objects.  Sequel also ships with a {core_extensions extension}[rdoc-ref:doc/core_extensions.rdoc] that integrates Sequel's DSL better into the Ruby language, allowing you to write:\n\n  :stamp.desc\n\ninstead of:\n\n  Sequel.desc(:stamp)\n\n=== Selecting Columns\n\nSelecting specific columns to be returned is also simple using +select+:\n\n  posts.select(:stamp)\n  # SELECT stamp FROM posts\n  posts.select(:stamp, :name)\n  # SELECT stamp, name FROM posts\n\nLike +order+, +select+ overrides an existing selection:\n\n  posts.select(:stamp).select(:name)\n  # SELECT name FROM posts\n\nAs you might expect, there are +order_append+ and +order_prepend+ equivalents for +select+ called +select_append+ and +select_prepend+:\n\n  posts.select(:stamp).select_append(:name)\n  # SELECT stamp, name FROM posts\n  posts.select(:stamp).select_prepend(:name)\n  # SELECT name, stamp FROM posts\n  \n=== Deleting Records\n\nDeleting records from the table is done with +delete+:\n\n  posts.where(Sequel[:stamp] \u003c Date.today - 3).delete\n  # DELETE FROM posts WHERE (stamp \u003c '2010-07-11')\n  \nBe very careful when deleting, as +delete+ affects all rows in the dataset.\nCall +where+ first and +delete+ second:\n\n  # DO THIS:\n  posts.where(Sequel[:stamp] \u003c Date.today - 7).delete\n  # NOT THIS:\n  posts.delete.where(Sequel[:stamp] \u003c Date.today - 7)\n\n=== Inserting Records\n\nInserting records into the table is done with +insert+:\n\n  posts.insert(category: 'ruby', author: 'david')\n  # INSERT INTO posts (category, author) VALUES ('ruby', 'david')\n  \n=== Updating Records\n\nUpdating records in the table is done with +update+:\n\n  posts.where(Sequel[:stamp] \u003c Date.today - 7).update(state: 'archived')\n  # UPDATE posts SET state = 'archived' WHERE (stamp \u003c '2010-07-07')\n\nYou can provide arbitrary expressions when choosing what values to set:\n\n  posts.where(Sequel[:stamp] \u003c Date.today - 7).update(backup_number: Sequel[:backup_number] + 1)\n  # UPDATE posts SET backup_number = (backup_number + 1) WHERE (stamp \u003c '2010-07-07'))))\n\nAs with +delete+, +update+ affects all rows in the dataset, so +where+ first,\n+update+ second:\n\n  # DO THIS:\n  posts.where(Sequel[:stamp] \u003c Date.today - 7).update(state: 'archived')\n  # NOT THIS:\n  posts.update(state: 'archived').where(Sequel[:stamp] \u003c Date.today - 7)\n\n=== Merging records\n\nMerging records using the SQL MERGE statement is done using \u003ctt\u003emerge*\u003c/tt\u003e methods.\nYou use +merge_using+ to specify the merge source and join conditions.\nYou can use +merge_insert+, +merge_delete+, and/or +merge_update+ to set the\nINSERT, DELETE, and UPDATE clauses for the merge. +merge_insert+ takes the same\narguments as +insert+, and +merge_update+ takes the same arguments as +update+.\n+merge_insert+, +merge_delete+, and +merge_update+ can all be called with blocks,\nto set the conditions for the related INSERT, DELETE, or UPDATE.\n\nFinally, after calling all of the other \u003ctt\u003emerge_*\u003c/tt\u003e methods, you call +merge+\nto run the MERGE statement on the database.\n\n  ds = DB[:m1]\n    merge_using(:m2, i1: :i2).\n    merge_insert(i1: :i2, a: Sequel[:b]+11).\n    merge_delete{a \u003e 30}.\n    merge_update(i1: Sequel[:i1]+:i2+10, a: Sequel[:a]+:b+20)\n\n  ds.merge\n  # MERGE INTO m1 USING m2 ON (i1 = i2)\n  # WHEN NOT MATCHED THEN INSERT (i1, a) VALUES (i2, (b + 11))\n  # WHEN MATCHED AND (a \u003e 30) THEN DELETE\n  # WHEN MATCHED THEN UPDATE SET i1 = (i1 + i2 + 10), a = (a + b + 20)\n\n=== Transactions\n\nYou can wrap a block of code in a database transaction using the \u003ctt\u003eDatabase#transaction\u003c/tt\u003e method:\n\n  DB.transaction do\n    # BEGIN\n    posts.insert(category: 'ruby', author: 'david')\n    # INSERT\n    posts.where(Sequel[:stamp] \u003c Date.today - 7).update(state: 'archived')\n    # UPDATE \n  end\n  # COMMIT\n\nIf the block does not raise an exception, the transaction will be committed.\nIf the block does raise an exception, the transaction will be rolled back,\nand the exception will be reraised.  If you want to rollback the transaction\nand not raise an exception outside the block, you can raise the\n\u003ctt\u003eSequel::Rollback\u003c/tt\u003e exception inside the block:\n\n  DB.transaction do\n    # BEGIN\n    posts.insert(category: 'ruby', author: 'david')\n    # INSERT\n    if posts.where('stamp \u003c ?', Date.today - 7).update(state: 'archived') == 0\n    # UPDATE \n      raise Sequel::Rollback\n    end\n  end\n  # ROLLBACK\n\n=== Joining Tables\n\nSequel makes it easy to join tables:\n\n  order_items = DB[:items].join(:order_items, item_id: :id).where(order_id: 1234)\n  # SELECT * FROM items\n  # INNER JOIN order_items ON (order_items.item_id = items.id)\n  # WHERE (order_id = 1234)\n\nThe important thing to note here is that item_id is automatically qualified with\nthe table being joined, and id is automatically qualified with the last table\njoined.\n\nYou can then do anything you like with the dataset:\n\n  order_total = order_items.sum(:price)\n  # SELECT sum(price) FROM items\n  # INNER JOIN order_items ON (order_items.item_id = items.id)\n  # WHERE (order_id = 1234)\n  \nNote that the default selection in Sequel is \u003ctt\u003e*\u003c/tt\u003e, which includes all columns\nin all joined tables.  Because Sequel returns results as a hash keyed by column name\nsymbols, if any tables have columns with the same name, this will clobber the columns\nin the returned hash.  So when joining you are usually going to want to change the\nselection using +select+, +select_all+, and/or +select_append+.\n\n== Column references in Sequel\n\nSequel expects column names to be specified using symbols. In addition, returned hashes always use symbols as their keys. This allows you to freely mix literal values and column references in many cases. For example, the two following lines produce equivalent SQL:\n\n  items.where(x: 1)\n  # SELECT * FROM items WHERE (x = 1)\n  items.where(1 =\u003e :x)\n  # SELECT * FROM items WHERE (1 = x)\"\n\nRuby strings are generally treated as SQL strings:\n\n  items.where(x: 'x')\n  # SELECT * FROM items WHERE (x = 'x')\n\n=== Qualifying identifiers (column/table names)\n\nAn identifier in SQL is a name that represents a column, table, or schema.\nThe recommended way to qualify columns is to use \u003ctt\u003eSequel[][]\u003c/tt\u003e or +Sequel.qualify+\n\n  Sequel[:table][:column]\n  Sequel.qualify(:table, :column)\n  # table.column\n\nYou can also qualify tables with schemas:\n\n  Sequel[:schema][:table]\n  # schema.table\n\nor use multi-level qualification:\n\n  Sequel[:schema][:table][:column]\n  # schema.table.column\n\n=== Expression aliases\n\nYou can alias identifiers using  \u003ctt\u003eSequel[].as\u003c/tt\u003e or +Sequel.as+:\n\n  Sequel[:column].as(:alias)\n  Sequel.as(:column, :alias)\n  # column AS alias\n\nYou can use the \u003ctt\u003eSequel.as\u003c/tt\u003e method to alias arbitrary expressions, not just identifiers:\n\n  Sequel.as(DB[:posts].select{max(id)}, :p)\n  # (SELECT max(id) FROM posts) AS p\n\nAnd most Sequel expression objects support an +as+ method for aliasing:\n\n  (Sequel[:column] + 2).as(:c_plus_2)\n  # (column + 2) AS c_plus_2\n\n== Sequel Models\n\nA model class wraps a dataset, and an instance of that class wraps a single record in the dataset.\n\nModel classes are defined as regular Ruby classes inheriting from \u003ctt\u003eSequel::Model\u003c/tt\u003e:\n\n  DB = Sequel.connect('sqlite://blog.db')\n  class Post \u003c Sequel::Model\n  end\n\nWhen a model class is created, it parses the schema in the table from the database, and\nautomatically sets up accessor methods for all of the columns in the table (Sequel::Model\nimplements the active record pattern).\n\nSequel model classes assume that the table name is an underscored plural of the class name:\n\n  Post.table_name # =\u003e :posts\n\nYou can explicitly set the table name or even the dataset used:\n\n  class Post \u003c Sequel::Model(:my_posts); end\n  # or:\n  class Post \u003c Sequel::Model(DB[:my_posts]); end\n\nIf you pass a symbol to the \u003ctt\u003eSequel::Model\u003c/tt\u003e method, it assumes you are referring to the table with the same name.  You can also call it with a dataset, which will set the defaults for all retrievals for that model:\n\n  class Post \u003c Sequel::Model(DB[:my_posts].where(category: 'ruby')); end\n  class Post \u003c Sequel::Model(DB[:my_posts].select(:id, :name).order(:date)); end\n\n=== Model instances\n\nModel instances are identified by a primary key.  Sequel queries the database to determine the primary key for each model. The \u003ctt\u003eModel.[]\u003c/tt\u003e method can be used to fetch records by their primary key:\n\n  post = Post[123]\n\nThe +pk+ method is used to retrieve the record's primary key value:\n\n  post.pk # =\u003e 123\n\nIf you want to override which column(s) to use as the primary key, you can use +set_primary_key+:\n\n  class Post \u003c Sequel::Model\n    set_primary_key [:category, :title]\n  end\n\n  post = Post['ruby', 'hello world']\n  post.pk # =\u003e ['ruby', 'hello world']\n\nYou can also define a model class that does not have a primary key via +no_primary_key+, but then you lose the ability to easily update and delete records:\n\n  Post.no_primary_key\n\nA single model instance can also be fetched by specifying a condition:\n\n  post = Post.first(title: 'hello world')\n  post = Post.first{num_comments \u003c 10}\n\nThe dataset for a model class returns rows of model instances instead of plain hashes:\n\n  DB[:posts].first.class # =\u003e Hash\n  Post.first.class # =\u003e Post\n\n=== Acts like a dataset\n\nA model class forwards many methods to the underlying dataset. This means that you can use most of the +Dataset+ API to create customized queries that return model instances, e.g.:\n\n  Post.where(category: 'ruby').each{|post| p post}\n\nYou can also manipulate the records in the dataset:\n\n  Post.where{num_comments \u003c 7}.delete\n  Post.where(Sequel.like(:title, /ruby/)).update(category: 'ruby')\n\n=== Accessing record values\n\nA model instance stores its values as a hash with column symbol keys, which you can access directly via the +values+ method:\n\n  post.values # =\u003e {:id =\u003e 123, :category =\u003e 'ruby', :title =\u003e 'hello world'}\n\nYou can read the record values as object attributes, assuming the attribute names are valid columns in the model's dataset:\n\n  post.id # =\u003e 123\n  post.title # =\u003e 'hello world'\n  \nIf the record's attributes names are not valid columns in the model's dataset (maybe because you used +select_append+ to add a computed value column), you can use \u003ctt\u003eModel#[]\u003c/tt\u003e to access the values:\n\n  post[:id] # =\u003e 123\n  post[:title] # =\u003e 'hello world'\n\nYou can also modify record values using attribute setters or the \u003ctt\u003e[]=\u003c/tt\u003e method.\n\n  post.title = 'hey there'\n  post[:title] = 'hey there'\n\nThat will just change the value for the object, it will not update the row in the database.  To update the database row, call the +save+ method:\n\n  post.save\n\n=== Mass assignment\n\nYou can also set the values for multiple columns in a single method call, using one of the mass-assignment methods.  See the {mass assignment guide}[rdoc-ref:doc/mass_assignment.rdoc] for details.  For example +set+ updates the model's column values without saving:\n\n  post.set(title: 'hey there', updated_by: 'foo')\n\nand +update+ updates the model's column values and then saves the changes to the database:\n\n  post.update(title: 'hey there', updated_by: 'foo')\n\n=== Creating new records\n\nNew model instances can be created by calling \u003ctt\u003eModel.new\u003c/tt\u003e, which returns a new model instance without updating the database:\n\n  post = Post.new(title: 'hello world')\n\nYou can save the record to the database later by calling +save+ on the model instance:\n\n  post.save\n\nIf you want to create a new record and save it to the database at the same time, you can use \u003ctt\u003eModel.create\u003c/tt\u003e:\n\n  post = Post.create(title: 'hello world')\n\nYou can also supply a block to \u003ctt\u003eModel.new\u003c/tt\u003e and \u003ctt\u003eModel.create\u003c/tt\u003e:\n\n  post = Post.new do |p|\n    p.title = 'hello world'\n  end\n\n  post = Post.create{|p| p.title = 'hello world'}\n\n=== Hooks\n\nYou can execute custom code when creating, updating, or deleting records by defining hook methods. The +before_create+ and +after_create+ hook methods wrap record creation. The +before_update+ and +after_update+ hook methods wrap record updating. The +before_save+ and +after_save+ hook methods wrap record creation and updating. The +before_destroy+ and +after_destroy+ hook methods wrap destruction. The +before_validation+ and +after_validation+ hook methods wrap validation. Example:\n\n  class Post \u003c Sequel::Model\n    def after_create\n      super\n      author.increase_post_count\n    end\n\n    def after_destroy\n      super\n      author.decrease_post_count\n    end\n  end\n\nNote the use of +super+ if you define your own hook methods.  Almost all \u003ctt\u003eSequel::Model\u003c/tt\u003e class and instance methods (not just hook methods) can be overridden safely, but you have to make sure to call +super+ when doing so, otherwise you risk breaking things.\n\nFor the example above, you should probably use a database trigger if you can.  Hooks can be used for data integrity, but they will only enforce that integrity when you are modifying the database through model instances, and even then they are often subject to race conditions.  It's best to use database triggers and database constraints to enforce data integrity.\n\n=== Deleting records\n\nYou can delete individual records by calling +delete+ or +destroy+. The only difference between the two methods is that +destroy+ invokes +before_destroy+ and +after_destroy+ hook methods, while +delete+ does not:\n\n  post.delete # =\u003e bypasses hooks\n  post.destroy # =\u003e runs hooks\n\nRecords can also be deleted en-masse by calling \u003ctt\u003edelete\u003c/tt\u003e and \u003ctt\u003edestroy\u003c/tt\u003e on the model's dataset. As stated above, you can specify filters for the deleted records:\n\n  Post.where(category: 32).delete # =\u003e bypasses hooks\n  Post.where(category: 32).destroy # =\u003e runs hooks\n\nPlease note that if \u003ctt\u003edestroy\u003c/tt\u003e is called, each record is deleted \nseparately, but \u003ctt\u003edelete\u003c/tt\u003e deletes all matching records with a single \nSQL query.\n\n=== Associations\n\nAssociations are used in order to specify relationships between model classes that reflect relationships between tables in the database, which are usually specified using foreign keys.  You specify model associations via class methods:\n\n  class Post \u003c Sequel::Model\n    many_to_one :author\n    one_to_many :comments\n    one_to_one :first_comment, class: :Comment, order: :id\n    many_to_many :tags\n    one_through_one :first_tag, class: :Tag, order: :name, right_key: :tag_id\n  end\n\n+many_to_one+ and +one_to_one+ create a getter and setter for each model object:\n\n  post = Post.create(name: 'hi!')\n  post.author = Author.first(name: 'Sharon')\n  post.author\n\n+one_to_many+ and +many_to_many+ create a getter method, a method for adding an object to the association, a method for removing an object from the association, and a method for removing all associated objects from the association:\n\n  post = Post.create(name: 'hi!')\n  post.comments\n\n  comment = Comment.create(text: 'hi')\n  post.add_comment(comment)\n  post.remove_comment(comment)\n  post.remove_all_comments\n\n  tag = Tag.create(tag: 'interesting')\n  post.add_tag(tag)\n  post.remove_tag(tag)\n  post.remove_all_tags\n  \nNote that the remove_* and remove_all_* methods do not delete the object from the database, they merely disassociate the associated object from the receiver.\n\nAll associations add a dataset method that can be used to further filter or reorder the returned objects, or modify all of them:\n\n  # Delete all of this post's comments from the database\n  post.comments_dataset.destroy\n\n  # Return all tags related to this post with no subscribers, ordered by the tag's name\n  post.tags_dataset.where(subscribers: 0).order(:name).all\n\n=== Eager Loading\n\nAssociations can be eagerly loaded via +eager+ and the \u003ctt\u003e:eager\u003c/tt\u003e association option. Eager loading is used when loading a group of objects. It loads all associated objects for all of the current objects in one query, instead of using a separate query to get the associated objects for each current object. Eager loading requires that you retrieve all model objects at once via +all+ (instead of individually by +each+). Eager loading can be cascaded, loading association's associated objects.\n\n  class Person \u003c Sequel::Model\n    one_to_many :posts, eager: [:tags]\n  end\n\n  class Post \u003c Sequel::Model\n    many_to_one :person\n    one_to_many :replies\n    many_to_many :tags\n  end\n\n  class Tag \u003c Sequel::Model\n    many_to_many :posts\n    many_to_many :replies\n  end\n\n  class Reply \u003c Sequel::Model\n    many_to_one :person\n    many_to_one :post\n    many_to_many :tags\n  end\n\n  # Eager loading via .eager\n  Post.eager(:person).all\n\n  # eager is a dataset method, so it works with filters/orders/limits/etc.\n  Post.where{topic \u003e 'M'}.order(:date).limit(5).eager(:person).all\n  \n  person = Person.first\n  # Eager loading via :eager (will eagerly load the tags for this person's posts)\n  person.posts\n  \n  # These are equivalent\n  Post.eager(:person, :tags).all\n  Post.eager(:person).eager(:tags).all\n  \n  # Cascading via .eager\n  Tag.eager(posts: :replies).all\n  \n  # Will also grab all associated posts' tags (because of :eager)\n  Reply.eager(person: :posts).all\n  \n  # No depth limit (other than memory/stack), and will also grab posts' tags\n  # Loads all people, their posts, their posts' tags, replies to those posts,\n  # the person for each reply, the tag for each reply, and all posts and\n  # replies that have that tag.  Uses a total of 8 queries.\n  Person.eager(posts: {replies: [:person, {tags: [:posts, :replies]}]}).all\n\nIn addition to using +eager+, you can also use +eager_graph+, which will use a single query to get the object and all associated objects.  This may be necessary if you want to filter or order the result set based on columns in associated tables.  It works with cascading as well, the API is similar.  Note that using +eager_graph+ to eagerly load multiple \u003ctt\u003e*_to_many\u003c/tt\u003e associations will cause the result set to be a cartesian product, so you should be very careful with your filters when using it in that case.\n\nYou can dynamically customize the eagerly loaded dataset by using a proc.  This proc is passed the dataset used for eager loading, and should return a modified copy of that dataset:\n\n  # Eagerly load only replies containing 'foo'\n  Post.eager(replies: proc{|ds| ds.where(Sequel.like(text, '%foo%'))}).all\n\nThis also works when using +eager_graph+, in which case the proc is called with dataset to graph into the current dataset:\n\n  Post.eager_graph(replies: proc{|ds| ds.where(Sequel.like(text, '%foo%'))}).all\n\nYou can dynamically customize eager loads for both +eager+ and +eager_graph+ while also cascading, by making the value a single entry hash with the proc as a key, and the cascaded associations as the value:\n\n  # Eagerly load only replies containing 'foo', and the person and tags for those replies\n  Post.eager(replies: {proc{|ds| ds.where(Sequel.like(text, '%foo%'))} =\u003e [:person, :tags]}).all\n\n=== Joining with Associations\n\nYou can use the +association_join+ method to add a join to the model's dataset based on the association:\n\n  Post.association_join(:author)\n  # SELECT * FROM posts\n  # INNER JOIN authors AS author ON (author.id = posts.author_id)\n\nThis comes with variants for different join types:\n\n  Post.association_left_join(:replies)\n  # SELECT * FROM posts\n  # LEFT JOIN replies ON (replies.post_id = posts.id)\n\nSimilar to the eager loading methods, you can use multiple associations and nested associations:\n\n  Post.association_join(:author, replies: :person).all\n  # SELECT * FROM posts\n  # INNER JOIN authors AS author ON (author.id = posts.author_id)\n  # INNER JOIN replies ON (replies.post_id = posts.id)\n  # INNER JOIN people AS person ON (person.id = replies.person_id)\n\n=== Extending the underlying dataset\n\nThe recommended way to implement table-wide logic by defining methods on the dataset using +dataset_module+:\n\n  class Post \u003c Sequel::Model\n    dataset_module do\n      def with_few_comments\n        where{num_comments \u003c 30}\n      end\n\n      def clean_boring\n        with_few_comments.delete\n      end\n    end\n  end\n\nThis allows you to have access to your model API from filtered datasets as well:\n\n  Post.where(category: 'ruby').clean_boring\n  # DELETE FROM posts WHERE ((category = 'ruby') AND (num_comments \u003c 30))\n\nInside +dataset_module+ blocks, there are numerous methods that support easy creation of dataset methods.\nMost of these methods are named after the dataset methods themselves, such as +select+, +order+, and\n+group+:\n\n  class Post \u003c Sequel::Model\n    dataset_module do\n      where(:with_few_comments, Sequel[:num_comments] \u003c 30)\n      select :with_title_and_date, :id, :title, :post_date\n      order :by_post_date, :post_date\n      limit :top10, 10\n    end\n  end\n\n  Post.with_few_comments.with_title_and_date.by_post_date.top10\n  # SELECT id, title, post_date\n  # FROM posts\n  # ORDER BY post_date\n  # LIMIT 10\n\nOne advantage of using these methods inside dataset_module blocks, instead of\ndefining methods manually, is that the created methods will generally cache\nthe resulting values and result in better performance.\n\n=== Model Validations\n\nYou can define a +validate+ method for your model, which +save+\nwill check before attempting to save the model in the database.\nIf an attribute of the model isn't valid, you should add an error\nmessage for that attribute to the model object's +errors+. If an\nobject has any errors added by the validate method, +save+ will\nraise an error by default:\n\n  class Post \u003c Sequel::Model\n    def validate\n      super\n      errors.add(:name, \"can't be empty\") if name.empty?\n      errors.add(:written_on, \"should be in the past\") if written_on \u003e= Time.now\n    end\n  end\n\n== Testing Sequel\n\nPlease see the {testing guide}[rdoc-ref:doc/testing.rdoc] for recommendations on testing\napplications that use Sequel, as well as the how to run the tests for Sequel itself.\n\n== Sequel Release Policy\n\nNew major versions of Sequel do not have a defined release policy, but historically have\noccurred once every few years.\n\nNew minor versions of Sequel are released around once a month near the start of the month.\n\nNew tiny versions of Sequel are only released to address security issues or regressions\nin the most current release.\n\n== Ruby Support Policy\n\nSequel fully supports the currently supported versions of Ruby (MRI) and JRuby.  It may\nsupport unsupported versions of Ruby or JRuby, but such support may be dropped in any\nminor version if keeping it becomes a support issue.  The minimum Ruby version\nrequired to run the current version of Sequel is 1.9.2, and the minimum JRuby version is\n9.2.0.0 (due to the bigdecimal dependency).\n\n== Maintainer\n\nJeremy Evans \u003ccode@jeremyevans.net\u003e\n","funding_links":[],"categories":["Ruby","Data Persistence","ORM/ODM","ORM / REST","ORM"],"sub_categories":["Object-relational mapping","Libraries"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremyevans%2Fsequel","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjeremyevans%2Fsequel","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremyevans%2Fsequel/lists"}