Module | Sequel::DatasetMethods |
In: |
lib/sequel/adapters/shared/postgres.rb
|
NULL | = | LiteralString.new('NULL').freeze |
LOCK_MODES | = | ['ACCESS SHARE', 'ROW SHARE', 'ROW EXCLUSIVE', 'SHARE UPDATE EXCLUSIVE', 'SHARE', 'SHARE ROW EXCLUSIVE', 'EXCLUSIVE', 'ACCESS EXCLUSIVE'].each(&:freeze).freeze |
Return the results of an EXPLAIN ANALYZE query as a string
# File lib/sequel/adapters/shared/postgres.rb, line 1209 1209: def analyze 1210: explain(:analyze=>true) 1211: end
Handle converting the ruby xor operator (^) into the PostgreSQL xor operator (#), and use the ILIKE and NOT ILIKE operators.
# File lib/sequel/adapters/shared/postgres.rb, line 1216 1216: def complex_expression_sql_append(sql, op, args) 1217: case op 1218: when :^ 1219: j = ' # ' 1220: c = false 1221: args.each do |a| 1222: sql << j if c 1223: literal_append(sql, a) 1224: c ||= true 1225: end 1226: when :ILIKE, 'NOT ILIKE''NOT ILIKE' 1227: sql << '(' 1228: literal_append(sql, args[0]) 1229: sql << ' ' << op.to_s << ' ' 1230: literal_append(sql, args[1]) 1231: sql << " ESCAPE " 1232: literal_append(sql, "\\") 1233: sql << ')' 1234: else 1235: super 1236: end 1237: end
Disables automatic use of INSERT … RETURNING. You can still use returning manually to force the use of RETURNING when inserting.
This is designed for cases where INSERT RETURNING cannot be used, such as when you are using partitioning with trigger functions or conditional rules, or when you are using a PostgreSQL version less than 8.2, or a PostgreSQL derivative that does not support returning.
Note that when this method is used, insert will not return the primary key of the inserted row, you will have to get the primary key of the inserted row before inserting via nextval, or after inserting via currval or lastval (making sure to use the same database connection for currval or lastval).
# File lib/sequel/adapters/shared/postgres.rb, line 1253 1253: def disable_insert_returning 1254: clone(:disable_insert_returning=>true) 1255: end
Return the results of an EXPLAIN query as a string
# File lib/sequel/adapters/shared/postgres.rb, line 1258 1258: def explain(opts=OPTS) 1259: with_sql((opts[:analyze] ? 'EXPLAIN ANALYZE ' : 'EXPLAIN ') + select_sql).map('QUERY PLAN''QUERY PLAN').join("\r\n") 1260: end
Run a full text search on PostgreSQL. By default, searching for the inclusion of any of the terms in any of the cols.
Options:
:headline : | Append a expression to the selected columns aliased to headline that contains an extract of the matched text. |
:language : | The language to use for the search (default: ‘simple’) |
:plain : | Whether a plain search should be used (default: false). In this case, terms should be a single string, and it will do a search where cols contains all of the words in terms. This ignores search operators in terms. |
:phrase : | Similar to :plain, but also adding an ILIKE filter to ensure that returned rows also include the exact phrase used. |
:rank : | Set to true to order by the rank, so that closer matches are returned first. |
:to_tsquery : | Can be set to :plain or :phrase to specify the function to use to convert the terms to a ts_query. |
:tsquery : | Specifies the terms argument is already a valid SQL expression returning a tsquery, and can be used directly in the query. |
:tsvector : | Specifies the cols argument is already a valid SQL expression returning a tsvector, and can be used directly in the query. |
# File lib/sequel/adapters/shared/postgres.rb, line 1286 1286: def full_text_search(cols, terms, opts = OPTS) 1287: lang = Sequel.cast(opts[:language] || 'simple', :regconfig) 1288: 1289: unless opts[:tsvector] 1290: phrase_cols = full_text_string_join(cols) 1291: cols = Sequel.function(:to_tsvector, lang, phrase_cols) 1292: end 1293: 1294: unless opts[:tsquery] 1295: phrase_terms = terms.is_a?(Array) ? terms.join(' | ') : terms 1296: 1297: query_func = case to_tsquery = opts[:to_tsquery] 1298: when :phrase, :plain 1299: "#{to_tsquery}to_tsquery""#{to_tsquery}to_tsquery" 1300: else 1301: (opts[:phrase] || opts[:plain]) ? :plainto_tsquery : :to_tsquery 1302: end 1303: 1304: terms = Sequel.function(query_func, lang, phrase_terms) 1305: end 1306: 1307: ds = where(Sequel.lit(["", " @@ ", ""], cols, terms)) 1308: 1309: if opts[:phrase] 1310: raise Error, "can't use :phrase with either :tsvector or :tsquery arguments to full_text_search together" if opts[:tsvector] || opts[:tsquery] 1311: ds = ds.grep(phrase_cols, "%#{escape_like(phrase_terms)}%", :case_insensitive=>true) 1312: end 1313: 1314: if opts[:rank] 1315: ds = ds.reverse{ts_rank_cd(cols, terms)} 1316: end 1317: 1318: if opts[:headline] 1319: ds = ds.select_append{ts_headline(lang, phrase_cols, terms).as(:headline)} 1320: end 1321: 1322: ds 1323: end
Insert given values into the database.
# File lib/sequel/adapters/shared/postgres.rb, line 1326 1326: def insert(*values) 1327: if @opts[:returning] 1328: # Already know which columns to return, let the standard code handle it 1329: super 1330: elsif @opts[:sql] || @opts[:disable_insert_returning] 1331: # Raw SQL used or RETURNING disabled, just use the default behavior 1332: # and return nil since sequence is not known. 1333: super 1334: nil 1335: else 1336: # Force the use of RETURNING with the primary key value, 1337: # unless it has been disabled. 1338: returning(insert_pk).insert(*values){|r| return r.values.first} 1339: end 1340: end
Handle uniqueness violations when inserting, by updating the conflicting row, using ON CONFLICT. With no options, uses ON CONFLICT DO NOTHING. Options:
:conflict_where : | The index filter, when using a partial index to determine uniqueness. |
:constraint : | An explicit constraint name, has precendence over :target. |
:target : | The column name or expression to handle uniqueness violations on. |
:update : | A hash of columns and values to set. Uses ON CONFLICT DO UPDATE. |
:update_where : | A WHERE condition to use for the update. |
Examples:
DB[:table].insert_conflict.insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT DO NOTHING DB[:table].insert_conflict(constraint: :table_a_uidx).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT ON CONSTRAINT table_a_uidx DO NOTHING DB[:table].insert_conflict(target: :a).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO NOTHING DB[:table].insert_conflict(target: :a, conflict_where: {c: true}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) WHERE (c IS TRUE) DO NOTHING DB[:table].insert_conflict(target: :a, update: {b: Sequel[:excluded][:b]}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO UPDATE SET b = excluded.b DB[:table].insert_conflict(constraint: :table_a_uidx, update: {b: Sequel[:excluded][:b]}, update_where: {Sequel[:table][:status_id] => 1}).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT ON CONSTRAINT table_a_uidx # DO UPDATE SET b = excluded.b WHERE (table.status_id = 1)
# File lib/sequel/adapters/shared/postgres.rb, line 1377 1377: def insert_conflict(opts=OPTS) 1378: clone(:insert_conflict => opts) 1379: end
Ignore uniqueness/exclusion violations when inserting, using ON CONFLICT DO NOTHING. Exists mostly for compatibility to MySQL‘s insert_ignore. Example:
DB[:table].insert_ignore.insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT DO NOTHING
# File lib/sequel/adapters/shared/postgres.rb, line 1387 1387: def insert_ignore 1388: insert_conflict 1389: end
Insert a record returning the record inserted. Always returns nil without inserting a query if disable_insert_returning is used.
# File lib/sequel/adapters/shared/postgres.rb, line 1393 1393: def insert_select(*values) 1394: return unless supports_insert_select? 1395: server?(:default).with_sql_first(insert_select_sql(*values)) 1396: end
The SQL to use for an insert_select, adds a RETURNING clause to the insert unless the RETURNING clause is already present.
# File lib/sequel/adapters/shared/postgres.rb, line 1400 1400: def insert_select_sql(*values) 1401: ds = opts[:returning] ? self : returning 1402: ds.insert_sql(*values) 1403: end
Locks all tables in the dataset‘s FROM clause (but not in JOINs) with the specified mode (e.g. ‘EXCLUSIVE’). If a block is given, starts a new transaction, locks the table, and yields. If a block is not given, just locks the tables. Note that PostgreSQL will probably raise an error if you lock the table outside of an existing transaction. Returns nil.
# File lib/sequel/adapters/shared/postgres.rb, line 1410 1410: def lock(mode, opts=OPTS) 1411: if block_given? # perform locking inside a transaction and yield to block 1412: @db.transaction(opts){lock(mode, opts); yield} 1413: else 1414: sql = 'LOCK TABLE '.dup 1415: source_list_append(sql, @opts[:from]) 1416: mode = mode.to_s.upcase.strip 1417: unless LOCK_MODES.include?(mode) 1418: raise Error, "Unsupported lock mode: #{mode}" 1419: end 1420: sql << " IN #{mode} MODE" 1421: @db.execute(sql, opts) 1422: end 1423: nil 1424: end
# File lib/sequel/adapters/shared/postgres.rb, line 1426 1426: def supports_cte?(type=:select) 1427: if type == :select 1428: server_version >= 80400 1429: else 1430: server_version >= 90100 1431: end 1432: end
PostgreSQL supports using the WITH clause in subqueries if it supports using WITH at all (i.e. on PostgreSQL 8.4+).
# File lib/sequel/adapters/shared/postgres.rb, line 1436 1436: def supports_cte_in_subqueries? 1437: supports_cte? 1438: end
DISTINCT ON is a PostgreSQL extension
# File lib/sequel/adapters/shared/postgres.rb, line 1441 1441: def supports_distinct_on? 1442: true 1443: end
PostgreSQL 9.5+ supports GROUP CUBE
# File lib/sequel/adapters/shared/postgres.rb, line 1446 1446: def supports_group_cube? 1447: server_version >= 90500 1448: end
PostgreSQL 9.5+ supports GROUP ROLLUP
# File lib/sequel/adapters/shared/postgres.rb, line 1451 1451: def supports_group_rollup? 1452: server_version >= 90500 1453: end
PostgreSQL 9.5+ supports GROUPING SETS
# File lib/sequel/adapters/shared/postgres.rb, line 1456 1456: def supports_grouping_sets? 1457: server_version >= 90500 1458: end
PostgreSQL 9.5+ supports the ON CONFLICT clause to INSERT.
# File lib/sequel/adapters/shared/postgres.rb, line 1466 1466: def supports_insert_conflict? 1467: server_version >= 90500 1468: end
PostgreSQL 9.3+ supports lateral subqueries
# File lib/sequel/adapters/shared/postgres.rb, line 1471 1471: def supports_lateral_subqueries? 1472: server_version >= 90300 1473: end
PostgreSQL supports modifying joined datasets
# File lib/sequel/adapters/shared/postgres.rb, line 1476 1476: def supports_modifying_joins? 1477: true 1478: end
PostgreSQL supports pattern matching via regular expressions
# File lib/sequel/adapters/shared/postgres.rb, line 1486 1486: def supports_regexp? 1487: true 1488: end
Returning is always supported.
# File lib/sequel/adapters/shared/postgres.rb, line 1481 1481: def supports_returning?(type) 1482: true 1483: end
PostgreSQL 9.5+ supports SKIP LOCKED.
# File lib/sequel/adapters/shared/postgres.rb, line 1491 1491: def supports_skip_locked? 1492: server_version >= 90500 1493: end
PostgreSQL supports timezones in literal timestamps
# File lib/sequel/adapters/shared/postgres.rb, line 1496 1496: def supports_timestamp_timezones? 1497: true 1498: end
Truncates the dataset. Returns nil.
Options:
:cascade : | whether to use the CASCADE option, useful when truncating tables with foreign keys. |
:only : | truncate using ONLY, so child tables are unaffected |
:restart : | use RESTART IDENTITY to restart any related sequences |
:only and :restart only work correctly on PostgreSQL 8.4+.
Usage:
DB[:table].truncate # TRUNCATE TABLE "table" DB[:table].truncate(cascade: true, only: true, restart: true) # TRUNCATE TABLE ONLY "table" RESTART IDENTITY CASCADE
# File lib/sequel/adapters/shared/postgres.rb, line 1521 1521: def truncate(opts = OPTS) 1522: if opts.empty? 1523: super() 1524: else 1525: clone(:truncate_opts=>opts).truncate 1526: end 1527: end
Return a clone of the dataset with an addition named window that can be referenced in window functions. See {SQL::Window} for a list of options that can be passed in.
# File lib/sequel/adapters/shared/postgres.rb, line 1532 1532: def window(name, opts) 1533: clone(:window=>(@opts[:window]||[]) + [[name, SQL::Window.new(opts)]]) 1534: end
If returned primary keys are requested, use RETURNING unless already set on the dataset. If RETURNING is already set, use existing returning values. If RETURNING is only set to return a single columns, return an array of just that column. Otherwise, return an array of hashes.
# File lib/sequel/adapters/shared/postgres.rb, line 1542 1542: def _import(columns, values, opts=OPTS) 1543: if @opts[:returning] 1544: statements = multi_insert_sql(columns, values) 1545: @db.transaction(Hash[opts].merge!(:server=>@opts[:server])) do 1546: statements.map{|st| returning_fetch_rows(st)} 1547: end.first.map{|v| v.length == 1 ? v.values.first : v} 1548: elsif opts[:return] == :primary_key 1549: returning(insert_pk)._import(columns, values, opts) 1550: else 1551: super 1552: end 1553: end