module Sequel::Postgres::DatasetMethods
Constants
- EXPLAIN_BOOLEAN_OPTIONS
- EXPLAIN_NONBOOLEAN_OPTIONS
- LOCK_MODES
- NULL
Public Instance Methods
Source
# File lib/sequel/adapters/shared/postgres.rb 2165 def analyze 2166 explain(:analyze=>true) 2167 end
Return the results of an EXPLAIN ANALYZE query as a string
Source
# File lib/sequel/adapters/shared/postgres.rb 2172 def complex_expression_sql_append(sql, op, args) 2173 case op 2174 when :^ 2175 j = ' # ' 2176 c = false 2177 args.each do |a| 2178 sql << j if c 2179 literal_append(sql, a) 2180 c ||= true 2181 end 2182 when :ILIKE, :'NOT ILIKE' 2183 sql << '(' 2184 literal_append(sql, args[0]) 2185 sql << ' ' << op.to_s << ' ' 2186 literal_append(sql, args[1]) 2187 sql << ')' 2188 else 2189 super 2190 end 2191 end
Handle converting the ruby xor operator (^) into the PostgreSQL xor operator (#), and use the ILIKE and NOT ILIKE operators.
Source
# File lib/sequel/adapters/shared/postgres.rb 2207 def disable_insert_returning 2208 clone(:disable_insert_returning=>true) 2209 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).
Source
# File lib/sequel/adapters/shared/postgres.rb 2212 def empty? 2213 return false if @opts[:values] 2214 super 2215 end
Always return false when using VALUES
Source
# File lib/sequel/adapters/shared/postgres.rb 2245 def explain(opts=OPTS) 2246 rows = clone(:append_sql=>explain_sql_string_origin(opts)).map(:'QUERY PLAN') 2247 2248 if rows.length == 1 2249 rows[0] 2250 elsif rows.all?{|row| String === row} 2251 rows.join("\r\n") 2252 # simplecov:disable 2253 else 2254 # This branch is unreachable in tests, but it seems better to just return 2255 # all rows than throw in error if this case actually happens. 2256 rows 2257 # simplecov:enable 2258 end 2259 end
Return the results of an EXPLAIN query. Boolean options:
- :analyze
-
Use the ANALYZE option.
- :buffers
-
Use the BUFFERS option.
- :costs
-
Use the COSTS option.
- :generic_plan
-
Use the GENERIC_PLAN option.
- :memory
-
Use the MEMORY option.
- :settings
-
Use the SETTINGS option.
- :summary
-
Use the SUMMARY option.
- :timing
-
Use the TIMING option.
- :verbose
-
Use the VERBOSE option.
- :wal
-
Use the WAL option.
Non boolean options:
- :format
-
Use the FORMAT option to change the format of the returned value. Values can be :text, :xml, :json, or :yaml.
- :serialize
-
Use the SERIALIZE option to get timing on serialization. Values can be :none, :text, or :binary.
See the PostgreSQL EXPLAIN documentation for an explanation of what each option does.
In most cases, the return value is a single string. However, using the format: :json option can result in the return value being an array containing a hash.
Source
# File lib/sequel/adapters/shared/postgres.rb 2270 def for_no_key_update 2271 cached_lock_style_dataset(:_for_no_key_update_ds, :no_key_update) 2272 end
Return a cloned dataset which will use FOR NO KEY UPDATE to lock returned rows. This is generally a better choice than using for_update on PostgreSQL, unless you will be deleting the row or modifying a key column. Supported on PostgreSQL 9.3+.
Source
# File lib/sequel/adapters/shared/postgres.rb 2298 def full_text_search(cols, terms, opts = OPTS) 2299 lang = Sequel.cast(opts[:language] || 'simple', :regconfig) 2300 2301 unless opts[:tsvector] 2302 phrase_cols = full_text_string_join(cols) 2303 cols = Sequel.function(:to_tsvector, lang, phrase_cols) 2304 end 2305 2306 unless opts[:tsquery] 2307 phrase_terms = terms.is_a?(Array) || terms.is_a?(Set) ? Sequel.array_or_set_join(terms, ' | ') : terms 2308 2309 query_func = case to_tsquery = opts[:to_tsquery] 2310 when :phrase, :plain 2311 :"#{to_tsquery}to_tsquery" 2312 when :websearch 2313 :"websearch_to_tsquery" 2314 else 2315 (opts[:phrase] || opts[:plain]) ? :plainto_tsquery : :to_tsquery 2316 end 2317 2318 terms = Sequel.function(query_func, lang, phrase_terms) 2319 end 2320 2321 ds = where(Sequel.lit(["", " @@ ", ""], cols, terms)) 2322 2323 if opts[:phrase] 2324 raise Error, "can't use :phrase with either :tsvector or :tsquery arguments to full_text_search together" if opts[:tsvector] || opts[:tsquery] 2325 ds = ds.grep(phrase_cols, "%#{escape_like(phrase_terms)}%", :case_insensitive=>true) 2326 end 2327 2328 if opts[:rank] 2329 ds = ds.reverse{ts_rank_cd(cols, terms)} 2330 end 2331 2332 if opts[:headline] 2333 ds = ds.select_append{ts_headline(lang, phrase_cols, terms).as(:headline)} 2334 end 2335 2336 ds 2337 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, :phrase, or :websearch to specify the function to use to convert the terms to a ts_query.
- :tsquery
-
Specifies the terms argument is already a valid
SQLexpression returning a tsquery, and can be used directly in the query. - :tsvector
-
Specifies the cols argument is already a valid
SQLexpression returning a tsvector, and can be used directly in the query.
Source
# File lib/sequel/adapters/shared/postgres.rb 2340 def insert(*values) 2341 if @opts[:returning] 2342 # Already know which columns to return, let the standard code handle it 2343 super 2344 elsif @opts[:sql] || @opts[:disable_insert_returning] 2345 # Raw SQL used or RETURNING disabled, just use the default behavior 2346 # and return nil since sequence is not known. 2347 super 2348 nil 2349 else 2350 # Force the use of RETURNING with the primary key value, 2351 # unless it has been disabled. 2352 returning(insert_pk).insert(*values){|r| return r.values.first} 2353 end 2354 end
Insert given values into the database.
Source
# File lib/sequel/adapters/shared/postgres.rb 2404 def insert_conflict(opts=OPTS) 2405 if opts[:select] && opts[:update] 2406 raise Error, "Cannot provide both :select and :update options to insert_conflict" 2407 end 2408 2409 clone(:insert_conflict => opts) 2410 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 precedence over :target.
- :target
-
The column name or expression to handle uniqueness violations on.
- :select
-
Use ON CONFLICT DO SELECT. This will use the dataset’s lock style. You must use returning on this dataset when using this option.
- :select_where
-
A WHERE condition to use for the select.
- :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) DB[:table].returning(:a).insert_conflict(target: :a, select: true).insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO SELECT RETURNING a DB[:table].returning(:a).for_update. insert_conflict(target: :a, select: true, select_where: {Sequel[:excluded][:b] => 3}). insert(a: 1, b: 2) # INSERT INTO TABLE (a, b) VALUES (1, 2) # ON CONFLICT (a) DO SELECT FOR UPDATE WHERE (excluded.b = 3) RETURNING a
Source
# File lib/sequel/adapters/shared/postgres.rb 2418 def insert_ignore 2419 insert_conflict 2420 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
Source
# File lib/sequel/adapters/shared/postgres.rb 2425 def insert_select(*values) 2426 return unless supports_insert_select? 2427 # Handle case where query does not return a row 2428 server?(:default).with_sql_first(insert_select_sql(*values)) || false 2429 end
Insert a record, returning the record inserted, using RETURNING. Always returns nil without running an INSERT statement if disable_insert_returning is used. If the query runs but returns no values, returns false.
Source
# File lib/sequel/adapters/shared/postgres.rb 2433 def insert_select_sql(*values) 2434 ds = opts[:returning] ? self : returning 2435 ds.insert_sql(*values) 2436 end
The SQL to use for an insert_select, adds a RETURNING clause to the insert unless the RETURNING clause is already present.
Source
# File lib/sequel/adapters/shared/postgres.rb 2440 def join_table(type, table, expr=nil, options=OPTS, &block) 2441 if expr.is_a?(SQL::AliasedExpression) && expr.expression.is_a?(Array) && !expr.expression.empty? && expr.expression.all? 2442 options = options.merge(:join_using=>true) 2443 end 2444 super 2445 end
Support SQL::AliasedExpression as expr to setup a USING join with a table alias for the USING columns.
Source
# File lib/sequel/adapters/shared/postgres.rb 2452 def lock(mode, opts=OPTS) 2453 if defined?(yield) # perform locking inside a transaction and yield to block 2454 @db.transaction(opts){lock(mode, opts); yield} 2455 else 2456 sql = 'LOCK TABLE '.dup 2457 source_list_append(sql, @opts[:from]) 2458 mode = mode.to_s.upcase.strip 2459 unless LOCK_MODES.include?(mode) 2460 raise Error, "Unsupported lock mode: #{mode}" 2461 end 2462 sql << " IN #{mode} MODE" 2463 @db.execute(sql, opts) 2464 end 2465 nil 2466 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.
Source
# File lib/sequel/adapters/shared/postgres.rb 2469 def merge(&block) 2470 sql = merge_sql 2471 if uses_returning?(:merge) 2472 returning_fetch_rows(sql, &block) 2473 else 2474 execute_ddl(sql) 2475 end 2476 end
Support MERGE RETURNING on PostgreSQL 17+.
Source
# File lib/sequel/adapters/shared/postgres.rb 2487 def merge_delete_when_not_matched_by_source(&block) 2488 _merge_when(:type=>:delete_not_matched_by_source, &block) 2489 end
Return a dataset with a WHEN NOT MATCHED BY SOURCE THEN DELETE clause added to the MERGE statement. If a block is passed, treat it as a virtual row and use it as additional conditions for the match.
merge_delete_not_matched_by_source # WHEN NOT MATCHED BY SOURCE THEN DELETE merge_delete_not_matched_by_source{a > 30} # WHEN NOT MATCHED BY SOURCE AND (a > 30) THEN DELETE
Source
# File lib/sequel/adapters/shared/postgres.rb 2500 def merge_do_nothing_when_matched(&block) 2501 _merge_when(:type=>:matched, &block) 2502 end
Return a dataset with a WHEN MATCHED THEN DO NOTHING clause added to the MERGE statement. If a block is passed, treat it as a virtual row and use it as additional conditions for the match.
merge_do_nothing_when_matched # WHEN MATCHED THEN DO NOTHING merge_do_nothing_when_matched{a > 30} # WHEN MATCHED AND (a > 30) THEN DO NOTHING
Source
# File lib/sequel/adapters/shared/postgres.rb 2513 def merge_do_nothing_when_not_matched(&block) 2514 _merge_when(:type=>:not_matched, &block) 2515 end
Return a dataset with a WHEN NOT MATCHED THEN DO NOTHING clause added to the MERGE statement. If a block is passed, treat it as a virtual row and use it as additional conditions for the match.
merge_do_nothing_when_not_matched # WHEN NOT MATCHED THEN DO NOTHING merge_do_nothing_when_not_matched{a > 30} # WHEN NOT MATCHED AND (a > 30) THEN DO NOTHING
Source
# File lib/sequel/adapters/shared/postgres.rb 2526 def merge_do_nothing_when_not_matched_by_source(&block) 2527 _merge_when(:type=>:not_matched_by_source, &block) 2528 end
Return a dataset with a WHEN NOT MATCHED BY SOURCE THEN DO NOTHING clause added to the MERGE BY SOURCE statement. If a block is passed, treat it as a virtual row and use it as additional conditions for the match.
merge_do_nothing_when_not_matched_by_source # WHEN NOT MATCHED BY SOURCE THEN DO NOTHING merge_do_nothing_when_not_matched_by_source{a > 30} # WHEN NOT MATCHED BY SOURCE AND (a > 30) THEN DO NOTHING
Source
# File lib/sequel/adapters/shared/postgres.rb 2531 def merge_insert(*values, &block) 2532 h = {:type=>:insert, :values=>values} 2533 if @opts[:override] 2534 h[:override] = insert_override_sql(String.new) 2535 end 2536 _merge_when(h, &block) 2537 end
Support OVERRIDING USER|SYSTEM VALUE for MERGE INSERT.
Source
# File lib/sequel/adapters/shared/postgres.rb 2548 def merge_update_when_not_matched_by_source(values, &block) 2549 _merge_when(:type=>:update_not_matched_by_source, :values=>values, &block) 2550 end
Return a dataset with a WHEN NOT MATCHED BY SOURCE THEN UPDATE clause added to the MERGE statement. If a block is passed, treat it as a virtual row and use it as additional conditions for the match.
merge_update_not_matched_by_source(i1: Sequel[:i1]+:i2+10, a: Sequel[:a]+:b+20) # WHEN NOT MATCHED BY SOURCE THEN UPDATE SET i1 = (i1 + i2 + 10), a = (a + b + 20) merge_update_not_matched_by_source(i1: :i2){a > 30} # WHEN NOT MATCHED BY SOURCE AND (a > 30) THEN UPDATE SET i1 = i2
Source
# File lib/sequel/adapters/shared/postgres.rb 2555 def overriding_system_value 2556 clone(:override=>:system) 2557 end
Use OVERRIDING USER VALUE for INSERT statements, so that identity columns always use the user supplied value, and an error is not raised for identity columns that are GENERATED ALWAYS.
Source
# File lib/sequel/adapters/shared/postgres.rb 2561 def overriding_user_value 2562 clone(:override=>:user) 2563 end
Use OVERRIDING USER VALUE for INSERT statements, so that identity columns always use the sequence value instead of the user supplied value.
Source
# File lib/sequel/adapters/shared/postgres.rb 2565 def supports_cte?(type=:select) 2566 if type == :select 2567 server_version >= 80400 2568 else 2569 server_version >= 90100 2570 end 2571 end
Source
# File lib/sequel/adapters/shared/postgres.rb 2575 def supports_cte_in_subqueries? 2576 supports_cte? 2577 end
PostgreSQL supports using the WITH clause in subqueries if it supports using WITH at all (i.e. on PostgreSQL 8.4+).
Source
# File lib/sequel/adapters/shared/postgres.rb 2580 def supports_distinct_on? 2581 true 2582 end
DISTINCT ON is a PostgreSQL extension
Source
# File lib/sequel/adapters/shared/postgres.rb 2585 def supports_group_cube? 2586 server_version >= 90500 2587 end
PostgreSQL 9.5+ supports GROUP CUBE
Source
# File lib/sequel/adapters/shared/postgres.rb 2590 def supports_group_rollup? 2591 server_version >= 90500 2592 end
PostgreSQL 9.5+ supports GROUP ROLLUP
Source
# File lib/sequel/adapters/shared/postgres.rb 2595 def supports_grouping_sets? 2596 server_version >= 90500 2597 end
PostgreSQL 9.5+ supports GROUPING SETS
Source
# File lib/sequel/adapters/shared/postgres.rb 2605 def supports_insert_conflict? 2606 server_version >= 90500 2607 end
PostgreSQL 9.5+ supports the ON CONFLICT clause to INSERT.
Source
# File lib/sequel/adapters/shared/postgres.rb 2600 def supports_insert_select? 2601 !@opts[:disable_insert_returning] 2602 end
True unless insert returning has been disabled for this dataset.
Source
# File lib/sequel/adapters/shared/postgres.rb 2610 def supports_lateral_subqueries? 2611 server_version >= 90300 2612 end
PostgreSQL 9.3+ supports lateral subqueries
Source
# File lib/sequel/adapters/shared/postgres.rb 2620 def supports_merge? 2621 server_version >= 150000 2622 end
PostgreSQL 15+ supports MERGE.
Source
# File lib/sequel/adapters/shared/postgres.rb 2615 def supports_modifying_joins? 2616 true 2617 end
PostgreSQL supports modifying joined datasets
Source
# File lib/sequel/adapters/shared/postgres.rb 2625 def supports_nowait? 2626 true 2627 end
PostgreSQL supports NOWAIT.
Source
# File lib/sequel/adapters/shared/postgres.rb 2640 def supports_regexp? 2641 true 2642 end
PostgreSQL supports pattern matching via regular expressions
Source
# File lib/sequel/adapters/shared/postgres.rb 2631 def supports_returning?(type) 2632 if type == :merge 2633 server_version >= 170000 2634 else 2635 true 2636 end 2637 end
MERGE RETURNING is supported on PostgreSQL 17+. Other RETURNING is supported on all supported PostgreSQL versions.
Source
# File lib/sequel/adapters/shared/postgres.rb 2645 def supports_skip_locked? 2646 server_version >= 90500 2647 end
PostgreSQL 9.5+ supports SKIP LOCKED.
Source
# File lib/sequel/adapters/shared/postgres.rb 2652 def supports_timestamp_timezones? 2653 # SEQUEL6: Remove 2654 true 2655 end
PostgreSQL supports timezones in literal timestamps
Source
# File lib/sequel/adapters/shared/postgres.rb 2659 def supports_window_clause? 2660 server_version >= 80400 2661 end
PostgreSQL 8.4+ supports WINDOW clause.
Source
# File lib/sequel/adapters/shared/postgres.rb 2670 def supports_window_function_frame_option?(option) 2671 case option 2672 when :rows, :range 2673 true 2674 when :offset 2675 server_version >= 90000 2676 when :groups, :exclude 2677 server_version >= 110000 2678 else 2679 false 2680 end 2681 end
Base support added in 8.4, offset supported added in 9.0, GROUPS and EXCLUDE support added in 11.0.
Source
# File lib/sequel/adapters/shared/postgres.rb 2664 def supports_window_functions? 2665 server_version >= 80400 2666 end
PostgreSQL 8.4+ supports window functions
Source
# File lib/sequel/adapters/shared/postgres.rb 2699 def truncate(opts = OPTS) 2700 if opts.empty? 2701 super() 2702 else 2703 clone(:truncate_opts=>opts).truncate 2704 end 2705 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
Source
# File lib/sequel/adapters/shared/postgres.rb 2710 def with_ties 2711 clone(:limit_with_ties=>true) 2712 end
Use WITH TIES when limiting the result set to also include additional rules that have the same results for the order column as the final row. Requires PostgreSQL 13.
Protected Instance Methods
Source
# File lib/sequel/adapters/shared/postgres.rb 2720 def _import(columns, values, opts=OPTS) 2721 if @opts[:returning] 2722 # no transaction: our multi_insert_sql_strategy should guarantee 2723 # that there's only ever a single statement. 2724 sql = multi_insert_sql(columns, values)[0] 2725 returning_fetch_rows(sql).map{|v| v.length == 1 ? v.values.first : v} 2726 elsif opts[:return] == :primary_key 2727 returning(insert_pk)._import(columns, values, opts) 2728 else 2729 super 2730 end 2731 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.
Source
# File lib/sequel/adapters/shared/postgres.rb 2733 def to_prepared_statement(type, *a) 2734 if type == :insert && !@opts.has_key?(:returning) 2735 returning(insert_pk).send(:to_prepared_statement, :insert_pk, *a) 2736 else 2737 super 2738 end 2739 end
Private Instance Methods
Source
# File lib/sequel/adapters/shared/postgres.rb 2754 def _merge_do_nothing_sql(sql, data) 2755 sql << " THEN DO NOTHING" 2756 end
Source
# File lib/sequel/adapters/shared/postgres.rb 2744 def _merge_insert_sql(sql, data) 2745 sql << " THEN INSERT" 2746 columns, values = _parse_insert_sql_args(data[:values]) 2747 _insert_columns_sql(sql, columns) 2748 if override = data[:override] 2749 sql << override 2750 end 2751 _insert_values_sql(sql, values) 2752 end
Append the INSERT sql used in a MERGE
Source
# File lib/sequel/adapters/shared/postgres.rb 2759 def _merge_when_sql(sql) 2760 super 2761 insert_returning_sql(sql) if uses_returning?(:merge) 2762 end
Support MERGE RETURNING on PostgreSQL 17+.
Source
# File lib/sequel/adapters/shared/postgres.rb 2765 def _truncate_sql(table) 2766 to = @opts[:truncate_opts] || OPTS 2767 "TRUNCATE TABLE#{' ONLY' if to[:only]} #{table}#{' RESTART IDENTITY' if to[:restart]}#{' CASCADE' if to[:cascade]}" 2768 end
Format TRUNCATE statement with PostgreSQL specific options.
Source
# File lib/sequel/adapters/shared/postgres.rb 2771 def aggregate_dataset_use_from_self? 2772 super || @opts[:values] 2773 end
Use from_self for aggregate dataset using VALUES.
Source
# File lib/sequel/adapters/shared/postgres.rb 2776 def check_truncation_allowed! 2777 raise(InvalidOperation, "Grouped datasets cannot be truncated") if opts[:group] 2778 raise(InvalidOperation, "Joined datasets cannot be truncated") if opts[:join] 2779 end
Allow truncation of multiple source tables.
Source
# File lib/sequel/adapters/shared/postgres.rb 3028 def compound_dataset_sql_append(sql, ds) 3029 sql << '(' 3030 super 3031 sql << ')' 3032 end
PostgreSQL requires parentheses around compound datasets if they use CTEs, and using them in other places doesn’t hurt.
Source
# File lib/sequel/adapters/shared/postgres.rb 2782 def default_timestamp_format 2783 "'%Y-%m-%d %H:%M:%S.%6N%z'" 2784 end
The strftime format to use when literalizing the time.
Source
# File lib/sequel/adapters/shared/postgres.rb 2787 def delete_from_sql(sql) 2788 sql << ' FROM ' 2789 source_list_append(sql, @opts[:from][0..0]) 2790 end
Only include the primary table in the main delete clause
Source
# File lib/sequel/adapters/shared/postgres.rb 2793 def delete_using_sql(sql) 2794 join_from_sql(:USING, sql) 2795 end
Use USING to specify additional tables in a delete query
Source
# File lib/sequel/adapters/shared/postgres.rb 2799 def derived_column_list_sql_append(sql, column_aliases) 2800 c = false 2801 comma = ', ' 2802 column_aliases.each do |a| 2803 sql << comma if c 2804 if a.is_a?(Array) 2805 raise Error, "column aliases specified as arrays must have only 2 elements, the first is alias name and the second is data type" unless a.length == 2 2806 a, type = a 2807 identifier_append(sql, a) 2808 sql << " " << db.cast_type_literal(type).to_s 2809 else 2810 identifier_append(sql, a) 2811 end 2812 c ||= true 2813 end 2814 end
Handle column aliases containing data types, useful for selecting from functions that return the record data type.
Source
# File lib/sequel/adapters/shared/postgres.rb 2828 def explain_sql_string_origin(opts) 2829 origin = String.new 2830 origin << 'EXPLAIN ' 2831 2832 # simplecov:disable 2833 if server_version < 90000 2834 if opts[:analyze] 2835 origin << 'ANALYZE ' 2836 end 2837 2838 return origin 2839 end 2840 # simplecov:enable 2841 2842 comma = nil 2843 paren = "(" 2844 2845 add_opt = lambda do |str, value| 2846 origin << paren if paren 2847 origin << comma if comma 2848 origin << str 2849 origin << " FALSE" unless value 2850 comma ||= ', ' 2851 paren &&= nil 2852 end 2853 2854 EXPLAIN_BOOLEAN_OPTIONS.each do |key, str| 2855 unless (value = opts[key]).nil? 2856 add_opt.call(str, value) 2857 end 2858 end 2859 2860 EXPLAIN_NONBOOLEAN_OPTIONS.each do |key, e_opts| 2861 if value = opts[key] 2862 if str = e_opts[value] 2863 add_opt.call(str, true) 2864 else 2865 raise Sequel::Error, "unrecognized value for Dataset#explain #{key.inspect} option: #{value.inspect}" 2866 end 2867 end 2868 end 2869 2870 origin << ') ' unless paren 2871 origin 2872 end
A mutable string used as the prefix when explaining a query.
Source
# File lib/sequel/adapters/shared/postgres.rb 3157 def full_text_string_join(cols) 3158 cols = Array(cols).map{|x| SQL::Function.new(:COALESCE, x, '')} 3159 cols = cols.zip([' '] * cols.length).flatten 3160 cols.pop 3161 SQL::StringExpression.new(:'||', *cols) 3162 end
Concatenate the expressions with a space in between
Source
# File lib/sequel/adapters/shared/postgres.rb 2875 def insert_conflict_sql(sql) 2876 if opts = @opts[:insert_conflict] 2877 sql << " ON CONFLICT" 2878 2879 if target = opts[:constraint] 2880 sql << " ON CONSTRAINT " 2881 identifier_append(sql, target) 2882 elsif target = opts[:target] 2883 sql << ' ' 2884 identifier_append(sql, Array(target)) 2885 if conflict_where = opts[:conflict_where] 2886 sql << " WHERE " 2887 literal_append(sql, conflict_where) 2888 end 2889 end 2890 2891 if values = opts[:update] 2892 sql << " DO UPDATE SET " 2893 update_sql_values_hash(sql, values) 2894 where = opts[:update_where] 2895 elsif opts[:select] 2896 sql << " DO SELECT" 2897 select_lock_sql(sql) 2898 where = opts[:select_where] 2899 else 2900 sql << " DO NOTHING" 2901 end 2902 2903 if where 2904 sql << " WHERE " 2905 literal_append(sql, where) 2906 end 2907 end 2908 end
Add ON CONFLICT clause if it should be used
Source
# File lib/sequel/adapters/shared/postgres.rb 2911 def insert_into_sql(sql) 2912 sql << " INTO " 2913 if (f = @opts[:from]) && f.length == 1 2914 identifier_append(sql, server_version >= 90500 ? f.first : unaliased_identifier(f.first)) 2915 else 2916 source_list_append(sql, f) 2917 end 2918 end
Include aliases when inserting into a single table on PostgreSQL 9.5+.
Source
# File lib/sequel/adapters/shared/postgres.rb 2935 def insert_override_sql(sql) 2936 case opts[:override] 2937 when :system 2938 sql << " OVERRIDING SYSTEM VALUE" 2939 when :user 2940 sql << " OVERRIDING USER VALUE" 2941 end 2942 end
Support OVERRIDING SYSTEM|USER VALUE in insert statements
Source
# File lib/sequel/adapters/shared/postgres.rb 2921 def insert_pk 2922 (f = opts[:from]) && !f.empty? && (t = f.first) 2923 2924 t = t.call(self) if t.is_a? Sequel::SQL::DelayedEvaluation 2925 2926 case t 2927 when Symbol, String, SQL::Identifier, SQL::QualifiedIdentifier 2928 if pk = db.primary_key(t) 2929 Sequel::SQL::Identifier.new(pk) 2930 end 2931 end 2932 end
Return the primary key to use for RETURNING in an INSERT statement
Source
# File lib/sequel/adapters/shared/postgres.rb 2946 def join_from_sql(type, sql) 2947 if(from = @opts[:from][1..-1]).empty? 2948 raise(Error, 'Need multiple FROM tables if updating/deleting a dataset with JOINs') if @opts[:join] 2949 else 2950 sql << ' ' << type.to_s << ' ' 2951 source_list_append(sql, from) 2952 select_join_sql(sql) 2953 end 2954 end
For multiple table support, PostgreSQL requires at least two from tables, with joins allowed.
Source
# File lib/sequel/adapters/shared/postgres.rb 2957 def join_using_clause_using_sql_append(sql, using_columns) 2958 if using_columns.is_a?(SQL::AliasedExpression) 2959 super(sql, using_columns.expression) 2960 sql << ' AS ' 2961 identifier_append(sql, using_columns.alias) 2962 else 2963 super 2964 end 2965 end
Support table aliases for USING columns
Source
# File lib/sequel/adapters/shared/postgres.rb 2968 def literal_blob_append(sql, v) 2969 sql << "'" << v.gsub(/[\000-\037\047\134\177-\377]/n){|b| "\\#{("%o" % b[0..1].unpack("C")[0]).rjust(3, '0')}"} << "'" 2970 end
Use a generic blob quoting method, hopefully overridden in one of the subadapter methods
Source
# File lib/sequel/adapters/shared/postgres.rb 2973 def literal_false 2974 'false' 2975 end
PostgreSQL uses FALSE for false values
Source
# File lib/sequel/adapters/shared/postgres.rb 2978 def literal_float(value) 2979 if value.finite? 2980 super 2981 elsif value.nan? 2982 "'NaN'" 2983 elsif value.infinite? == 1 2984 "'Infinity'" 2985 else 2986 "'-Infinity'" 2987 end 2988 end
PostgreSQL quotes NaN and Infinity.
Source
# File lib/sequel/adapters/shared/postgres.rb 2991 def literal_integer(v) 2992 if v > 9223372036854775807 || v < -9223372036854775808 2993 literal_integer_outside_bigint_range(v) 2994 else 2995 v.to_s 2996 end 2997 end
Handle Ruby integers outside PostgreSQL bigint range specially.
Source
# File lib/sequel/adapters/shared/postgres.rb 3002 def literal_integer_outside_bigint_range(v) 3003 raise IntegerOutsideBigintRange, "attempt to literalize Ruby integer outside PostgreSQL bigint range: #{v}" 3004 end
Raise IntegerOutsideBigintRange when attempting to literalize Ruby integer outside PostgreSQL bigint range, so PostgreSQL doesn’t treat the value as numeric.
Source
# File lib/sequel/adapters/shared/postgres.rb 3007 def literal_string_append(sql, v) 3008 sql << "'" << v.gsub("'", "''") << "'" 3009 end
Assume that SQL standard quoting is on, per Sequel’s defaults
Source
# File lib/sequel/adapters/shared/postgres.rb 3012 def literal_true 3013 'true' 3014 end
PostgreSQL uses true for true values
Source
# File lib/sequel/adapters/shared/postgres.rb 3017 def multi_insert_sql_strategy 3018 :values 3019 end
PostgreSQL supports multiple rows in INSERT.
Source
# File lib/sequel/adapters/shared/postgres.rb 3022 def non_sql_option?(key) 3023 super || key == :cursor || key == :insert_conflict 3024 end
Source
# File lib/sequel/adapters/shared/postgres.rb 3036 def requires_like_escape? 3037 false 3038 end
Backslash is supported by default as the escape character on PostgreSQL, and using ESCAPE can break LIKE ANY() usage.
Source
# File lib/sequel/adapters/shared/postgres.rb 3041 def select_limit_sql(sql) 3042 l = @opts[:limit] 3043 o = @opts[:offset] 3044 3045 return unless l || o 3046 3047 if @opts[:limit_with_ties] 3048 if o 3049 sql << " OFFSET " 3050 literal_append(sql, o) 3051 end 3052 3053 if l 3054 sql << " FETCH FIRST " 3055 literal_append(sql, l) 3056 sql << " ROWS WITH TIES" 3057 end 3058 else 3059 if l 3060 sql << " LIMIT " 3061 literal_append(sql, l) 3062 end 3063 3064 if o 3065 sql << " OFFSET " 3066 literal_append(sql, o) 3067 end 3068 end 3069 end
Support FETCH FIRST WITH TIES on PostgreSQL 13+.
Source
# File lib/sequel/adapters/shared/postgres.rb 3073 def select_lock_sql(sql) 3074 lock = @opts[:lock] 3075 case lock 3076 when :share 3077 sql << ' FOR SHARE' 3078 when :no_key_update 3079 sql << ' FOR NO KEY UPDATE' 3080 when :key_share 3081 sql << ' FOR KEY SHARE' 3082 else 3083 super 3084 end 3085 3086 if lock 3087 if @opts[:skip_locked] 3088 sql << " SKIP LOCKED" 3089 elsif @opts[:nowait] 3090 sql << " NOWAIT" 3091 end 3092 end 3093 end
Support FOR SHARE locking when using the :share lock style. Use SKIP LOCKED if skipping locked rows.
Source
# File lib/sequel/adapters/shared/postgres.rb 3096 def select_values_sql(sql) 3097 sql << "VALUES " 3098 expression_list_append(sql, opts[:values]) 3099 end
Support VALUES clause instead of the SELECT clause to return rows.
Source
# File lib/sequel/adapters/shared/postgres.rb 3102 def select_with_sql_base 3103 opts[:with].any?{|w| w[:recursive]} ? "WITH RECURSIVE " : super 3104 end
Use WITH RECURSIVE instead of WITH if any of the CTEs is recursive
Source
# File lib/sequel/adapters/shared/postgres.rb 3107 def select_with_sql_cte(sql, cte) 3108 super 3109 select_with_sql_cte_search_cycle(sql, cte) 3110 end
Support PostgreSQL 14+ CTE SEARCH/CYCLE clauses
Source
# File lib/sequel/adapters/shared/postgres.rb 3112 def select_with_sql_cte_search_cycle(sql, cte) 3113 if search_opts = cte[:search] 3114 sql << if search_opts[:type] == :breadth 3115 " SEARCH BREADTH FIRST BY " 3116 else 3117 " SEARCH DEPTH FIRST BY " 3118 end 3119 3120 identifier_list_append(sql, Array(search_opts[:by])) 3121 sql << " SET " 3122 identifier_append(sql, search_opts[:set] || :ordercol) 3123 end 3124 3125 if cycle_opts = cte[:cycle] 3126 sql << " CYCLE " 3127 identifier_list_append(sql, Array(cycle_opts[:columns])) 3128 sql << " SET " 3129 identifier_append(sql, cycle_opts[:cycle_column] || :is_cycle) 3130 if cycle_opts.has_key?(:cycle_value) 3131 sql << " TO " 3132 literal_append(sql, cycle_opts[:cycle_value]) 3133 sql << " DEFAULT " 3134 literal_append(sql, cycle_opts.fetch(:noncycle_value, false)) 3135 end 3136 sql << " USING " 3137 identifier_append(sql, cycle_opts[:path_column] || :path) 3138 end 3139 end
Source
# File lib/sequel/adapters/shared/postgres.rb 3142 def server_version 3143 db.server_version(@opts[:server]) 3144 end
The version of the database server
Source
# File lib/sequel/adapters/shared/postgres.rb 3147 def supports_filtered_aggregates? 3148 server_version >= 90400 3149 end
PostgreSQL 9.4+ supports the FILTER clause for aggregate functions.
Source
# File lib/sequel/adapters/shared/postgres.rb 3152 def supports_quoted_function_names? 3153 true 3154 end
PostgreSQL supports quoted function names.
Source
# File lib/sequel/adapters/shared/postgres.rb 3165 def update_from_sql(sql) 3166 join_from_sql(:FROM, sql) 3167 end
Use FROM to specify additional tables in an update query
Source
# File lib/sequel/adapters/shared/postgres.rb 3170 def update_table_sql(sql) 3171 sql << ' ' 3172 source_list_append(sql, @opts[:from][0..0]) 3173 end
Only include the primary table in the main update clause