diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 4b2047dfb..d6e59bb1c 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -30,11 +30,16 @@ jobs:
- forest_admin_datasource_mongoid
- forest_admin_rpc_agent
- forest_admin_datasource_rpc
+ - forest_admin_datasource_snowflake
steps:
- name: Checkout
uses: actions/checkout@v4
+ - name: Install unixODBC headers for ruby-odbc
+ if: ${{ matrix.packages == 'forest_admin_datasource_snowflake' }}
+ run: sudo apt-get update && sudo apt-get install -y unixodbc-dev
+
- name: Set up Ruby ${{ matrix.ruby-version }}
uses: ruby/setup-ruby@v1
with:
@@ -66,6 +71,7 @@ jobs:
- forest_admin_datasource_mongoid
- forest_admin_rpc_agent
- forest_admin_datasource_rpc
+ - forest_admin_datasource_snowflake
services:
mongodb:
image: mongo:latest
@@ -75,6 +81,10 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
+ - name: Install unixODBC headers for ruby-odbc
+ if: ${{ matrix.packages == 'forest_admin_datasource_snowflake' }}
+ run: sudo apt-get update && sudo apt-get install -y unixodbc-dev
+
- name: Set up Ruby ${{ matrix.ruby-version }}
uses: ruby/setup-ruby@v1
with:
@@ -129,7 +139,7 @@ jobs:
with:
verbose: true
oidc: true
- files: ${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_agent/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_active_record/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_customizer/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_toolkit/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_mongoid/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_rpc_agent/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_rpc/coverage.json
+ files: ${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_agent/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_active_record/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_customizer/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_toolkit/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_mongoid/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_rpc_agent/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_rpc/coverage.json,${{ github.workspace }}/reports/${{ matrix.ruby-version }}-forest_admin_datasource_snowflake/coverage.json
deploy:
name: Release package
diff --git a/.releaserc.js b/.releaserc.js
index 234ee0308..7397495c8 100644
--- a/.releaserc.js
+++ b/.releaserc.js
@@ -27,7 +27,8 @@ module.exports = {
'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_rails/lib/forest_admin_rails/version.rb; '+
'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_datasource_mongoid/lib/forest_admin_datasource_mongoid/version.rb; '+
'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_rpc_agent/lib/forest_admin_rpc_agent/version.rb; '+
- 'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_datasource_rpc/lib/forest_admin_datasource_rpc/version.rb; ',
+ 'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_datasource_rpc/lib/forest_admin_datasource_rpc/version.rb; '+
+ 'sed -i \'s/VERSION = ".*"/VERSION = "${nextRelease.version}"/g\' packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb; ',
successCmd:
'( cd packages/forest_admin_agent && gem build && gem push forest_admin_agent-*.gem );' +
'( cd packages/forest_admin_datasource_active_record && gem build && gem push forest_admin_datasource_active_record-*.gem );' +
@@ -37,7 +38,8 @@ module.exports = {
'( cd packages/forest_admin_rails && gem build && gem push forest_admin_rails-*.gem );' +
'( cd packages/forest_admin_datasource_mongoid && gem build && gem push forest_admin_datasource_mongoid-*.gem );' +
'( cd packages/forest_admin_rpc_agent && gem build && gem push forest_admin_rpc_agent-*.gem );' +
- '( cd packages/forest_admin_datasource_rpc && gem build && gem push forest_admin_datasource_rpc-*.gem );' ,
+ '( cd packages/forest_admin_datasource_rpc && gem build && gem push forest_admin_datasource_rpc-*.gem );' +
+ '( cd packages/forest_admin_datasource_snowflake && gem build && gem push forest_admin_datasource_snowflake-*.gem );' ,
},
],
[
@@ -56,6 +58,7 @@ module.exports = {
'packages/forest_admin_datasource_mongoid/lib/forest_admin_datasource_mongoid/version.rb',
'packages/forest_admin_rpc_agent/lib/forest_admin_rpc_agent/version.rb',
'packages/forest_admin_datasource_rpc/lib/forest_admin_datasource_rpc/version.rb',
+ 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb',
'package.json'
],
},
diff --git a/.rubocop.yml b/.rubocop.yml
index efe3deaa3..9751d3d85 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -107,6 +107,7 @@ Style/MutableConstant:
- 'packages/forest_admin_test_toolkit/lib/forest_admin_test_toolkit/version.rb'
- 'packages/forest_admin_datasource_customizer/lib/forest_admin_datasource_customizer/version.rb'
- 'packages/forest_admin_datasource_active_record/lib/forest_admin_datasource_active_record/version.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb'
# Offense count: 38
# This cop supports safe autocorrection (--autocorrect).
@@ -187,6 +188,7 @@ Style/StringLiterals:
- 'packages/forest_admin_datasource_active_record/lib/forest_admin_datasource_active_record.rb'
- 'packages/forest_admin_datasource_active_record/lib/forest_admin_datasource_active_record/version.rb'
- 'packages/forest_admin_datasource_active_record/spec/spec_helper.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb'
# Offense count: 1
# This cop supports safe autocorrection (--autocorrect).
@@ -219,6 +221,7 @@ Lint/NestedMethodDefinition:
Performance/CollectionLiteralInLoop:
Exclude:
- 'packages/forest_admin_agent/lib/forest_admin_agent/utils/condition_tree_parser.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb'
Naming/PredicatePrefix:
Exclude:
@@ -226,6 +229,7 @@ Naming/PredicatePrefix:
Metrics/ParameterLists:
Exclude:
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/routes/query_handler.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/services/smart_action_checker.rb'
- 'packages/forest_admin_agent/spec/lib/forest_admin_agent/routes/resources/related/list_related_spec.rb'
@@ -261,6 +265,8 @@ Metrics/MethodLength:
CountAsOne: ['array', 'hash', 'method_call']
Max: 20
Exclude:
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/collection.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/query.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/auth/oauth2/forest_provider.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/builder/agent_factory.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/http/error_translator.rb'
@@ -316,6 +322,9 @@ Metrics/BlockLength:
Metrics/ClassLength:
Exclude:
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/collection.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb'
+ - 'packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/query.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/builder/agent_factory.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/utils/schema/generator_field.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/routes/charts/charts.rb'
@@ -404,6 +413,18 @@ RSpec/VerifiedDoubles:
Exclude:
- 'packages/forest_admin_datasource_customizer/spec/lib/forest_admin_datasource_customizer/composite_datasource_spec.rb'
+RSpec/VerifiedDoubleReference:
+ Exclude:
+ - 'packages/forest_admin_datasource_snowflake/spec/**/*'
+
+RSpec/StubbedMock:
+ Exclude:
+ - 'packages/forest_admin_datasource_snowflake/spec/**/*'
+
+RSpec/MessageSpies:
+ Exclude:
+ - 'packages/forest_admin_datasource_snowflake/spec/**/*'
+
RSpec/MultipleMemoizedHelpers:
Max: 15
diff --git a/packages/forest_admin_datasource_snowflake/.rspec b/packages/forest_admin_datasource_snowflake/.rspec
new file mode 100644
index 000000000..34c5164d9
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/.rspec
@@ -0,0 +1,3 @@
+--format documentation
+--color
+--require spec_helper
diff --git a/packages/forest_admin_datasource_snowflake/Gemfile b/packages/forest_admin_datasource_snowflake/Gemfile
new file mode 100644
index 000000000..235c6d851
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/Gemfile
@@ -0,0 +1,13 @@
+source 'https://rubygems.org'
+
+gemspec
+
+gem 'forest_admin_datasource_toolkit', path: '../forest_admin_datasource_toolkit'
+
+group :development, :test do
+ gem 'pry'
+ gem 'rspec', '~> 3.12'
+ gem 'rubocop', require: false
+ gem 'rubocop-rspec', require: false
+ gem 'simplecov', require: false
+end
diff --git a/packages/forest_admin_datasource_snowflake/Gemfile-test b/packages/forest_admin_datasource_snowflake/Gemfile-test
new file mode 100644
index 000000000..58ddcc2be
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/Gemfile-test
@@ -0,0 +1,14 @@
+source "https://rubygems.org"
+
+gemspec
+
+gem 'rake', '~> 13.0'
+gem 'rubocop', '~> 1.21'
+
+group :development, :test do
+ gem 'forest_admin_datasource_toolkit', path: '../forest_admin_datasource_toolkit'
+ gem 'rspec', '~> 3.12'
+ gem 'simplecov', '~> 0.22', require: false
+ gem 'simplecov-html', '~> 0.12.3'
+ gem 'simplecov_json_formatter', '~> 0.1.4'
+end
diff --git a/packages/forest_admin_datasource_snowflake/LICENSE b/packages/forest_admin_datasource_snowflake/LICENSE
new file mode 100644
index 000000000..9cecc1d46
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/packages/forest_admin_datasource_snowflake/Rakefile b/packages/forest_admin_datasource_snowflake/Rakefile
new file mode 100644
index 000000000..f34a48cfd
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/Rakefile
@@ -0,0 +1,5 @@
+require 'rspec/core/rake_task'
+
+RSpec::Core::RakeTask.new(:spec)
+
+task default: :spec
diff --git a/packages/forest_admin_datasource_snowflake/forest_admin_datasource_snowflake.gemspec b/packages/forest_admin_datasource_snowflake/forest_admin_datasource_snowflake.gemspec
new file mode 100644
index 000000000..5d6c999b8
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/forest_admin_datasource_snowflake.gemspec
@@ -0,0 +1,37 @@
+lib = File.expand_path('lib', __dir__)
+$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
+
+require_relative 'lib/forest_admin_datasource_snowflake/version'
+
+Gem::Specification.new do |spec|
+ spec.name = 'forest_admin_datasource_snowflake'
+ spec.version = ForestAdminDatasourceSnowflake::VERSION
+ spec.authors = ['Forest Admin']
+ spec.email = ['support@forestadmin.com']
+ spec.homepage = 'https://www.forestadmin.com'
+ spec.summary = 'Snowflake datasource for Forest Admin (read-only).'
+ spec.description = 'Exposes Snowflake tables and views as Forest Admin collections via ODBC. ' \
+ 'Queries are translated from Forest ConditionTrees to parameterized SQL; ' \
+ 'no ActiveRecord involvement on the Snowflake side.'
+ spec.license = 'GPL-3.0'
+ spec.required_ruby_version = '>= 3.0.0'
+
+ spec.metadata['homepage_uri'] = spec.homepage
+ spec.metadata['source_code_uri'] = 'https://github.com/ForestAdmin/agent-ruby'
+ spec.metadata['changelog_uri'] = 'https://github.com/ForestAdmin/agent-ruby/blob/main/CHANGELOG.md'
+ spec.metadata['rubygems_mfa_required'] = 'true'
+
+ spec.files = Dir.chdir(__dir__) do
+ `git ls-files -z`.split("\x0").reject do |f|
+ (File.expand_path(f) == __FILE__) ||
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
+ end
+ end
+ spec.bindir = 'exe'
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
+ spec.require_paths = ['lib']
+
+ spec.add_dependency 'connection_pool', '~> 2.4'
+ spec.add_dependency 'ruby-odbc', '~> 0.99999'
+ spec.add_dependency 'zeitwerk', '~> 2.3'
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake.rb
new file mode 100644
index 000000000..1d0195ad9
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake.rb
@@ -0,0 +1,11 @@
+require_relative 'forest_admin_datasource_snowflake/version'
+require 'odbc'
+require 'zeitwerk'
+
+loader = Zeitwerk::Loader.for_gem
+loader.inflector.inflect('odbc' => 'ODBC')
+loader.setup
+
+module ForestAdminDatasourceSnowflake
+ class Error < StandardError; end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/collection.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/collection.rb
new file mode 100644
index 000000000..ea2512da4
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/collection.rb
@@ -0,0 +1,129 @@
+require 'odbc'
+require 'date'
+require 'json'
+
+module ForestAdminDatasourceSnowflake
+ class Collection < ForestAdminDatasourceToolkit::Collection
+ READ_ONLY_MESSAGE = 'forest_admin_datasource_snowflake is read-only.'.freeze
+ ReadOnlyError = ForestAdminDatasourceToolkit::Exceptions::ForestException
+
+ attr_reader :table_name
+
+ def initialize(datasource, table_name)
+ super
+ @table_name = table_name
+ @primary_keys = []
+ @json_columns = []
+ fetch_fields
+ enable_count
+ end
+
+ def list(_caller, filter, projection)
+ sql, binds = Utils::Query.new(self, projection: projection, filter: filter).to_sql
+ execute_to_hashes(sql, binds, projection.to_a)
+ end
+
+ def aggregate(_caller, filter, aggregation, limit = nil)
+ sql, binds, group_columns = Utils::Query.new(
+ self,
+ filter: filter,
+ aggregation: aggregation,
+ limit: limit
+ ).to_aggregate_sql
+
+ raw_rows = execute_raw(sql, binds)
+ raw_rows.map do |row|
+ value = coerce_value(row.first)
+ group_hash = group_columns.each_with_index.to_h { |col, i| [col, coerce_for_column(col, row[i + 1])] }
+ { 'value' => value, 'group' => group_hash }
+ end
+ end
+
+ def create(_caller, _data) = raise(ReadOnlyError, READ_ONLY_MESSAGE)
+ def update(_caller, _filter, _data) = raise(ReadOnlyError, READ_ONLY_MESSAGE)
+ def delete(_caller, _filter) = raise(ReadOnlyError, READ_ONLY_MESSAGE)
+
+ private
+
+ def fetch_fields
+ rows = @datasource.with_connection do |conn|
+ stmt = conn.columns(@table_name)
+ begin
+ stmt.fetch_all || []
+ ensure
+ stmt.drop
+ end
+ end
+
+ native_types = @datasource.fetch_snowflake_native_types(@table_name)
+ pk_name = (rows.find { |r| r[3].to_s.casecmp('id').zero? } || rows.first)&.dig(3)
+
+ rows.each do |row|
+ column_name = row[3]
+ odbc_type = row[4]
+ nullable = row[10] != 0
+
+ forest_type = Parser::Column.forest_type_for_snowflake_native(native_types[column_name]) ||
+ Parser::Column.forest_type_for(odbc_type)
+ @json_columns << column_name if forest_type == 'Json'
+
+ field = ForestAdminDatasourceToolkit::Schema::ColumnSchema.new(
+ column_type: forest_type,
+ filter_operators: Parser::Column.operators_for_column_type(forest_type),
+ is_primary_key: column_name == pk_name,
+ is_read_only: true,
+ is_sortable: true,
+ default_value: nil,
+ enum_values: [],
+ validation: nullable ? [] : [{ operator: 'Present' }]
+ )
+ @primary_keys << column_name if field.is_primary_key
+ add_field(column_name, field)
+ end
+ end
+
+ def execute_to_hashes(sql, binds, projected_columns)
+ rows = execute_raw(sql, binds)
+ rows.map { |row| projected_columns.each_with_index.to_h { |col, i| [col, coerce_for_column(col, row[i])] } }
+ end
+
+ def coerce_for_column(column_name, value)
+ return parse_json_value(value) if @json_columns.include?(column_name)
+
+ coerce_value(value)
+ end
+
+ def coerce_value(value)
+ case value
+ when ::ODBC::TimeStamp
+ ::Time.utc(value.year, value.month, value.day, value.hour, value.minute, value.second)
+ when ::ODBC::Date
+ ::Date.new(value.year, value.month, value.day)
+ when ::ODBC::Time
+ format('%02d:%02d:%02d', h: value.hour, m: value.minute, s: value.second)
+ else
+ value
+ end
+ end
+
+ def parse_json_value(value)
+ return value unless value.is_a?(String)
+
+ JSON.parse(value)
+ rescue JSON::ParserError
+ value
+ end
+
+ def execute_raw(sql, binds)
+ @datasource.with_connection do |conn|
+ stmt = conn.prepare(sql)
+ begin
+ stmt.execute(*binds)
+ stmt.fetch_all || []
+ ensure
+ stmt.drop
+ end
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb
new file mode 100644
index 000000000..30c58f5a4
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/datasource.rb
@@ -0,0 +1,165 @@
+require 'odbc'
+require 'connection_pool'
+
+module ForestAdminDatasourceSnowflake
+ class Datasource < ForestAdminDatasourceToolkit::Datasource
+ DEFAULT_POOL_SIZE = 5
+ DEFAULT_POOL_TIMEOUT = 5
+
+ CONNECTION_LOST_PATTERNS = [
+ /Communication link failure/i,
+ /Connection.*lost/i,
+ /Connection is closed/i,
+ /Session.*expired/i,
+ /Session.*timed out/i,
+ /Broken pipe/i,
+ /Not connected/i,
+ /timeout expired/i,
+ /Authentication token has expired/i,
+ /token.*expired/i
+ ].freeze
+
+ SYSTEM_SCHEMAS = %w[INFORMATION_SCHEMA].freeze
+
+ attr_reader :pool
+
+ def initialize(conn_str:, tables: nil, schema: nil,
+ pool_size: DEFAULT_POOL_SIZE, pool_timeout: DEFAULT_POOL_TIMEOUT,
+ statement_timeout: nil, introspect_relations: false)
+ super()
+ @conn_str = conn_str
+ @tables_filter = tables&.map(&:to_s)&.map(&:upcase)
+ @schema_override = schema
+ @statement_timeout = statement_timeout
+ @introspect_relations = introspect_relations
+ @pool = ConnectionPool.new(size: pool_size, timeout: pool_timeout) do
+ open_connection(conn_str)
+ end
+
+ generate_collections
+ discover_relations if @introspect_relations
+ end
+
+ def with_connection(&block)
+ retried = false
+ begin
+ @pool.with(&block)
+ rescue ::ODBC::Error => e
+ if !retried && connection_lost?(e)
+ retried = true
+ reset_pool!
+ retry
+ end
+ raise
+ end
+ end
+
+ def shutdown!
+ @pool.shutdown { |conn| safe_disconnect(conn) }
+ end
+
+ def fetch_snowflake_native_types(table_name)
+ with_connection do |conn|
+ stmt = conn.prepare(
+ 'SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS ' \
+ 'WHERE TABLE_NAME = ? AND TABLE_SCHEMA = CURRENT_SCHEMA()'
+ )
+ begin
+ stmt.execute(table_name.to_s.upcase)
+ rows = stmt.fetch_all || []
+ rows.to_h { |r| [r[0], r[1]] }
+ ensure
+ stmt.drop
+ end
+ end
+ rescue ::ODBC::Error
+ {}
+ end
+
+ private
+
+ def open_connection(conn_str)
+ attrs = conn_str.split(';').reject(&:empty?).to_h { |option| option.split('=', 2) }
+ driver = ::ODBC::Driver.new
+ driver.name = 'odbc'
+ driver.attrs = attrs
+ conn = ::ODBC::Database.new.drvconnect(driver)
+ apply_session_settings(conn)
+ conn
+ end
+
+ def apply_session_settings(conn)
+ run_session_statement(conn, "ALTER SESSION SET TIMEZONE = 'UTC'")
+ return unless @statement_timeout
+
+ seconds = Integer(@statement_timeout)
+ run_session_statement(conn, "ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = #{seconds}")
+ end
+
+ def run_session_statement(conn, sql)
+ stmt = conn.prepare(sql)
+ begin
+ stmt.execute
+ ensure
+ stmt.drop
+ end
+ end
+
+ def connection_lost?(error)
+ message = error.message.to_s
+ CONNECTION_LOST_PATTERNS.any? { |pattern| pattern.match?(message) }
+ end
+
+ def reset_pool!
+ @pool.reload { |conn| safe_disconnect(conn) }
+ end
+
+ def safe_disconnect(connection)
+ connection.disconnect if connection.respond_to?(:disconnect)
+ rescue StandardError
+ nil
+ end
+
+ def generate_collections
+ visible_tables.each do |table_name|
+ add_collection(Collection.new(self, table_name))
+ end
+ end
+
+ def discover_relations
+ Parser::Relation.discover(self).each do |fk|
+ source = collections[fk[:source_table]]
+ next if source.nil? || collections[fk[:target_table]].nil?
+
+ relation = ForestAdminDatasourceToolkit::Schema::Relations::ManyToOneSchema.new(
+ foreign_collection: fk[:target_table],
+ foreign_key: fk[:source_column],
+ foreign_key_target: fk[:target_column]
+ )
+ relation_name = "#{fk[:source_column]}_#{fk[:target_table]}".downcase
+ source.add_field(relation_name, relation)
+ end
+ rescue ::ODBC::Error => e
+ warn "[forest_admin_datasource_snowflake] FK introspection skipped: #{e.message}"
+ end
+
+ def visible_tables
+ with_connection do |conn|
+ stmt = conn.tables
+ rows = begin
+ stmt.fetch_all || []
+ ensure
+ stmt.drop
+ end
+
+ rows
+ .map { |row| { catalog: row[0], schema: row[1], name: row[2], type: row[3] } }
+ .reject { |t| SYSTEM_SCHEMAS.include?(t[:schema].to_s.upcase) }
+ .reject { |t| t[:type].to_s.upcase == 'SYSTEM TABLE' }
+ .select { |t| @schema_override.nil? || t[:schema].to_s.casecmp(@schema_override).zero? }
+ .select { |t| @tables_filter.nil? || @tables_filter.include?(t[:name].to_s.upcase) }
+ .map { |t| t[:name] }
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/column.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/column.rb
new file mode 100644
index 000000000..94d6f49bb
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/column.rb
@@ -0,0 +1,92 @@
+require 'odbc'
+
+module ForestAdminDatasourceSnowflake
+ module Parser
+ module Column
+ include ForestAdminDatasourceToolkit::Components::Query::ConditionTree
+
+ ODBC_TYPE_TO_FOREST = {
+ ODBC::SQL_BIT => 'Boolean',
+ ODBC::SQL_TINYINT => 'Number',
+ ODBC::SQL_SMALLINT => 'Number',
+ ODBC::SQL_INTEGER => 'Number',
+ ODBC::SQL_BIGINT => 'Number',
+ ODBC::SQL_NUMERIC => 'Number',
+ ODBC::SQL_DECIMAL => 'Number',
+ ODBC::SQL_DOUBLE => 'Number',
+ ODBC::SQL_REAL => 'Number',
+ ODBC::SQL_FLOAT => 'Number',
+ ODBC::SQL_DATE => 'Dateonly',
+ ODBC::SQL_TYPE_DATE => 'Dateonly',
+ ODBC::SQL_TIME => 'Time',
+ ODBC::SQL_TYPE_TIME => 'Time',
+ ODBC::SQL_TIMESTAMP => 'Date',
+ ODBC::SQL_TYPE_TIMESTAMP => 'Date',
+ ODBC::SQL_CHAR => 'String',
+ ODBC::SQL_VARCHAR => 'String',
+ ODBC::SQL_LONGVARCHAR => 'String',
+ ODBC::SQL_WCHAR => 'String',
+ ODBC::SQL_WVARCHAR => 'String',
+ ODBC::SQL_WLONGVARCHAR => 'String',
+ ODBC::SQL_BINARY => 'Binary',
+ ODBC::SQL_VARBINARY => 'Binary',
+ ODBC::SQL_LONGVARBINARY => 'Binary',
+ ODBC::SQL_GUID => 'Uuid'
+ }.freeze
+
+ SNOWFLAKE_VARIANT_TYPE = 2004
+ ODBC_TYPE_TO_FOREST_WITH_SNOWFLAKE = ODBC_TYPE_TO_FOREST.merge(SNOWFLAKE_VARIANT_TYPE => 'Json').freeze
+
+ SNOWFLAKE_NATIVE_TYPE_TO_FOREST = {
+ 'VARIANT' => 'Json',
+ 'OBJECT' => 'Json',
+ 'ARRAY' => 'Json',
+ 'BINARY' => 'Binary',
+ 'VARBINARY' => 'Binary'
+ }.freeze
+
+ module_function
+
+ def forest_type_for(odbc_type)
+ ODBC_TYPE_TO_FOREST_WITH_SNOWFLAKE[odbc_type] || 'String'
+ end
+
+ def forest_type_for_snowflake_native(snowflake_type)
+ SNOWFLAKE_NATIVE_TYPE_TO_FOREST[snowflake_type.to_s.upcase]
+ end
+
+ def operators_for_column_type(type)
+ result = [Operators::PRESENT, Operators::BLANK, Operators::MISSING]
+ equality = [Operators::EQUAL, Operators::NOT_EQUAL, Operators::IN, Operators::NOT_IN]
+ orderables = [
+ Operators::LESS_THAN,
+ Operators::GREATER_THAN,
+ Operators::LESS_THAN_OR_EQUAL,
+ Operators::GREATER_THAN_OR_EQUAL
+ ]
+ strings = [
+ Operators::CONTAINS,
+ Operators::I_CONTAINS,
+ Operators::NOT_CONTAINS,
+ Operators::NOT_I_CONTAINS,
+ Operators::STARTS_WITH,
+ Operators::I_STARTS_WITH,
+ Operators::ENDS_WITH,
+ Operators::I_ENDS_WITH,
+ Operators::LIKE,
+ Operators::I_LIKE,
+ Operators::SHORTER_THAN,
+ Operators::LONGER_THAN
+ ]
+
+ return result unless type.is_a?(String)
+
+ result += equality if %w[Boolean Binary Enum Uuid Json].include?(type)
+ result += equality + orderables if %w[Date Dateonly Time Number].include?(type)
+ result += equality + orderables + strings if type == 'String'
+
+ result
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/relation.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/relation.rb
new file mode 100644
index 000000000..8fc94c710
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/parser/relation.rb
@@ -0,0 +1,35 @@
+module ForestAdminDatasourceSnowflake
+ module Parser
+ module Relation
+ PK_TABLE_NAME_IDX = 3
+ PK_COLUMN_NAME_IDX = 4
+ FK_TABLE_NAME_IDX = 7
+ FK_COLUMN_NAME_IDX = 8
+
+ QUERY = 'SHOW IMPORTED KEYS IN SCHEMA'.freeze
+
+ module_function
+
+ def discover(datasource)
+ rows = datasource.with_connection do |conn|
+ stmt = conn.prepare(QUERY)
+ begin
+ stmt.execute
+ stmt.fetch_all || []
+ ensure
+ stmt.drop
+ end
+ end
+
+ rows.map do |row|
+ {
+ source_table: row[FK_TABLE_NAME_IDX],
+ source_column: row[FK_COLUMN_NAME_IDX],
+ target_table: row[PK_TABLE_NAME_IDX],
+ target_column: row[PK_COLUMN_NAME_IDX]
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/identifier.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/identifier.rb
new file mode 100644
index 000000000..308df5da7
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/identifier.rb
@@ -0,0 +1,14 @@
+module ForestAdminDatasourceSnowflake
+ module Utils
+ module Identifier
+ module_function
+
+ def quote(name)
+ s = name.to_s
+ return s if s == '*'
+
+ %("#{s.gsub('"', '""')}")
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/query.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/query.rb
new file mode 100644
index 000000000..54e943848
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/utils/query.rb
@@ -0,0 +1,168 @@
+module ForestAdminDatasourceSnowflake
+ module Utils
+ class Query
+ Operators = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Operators
+ ConditionTreeBranch = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Nodes::ConditionTreeBranch
+ ConditionTreeLeaf = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Nodes::ConditionTreeLeaf
+
+ def initialize(collection, projection: nil, filter: nil, aggregation: nil, limit: nil)
+ @collection = collection
+ @projection = projection
+ @filter = filter
+ @aggregation = aggregation
+ @limit = limit
+ @binds = []
+ end
+
+ def to_sql
+ @binds = []
+ cols = @projection ? @projection.columns.map { |c| q(c) } : ['*']
+ sql = "SELECT #{cols.join(", ")} FROM #{q(@collection.table_name)}"
+
+ where = build_where_clause(@filter&.condition_tree)
+ sql << " WHERE #{where}" if where
+
+ order_by = build_order_by(@filter&.sort)
+ sql << " ORDER BY #{order_by}" if order_by
+
+ if @filter&.page
+ limit = @filter.page.respond_to?(:limit) ? @filter.page.limit : nil
+ offset = @filter.page.respond_to?(:offset) ? @filter.page.offset : nil
+ sql << " LIMIT #{Integer(limit)}" if limit
+ sql << " OFFSET #{Integer(offset)}" if offset
+ end
+
+ [sql, @binds]
+ end
+
+ def to_aggregate_sql
+ @binds = []
+ op_expr = build_aggregation_expression(@aggregation)
+
+ group_cols = (@aggregation.groups || []).map { |g| g[:field] }
+ select_cols = [op_expr, *group_cols.map { |c| q(c) }]
+ sql = "SELECT #{select_cols.join(", ")} FROM #{q(@collection.table_name)}"
+
+ where = build_where_clause(@filter&.condition_tree)
+ sql << " WHERE #{where}" if where
+
+ sql << " GROUP BY #{group_cols.map { |c| q(c) }.join(", ")}" if group_cols.any?
+ sql << " LIMIT #{Integer(@limit)}" if @limit
+
+ [sql, @binds, group_cols]
+ end
+
+ private
+
+ def q(identifier)
+ Identifier.quote(identifier)
+ end
+
+ def build_aggregation_expression(aggregation)
+ op = aggregation.operation.to_s.upcase
+ field = aggregation.field
+
+ case op
+ when 'COUNT'
+ field ? "COUNT(#{q(field)})" : 'COUNT(*)'
+ when 'SUM', 'AVG', 'MIN', 'MAX'
+ if field.nil? || field.to_s.empty?
+ raise ForestAdminDatasourceSnowflake::Error, "Aggregation '#{op}' requires a field"
+ end
+
+ "#{op}(#{q(field)})"
+ else
+ raise ForestAdminDatasourceSnowflake::Error, "Unsupported aggregation operation: #{op}"
+ end
+ end
+
+ def build_order_by(sort)
+ return nil if sort.nil? || sort.empty?
+
+ sort.map { |s| "#{q(s[:field])} #{s[:ascending] ? "ASC" : "DESC"}" }.join(', ')
+ end
+
+ def build_where_clause(node)
+ return nil if node.nil?
+
+ case node
+ when ConditionTreeBranch
+ fragments = node.conditions.filter_map { |child| build_where_clause(child) }
+ return nil if fragments.empty?
+
+ joiner = node.aggregator.to_s.upcase == 'OR' ? ' OR ' : ' AND '
+ "(#{fragments.join(joiner)})"
+ when ConditionTreeLeaf
+ translate_leaf(node)
+ else
+ raise ForestAdminDatasourceSnowflake::Error, "Unsupported condition tree node: #{node.class}"
+ end
+ end
+
+ def translate_leaf(leaf)
+ field = q(leaf.field)
+ case leaf.operator
+ when Operators::EQUAL then bind!(leaf.value)
+ "#{field} = ?"
+ when Operators::NOT_EQUAL then bind!(leaf.value)
+ "#{field} <> ?"
+ when Operators::LESS_THAN then bind!(leaf.value)
+ "#{field} < ?"
+ when Operators::GREATER_THAN then bind!(leaf.value)
+ "#{field} > ?"
+ when Operators::LESS_THAN_OR_EQUAL then bind!(leaf.value)
+ "#{field} <= ?"
+ when Operators::GREATER_THAN_OR_EQUAL then bind!(leaf.value)
+ "#{field} >= ?"
+ when Operators::IN then translate_in(field, leaf.value)
+ when Operators::NOT_IN then translate_in(field, leaf.value, negate: true)
+ when Operators::PRESENT then "#{field} IS NOT NULL"
+ when Operators::MISSING then "#{field} IS NULL"
+ when Operators::BLANK then "(#{field} IS NULL OR #{field} = '')"
+ when Operators::CONTAINS then translate_like(field, "%#{leaf.value}%")
+ when Operators::I_CONTAINS then translate_ilike(field, "%#{leaf.value}%")
+ when Operators::NOT_CONTAINS then translate_like(field, "%#{leaf.value}%", negate: true)
+ when Operators::NOT_I_CONTAINS then translate_ilike(field, "%#{leaf.value}%", negate: true)
+ when Operators::STARTS_WITH then translate_like(field, "#{leaf.value}%")
+ when Operators::I_STARTS_WITH then translate_ilike(field, "#{leaf.value}%")
+ when Operators::ENDS_WITH then translate_like(field, "%#{leaf.value}")
+ when Operators::I_ENDS_WITH then translate_ilike(field, "%#{leaf.value}")
+ when Operators::LIKE then translate_like(field, leaf.value)
+ when Operators::I_LIKE then translate_ilike(field, leaf.value)
+ when Operators::SHORTER_THAN then bind!(leaf.value)
+ "LENGTH(#{field}) < ?"
+ when Operators::LONGER_THAN then bind!(leaf.value)
+ "LENGTH(#{field}) > ?"
+ else
+ raise ForestAdminDatasourceSnowflake::Error,
+ "Unsupported operator '#{leaf.operator}' on field '#{leaf.field}'"
+ end
+ end
+
+ def translate_in(quoted_field, values, negate: false)
+ list = Array(values)
+ return negate ? '1=1' : '1=0' if list.empty?
+
+ placeholders = list.map do |v|
+ bind!(v)
+ '?'
+ end.join(', ')
+ "#{quoted_field} #{negate ? "NOT IN" : "IN"} (#{placeholders})"
+ end
+
+ def translate_like(quoted_field, value, negate: false)
+ bind!(value)
+ "#{quoted_field} #{negate ? "NOT LIKE" : "LIKE"} ?"
+ end
+
+ def translate_ilike(quoted_field, value, negate: false)
+ bind!(value)
+ "LOWER(#{quoted_field}) #{negate ? "NOT LIKE" : "LIKE"} LOWER(?)"
+ end
+
+ def bind!(value)
+ @binds << value
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb
new file mode 100644
index 000000000..63c0c5a5a
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/lib/forest_admin_datasource_snowflake/version.rb
@@ -0,0 +1,3 @@
+module ForestAdminDatasourceSnowflake
+ VERSION = "1.27.0"
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/collection_spec.rb b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/collection_spec.rb
new file mode 100644
index 000000000..e554db25c
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/collection_spec.rb
@@ -0,0 +1,212 @@
+require 'spec_helper'
+
+RSpec.describe ForestAdminDatasourceSnowflake::Collection do
+ let(:odbc_connection) { instance_double('ODBC::Connection') }
+ let(:datasource) do
+ ForestAdminDatasourceSnowflake::Datasource.new(
+ conn_str: 'DRIVER={Snowflake};X=1',
+ pool_size: 1,
+ pool_timeout: 1
+ )
+ end
+ let(:collection) { datasource.get_collection('BILLING_USAGE') }
+ let(:driver_double) { instance_double('ODBC::Driver') }
+ let(:database_double) { instance_double('ODBC::Database') }
+
+ let(:tables_stmt) { instance_double('ODBC::Statement', drop: nil) }
+ let(:columns_stmt) { instance_double('ODBC::Statement', drop: nil) }
+ let(:prepared_stmt) { instance_double('ODBC::Statement', drop: nil) }
+ let(:session_stmt) { instance_double('ODBC::Statement', drop: nil, execute: nil) }
+ let(:is_columns_stmt) { instance_double('ODBC::Statement', drop: nil, execute: nil, fetch_all: []) }
+
+ before do
+ allow(ODBC::Driver).to receive(:new).and_return(driver_double)
+ allow(driver_double).to receive(:name=)
+ allow(driver_double).to receive(:attrs=)
+ allow(ODBC::Database).to receive(:new).and_return(database_double)
+ allow(database_double).to receive(:drvconnect).and_return(odbc_connection)
+
+ allow(tables_stmt).to receive(:fetch_all).and_return([
+ ['BILLING_POC', 'PUBLIC', 'BILLING_USAGE', 'TABLE', nil]
+ ])
+
+ allow(odbc_connection).to receive_messages(tables: tables_stmt, columns: columns_stmt)
+ allow(odbc_connection).to receive(:prepare).with(/ALTER SESSION/).and_return(session_stmt)
+ allow(odbc_connection).to receive(:prepare).with(/INFORMATION_SCHEMA\.COLUMNS/).and_return(is_columns_stmt)
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'BILLING_USAGE', 'ID',
+ ODBC::SQL_DECIMAL, nil, nil, nil, nil, nil, 0],
+ [nil, nil, 'BILLING_USAGE', 'CUSTOMER_ID',
+ ODBC::SQL_DECIMAL, nil, nil, nil, nil, nil, 0],
+ [nil, nil, 'BILLING_USAGE', 'EVENT_TYPE',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1]
+ ])
+ end
+
+ describe 'schema introspection' do
+ it 'introspects all columns with Forest types and operators' do
+ expect(collection.schema[:fields].keys).to contain_exactly('ID', 'CUSTOMER_ID', 'EVENT_TYPE')
+
+ id_field = collection.schema[:fields]['ID']
+ expect(id_field.column_type).to eq('Number')
+ expect(id_field.is_primary_key).to be(true)
+ expect(id_field.is_read_only).to be(true)
+ end
+
+ it 'overrides ODBC type with Snowflake native type for VARIANT/OBJECT/ARRAY (mapped to Json) and BINARY' do
+ allow(is_columns_stmt).to receive(:fetch_all).and_return([
+ ['META', 'VARIANT'],
+ ['BLOB', 'BINARY']
+ ])
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'BILLING_USAGE', 'META',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1],
+ [nil, nil, 'BILLING_USAGE', 'BLOB',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1]
+ ])
+
+ expect(collection.schema[:fields]['META'].column_type).to eq('Json')
+ expect(collection.schema[:fields]['BLOB'].column_type).to eq('Binary')
+ end
+
+ it 'falls back to ODBC type when the column is not in the Snowflake-native override list' do
+ allow(is_columns_stmt).to receive(:fetch_all).and_return([['ID', 'NUMBER']])
+
+ expect(collection.schema[:fields]['ID'].column_type).to eq('Number')
+ end
+
+ it 'returns invalid JSON unchanged so a malformed row does not crash the list' do
+ allow(is_columns_stmt).to receive(:fetch_all).and_return([['META', 'VARIANT']])
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'BILLING_USAGE', 'META',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1]
+ ])
+ allow(odbc_connection).to receive(:prepare).with(/FROM "BILLING_USAGE"/).and_return(prepared_stmt)
+ allow(prepared_stmt).to receive(:execute)
+ allow(prepared_stmt).to receive(:fetch_all).and_return([['not-json']])
+
+ result = collection.list(:caller, Filter.new, Projection.new(['META']))
+ expect(result.first['META']).to eq('not-json')
+ end
+
+ it 'designates the first column as primary key when no "id" exists' do
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'T', 'PK', ODBC::SQL_VARCHAR, nil, nil, nil,
+ nil, nil, 0],
+ [nil, nil, 'T', 'X', ODBC::SQL_VARCHAR, nil, nil, nil,
+ nil, nil, 1]
+ ])
+ allow(tables_stmt).to receive(:fetch_all).and_return([
+ ['BILLING_POC', 'PUBLIC', 'T', 'TABLE', nil]
+ ])
+
+ ds = ForestAdminDatasourceSnowflake::Datasource.new(conn_str: 'DRIVER={X}', pool_size: 1)
+ coll = ds.get_collection('T')
+ expect(coll.schema[:fields]['PK'].is_primary_key).to be(true)
+ expect(coll.schema[:fields]['X'].is_primary_key).to be(false)
+ end
+ end
+
+ describe '#list' do
+ it 'prepares the SQL, binds positionally, and projects rows into hashes' do
+ expected_sql = 'SELECT "ID", "CUSTOMER_ID" FROM "BILLING_USAGE" WHERE "CUSTOMER_ID" = ?'
+ expect(odbc_connection).to receive(:prepare).with(expected_sql).and_return(prepared_stmt)
+ expect(prepared_stmt).to receive(:execute).with(42)
+ expect(prepared_stmt).to receive(:fetch_all).and_return([[1, 42], [2, 42]])
+
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('CUSTOMER_ID', Operators::EQUAL, 42))
+ result = collection.list(:caller, filter, Projection.new(%w[ID CUSTOMER_ID]))
+
+ expect(result).to eq([
+ { 'ID' => 1, 'CUSTOMER_ID' => 42 },
+ { 'ID' => 2, 'CUSTOMER_ID' => 42 }
+ ])
+ end
+
+ it 'returns an empty array when the query yields no rows' do
+ allow(odbc_connection).to receive(:prepare).and_return(prepared_stmt)
+ allow(prepared_stmt).to receive(:execute)
+ allow(prepared_stmt).to receive(:fetch_all).and_return(nil)
+
+ result = collection.list(:caller, Filter.new, Projection.new(['ID']))
+ expect(result).to eq([])
+ end
+
+ it 'coerces ODBC::Date / ODBC::TimeStamp values to Ruby Date / Time so JSON serializes correctly' do
+ odbc_date = ODBC::Date.new(2026, 4, 28)
+ odbc_ts = ODBC::TimeStamp.new(2026, 4, 28, 10, 30, 15)
+
+ allow(odbc_connection).to receive(:prepare).with(/FROM "BILLING_USAGE"/).and_return(prepared_stmt)
+ allow(prepared_stmt).to receive(:execute)
+ allow(prepared_stmt).to receive(:fetch_all).and_return([[1, odbc_date, odbc_ts]])
+
+ result = collection.list(:caller, Filter.new, Projection.new(%w[ID AS_OF_DATE OCCURRED_AT]))
+
+ expect(result.first['AS_OF_DATE']).to be_a(Date).and eq(Date.new(2026, 4, 28))
+ expect(result.first['OCCURRED_AT']).to be_a(Time).and eq(Time.utc(2026, 4, 28, 10, 30, 15))
+ end
+
+ it 'parses JSON-typed columns into Ruby objects so the UI receives structured data' do
+ allow(is_columns_stmt).to receive(:fetch_all).and_return([
+ ['ID', 'NUMBER'],
+ ['META', 'VARIANT']
+ ])
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'BILLING_USAGE', 'ID',
+ ODBC::SQL_DECIMAL, nil, nil, nil, nil, nil, 0],
+ [nil, nil, 'BILLING_USAGE', 'META',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1]
+ ])
+ allow(odbc_connection).to receive(:prepare).with(/FROM "BILLING_USAGE"/).and_return(prepared_stmt)
+ allow(prepared_stmt).to receive(:execute)
+ allow(prepared_stmt).to receive(:fetch_all).and_return([[1, '{"foo":1,"bar":[true,null]}']])
+
+ result = collection.list(:caller, Filter.new, Projection.new(%w[ID META]))
+
+ expect(result.first['META']).to eq({ 'foo' => 1, 'bar' => [true, nil] })
+ expect(collection.schema[:fields]['META'].column_type).to eq('Json')
+ end
+ end
+
+ describe '#aggregate' do
+ it 'returns Forest-shaped {value, group} rows from the result set' do
+ expected_sql = 'SELECT COUNT(*), "EVENT_TYPE" FROM "BILLING_USAGE" GROUP BY "EVENT_TYPE"'
+ allow(odbc_connection).to receive(:prepare).with(expected_sql).and_return(prepared_stmt)
+ allow(prepared_stmt).to receive(:execute)
+ allow(prepared_stmt).to receive(:fetch_all).and_return([[12, 'login'], [3, 'purchase']])
+
+ result = collection.aggregate(
+ :caller,
+ Filter.new,
+ Aggregation.new(operation: 'Count', groups: [{ field: 'EVENT_TYPE' }])
+ )
+
+ expect(result).to eq([
+ { 'value' => 12, 'group' => { 'EVENT_TYPE' => 'login' } },
+ { 'value' => 3, 'group' => { 'EVENT_TYPE' => 'purchase' } }
+ ])
+ end
+ end
+
+ describe 'write methods' do
+ let(:read_only_error) { ForestAdminDatasourceToolkit::Exceptions::ForestException }
+
+ it '#create raises a ForestException with a read-only message' do
+ expect { collection.create(:caller, {}) }.to raise_error(read_only_error, /read-only/)
+ end
+
+ it '#update raises a ForestException with a read-only message' do
+ expect { collection.update(:caller, Filter.new, {}) }.to raise_error(read_only_error, /read-only/)
+ end
+
+ it '#delete raises a ForestException with a read-only message' do
+ expect { collection.delete(:caller, Filter.new) }.to raise_error(read_only_error, /read-only/)
+ end
+
+ it 'declares every column as is_read_only so Forest emits collection-level isReadOnly: true' do
+ column_fields = collection.schema[:fields].values.select { |f| f.type == 'Column' }
+ expect(column_fields).not_to be_empty
+ expect(column_fields).to all(have_attributes(is_read_only: true))
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/datasource_spec.rb b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/datasource_spec.rb
new file mode 100644
index 000000000..0feb0d3ec
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/datasource_spec.rb
@@ -0,0 +1,264 @@
+require 'spec_helper'
+
+RSpec.describe ForestAdminDatasourceSnowflake::Datasource do
+ subject(:datasource) do
+ described_class.new(
+ conn_str: 'DRIVER={Snowflake};Server=acc.snowflakecomputing.com;UID=u;PWD=p',
+ pool_size: 1,
+ pool_timeout: 1
+ )
+ end
+
+ let(:odbc_connection) { instance_double('ODBC::Connection') }
+ let(:driver_double) { instance_double('ODBC::Driver') }
+ let(:database_double) { instance_double('ODBC::Database') }
+
+ let(:tables_stmt) { instance_double('ODBC::Statement', drop: nil) }
+ let(:columns_stmt) { instance_double('ODBC::Statement', drop: nil) }
+ let(:session_stmt) { instance_double('ODBC::Statement', drop: nil, execute: nil) }
+ let(:is_columns_stmt) { instance_double('ODBC::Statement', drop: nil, execute: nil, fetch_all: []) }
+
+ before do
+ allow(ODBC::Driver).to receive(:new).and_return(driver_double)
+ allow(driver_double).to receive(:name=)
+ allow(driver_double).to receive(:attrs=)
+ allow(ODBC::Database).to receive(:new).and_return(database_double)
+ allow(database_double).to receive(:drvconnect).and_return(odbc_connection)
+
+ allow(odbc_connection).to receive(:prepare).with(/ALTER SESSION/).and_return(session_stmt)
+ allow(odbc_connection).to receive(:prepare).with(/INFORMATION_SCHEMA\.COLUMNS/).and_return(is_columns_stmt)
+
+ allow(tables_stmt).to receive(:fetch_all).and_return([
+ ['BILLING_POC', 'PUBLIC', 'BILLING_USAGE',
+ 'TABLE', nil],
+ ['BILLING_POC', 'PUBLIC', 'INTERNAL_LOG',
+ 'TABLE', nil],
+ ['BILLING_POC', 'INFORMATION_SCHEMA', 'COLUMNS',
+ 'VIEW', nil],
+ ['BILLING_POC', 'PUBLIC', 'IGNORE_ME',
+ 'SYSTEM TABLE', nil]
+ ])
+
+ allow(odbc_connection).to receive_messages(tables: tables_stmt, columns: columns_stmt)
+ allow(columns_stmt).to receive(:fetch_all).and_return([
+ [nil, nil, 'BILLING_USAGE', 'ID',
+ ODBC::SQL_DECIMAL, nil, nil, nil, nil, nil, 0],
+ [nil, nil, 'BILLING_USAGE', 'CUSTOMER_ID',
+ ODBC::SQL_DECIMAL, nil, nil, nil, nil, nil, 0],
+ [nil, nil, 'BILLING_USAGE', 'EVENT_TYPE',
+ ODBC::SQL_VARCHAR, nil, nil, nil, nil, nil, 1],
+ [nil, nil, 'BILLING_USAGE', 'OCCURRED_AT',
+ ODBC::SQL_TIMESTAMP, nil, nil, nil, nil, nil, 1]
+ ])
+ end
+
+ describe 'introspection' do
+ it 'exposes only user-schema, non-system tables as Forest collections' do
+ expect(datasource.collections.keys).to contain_exactly('BILLING_USAGE', 'INTERNAL_LOG')
+ end
+
+ it 'honors the optional :tables whitelist (case-insensitive)' do
+ ds = described_class.new(
+ conn_str: 'DRIVER={Snowflake};X=1',
+ tables: ['billing_usage'],
+ pool_size: 1
+ )
+ expect(ds.collections.keys).to eq(['BILLING_USAGE'])
+ end
+
+ it 'honors the optional :schema filter' do
+ allow(tables_stmt).to receive(:fetch_all).and_return([
+ ['BILLING_POC', 'PUBLIC', 'A', 'TABLE', nil],
+ ['BILLING_POC', 'PRIVATE', 'B', 'TABLE', nil]
+ ])
+ ds = described_class.new(
+ conn_str: 'DRIVER={Snowflake};X=1',
+ schema: 'PRIVATE',
+ pool_size: 1
+ )
+ expect(ds.collections.keys).to eq(['B'])
+ end
+ end
+
+ describe '#with_connection' do
+ it 'yields a connection from the pool' do
+ datasource.with_connection do |conn|
+ expect(conn).to be(odbc_connection)
+ end
+ end
+ end
+
+ describe 'connection pool' do
+ it 'wraps connections in a ConnectionPool with the configured size' do
+ expect(datasource.pool).to be_a(ConnectionPool)
+ end
+ end
+
+ describe 'session settings' do
+ let(:alter_stmt) { instance_double('ODBC::Statement', drop: nil, execute: nil) }
+
+ it 'always normalizes the session timezone to UTC so TIMESTAMP_LTZ/TZ serialize consistently' do
+ expect(odbc_connection).to receive(:prepare)
+ .with("ALTER SESSION SET TIMEZONE = 'UTC'").and_return(alter_stmt)
+
+ described_class.new(conn_str: 'DRIVER={X}', pool_size: 1)
+ end
+
+ it 'runs ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS on each new connection when set' do
+ expect(odbc_connection).to receive(:prepare)
+ .with('ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = 60').and_return(alter_stmt)
+
+ described_class.new(
+ conn_str: 'DRIVER={X}',
+ pool_size: 1,
+ statement_timeout: 60
+ )
+ end
+
+ it 'does not run STATEMENT_TIMEOUT_IN_SECONDS when statement_timeout is nil' do
+ expect(odbc_connection).not_to receive(:prepare).with(/STATEMENT_TIMEOUT/)
+ described_class.new(conn_str: 'DRIVER={X}', pool_size: 1)
+ end
+ end
+
+ describe '#fetch_snowflake_native_types' do
+ it 'returns COLUMN_NAME => DATA_TYPE from INFORMATION_SCHEMA.COLUMNS' do
+ stmt = instance_double('ODBC::Statement', drop: nil, execute: nil)
+ allow(odbc_connection).to receive(:prepare).with(/INFORMATION_SCHEMA\.COLUMNS/).and_return(stmt)
+ allow(stmt).to receive(:fetch_all).and_return([%w[META VARIANT], %w[BLOB BINARY]])
+
+ expect(datasource.fetch_snowflake_native_types('billing_usage')).to eq(
+ 'META' => 'VARIANT',
+ 'BLOB' => 'BINARY'
+ )
+ end
+
+ it 'returns an empty hash when the query errors (lacking permissions, etc.)' do
+ stmt = instance_double('ODBC::Statement', drop: nil)
+ allow(odbc_connection).to receive(:prepare).with(/INFORMATION_SCHEMA\.COLUMNS/).and_return(stmt)
+ allow(stmt).to receive(:execute).and_raise(ODBC::Error, 'permission denied')
+
+ expect(datasource.fetch_snowflake_native_types('billing_usage')).to eq({})
+ end
+ end
+
+ describe 'connection retry on lost connections' do
+ it 'retries the block exactly once after a connection-lost ODBC error' do
+ attempts = 0
+ datasource
+
+ result = datasource.with_connection do |_conn|
+ attempts += 1
+ raise ODBC::Error, 'Communication link failure' if attempts == 1
+
+ :recovered
+ end
+
+ expect(result).to eq(:recovered)
+ expect(attempts).to eq(2)
+ end
+
+ it 'cycles the pool between attempts so stale connections get closed' do
+ datasource
+ expect(datasource.pool).to receive(:reload).and_call_original
+
+ attempts = 0
+ datasource.with_connection do |_conn|
+ attempts += 1
+ raise ODBC::Error, 'Connection is closed' if attempts == 1
+ end
+ end
+
+ it 'retries on Snowflake auth token expiry so a fresh connection re-authenticates' do
+ datasource
+ attempts = 0
+
+ result = datasource.with_connection do |_conn|
+ attempts += 1
+ raise ODBC::Error, '08001 (390114) Authentication token has expired.' if attempts == 1
+
+ :reauthed
+ end
+
+ expect(result).to eq(:reauthed)
+ expect(attempts).to eq(2)
+ end
+
+ it 'does not retry on errors that are not connection-related' do
+ datasource
+ attempts = 0
+
+ expect do
+ datasource.with_connection do |_conn|
+ attempts += 1
+ raise ODBC::Error, 'Syntax error at end of input'
+ end
+ end.to raise_error(ODBC::Error, /Syntax error/)
+
+ expect(attempts).to eq(1)
+ end
+
+ it 'gives up after one retry and re-raises' do
+ datasource
+ attempts = 0
+
+ expect do
+ datasource.with_connection do |_conn|
+ attempts += 1
+ raise ODBC::Error, 'Communication link failure'
+ end
+ end.to raise_error(ODBC::Error)
+
+ expect(attempts).to eq(2)
+ end
+ end
+
+ describe 'introspect_relations' do
+ let(:relation_stmt) { instance_double('ODBC::Statement', drop: nil) }
+
+ let(:imported_keys_row) do
+ [Time.now, 'DB', 'PUBLIC', 'INTERNAL_LOG', 'ID',
+ 'DB', 'PUBLIC', 'BILLING_USAGE', 'CUSTOMER_ID',
+ 1, 'NO ACTION', 'NO ACTION', 'fk1', 'pk1', 'NOT_DEFERRABLE', 'false', '']
+ end
+
+ before do
+ allow(odbc_connection).to receive(:prepare)
+ .with('SHOW IMPORTED KEYS IN SCHEMA').and_return(relation_stmt)
+ allow(relation_stmt).to receive(:execute)
+ allow(relation_stmt).to receive(:fetch_all).and_return([imported_keys_row])
+ end
+
+ it 'adds a ManyToOne field on the source collection per discovered FK' do
+ ds = described_class.new(
+ conn_str: 'DRIVER={X}',
+ pool_size: 1,
+ introspect_relations: true
+ )
+
+ source = ds.get_collection('BILLING_USAGE')
+ relation = source.schema[:fields]['customer_id_internal_log']
+ expect(relation).to be_a(ForestAdminDatasourceToolkit::Schema::Relations::ManyToOneSchema)
+ expect(relation.foreign_collection).to eq('INTERNAL_LOG')
+ expect(relation.foreign_key).to eq('CUSTOMER_ID')
+ expect(relation.foreign_key_target).to eq('ID')
+ end
+
+ it 'silently skips when the FK introspection query errors (e.g. permissions)' do
+ allow(relation_stmt).to receive(:execute).and_raise(ODBC::Error, 'permission denied')
+
+ expect do
+ described_class.new(
+ conn_str: 'DRIVER={X}',
+ pool_size: 1,
+ introspect_relations: true
+ )
+ end.not_to raise_error
+ end
+
+ it 'is off by default - no FK query runs unless introspect_relations: true' do
+ expect(odbc_connection).not_to receive(:prepare).with('SHOW IMPORTED KEYS IN SCHEMA')
+ described_class.new(conn_str: 'DRIVER={X}', pool_size: 1)
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/parser/column_spec.rb b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/parser/column_spec.rb
new file mode 100644
index 000000000..00092ddc9
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/parser/column_spec.rb
@@ -0,0 +1,88 @@
+require 'spec_helper'
+
+RSpec.describe ForestAdminDatasourceSnowflake::Parser::Column do
+ describe '.forest_type_for' do
+ {
+ ODBC::SQL_BIT => 'Boolean',
+ ODBC::SQL_INTEGER => 'Number',
+ ODBC::SQL_DECIMAL => 'Number',
+ ODBC::SQL_DOUBLE => 'Number',
+ ODBC::SQL_TYPE_DATE => 'Dateonly',
+ ODBC::SQL_TYPE_TIMESTAMP => 'Date',
+ ODBC::SQL_TYPE_TIME => 'Time',
+ ODBC::SQL_VARCHAR => 'String',
+ ODBC::SQL_LONGVARCHAR => 'String',
+ ODBC::SQL_VARBINARY => 'Binary',
+ ODBC::SQL_GUID => 'Uuid',
+ 2004 => 'Json'
+ }.each do |odbc_type, expected_forest_type|
+ it "maps ODBC type #{odbc_type} to '#{expected_forest_type}'" do
+ expect(described_class.forest_type_for(odbc_type)).to eq(expected_forest_type)
+ end
+ end
+
+ it "falls back to 'String' for unknown types" do
+ expect(described_class.forest_type_for(99_999)).to eq('String')
+ end
+ end
+
+ describe '.forest_type_for_snowflake_native' do
+ {
+ 'VARIANT' => 'Json',
+ 'OBJECT' => 'Json',
+ 'ARRAY' => 'Json',
+ 'BINARY' => 'Binary',
+ 'VARBINARY' => 'Binary'
+ }.each do |native_type, expected_forest_type|
+ it "maps Snowflake native type '#{native_type}' to '#{expected_forest_type}'" do
+ expect(described_class.forest_type_for_snowflake_native(native_type)).to eq(expected_forest_type)
+ end
+ end
+
+ it 'is case-insensitive' do
+ expect(described_class.forest_type_for_snowflake_native('variant')).to eq('Json')
+ end
+
+ it 'returns nil for types not in the override list (let ODBC mapping take over)' do
+ expect(described_class.forest_type_for_snowflake_native('NUMBER')).to be_nil
+ expect(described_class.forest_type_for_snowflake_native('TIMESTAMP_NTZ')).to be_nil
+ expect(described_class.forest_type_for_snowflake_native(nil)).to be_nil
+ end
+ end
+
+ describe '.operators_for_column_type' do
+ let(:base_operators) { [Operators::PRESENT, Operators::BLANK, Operators::MISSING] }
+
+ it 'returns only base operators for unknown / non-string input' do
+ expect(described_class.operators_for_column_type(nil)).to match_array(base_operators)
+ end
+
+ it 'includes equality + ordering for Number' do
+ ops = described_class.operators_for_column_type('Number')
+ expect(ops).to include(*base_operators)
+ expect(ops).to include(Operators::EQUAL, Operators::NOT_EQUAL, Operators::IN, Operators::NOT_IN)
+ expect(ops).to include(Operators::LESS_THAN, Operators::GREATER_THAN)
+ expect(ops).not_to include(Operators::CONTAINS, Operators::LIKE)
+ end
+
+ it 'includes equality for Boolean but no ordering or string ops' do
+ ops = described_class.operators_for_column_type('Boolean')
+ expect(ops).to include(Operators::EQUAL, Operators::NOT_EQUAL)
+ expect(ops).not_to include(Operators::LESS_THAN, Operators::CONTAINS)
+ end
+
+ it 'includes string-specific operators for String' do
+ ops = described_class.operators_for_column_type('String')
+ expect(ops).to include(Operators::CONTAINS, Operators::I_CONTAINS, Operators::STARTS_WITH, Operators::LIKE,
+ Operators::I_LIKE, Operators::SHORTER_THAN, Operators::LONGER_THAN)
+ end
+
+ it 'includes ordering for Date / Dateonly / Time' do
+ %w[Date Dateonly Time].each do |type|
+ ops = described_class.operators_for_column_type(type)
+ expect(ops).to include(Operators::LESS_THAN, Operators::GREATER_THAN, Operators::EQUAL),
+ "expected ordering ops for #{type}"
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/identifier_spec.rb b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/identifier_spec.rb
new file mode 100644
index 000000000..447f25b51
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/identifier_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+RSpec.describe ForestAdminDatasourceSnowflake::Utils::Identifier do
+ describe '.quote' do
+ it 'wraps barewords in double quotes' do
+ expect(described_class.quote('billing_usage')).to eq('"billing_usage"')
+ end
+
+ it 'preserves the case of the input (Snowflake folding only applies to UNquoted)' do
+ expect(described_class.quote('BILLING_USAGE')).to eq('"BILLING_USAGE"')
+ expect(described_class.quote('Billing_Usage')).to eq('"Billing_Usage"')
+ end
+
+ it 'escapes embedded double quotes by doubling them' do
+ expect(described_class.quote('weird"name')).to eq('"weird""name"')
+ end
+
+ it 'accepts symbols and stringifies them first' do
+ expect(described_class.quote(:id)).to eq('"id"')
+ end
+
+ it "passes the literal '*' through unmodified for SELECT */COUNT(*)" do
+ expect(described_class.quote('*')).to eq('*')
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/query_spec.rb b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/query_spec.rb
new file mode 100644
index 000000000..e5cd08776
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/lib/forest_admin_datasource_snowflake/utils/query_spec.rb
@@ -0,0 +1,172 @@
+require 'spec_helper'
+
+RSpec.describe ForestAdminDatasourceSnowflake::Utils::Query do
+ let(:collection) { instance_double('Collection', table_name: 'BILLING_USAGE') }
+
+ describe '#to_sql' do
+ it 'selects projected columns from the table when no filter is given' do
+ sql, binds = described_class.new(
+ collection,
+ projection: Projection.new(%w[id customer_id amount_cents])
+ ).to_sql
+
+ expect(sql).to eq('SELECT "id", "customer_id", "amount_cents" FROM "BILLING_USAGE"')
+ expect(binds).to eq([])
+ end
+
+ it 'selects * when projection is missing' do
+ sql, = described_class.new(collection).to_sql
+ expect(sql).to eq('SELECT * FROM "BILLING_USAGE"')
+ end
+
+ it 'translates a single equal leaf to a parameterized WHERE with quoted column' do
+ filter = Filter.new(
+ condition_tree: ConditionTreeLeaf.new('CUSTOMER_ID', Operators::EQUAL, 42)
+ )
+ sql, binds = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to eq('SELECT "id" FROM "BILLING_USAGE" WHERE "CUSTOMER_ID" = ?')
+ expect(binds).to eq([42])
+ end
+
+ it 'composes branches with AND/OR and bind values in declaration order' do
+ gt_amount = ConditionTreeLeaf.new('AMOUNT', Operators::GREATER_THAN, 1000)
+ in_customer = ConditionTreeLeaf.new('CUSTOMER', Operators::IN, [1, 2, 3])
+ or_branch = ConditionTreeBranch.new('Or', [gt_amount, in_customer])
+ eq_status = ConditionTreeLeaf.new('STATUS', Operators::EQUAL, 'paid')
+ filter = Filter.new(condition_tree: ConditionTreeBranch.new('And', [eq_status, or_branch]))
+ sql, binds = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to eq(
+ 'SELECT "id" FROM "BILLING_USAGE" WHERE ("STATUS" = ? AND ("AMOUNT" > ? OR "CUSTOMER" IN (?, ?, ?)))'
+ )
+ expect(binds).to eq(['paid', 1000, 1, 2, 3])
+ end
+
+ it 'translates IN with empty list to an always-false predicate' do
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('id', Operators::IN, []))
+ sql, binds = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to eq('SELECT "id" FROM "BILLING_USAGE" WHERE 1=0')
+ expect(binds).to eq([])
+ end
+
+ it 'translates I_CONTAINS into a case-insensitive LIKE with wildcards' do
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('EVENT_TYPE', Operators::I_CONTAINS, 'login'))
+ sql, binds = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to include('LOWER("EVENT_TYPE") LIKE LOWER(?)')
+ expect(binds).to eq(['%login%'])
+ end
+
+ it 'translates STARTS_WITH and ENDS_WITH with the right wildcards' do
+ sw = Filter.new(condition_tree: ConditionTreeLeaf.new('NAME', Operators::STARTS_WITH, 'foo'))
+ ew = Filter.new(condition_tree: ConditionTreeLeaf.new('NAME', Operators::ENDS_WITH, 'bar'))
+
+ sw_sql, sw_binds = described_class.new(collection, projection: Projection.new(['id']), filter: sw).to_sql
+ ew_sql, ew_binds = described_class.new(collection, projection: Projection.new(['id']), filter: ew).to_sql
+
+ expect(sw_sql).to include('"NAME" LIKE ?')
+ expect(ew_sql).to include('"NAME" LIKE ?')
+ expect(sw_binds).to eq(['foo%'])
+ expect(ew_binds).to eq(['%bar'])
+ end
+
+ it 'translates PRESENT / MISSING / BLANK without bind values' do
+ [Operators::PRESENT, Operators::MISSING, Operators::BLANK].each do |op|
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('id', op, nil))
+ _, binds = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+ expect(binds).to eq([]), "expected no binds for #{op}"
+ end
+ end
+
+ it 'appends ORDER BY for sort directives, with quoted columns' do
+ filter = Filter.new(sort: [{ field: 'OCCURRED_AT', ascending: false }, { field: 'id', ascending: true }])
+ sql, = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to end_with('ORDER BY "OCCURRED_AT" DESC, "id" ASC')
+ end
+
+ it 'appends LIMIT and OFFSET when filter has a Page' do
+ filter = Filter.new(page: Page.new(offset: 30, limit: 15))
+ sql, = described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+
+ expect(sql).to end_with('LIMIT 15 OFFSET 30')
+ end
+
+ it 'rejects operators that the toolkit allows but our translator does not yet implement' do
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('id', Operators::MATCH, /foo/))
+ expect do
+ described_class.new(collection, projection: Projection.new(['id']), filter: filter).to_sql
+ end.to raise_error(ForestAdminDatasourceSnowflake::Error, /Unsupported operator/)
+ end
+
+ it 'quotes identifiers containing reserved words or special chars correctly' do
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('order', Operators::EQUAL, 1))
+ sql, = described_class.new(collection, projection: Projection.new(['select']), filter: filter).to_sql
+
+ expect(sql).to include('"order" = ?')
+ expect(sql).to include('"select"')
+ end
+ end
+
+ describe '#to_aggregate_sql' do
+ it 'builds COUNT(*) with no group_by' do
+ sql, binds, groups = described_class.new(
+ collection,
+ aggregation: Aggregation.new(operation: 'Count')
+ ).to_aggregate_sql
+
+ expect(sql).to eq('SELECT COUNT(*) FROM "BILLING_USAGE"')
+ expect(binds).to eq([])
+ expect(groups).to eq([])
+ end
+
+ it 'builds SUM with WHERE and GROUP BY, returns group columns alongside SQL' do
+ filter = Filter.new(condition_tree: ConditionTreeLeaf.new('STATUS', Operators::EQUAL, 'paid'))
+ sql, binds, groups = described_class.new(
+ collection,
+ filter: filter,
+ aggregation: Aggregation.new(
+ operation: 'Sum', field: 'AMOUNT_CENTS',
+ groups: [{ field: 'CUSTOMER_ID' }]
+ )
+ ).to_aggregate_sql
+
+ expect(sql).to eq(
+ 'SELECT SUM("AMOUNT_CENTS"), "CUSTOMER_ID" FROM "BILLING_USAGE" WHERE "STATUS" = ? GROUP BY "CUSTOMER_ID"'
+ )
+ expect(binds).to eq(['paid'])
+ expect(groups).to eq(['CUSTOMER_ID'])
+ end
+
+ it 'caps results when limit is provided' do
+ sql, = described_class.new(
+ collection,
+ aggregation: Aggregation.new(operation: 'Count', groups: [{ field: 'STATUS' }]),
+ limit: 5
+ ).to_aggregate_sql
+
+ expect(sql).to end_with('LIMIT 5')
+ end
+
+ it 'rejects aggregation operations the toolkit allows but our translator does not implement' do
+ agg = instance_double('Aggregation', operation: 'Variance', field: 'x', groups: [])
+ expect do
+ described_class.new(collection, aggregation: agg).to_aggregate_sql
+ end.to raise_error(ForestAdminDatasourceSnowflake::Error, /Unsupported aggregation/)
+ end
+
+ it 'rejects SUM/AVG/MIN/MAX without a field rather than emitting invalid SQL like SUM()' do
+ %w[Sum Avg Min Max].each do |op|
+ expect do
+ described_class.new(
+ collection,
+ aggregation: Aggregation.new(operation: op)
+ ).to_aggregate_sql
+ end.to raise_error(ForestAdminDatasourceSnowflake::Error, /requires a field/),
+ "expected #{op} without field to raise"
+ end
+ end
+ end
+end
diff --git a/packages/forest_admin_datasource_snowflake/spec/spec_helper.rb b/packages/forest_admin_datasource_snowflake/spec/spec_helper.rb
new file mode 100644
index 000000000..9a4777aa5
--- /dev/null
+++ b/packages/forest_admin_datasource_snowflake/spec/spec_helper.rb
@@ -0,0 +1,36 @@
+require 'simplecov'
+require 'simplecov_json_formatter'
+require 'simplecov-html'
+require 'forest_admin_datasource_toolkit'
+require 'forest_admin_datasource_snowflake'
+
+SimpleCov.formatters = [SimpleCov::Formatter::JSONFormatter, SimpleCov::Formatter::HTMLFormatter]
+SimpleCov.start do
+ add_filter 'spec'
+end
+
+SimpleCov.coverage_dir 'coverage'
+SimpleCov.at_exit do
+ result = SimpleCov.result
+ result.format!
+end
+
+Filter = ForestAdminDatasourceToolkit::Components::Query::Filter
+Page = ForestAdminDatasourceToolkit::Components::Query::Page
+Projection = ForestAdminDatasourceToolkit::Components::Query::Projection
+Aggregation = ForestAdminDatasourceToolkit::Components::Query::Aggregation
+Operators = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Operators
+ConditionTreeLeaf = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Nodes::ConditionTreeLeaf
+ConditionTreeBranch = ForestAdminDatasourceToolkit::Components::Query::ConditionTree::Nodes::ConditionTreeBranch
+
+RSpec.configure do |config|
+ config.expect_with :rspec do |c|
+ c.syntax = :expect
+ end
+
+ config.example_status_persistence_file_path = '.rspec_status'
+ config.disable_monkey_patching!
+ config.warnings = false
+ config.order = :random
+ Kernel.srand config.seed
+end