packages feed

dataframe-persistent 0.2.0.0 → 0.3.0.0

raw patch · 14 files changed

+1606/−838 lines, 14 filesdep +conduitdep +dataframe-coredep +dataframe-operationsdep ~bytestringdep ~dataframedep ~resourcetPVP ok

version bump matches the API change (PVP)

Dependencies added: conduit, dataframe-core, dataframe-operations

Dependency ranges changed: bytestring, dataframe, resourcet

API changes (from Hackage documentation)

+ DataFrame.IO.Persistent.Read: ColumnInfo :: Text -> Text -> Bool -> Bool -> ColumnInfo
+ DataFrame.IO.Persistent.Read: ReadQuery :: Maybe Text -> [PersistValue] -> Maybe Text -> Maybe Int -> Maybe Int -> ReadQuery
+ DataFrame.IO.Persistent.Read: [ciDeclType] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Read: [ciName] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Read: [ciNotNull] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Read: [ciPk] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Read: [rqLimit] :: ReadQuery -> Maybe Int
+ DataFrame.IO.Persistent.Read: [rqOffset] :: ReadQuery -> Maybe Int
+ DataFrame.IO.Persistent.Read: [rqOrderBy] :: ReadQuery -> Maybe Text
+ DataFrame.IO.Persistent.Read: [rqParams] :: ReadQuery -> [PersistValue]
+ DataFrame.IO.Persistent.Read: [rqWhere] :: ReadQuery -> Maybe Text
+ DataFrame.IO.Persistent.Read: allRows :: ReadQuery
+ DataFrame.IO.Persistent.Read: buildColumn :: (Columnable a, PersistField a) => ColumnReader
+ DataFrame.IO.Persistent.Read: buildNullableColumn :: (Columnable (Maybe a), PersistField a) => ColumnReader
+ DataFrame.IO.Persistent.Read: data ColumnInfo
+ DataFrame.IO.Persistent.Read: data ReadQuery
+ DataFrame.IO.Persistent.Read: describeTable :: FilePath -> Text -> IO DataFrame
+ DataFrame.IO.Persistent.Read: describeTableConn :: forall (m :: Type -> Type). MonadResource m => Text -> ReaderT SqlBackend m DataFrame
+ DataFrame.IO.Persistent.Read: freezeOrThrow :: forall (cols :: [Type]) m. (KnownSchema cols, MonadIO m) => DataFrame -> m (TypedDataFrame cols)
+ DataFrame.IO.Persistent.Read: inferColumn :: [PersistValue] -> Column
+ DataFrame.IO.Persistent.Read: instance GHC.Classes.Eq DataFrame.IO.Persistent.Read.ReadQuery
+ DataFrame.IO.Persistent.Read: instance GHC.Show.Show DataFrame.IO.Persistent.Read.ReadQuery
+ DataFrame.IO.Persistent.Read: limit :: Int -> ReadQuery -> ReadQuery
+ DataFrame.IO.Persistent.Read: listTables :: FilePath -> IO [Text]
+ DataFrame.IO.Persistent.Read: listTablesConn :: forall (m :: Type -> Type). MonadResource m => ReaderT SqlBackend m [Text]
+ DataFrame.IO.Persistent.Read: orderBy :: Text -> ReadQuery -> ReadQuery
+ DataFrame.IO.Persistent.Read: readSql :: FilePath -> Text -> IO DataFrame
+ DataFrame.IO.Persistent.Read: readSqlTyped :: forall (cols :: [Type]). KnownSchema cols => FilePath -> Text -> IO (TypedDataFrame cols)
+ DataFrame.IO.Persistent.Read: readSqlWith :: FilePath -> Text -> [PersistValue] -> IO DataFrame
+ DataFrame.IO.Persistent.Read: readTable :: FilePath -> Text -> IO DataFrame
+ DataFrame.IO.Persistent.Read: readTableConn :: forall (m :: Type -> Type). MonadResource m => Text -> ReaderT SqlBackend m DataFrame
+ DataFrame.IO.Persistent.Read: readTableConnWith :: forall (m :: Type -> Type). MonadResource m => Text -> ReadQuery -> ReaderT SqlBackend m DataFrame
+ DataFrame.IO.Persistent.Read: readTableTyped :: forall (cols :: [Type]). KnownSchema cols => FilePath -> Text -> IO (TypedDataFrame cols)
+ DataFrame.IO.Persistent.Read: readTableTypedConn :: forall (cols :: [Type]) (m :: Type -> Type). (KnownSchema cols, MonadResource m) => Text -> ReaderT SqlBackend m (TypedDataFrame cols)
+ DataFrame.IO.Persistent.Read: readTableWith :: FilePath -> Text -> ReadQuery -> IO DataFrame
+ DataFrame.IO.Persistent.Read: selectToDataFrame :: forall r (m :: Type -> Type). (MonadIO m, PersistEntity r, PersistEntityBackend r ~ SqlBackend) => [Filter r] -> [SelectOpt r] -> ReaderT SqlBackend m DataFrame
+ DataFrame.IO.Persistent.Read: type ColumnReader = [PersistValue] -> Column
+ DataFrame.IO.Persistent.Read: where_ :: Text -> [PersistValue] -> ReadQuery -> ReadQuery
+ DataFrame.IO.Persistent.Read.Columns: buildColumn :: (Columnable a, PersistField a) => ColumnReader
+ DataFrame.IO.Persistent.Read.Columns: buildNullableColumn :: (Columnable (Maybe a), PersistField a) => ColumnReader
+ DataFrame.IO.Persistent.Read.Columns: columnReaderFor :: HaskellType -> Bool -> ColumnReader
+ DataFrame.IO.Persistent.Read.Columns: freezeOrThrow :: forall (cols :: [Type]) m. (KnownSchema cols, MonadIO m) => DataFrame -> m (TypedDataFrame cols)
+ DataFrame.IO.Persistent.Read.Columns: inferColumn :: [PersistValue] -> Column
+ DataFrame.IO.Persistent.Read.Columns: type ColumnReader = [PersistValue] -> Column
+ DataFrame.IO.Persistent.Read.Sqlite: runNamedQuery :: Text -> Text -> [PersistValue] -> IO ([Text], [[PersistValue]])
+ DataFrame.IO.Persistent.Schema: ColumnInfo :: Text -> Text -> Bool -> Bool -> ColumnInfo
+ DataFrame.IO.Persistent.Schema: DeclareOptions :: Bool -> (Text -> Text -> Maybe HaskellType) -> Maybe [Text] -> [Text] -> Maybe String -> Maybe String -> DeclareOptions
+ DataFrame.IO.Persistent.Schema: HTBool :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTByteString :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTDay :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTDouble :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTInt :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTText :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTTimeOfDay :: HaskellType
+ DataFrame.IO.Persistent.Schema: HTUTCTime :: HaskellType
+ DataFrame.IO.Persistent.Schema: [ciDeclType] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Schema: [ciName] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Schema: [ciNotNull] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Schema: [ciPk] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Schema: [entityName] :: DeclareOptions -> Maybe String
+ DataFrame.IO.Persistent.Schema: [excludeColumns] :: DeclareOptions -> [Text]
+ DataFrame.IO.Persistent.Schema: [honorNotNull] :: DeclareOptions -> Bool
+ DataFrame.IO.Persistent.Schema: [includeColumns] :: DeclareOptions -> Maybe [Text]
+ DataFrame.IO.Persistent.Schema: [schemaTypeName] :: DeclareOptions -> Maybe String
+ DataFrame.IO.Persistent.Schema: [typeOverride] :: DeclareOptions -> Text -> Text -> Maybe HaskellType
+ DataFrame.IO.Persistent.Schema: data ColumnInfo
+ DataFrame.IO.Persistent.Schema: data DeclareOptions
+ DataFrame.IO.Persistent.Schema: data HaskellType
+ DataFrame.IO.Persistent.Schema: declareEntity :: FilePath -> String -> Q [Dec]
+ DataFrame.IO.Persistent.Schema: declareEntityWith :: DeclareOptions -> FilePath -> String -> Q [Dec]
+ DataFrame.IO.Persistent.Schema: declareTable :: FilePath -> String -> Q [Dec]
+ DataFrame.IO.Persistent.Schema: declareTableFromSchema :: [ColumnInfo] -> String -> Q [Dec]
+ DataFrame.IO.Persistent.Schema: declareTableWith :: DeclareOptions -> FilePath -> String -> Q [Dec]
+ DataFrame.IO.Persistent.Schema: defaultDeclareOptions :: DeclareOptions
+ DataFrame.IO.Persistent.Schema.Common: DeclareOptions :: Bool -> (Text -> Text -> Maybe HaskellType) -> Maybe [Text] -> [Text] -> Maybe String -> Maybe String -> DeclareOptions
+ DataFrame.IO.Persistent.Schema.Common: [entityName] :: DeclareOptions -> Maybe String
+ DataFrame.IO.Persistent.Schema.Common: [excludeColumns] :: DeclareOptions -> [Text]
+ DataFrame.IO.Persistent.Schema.Common: [honorNotNull] :: DeclareOptions -> Bool
+ DataFrame.IO.Persistent.Schema.Common: [includeColumns] :: DeclareOptions -> Maybe [Text]
+ DataFrame.IO.Persistent.Schema.Common: [schemaTypeName] :: DeclareOptions -> Maybe String
+ DataFrame.IO.Persistent.Schema.Common: [typeOverride] :: DeclareOptions -> Text -> Text -> Maybe HaskellType
+ DataFrame.IO.Persistent.Schema.Common: data DeclareOptions
+ DataFrame.IO.Persistent.Schema.Common: defaultDeclareOptions :: DeclareOptions
+ DataFrame.IO.Persistent.Schema.Common: entityNameOf :: DeclareOptions -> Text -> String
+ DataFrame.IO.Persistent.Schema.Common: fieldIdentifier :: Text -> Text
+ DataFrame.IO.Persistent.Schema.Common: introspectQ :: FilePath -> String -> Q [ColumnInfo]
+ DataFrame.IO.Persistent.Schema.Common: isNullable :: DeclareOptions -> ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Schema.Common: pascalCase :: Text -> String
+ DataFrame.IO.Persistent.Schema.Common: persistType :: HaskellType -> Text
+ DataFrame.IO.Persistent.Schema.Common: resolvedType :: DeclareOptions -> ColumnInfo -> HaskellType
+ DataFrame.IO.Persistent.Schema.Common: schemaTypeNameOf :: DeclareOptions -> Text -> String
+ DataFrame.IO.Persistent.Schema.Common: selectColumns :: DeclareOptions -> [ColumnInfo] -> [ColumnInfo]
+ DataFrame.IO.Persistent.Schema.Common: thType :: HaskellType -> Type
+ DataFrame.IO.Persistent.Schema.Common: warnOnNumeric :: [ColumnInfo] -> Q ()
+ DataFrame.IO.Persistent.Schema.Introspect: ColumnInfo :: Text -> Text -> Bool -> Bool -> ColumnInfo
+ DataFrame.IO.Persistent.Schema.Introspect: HTBool :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTByteString :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTDay :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTDouble :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTInt :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTText :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTTimeOfDay :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: HTUTCTime :: HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: [ciDeclType] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Schema.Introspect: [ciName] :: ColumnInfo -> Text
+ DataFrame.IO.Persistent.Schema.Introspect: [ciNotNull] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Schema.Introspect: [ciPk] :: ColumnInfo -> Bool
+ DataFrame.IO.Persistent.Schema.Introspect: data ColumnInfo
+ DataFrame.IO.Persistent.Schema.Introspect: data HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: haskellTypeName :: HaskellType -> Text
+ DataFrame.IO.Persistent.Schema.Introspect: inferType :: Text -> HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: instance GHC.Classes.Eq DataFrame.IO.Persistent.Schema.Introspect.ColumnInfo
+ DataFrame.IO.Persistent.Schema.Introspect: instance GHC.Classes.Eq DataFrame.IO.Persistent.Schema.Introspect.HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: instance GHC.Show.Show DataFrame.IO.Persistent.Schema.Introspect.ColumnInfo
+ DataFrame.IO.Persistent.Schema.Introspect: instance GHC.Show.Show DataFrame.IO.Persistent.Schema.Introspect.HaskellType
+ DataFrame.IO.Persistent.Schema.Introspect: introspectTable :: FilePath -> String -> IO [ColumnInfo]
+ DataFrame.IO.Persistent.Schema.Introspect: introspectTableConn :: forall (m :: Type -> Type). MonadResource m => Text -> ReaderT SqlBackend m [ColumnInfo]
+ DataFrame.IO.Persistent.Schema.Introspect: introspectTableNames :: FilePath -> IO [Text]
+ DataFrame.IO.Persistent.Schema.Introspect: introspectTableNamesConn :: forall (m :: Type -> Type). MonadResource m => ReaderT SqlBackend m [Text]
+ DataFrame.IO.Persistent.Schema.Introspect: quoteIdent :: Text -> Text
+ DataFrame.IO.Persistent.Schema.Introspect: runRawRows :: forall (m :: Type -> Type). MonadResource m => Text -> [PersistValue] -> ReaderT SqlBackend m [[PersistValue]]

Files

LICENSE view
@@ -1,674 +1,20 @@-                    GNU GENERAL PUBLIC LICENSE-                       Version 3, 29 June 2007-- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>- 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 <https://www.gnu.org/licenses/>.--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:--    <program>  Copyright (C) <year>  <name of author>-    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.+Copyright (c) 2026 Michael Chavinda -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".+Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions: -  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-<https://www.gnu.org/licenses/>.+The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software. -  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-<https://www.gnu.org/licenses/why-not-lgpl.html>.+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
README.md view
@@ -1,177 +1,415 @@+<!--+  This file is the runnable scripths source for dataframe-persistent's README.+  Every ```haskell block executes in order in one shared session against+  ./data/chinook.db. Regenerate the rendered README with:++      scripths docs/base_scripts/base_readme.md -o README.md++  Run it from THIS directory (dataframe-persistent/) so ./data/... resolves and+  the local package is picked up. Every ```haskell block runs, including the+  compile-time $(declareTable ...) / $(declareEntity ...) splices.+-->+ # dataframe-persistent -Persistent database integration for the Haskell DataFrame library.+Load SQLite into a [`dataframe`](https://hackage.haskell.org/package/dataframe). The schema is read+for you: at runtime when you're exploring, or at compile time when you want type safety. You don't+write a `persistent` entity, a `persistLowerCase` block, or any instances. -## Overview+> **This README is a runnable [scripths](https://github.com/DataHaskell/scripths) notebook.**+> Every Haskell block runs top-to-bottom in one shared session against+> [`./data/chinook.db`](./data/chinook.db). Reproduce every output below with+> `scripths docs/base_scripts/base_readme.md -o README.md` run from `dataframe-persistent/`. -This package provides seamless integration between the `dataframe` library and the `persistent` database library, allowing you to:+## Three ways in -- Load database entities directly into DataFrames-- Perform DataFrame operations on database data  -- Save DataFrame results back to the database-- Work with type-safe database entities+| Tier | You write | You get |+|------|-----------|---------|+| **Runtime** | `readTable db "artists"` | a `DataFrame`, types inferred from the schema |+| **Typed** | `$(declareTable db "artists")` + `readTableTyped @Schema` | a compile-time schema type; columns checked by `col @"Name"` |+| **Persistent** | `$(declareEntity db "artists")` | a full `persistent` entity: typed `Filter` DSL, write-back | -## Installation+## Tier 0: runtime reads -Add to your `package.yaml`:+This is the quickest way in, similar to pandas' `read_sql_table` / `read_sql`. You point at a file+and a table. -```yaml-dependencies:-- dataframe ^>= 0.4-- dataframe-persistent ^>= 0.1-- persistent >= 2.14-- persistent-sqlite >= 2.13  # or your preferred backend+```haskell+-- cabal: build-depends: dataframe, dataframe-persistent, text+-- cabal: default-extensions: OverloadedStrings, TemplateHaskell, DataKinds+-- cabal: default-extensions: TypeApplications, TypeOperators, FlexibleContexts+import qualified DataFrame as D+import DataFrame.IO.Persistent.Read+import Data.Function ((&)) ``` -Or to your `.cabal` file:+> <!-- scripths:mime text/plain --> -```cabal-build-depends:-  dataframe ^>= 0.4,-  dataframe-persistent ^>= 0.1,-  persistent >= 2.14,-  persistent-sqlite >= 2.13+What tables are in this database?++```haskell+listTables "./data/chinook.db" ``` -## Quick Start+> <!-- scripths:mime text/plain -->+> ["albums","artists","customers","employees","genres","invoice_items","invoices","media_types","playlist_track","playlists","tracks"] +`describeTable` shows a table's columns and their inferred types before you load it (it returns a+`describeColumns`-style `DataFrame`):+ ```haskell-{-# LANGUAGE DataKinds #-}-{-# LANGUAGE DerivingStrategies #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE GADTs #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE QuasiQuotes #-}-{-# LANGUAGE StandaloneDeriving #-}-{-# LANGUAGE TemplateHaskell #-}-{-# LANGUAGE TypeApplications #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE UndecidableInstances #-}+D.toMarkdown' <$> describeTable "./data/chinook.db" "artists"+``` -import Control.Monad.IO.Class (liftIO)-import Database.Persist-import Database.Persist.Sqlite-import Database.Persist.TH-import qualified DataFrame as DF-import qualified DataFrame.Functions as F-import DataFrame.IO.Persistent-import DataFrame.IO.Persistent.TH-import qualified Data.Vector as V+> <!-- scripths:mime text/plain -->+> | Column Name<br>Text | Type<br>Text | SQLite Type<br>Text | Nullable<br>Bool | Primary Key<br>Bool |+> | --------------------|--------------|---------------------|------------------|-------------------- |+> | ArtistId            | Int          | INTEGER             | False            | True                |+> | Name                | Maybe Text   | NVARCHAR(120)       | True             | False               | -import DataFrame.Functions ((.<))+Load the whole table. The column types (and nullability) come from the schema: --- Define your entities-share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|-TestUser-    name Text-    age Int-    active Bool-    deriving Show Eq-|]+```haskell+D.toMarkdown' . D.take 5 <$> readTable "./data/chinook.db" "artists"+``` --- Derive DataFrame instances-$(derivePersistentDataFrame ''TestUser)+> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int |    Name<br>Maybe Text    |+> | ----------------|------------------------- |+> | 1               | Just "AC/DC"             |+> | 2               | Just "Accept"            |+> | 3               | Just "Aerosmith"         |+> | 4               | Just "Alanis Morissette" |+> | 5               | Just "Alice In Chains"   | --- Example usage-main :: IO ()-main = runSqlite "example.db" $ do-    -- Run migrations-    runMigration migrateAll-    -    -- Insert some test data-    _ <- insert $ TestUser "Alice" 25 True-    _ <- insert $ TestUser "Bob" 30 False-    _ <- insert $ TestUser "Charlie" 35 True-    -    -- Load from database-    allUsersDF <- fromPersistent @TestUser []-    liftIO $ putStrLn $ "Loaded " ++ show (nRows allUsersDF) ++ " users"-    -    -- Load with filters-    activeUsersDF <- fromPersistent @TestUser [TestUserActive ==. True]-    liftIO $ putStrLn $ "Active users: " ++ show (nRows activeUsersDF)-    -    -- Process with DataFrame operations-    -- Expressions are automaticaly generated.-    let youngUsers = DF.filterWhere (test_user_age .< 30) allUsersDF-        ages = V.toList $ DF.columnAsVector test_user_age youngUsers-    liftIO $ putStrLn $ "Young user ages: " ++ show ages-    -    -- Custom configuration-    let config = defaultPersistentConfig -                    { pcIdColumnName = "user_id"-                    , pcIncludeId = True-                    }-    customDF <- fromPersistentWith @TestUser config []-    liftIO $ putStrLn $ "Columns with custom config: " ++ show (DF.columnNames customDF)+Tables larger than memory? Filter them in the database. Raw SQL works as you'd expect:++```haskell+D.toMarkdown' <$> readSql "./data/chinook.db" "SELECT * FROM artists WHERE Name LIKE 'A%' LIMIT 5" ``` -## Features+> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int |   Name<br>Text    |+> | ----------------|------------------ |+> | 1               | AC/DC             |+> | 2               | Accept            |+> | 3               | Aerosmith         |+> | 4               | Alanis Morissette |+> | 5               | Alice In Chains   | -- **Type-safe conversions** between Persistent entities and DataFrames-- **Template Haskell support** for automatic instance generation-- **Configurable loading** with batch size and column selection-- **Column name cleaning** - removes table prefixes automatically (e.g., `test_user_name` → `name`)-- **Automatically generate typed expressions** - creates expressions in snake case prefixed by table name (e.g `test_user_name`).-- **Type preservation** - maintains proper types for Text, Int, Bool, Day, etc.-- **Empty DataFrame support** - preserves column structure even with no data-- **Support for all Persistent backends** (SQLite, PostgreSQL, MySQL, etc.)+Or push a `WHERE` / `LIMIT` down to a named table with a `ReadQuery` value: -## Configuration Options+```haskell+D.toMarkdown' <$> readTableWith "./data/chinook.db" "artists" (allRows & limit 3)+``` +> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int | Name<br>Maybe Text |+> | ----------------|------------------- |+> | 1               | Just "AC/DC"       |+> | 2               | Just "Accept"      |+> | 3               | Just "Aerosmith"   |++## Tier 1: typed schema++`declareTable` reads the schema at compile time and emits just the schema type. You read into it+with `readTableTyped`, where the schema is a type argument and the database and table are ordinary+values. Column references go through `col @"Name"`, checked against the schema, so a typo or a wrong+type is a compile error. Nothing is keyed on a generated function name.+ ```haskell-data PersistentConfig = PersistentConfig-    { pcBatchSize :: Int        -- Number of records to fetch at once (default: 10000)-    , pcIncludeId :: Bool       -- Whether to include entity ID as column (default: True)-    , pcIdColumnName :: Text    -- Name for the ID column (default: "id")-    }+import qualified DataFrame.Typed as DT+import DataFrame.Typed ((.==.))+import DataFrame.IO.Persistent.Schema (declareTable) ``` -## Advanced Usage+> <!-- scripths:mime text/plain --> -### Custom Field Extraction+The splice brings one thing into scope, the type+`type ArtistsSchema = '[Column "ArtistId" Int, Column "Name" (Maybe Text)]`: -You can also extract fields from individual entities:+```haskell+$(declareTable "./data/chinook.db" "artists")+``` +> <!-- scripths:mime text/plain -->++`readTableTyped @ArtistsSchema` reads any database/table into a `TypedDataFrame ArtistsSchema` (it+validates the schema as it reads). You can bind your own reader:+ ```haskell-let user = TestUser "Alice" 25 True-    columns = persistFieldsToColumns user--- Result: [("name", SomeColumn ["Alice"]), ("age", SomeColumn [25]), ("active", SomeColumn [True])]+artists = readTableTyped @ArtistsSchema "./data/chinook.db" "artists" ``` -### Working with Vector Data+> <!-- scripths:mime text/plain --> +`thaw` drops a typed frame back to an untyped `DataFrame`:+ ```haskell--- Extract specific column data-let names = V.toList $ DF.columnAsVector test_user_name df-    ages = V.toList $ DF.columnAsVector test_user_age df-    activeFlags = V.toList $ DF.columnAsVector test_user_active df+D.toMarkdown' . D.take 5 . DT.thaw <$> artists ``` -## Examples+> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int |    Name<br>Maybe Text    |+> | ----------------|------------------------- |+> | 1               | Just "AC/DC"             |+> | 2               | Just "Accept"            |+> | 3               | Just "Aerosmith"         |+> | 4               | Just "Alanis Morissette" |+> | 5               | Just "Alice In Chains"   | -For comprehensive examples and test cases, see:-- [`tests/PersistentTests.hs`](tests/PersistentTests.hs) - Full test suite with examples-- [`../docs/persistent_integration.md`](../docs/persistent_integration.md) - Detailed integration guide+Column access is checked against the schema. `col @"Name"` only compiles because `"Name"` is a+column of `ArtistsSchema` (its element type is `Maybe Text`): -## Status+```haskell+DT.columnAsList @"Name" . DT.take 3 <$> artists+``` -This package is **actively maintained** and tested. Current test coverage includes:-- ✅ Entity loading with and without filters-- ✅ Custom configuration options-- ✅ DataFrame operations on Persistent data-- ✅ Empty result set handling-- ✅ Field extraction utilities-- ✅ Multi-table relationships+> <!-- scripths:mime text/plain -->+> [Just "AC/DC",Just "Accept",Just "Aerosmith"] -## Documentation+A filter on a column that doesn't exist (or has the wrong type) is a compile error rather than a+runtime surprise: -For detailed documentation, see:-- [Main dataframe documentation](https://github.com/mchav/dataframe)-- [Persistent integration guide](../docs/persistent_integration.md)+```haskell+D.toMarkdown' . DT.thaw . DT.filterWhere (DT.col @"Name" .==. DT.lit (Just "Accept")) <$> artists+``` -## License+> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int | Name<br>Maybe Text |+> | ----------------|------------------- |+> | 2               | Just "Accept"      | -GPL-3.0-or-later (same as the main dataframe package)+Because the database is a value, reading the same table from two sources to join them is just two+calls with the same `@ArtistsSchema`:++```text+a <- readTableTyped @ArtistsSchema "europe.sqlite" "artists"+b <- readTableTyped @ArtistsSchema "us.sqlite"     "artists"+-- DT.thaw a / DT.thaw b, then DataFrame.innerJoin on "ArtistId", etc.+```++(`readSqlTyped @cols db "SELECT ... JOIN ..."` does the same for an arbitrary query. The Postgres+section below reads this same `ArtistsSchema` from a different backend.)++## Tier 2: generate a `persistent` entity++If you want the full `persistent` experience (the typed `Filter` DSL, relations, write-back),+`declareEntity` builds the entity from the live schema, so you skip the `persistLowerCase` block. It+needs the usual `persistent` extensions and unqualified `Text` / `Int64` in scope:++```haskell+-- cabal: build-depends: persistent, persistent-sqlite+-- cabal: default-extensions: GADTs, TypeFamilies, FlexibleInstances, MultiParamTypeClasses+-- cabal: default-extensions: StandaloneDeriving, DerivingStrategies, GeneralizedNewtypeDeriving+-- cabal: default-extensions: UndecidableInstances+import Data.Int (Int64)+import Data.Text (Text)+import Database.Persist (Filter, SelectOpt (..), (<-.), (==.))+import Database.Persist.Sqlite (runSqlite)+import DataFrame.IO.Persistent.Schema (declareEntity)+```++> <!-- scripths:mime text/plain -->++This generates the `Albums` entity (`Id`, `title`, `artistId`), bound to the real+`albums` / `AlbumId` / `Title` / `ArtistId` SQLite names, plus its `EntityField` constructors:++```haskell+$(declareEntity "./data/chinook.db" "albums")+```++> <!-- scripths:mime text/plain -->++Now load it with `selectToDataFrame`. It's a generic loader: it works for any `persistent` entity,+so the one `declareEntity` splice is all the boilerplate.++```text+selectToDataFrame+    :: (MonadIO m, PersistEntity r, PersistEntityBackend r ~ SqlBackend)+    => [Filter r]      -- persistent's typed WHERE DSL, e.g. [AlbumsArtistId ==. 1]+    -> [SelectOpt r]   -- ordering / paging,        e.g. [Asc AlbumsTitle, LimitTo 10]+    -> ReaderT SqlBackend m DataFrame+```++It runs persistent's `selectList filters opts` and turns the `[Entity Albums]` into a `DataFrame`:+the entity key becomes an `id` column and each field becomes a column (named by its+Haskell field, e.g. `title`, `artistId`), with element types decoded from the stored values. The+`[Filter Albums]` and `[SelectOpt Albums]` you pass are persistent's own, checked against the+entity, so a filter for the wrong field won't compile.++Find AC/DC's albums (`ArtistId` 1):++```haskell+D.toMarkdown' <$> runSqlite "./data/chinook.db" (selectToDataFrame [AlbumsArtistId ==. 1] [])+```++> <!-- scripths:mime text/plain -->+> | id<br>Int |             title<br>Text             | artistId<br>Int |+> | ----------|---------------------------------------|---------------- |+> | 1         | For Those About To Rock We Salute You | 1               |+> | 4         | Let There Be Rock                     | 1               |++You can use both arguments together: filter and order/page in one query. Here are the albums by+AC/DC or Alanis Morissette (`ArtistId` 1 or 4), sorted by title, capped at 5. (`<-.` is persistent's+"field in list"; an empty filter list loads everything.)++```haskell+D.toMarkdown' <$> runSqlite "./data/chinook.db"+    (selectToDataFrame [AlbumsArtistId <-. [1, 4]] [Asc AlbumsTitle, LimitTo 5])+```++> <!-- scripths:mime text/plain -->+> | id<br>Int |             title<br>Text             | artistId<br>Int |+> | ----------|---------------------------------------|---------------- |+> | 1         | For Those About To Rock We Salute You | 1               |+> | 6         | Jagged Little Pill                    | 4               |+> | 4         | Let There Be Rock                     | 1               |++## Hand-off between dataframe and persistent++The `...Conn` readers run on a `ReaderT SqlBackend m`, so a raw read, an entity read, and ordinary+`persistent` queries all compose in one `runSqlite` transaction (this works on Postgres/MySQL too).+Here both reads share one connection and return each frame's `(rows, columns)`:++```haskell+runSqlite "./data/chinook.db" $ do+    artists <- readTableConn "artists"                       -- raw → DataFrame+    albums  <- selectToDataFrame ([] :: [Filter Albums]) []  -- entity → DataFrame+    pure (D.dimensions artists, D.dimensions albums)+```++> <!-- scripths:mime text/plain -->+> ((275,2),(347,3))++## PostgreSQL (and other backends)++Everything except the file-path helpers and the compile-time splices is backend-agnostic: the+`...Conn` readers and `selectToDataFrame` run on any `persistent` `SqlBackend`. Introspection picks+`PRAGMA` for SQLite and `information_schema` for PostgreSQL/MySQL. The library doesn't depend on+`persistent-postgresql`; you bring the connection.++These examples run against a real PostgreSQL with the same `artists` / `albums` data, and the+notebook starts it itself. The block below uses GHCi's `:!` shell escape to spin up a throwaway+cluster on port 54329 and load the two tables from the SQLite fixture. It needs `postgres` and+`sqlite3` on `PATH` (e.g. `brew install postgresql@16`). A matching teardown runs at the end of the+section.++```haskell+:! bash scripts/pg-setup.sh+```++> <!-- scripths:mime text/plain -->+> postgres ready on port 54329 (db chinook: artists + albums)++Open a connection (you supply `persistent-postgresql`; `runPg` is the usual `runSqlConn` wrapper):++```haskell+-- cabal: build-depends: persistent, persistent-postgresql, transformers, resourcet, monad-logger+import Control.Monad.Trans.Reader (ReaderT)+import Control.Monad.Trans.Resource (ResourceT, runResourceT)+import Control.Monad.Logger (NoLoggingT, runNoLoggingT)+import Database.Persist.Sql (SqlBackend)+import Database.Persist.Postgresql (runSqlConn, withPostgresqlConn)++runPg :: ReaderT SqlBackend (ResourceT (NoLoggingT IO)) a -> IO a+runPg act =+    runNoLoggingT (runResourceT (withPostgresqlConn "host=localhost port=54329 dbname=chinook user=postgres" (runSqlConn act)))+```++> <!-- scripths:mime text/plain -->++Discovery and reads use the same functions as SQLite, just `...Conn` wrapped in `runPg`:++```haskell+runPg listTablesConn+```++> <!-- scripths:mime text/plain -->+> ["albums","artists"]++```haskell+D.toMarkdown' <$> runPg (describeTableConn "artists")+```++> <!-- scripths:mime text/plain -->+> | Column Name<br>Text | Type<br>Text | SQLite Type<br>Text | Nullable<br>Bool | Primary Key<br>Bool |+> | --------------------|--------------|---------------------|------------------|-------------------- |+> | ArtistId            | Int          | integer             | False            | True                |+> | Name                | Maybe Text   | text                | True             | False               |++```haskell+D.toMarkdown' . D.take 5 <$> runPg (readTableConn "artists")+```++> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int |    Name<br>Maybe Text    |+> | ----------------|------------------------- |+> | 1               | Just "AC/DC"             |+> | 2               | Just "Accept"            |+> | 3               | Just "Aerosmith"         |+> | 4               | Just "Alanis Morissette" |+> | 5               | Just "Alice In Chains"   |++The typed reader is backend-agnostic too. The same `ArtistsSchema` generated from the SQLite file in+Tier 1 validates this PostgreSQL read, so it's one schema type across two databases:++```haskell+D.toMarkdown' . D.take 3 . DT.thaw <$> runPg (readTableTypedConn @ArtistsSchema "artists")+```++> <!-- scripths:mime text/plain -->+> | ArtistId<br>Int | Name<br>Maybe Text |+> | ----------------|------------------- |+> | 1               | Just "AC/DC"       |+> | 2               | Just "Accept"      |+> | 3               | Just "Aerosmith"   |++The `Albums` entity generated from SQLite at compile time is a plain `persistent` entity, so the+same `declareEntity` splice and `selectToDataFrame` run unchanged against PostgreSQL:++```haskell+D.toMarkdown' <$> runPg (selectToDataFrame [AlbumsArtistId <-. [1, 4]] [Asc AlbumsTitle, LimitTo 5])+```++> <!-- scripths:mime text/plain -->+> | id<br>Int |             title<br>Text             | artistId<br>Int |+> | ----------|---------------------------------------|---------------- |+> | 1         | For Those About To Rock We Salute You | 1               |+> | 6         | Jagged Little Pill                    | 4               |+> | 4         | Let There Be Rock                     | 1               |++Tear the throwaway cluster back down (again via `:!`):++```haskell+:! bash scripts/pg-teardown.sh+```++> <!-- scripths:mime text/plain -->+> postgres stopped and removed++## How types are inferred++SQLite type affinities map to Haskell element types as below. `NOT NULL` columns are non-null,+everything else becomes `Maybe`. You can override a column with `typeOverride` in `DeclareOptions`+(`declareTableWith` / `declareEntityWith`).++| SQLite declared type | Haskell type |+|----------------------|--------------|+| `INTEGER`, `INT...` | `Int` |+| `REAL`, `FLOAT`, `DOUBLE`, `NUMERIC`, `DECIMAL` | `Double` |+| `TEXT`, `VARCHAR`, `CHAR`, `CLOB` | `Text` |+| `BOOLEAN` | `Bool` |+| `BLOB` / no declared type | `ByteString` |+| `DATE` | `Day` |+| `DATETIME`, `TIMESTAMP` | `UTCTime` |+| `TIME` | `TimeOfDay` |++## Install++```+build-depends: dataframe, dataframe-persistent, persistent-sqlite+```++The classic path still works and is unchanged: hand-write a `persistent` entity with+`share`/`persistLowerCase` and `derivePersistentDataFrame`, then load with `fromPersistent`.
dataframe-persistent.cabal view
@@ -1,13 +1,13 @@ cabal-version:      2.4 name:               dataframe-persistent-version:            0.2.0.0+version:            0.3.0.0  synopsis: Persistent database integration for the dataframe library  description: This package provides integration between the dataframe library and the Persistent database library, allowing you to load database entities into DataFrames and save DataFrames back to the database.  bug-reports: https://github.com/mchav/dataframe/issues-license:            GPL-3.0-or-later+license:            MIT license-file:       ./LICENSE author:             Michael Chavinda, Junji Hashimoto maintainer:         mschavinda@gmail.com@@ -15,7 +15,7 @@ copyright: (c) 2024-2025 Michael Chavinda category: Data, Database tested-with: GHC ==9.4.8 || ==9.6.7 || ==9.8.4 || ==9.10.3 || ==9.12.2-extra-doc-files: ./CHANGELOG.md ./README.md+extra-doc-files: CHANGELOG.md README.md  source-repository head   type:     git@@ -33,12 +33,22 @@     import: warnings     default-extensions: Strict     exposed-modules: DataFrame.IO.Persistent,-                    DataFrame.IO.Persistent.TH+                    DataFrame.IO.Persistent.TH,+                    DataFrame.IO.Persistent.Read,+                    DataFrame.IO.Persistent.Read.Columns,+                    DataFrame.IO.Persistent.Read.Sqlite,+                    DataFrame.IO.Persistent.Schema,+                    DataFrame.IO.Persistent.Schema.Common,+                    DataFrame.IO.Persistent.Schema.Introspect     build-depends:    base >= 4 && <5,-                      bytestring >= 0.11 && < 0.13,+                      bytestring >= 0.10 && < 0.13,+                      conduit >= 1.3 && < 1.4,                       containers >= 0.6.7 && < 0.9,-                      dataframe ^>= 0.4,+                      dataframe-core ^>= 1.0,+                      dataframe-operations ^>= 1.0,                       persistent >= 2.14 && < 3,+                      persistent-sqlite >= 2.13 && < 3,+                      resourcet >= 1.2 && < 2,                       template-haskell >= 2.0 && < 3,                       text >= 2.0 && < 3,                       time >= 1.12 && < 2,@@ -51,9 +61,12 @@     import: warnings     type: exitcode-stdio-1.0     main-is: Main.hs-    other-modules: PersistentTests+    other-modules: PersistentTests,+                   SchemaTHTests     build-depends:  base >= 4 && < 5,-                    dataframe ^>= 0.4,+                    dataframe >= 1 && < 3,+                    dataframe-core ^>= 1.0,+                    dataframe-operations ^>= 1.0,                     dataframe-persistent,                     HUnit ^>= 1.6,                     monad-logger >= 0.3 && < 0.4,
src/DataFrame/IO/Persistent.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE AllowAmbiguousTypes #-}-{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ExistentialQuantification #-}@@ -42,19 +41,16 @@ import Control.Monad (forM) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Reader (ReaderT)-import Data.ByteString (ByteString) import qualified Data.Map.Strict as M import Data.Proxy (Proxy (..)) import Data.Text (Text) import qualified Data.Text as T-import Data.Time (Day, TimeOfDay, UTCTime) import qualified Data.Vector as V import qualified DataFrame.Internal.Column as DFCol import DataFrame.Internal.DataFrame (DataFrame (..)) import qualified DataFrame.Internal.DataFrame as DF import Database.Persist import Database.Persist.Sql hiding (Column)-import Database.Persist.Types (fieldHaskell, getEntityFields, unFieldNameHS) import Unsafe.Coerce (unsafeCoerce)  -- | Get number of rows in a DataFrame@@ -147,7 +143,7 @@                 numCols = length colNames                 dimensions = (0, numCols)                 emptyColumns = replicate numCols (DFCol.fromList ([] :: [Text]))-            return $ DataFrame (V.fromList emptyColumns) indices dimensions+            return $ DataFrame (V.fromList emptyColumns) indices dimensions M.empty         else do             -- Create columns from entity data             columns <- createColumnsFromEntities @record config entities@@ -155,7 +151,7 @@                 numRows = if null entities then 0 else length entities                 numCols = length colNames                 dimensions = (numRows, numCols)-            return $ DataFrame (V.fromList columns) indices dimensions+            return $ DataFrame (V.fromList columns) indices dimensions M.empty  -- | Create columns from entities createColumnsFromEntities ::@@ -217,11 +213,10 @@     ReaderT SqlBackend m [Key record] toPersistent df = do     let rowCount = nRows df-    keys <- forM [0 .. rowCount - 1] $ \i -> do+    forM [0 .. rowCount - 1] $ \i -> do         case rowToEntity i df of             Left err -> error $ "Failed to convert row " <> show i <> ": " <> err             Right entity -> insert (entityVal entity)-    return keys  -- | Convert entity fields to columns (helper for implementations) entityToColumns ::
+ src/DataFrame/IO/Persistent/Read.hs view
@@ -0,0 +1,291 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}++{- |+Module      : DataFrame.IO.Persistent.Read+License     : MIT++The runtime front door for loading SQLite into a 'DataFrame'. Mirrors the+ergonomics of @readCsv@: point at a file and a table and get a 'DataFrame', with+column types inferred from the SQLite schema. No Template Haskell, no entity+boilerplate, and it works directly in GHCi.++For compile-time typed schemas use "DataFrame.IO.Persistent.Schema"; for the+@persistent@ entity path use "DataFrame.IO.Persistent".+-}+module DataFrame.IO.Persistent.Read (+    -- * Reading a whole table (types from the schema)+    readTable,+    readTableWith,+    readTableConn,+    readTableConnWith,++    -- * Reading an arbitrary query (types sniffed from values)+    readSql,+    readSqlWith,++    -- * Reading straight into a typed schema (schema as a type argument)+    readTableTyped,+    readTableTypedConn,+    readSqlTyped,++    -- * Loading @persistent@ entities generically (no instance required)+    selectToDataFrame,++    -- * Discovery+    listTables,+    listTablesConn,+    describeTable,+    describeTableConn,++    -- * Filtering pushed down to SQLite+    ReadQuery (..),+    allRows,+    where_,+    limit,+    orderBy,++    -- * Column builders (used by generated readers)+    ColumnReader,+    buildColumn,+    buildNullableColumn,+    inferColumn,+    freezeOrThrow,++    -- * Re-exports+    ColumnInfo (..),+) where++import Control.Monad.IO.Class (MonadIO)+import Control.Monad.Trans.Reader (ReaderT)+import Control.Monad.Trans.Resource (MonadResource)+import Data.List (transpose)+import Data.Text (Text)+import qualified Data.Text as T+import Database.Persist+import Database.Persist.Sql (SqlBackend)+import Database.Persist.Sqlite (runSqlite)++import DataFrame.IO.Persistent.Read.Columns+import DataFrame.IO.Persistent.Read.Sqlite (runNamedQuery)+import DataFrame.IO.Persistent.Schema.Introspect+import DataFrame.Internal.Column (fromList)+import DataFrame.Internal.DataFrame (DataFrame, fromNamedColumns)+import DataFrame.Typed.Schema (KnownSchema)+import DataFrame.Typed.Types (TypedDataFrame)++{- | A SQLite-side filter pushed into the generated @SELECT@. Build with+'allRows' and the '&'-friendly combinators 'where_', 'limit', 'orderBy'.+-}+data ReadQuery = ReadQuery+    { rqWhere :: Maybe Text+    -- ^ A @WHERE@ body (without the @WHERE@ keyword); may contain @?@ placeholders.+    , rqParams :: [PersistValue]+    -- ^ Values bound to the placeholders in 'rqWhere'.+    , rqOrderBy :: Maybe Text+    -- ^ An @ORDER BY@ body (without the keyword).+    , rqLimit :: Maybe Int+    , rqOffset :: Maybe Int+    }+    deriving (Eq, Show)++-- | The unfiltered query: every row, every column.+allRows :: ReadQuery+allRows = ReadQuery Nothing [] Nothing Nothing Nothing++-- | Add a @WHERE@ clause (with bound parameters) to a 'ReadQuery'.+where_ :: Text -> [PersistValue] -> ReadQuery -> ReadQuery+where_ clause params q = q{rqWhere = Just clause, rqParams = params}++-- | Limit the number of rows fetched.+limit :: Int -> ReadQuery -> ReadQuery+limit n q = q{rqLimit = Just n}++-- | Add an @ORDER BY@ clause.+orderBy :: Text -> ReadQuery -> ReadQuery+orderBy clause q = q{rqOrderBy = Just clause}++{- | Read an entire table into a 'DataFrame', inferring column types (and+nullability) from the SQLite schema. The @pd.read_sql_table@ analogue.+-}+readTable :: FilePath -> Text -> IO DataFrame+readTable path table = readTableWith path table allRows++-- | 'readTable' with a SQLite-side filter (e.g. for tables larger than memory).+readTableWith :: FilePath -> Text -> ReadQuery -> IO DataFrame+readTableWith path table q = do+    readers <- columnReadersFor path table+    runSqlite (T.pack path) (readColumnsConn table readers q)++{- | 'readTable' over an existing @persistent@ connection (any 'SqlBackend',+so it shares a transaction with @fromPersistent@ / @insert@).+-}+readTableConn :: (MonadResource m) => Text -> ReaderT SqlBackend m DataFrame+readTableConn table = readTableConnWith table allRows++-- | 'readTableConn' with a SQLite-side filter.+readTableConnWith ::+    (MonadResource m) => Text -> ReadQuery -> ReaderT SqlBackend m DataFrame+readTableConnWith table q = do+    cols <- introspectTableConn table+    readColumnsConn table (map columnInfoReader cols) q++columnReadersFor :: FilePath -> Text -> IO [(Text, ColumnReader)]+columnReadersFor path table =+    map columnInfoReader <$> introspectTable path (T.unpack table)++columnInfoReader :: ColumnInfo -> (Text, ColumnReader)+columnInfoReader ci =+    (ciName ci, columnReaderFor (inferType (ciDeclType ci)) (not (ciNotNull ci)))++{- | Run an arbitrary SQL query into a 'DataFrame'. Result columns keep their+query names (aliases included); types are inferred from the returned values.+-}+readSql :: FilePath -> Text -> IO DataFrame+readSql path sql = readSqlWith path sql []++-- | 'readSql' with bound query parameters (injection-safe).+readSqlWith :: FilePath -> Text -> [PersistValue] -> IO DataFrame+readSqlWith path sql params = do+    (names, rows) <- runNamedQuery (T.pack path) sql params+    pure (assembleInferred names rows)++{- | Read a whole table straight into a typed 'TypedDataFrame', validating the+schema at the boundary. The schema is a /type argument/ while the database and+table are ordinary values, so the same table name in two different databases is+just two calls with the same @\@Schema@, no generated names to collide:++@+a <- readTableTyped \@ArtistsSchema "db1.sqlite" "artists"+b <- readTableTyped \@ArtistsSchema "db2.sqlite" "artists"+-- ... then join a and b+@+-}+readTableTyped ::+    forall cols. (KnownSchema cols) => FilePath -> Text -> IO (TypedDataFrame cols)+readTableTyped path table = readTable path table >>= freezeOrThrow++-- | 'readTableTyped' over an existing connection (any backend).+readTableTypedConn ::+    forall cols m.+    (KnownSchema cols, MonadResource m) =>+    Text -> ReaderT SqlBackend m (TypedDataFrame cols)+readTableTypedConn table = readTableConn table >>= freezeOrThrow++-- | Read an arbitrary query (e.g. a join) straight into a typed 'TypedDataFrame'.+readSqlTyped ::+    forall cols. (KnownSchema cols) => FilePath -> Text -> IO (TypedDataFrame cols)+readSqlTyped path sql = readSql path sql >>= freezeOrThrow++-- | List the user tables in a SQLite database.+listTables :: FilePath -> IO [Text]+listTables = introspectTableNames++{- | 'listTables' over an existing connection (works on any backend, e.g. a+PostgreSQL 'SqlBackend' opened with @withPostgresqlConn@).+-}+listTablesConn :: (MonadResource m) => ReaderT SqlBackend m [Text]+listTablesConn = introspectTableNamesConn++{- | A @describeColumns@-style summary of a table's schema (one row per column),+read from the schema without scanning the data.+-}+describeTable :: FilePath -> Text -> IO DataFrame+describeTable path table = schemaFrame <$> introspectTable path (T.unpack table)++-- | 'describeTable' over an existing connection (any backend).+describeTableConn :: (MonadResource m) => Text -> ReaderT SqlBackend m DataFrame+describeTableConn table = schemaFrame <$> introspectTableConn table++schemaFrame :: [ColumnInfo] -> DataFrame+schemaFrame cols =+    fromNamedColumns+        [ ("Column Name", fromList (map ciName cols))+        , ("Type", fromList (map columnHaskellType cols))+        , ("SQLite Type", fromList (map ciDeclType cols))+        , ("Nullable", fromList (map (not . ciNotNull) cols))+        , ("Primary Key", fromList (map ciPk cols))+        ]++columnHaskellType :: ColumnInfo -> Text+columnHaskellType c =+    let base = haskellTypeName (inferType (ciDeclType c))+     in if ciNotNull c then base else "Maybe " <> base++{- | Load any @persistent@ entity into a 'DataFrame' without deriving an+instance: filters give you the typed @persistent@ DSL, the rows are decoded+generically. Powers the @declareEntity@ workflow.+-}+selectToDataFrame ::+    forall r m.+    ( MonadIO m+    , PersistEntity r+    , PersistEntityBackend r ~ SqlBackend+    ) =>+    [Filter r] -> [SelectOpt r] -> ReaderT SqlBackend m DataFrame+selectToDataFrame filters opts =+    entitiesToDataFrame <$> selectList filters opts++entitiesToDataFrame :: forall r. (PersistEntity r) => [Entity r] -> DataFrame+entitiesToDataFrame ents =+    assembleInferred ("id" : entityFieldNames @r) (map entityRow ents)++-- @keyToValues@ decodes any key (single or backend) without a @ToBackendKey@+-- constraint; single-column keys (the common case) yield the @id@ column.+entityRow :: (PersistEntity r) => Entity r -> [PersistValue]+entityRow (Entity k v) = keyToValues k ++ toPersistFields v++entityFieldNames :: forall r. (PersistEntity r) => [Text]+entityFieldNames =+    map+        (unFieldNameHS . fieldHaskell)+        (getEntityFields (entityDef (Nothing :: Maybe r)))++{- | The streaming engine behind every table reader: build the @SELECT@, fetch+rows, transpose into columns, and apply each column's reader.+-}+readColumnsConn ::+    (MonadResource m) =>+    Text -> [(Text, ColumnReader)] -> ReadQuery -> ReaderT SqlBackend m DataFrame+readColumnsConn table cols q = do+    rows <- runRawRows (selectSql table (map fst cols) q) (rqParams q)+    pure (assembleColumns cols rows)++assembleColumns :: [(Text, ColumnReader)] -> [[PersistValue]] -> DataFrame+assembleColumns cols rows =+    fromNamedColumns (zipWith apply cols (cells (length cols) rows))+  where+    apply (name, rdr) pvs = (name, rdr pvs)++assembleInferred :: [Text] -> [[PersistValue]] -> DataFrame+assembleInferred names rows =+    fromNamedColumns (zip names (map inferColumn (cells (length names) rows)))++{- | Transpose rows into per-column value lists, padding to @n@ empty columns+when there are no rows (so column structure survives an empty result).+-}+cells :: Int -> [[PersistValue]] -> [[PersistValue]]+cells n [] = replicate n []+cells _ rows = transpose rows++selectSql :: Text -> [Text] -> ReadQuery -> Text+selectSql table cols q =+    T.unwords (filter (not . T.null) clauses)+  where+    colList = if null cols then "*" else T.intercalate ", " (map quoteIdent cols)+    clauses =+        [ "SELECT " <> colList+        , "FROM " <> quoteIdent table+        , maybe "" ("WHERE " <>) (rqWhere q)+        , maybe "" ("ORDER BY " <>) (rqOrderBy q)+        , maybe "" (("LIMIT " <>) . tshow) (rqLimit q)+        , maybe "" (("OFFSET " <>) . tshow) (rqOffset q)+        ]++tshow :: (Show a) => a -> Text+tshow = T.pack . show
+ src/DataFrame/IO/Persistent/Read/Columns.hs view
@@ -0,0 +1,121 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+-- 'buildNullableColumn' deliberately constrains @Columnable (Maybe a)@ (needed to+-- build a bitmap-backed nullable column); GHC flags that as simplifiable.+{-# OPTIONS_GHC -Wno-simplifiable-class-constraints #-}++{- |+Module      : DataFrame.IO.Persistent.Read.Columns+License     : MIT++Turning rows of 'PersistValue's into typed dataframe 'Column's: decoders driven+by a known 'HaskellType', value-sniffing inference for unknown columns, and the+typed-schema boundary. Shared by the runtime readers and the generated readers.+-}+module DataFrame.IO.Persistent.Read.Columns (+    ColumnReader,+    buildColumn,+    buildNullableColumn,+    columnReaderFor,+    inferColumn,+    freezeOrThrow,+) where++import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.ByteString (ByteString)+import Data.List (find)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Time (Day, TimeOfDay, UTCTime)+import Data.Typeable (Proxy (..), typeRep)+import Database.Persist (PersistField (fromPersistValue), PersistValue (..))++import DataFrame.IO.Persistent.Schema.Introspect (HaskellType (..))+import DataFrame.Internal.Column (Column, Columnable, fromList)+import DataFrame.Internal.DataFrame (DataFrame)+import DataFrame.Typed.Freeze (freezeWithError)+import DataFrame.Typed.Schema (KnownSchema)+import DataFrame.Typed.Types (TypedDataFrame)++-- | A function that turns one column's worth of 'PersistValue's into a 'Column'.+type ColumnReader = [PersistValue] -> Column++-- | Build a non-null column, decoding each value with 'fromPersistValue'.+buildColumn :: forall a. (Columnable a, PersistField a) => ColumnReader+buildColumn pvs = case traverse fromPersistValue pvs of+    Left err -> error (decodeError (typeName @a) err)+    Right (xs :: [a]) -> fromList xs++-- | Build a nullable column (@PersistNull@ becomes @Nothing@).+buildNullableColumn ::+    forall a. (Columnable (Maybe a), PersistField a) => ColumnReader+buildNullableColumn pvs = case traverse fromPersistValue pvs of+    Left err -> error (decodeError (typeName @(Maybe a)) err)+    Right (xs :: [Maybe a]) -> fromList xs++{- | Infer a column's type by sniffing the first non-null value; nullable if any+value is @PersistNull@. Used for arbitrary queries and generic entity loads.+-}+inferColumn :: [PersistValue] -> Column+inferColumn pvs = columnReaderFor (inferHaskellType pvs) (any isNull pvs) pvs++columnReaderFor :: HaskellType -> Bool -> ColumnReader+columnReaderFor ht True = nullableReaderFor ht+columnReaderFor ht False = readerFor ht++readerFor :: HaskellType -> ColumnReader+readerFor HTInt = buildColumn @Int+readerFor HTDouble = buildColumn @Double+readerFor HTText = buildColumn @Text+readerFor HTBool = buildColumn @Bool+readerFor HTByteString = buildColumn @ByteString+readerFor HTDay = buildColumn @Day+readerFor HTUTCTime = buildColumn @UTCTime+readerFor HTTimeOfDay = buildColumn @TimeOfDay++nullableReaderFor :: HaskellType -> ColumnReader+nullableReaderFor HTInt = buildNullableColumn @Int+nullableReaderFor HTDouble = buildNullableColumn @Double+nullableReaderFor HTText = buildNullableColumn @Text+nullableReaderFor HTBool = buildNullableColumn @Bool+nullableReaderFor HTByteString = buildNullableColumn @ByteString+nullableReaderFor HTDay = buildNullableColumn @Day+nullableReaderFor HTUTCTime = buildNullableColumn @UTCTime+nullableReaderFor HTTimeOfDay = buildNullableColumn @TimeOfDay++inferHaskellType :: [PersistValue] -> HaskellType+inferHaskellType = maybe HTText haskellTypeOf . find (not . isNull)++haskellTypeOf :: PersistValue -> HaskellType+haskellTypeOf (PersistInt64 _) = HTInt+haskellTypeOf (PersistDouble _) = HTDouble+haskellTypeOf (PersistBool _) = HTBool+haskellTypeOf (PersistByteString _) = HTByteString+haskellTypeOf (PersistDay _) = HTDay+haskellTypeOf (PersistUTCTime _) = HTUTCTime+haskellTypeOf (PersistTimeOfDay _) = HTTimeOfDay+haskellTypeOf _ = HTText++isNull :: PersistValue -> Bool+isNull PersistNull = True+isNull _ = False++typeName :: forall a. (Columnable a) => String+typeName = show (typeRep (Proxy @a))++decodeError :: String -> Text -> String+decodeError ty err = "buildColumn: failed to decode column as " <> ty <> ": " <> T.unpack err++{- | Validate an untyped 'DataFrame' against a typed schema and wrap it, throwing+an 'IOError' on mismatch. The generated @declareTable@ readers call this; the+schema came from the same database, so success is the normal case.+-}+freezeOrThrow ::+    forall cols m.+    (KnownSchema cols, MonadIO m) =>+    DataFrame -> m (TypedDataFrame cols)+freezeOrThrow df =+    either (liftIO . ioError . userError . T.unpack) pure (freezeWithError @cols df)
+ src/DataFrame/IO/Persistent/Read/Sqlite.hs view
@@ -0,0 +1,65 @@+{- |+Module      : DataFrame.IO.Persistent.Read.Sqlite+License     : MIT++A minimal direct-SQLite query that returns result column /names/ alongside the+values. @persistent@'s @rawQuery@ drops the names, so for arbitrary @readSql@+queries we prepare the statement ourselves and read @sqlite3_column_name@, which+works even for aliased expressions and empty result sets.+-}+module DataFrame.IO.Persistent.Read.Sqlite (+    runNamedQuery,+) where++import Control.Exception (bracket)+import qualified Data.ByteString as BS+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Database.Persist (PersistValue)+import Database.Sqlite (+    StepResult (Done, Row),+    bind,+    close,+    columns,+    finalize,+    open,+    prepare,+    step,+ )+import Database.Sqlite.Internal (Statement (Statement))+import Foreign.C.String (CString)+import Foreign.C.Types (CInt (..))+import Foreign.Ptr (Ptr)++-- @sqlite3_column_count@ / @sqlite3_column_name@ are not re-exported by+-- @Database.Sqlite@, so we bind them directly against the statement pointer.+foreign import ccall unsafe "sqlite3_column_count"+    c_sqlite3_column_count :: Ptr () -> IO CInt++foreign import ccall unsafe "sqlite3_column_name"+    c_sqlite3_column_name :: Ptr () -> CInt -> IO CString++{- | Run @sql@ (with bound @params@) against the database at @dbPath@ and return+the result column names together with every row's values.+-}+runNamedQuery :: Text -> Text -> [PersistValue] -> IO ([Text], [[PersistValue]])+runNamedQuery dbPath sql params =+    bracket (open dbPath) close $ \conn ->+        bracket (prepare conn sql) finalize $ \stmt@(Statement p) -> do+            bind stmt params+            n <- fromIntegral <$> c_sqlite3_column_count p+            names <- mapM (columnName p) [0 .. n - 1]+            rows <- stepRows stmt+            pure (names, rows)++columnName :: Ptr () -> Int -> IO Text+columnName p i = do+    cstr <- c_sqlite3_column_name p (fromIntegral i)+    TE.decodeUtf8 <$> BS.packCString cstr++stepRows :: Statement -> IO [[PersistValue]]+stepRows stmt = do+    result <- step stmt+    case result of+        Row -> (:) <$> columns stmt <*> stepRows stmt+        Done -> pure []
+ src/DataFrame/IO/Persistent/Schema.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskellQuotes #-}++{- |+Module      : DataFrame.IO.Persistent.Schema+License     : MIT++Template Haskell that reads a SQLite table's schema __at compile time__ and+generates either a typed-schema type synonym ('declareTable') or a @persistent@+entity ('declareEntity'). Both replace the hand-written @persistLowerCase@ ++@derivePersistentDataFrame@ boilerplate.++'declareTable' emits only the schema /type/. You read into it with the generic+'DataFrame.IO.Persistent.Read.readTableTyped', so the database and table are+runtime values and the same schema can be reused across databases.++@+-- Typed schema, checked at compile time:+\$('declareTable' "chinook.db" "artists")+-- generates: type ArtistsSchema = '[Column "ArtistId" Int, Column "Name" (Maybe Text)]+-- read any database/table into it:+--   readTableTyped \@ArtistsSchema "chinook.db" "artists" :: IO (TypedDataFrame ArtistsSchema)++-- Persistent entity: full Filter DSL, write-back, no hand-written schema.+\$('declareEntity' "chinook.db" "artists")+-- then: runSqlite "chinook.db" (selectToDataFrame [ArtistsName ==. Just "Accept"] [])+@+-}+module DataFrame.IO.Persistent.Schema (+    -- * Typed schema+    declareTable,+    declareTableWith,+    declareTableFromSchema,++    -- * Persistent entity generation+    declareEntity,+    declareEntityWith,++    -- * Options + re-exports+    DeclareOptions (..),+    defaultDeclareOptions,+    ColumnInfo (..),+    HaskellType (..),+) where++import Data.List (partition)+import Data.Text (Text)+import qualified Data.Text as T+import Language.Haskell.TH++import Database.Persist.Quasi (lowerCaseSettings, parse)+import Database.Persist.Quasi.Internal (UnboundEntityDef)+import Database.Persist.TH (mkPersist, sqlSettings)++import DataFrame.IO.Persistent.Schema.Common+import DataFrame.IO.Persistent.Schema.Introspect+import DataFrame.Typed.Types (Column)++{- | Read @table@ from the SQLite database at @path@ and emit a typed schema+synonym, @type \<Table\>Schema = '[Column ...]@. Read into it with+'DataFrame.IO.Persistent.Read.readTableTyped'.+-}+declareTable :: FilePath -> String -> Q [Dec]+declareTable = declareTableWith defaultDeclareOptions++-- | 'declareTable' with custom 'DeclareOptions'.+declareTableWith :: DeclareOptions -> FilePath -> String -> Q [Dec]+declareTableWith opts path table = do+    cols <- introspectQ path table+    warnOnNumeric cols+    schemaDecl opts (T.pack table) cols++{- | Like 'declareTable' but from an explicit column list, so __no database is+opened at build time__ (use in CI / cross-compilation / sdist consumers).+-}+declareTableFromSchema :: [ColumnInfo] -> String -> Q [Dec]+declareTableFromSchema cols name =+    schemaDecl defaultDeclareOptions (T.pack name) cols++-- | Emit @type \<Table\>Schema = '[Column ...]@ for the selected columns.+schemaDecl :: DeclareOptions -> Text -> [ColumnInfo] -> Q [Dec]+schemaDecl opts table cols0 = do+    let cols = selectColumns opts cols0+    failOnEmpty table cols+    pure [TySynD (mkName (schemaTypeNameOf opts table)) [] (schemaType opts cols)]++failOnEmpty :: Text -> [ColumnInfo] -> Q ()+failOnEmpty table [] =+    fail ("declareTable: no columns selected for table " <> show (T.unpack table))+failOnEmpty _ _ = pure ()++schemaType :: DeclareOptions -> [ColumnInfo] -> Type+schemaType opts cols =+    buildSchemaType+        [(ciName c, thType (resolvedType opts c), isNullable opts c) | c <- cols]++-- | Fold @(name, type, nullable)@ triples into a promoted @'[Column name ty]@.+buildSchemaType :: [(Text, Type, Bool)] -> Type+buildSchemaType = foldr cons PromotedNilT+  where+    cons col acc = PromotedConsT `AppT` columnEntry col `AppT` acc++columnEntry :: (Text, Type, Bool) -> Type+columnEntry (name, ty, nullable) =+    ConT ''Column+        `AppT` LitT (StrTyLit (T.unpack name))+        `AppT` wrapMaybe nullable ty++wrapMaybe :: Bool -> Type -> Type+wrapMaybe True ty = ConT ''Maybe `AppT` ty+wrapMaybe False ty = ty++{- | Read @table@ at compile time and generate a @persistent@ entity for it+(via 'mkPersist'), giving the full @persistent@ typed-'Filter' DSL with no+hand-written schema. Load it with 'DataFrame.IO.Persistent.Read.selectToDataFrame'.+-}+declareEntity :: FilePath -> String -> Q [Dec]+declareEntity = declareEntityWith defaultDeclareOptions++-- | 'declareEntity' with custom 'DeclareOptions'.+declareEntityWith :: DeclareOptions -> FilePath -> String -> Q [Dec]+declareEntityWith opts path table = do+    cols <- introspectQ path table+    let tableT = T.pack table+        ent = T.pack (entityNameOf opts tableT)+        dsl = renderEntityDsl opts ent tableT (selectColumns opts cols)+    parseEntityDefs dsl >>= mkPersist sqlSettings++parseEntityDefs :: Text -> Q [UnboundEntityDef]+parseEntityDefs dsl = case snd (parse lowerCaseSettings [(Nothing, dsl)]) of+    Left errs -> fail ("declareEntity: could not build entity definition:\n" <> show errs)+    Right defs -> pure defs++{- | Render the @persistLowerCase@ DSL text for an entity. An integer primary key+becomes the @Id@ field; every other column is a field bound to its DB name.+-}+renderEntityDsl :: DeclareOptions -> Text -> Text -> [ColumnInfo] -> Text+renderEntityDsl opts ent table cols =+    T.unlines ((ent <> " sql=" <> table) : idLines <> map (renderField opts) fields)+  where+    (pks, others) = partition (isIntPk opts) cols+    -- Rename persistent's default (ToBackendKey-enabled) key column rather than+    -- declaring a natural key, so generated entities keep fromSqlKey/ToBackendKey.+    (idLines, fields) = case pks of+        [pk] -> (["    Id sql=" <> ciName pk], others)+        _ -> ([], cols)++isIntPk :: DeclareOptions -> ColumnInfo -> Bool+isIntPk opts c = ciPk c && resolvedType opts c == HTInt++renderField :: DeclareOptions -> ColumnInfo -> Text+renderField opts c =+    "    "+        <> fieldIdentifier (ciName c)+        <> " "+        <> persistType (resolvedType opts c)+        <> " sql="+        <> ciName c+        <> (if isNullable opts c then " Maybe" else "")
+ src/DataFrame/IO/Persistent/Schema/Common.hs view
@@ -0,0 +1,203 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskellQuotes #-}++{- |+Module      : DataFrame.IO.Persistent.Schema.Common+License     : MIT++Shared options, name mangling, type mapping, and compile-time introspection used+by both the typed-schema splice (@declareTable@) and the entity splice+(@declareEntity@) in "DataFrame.IO.Persistent.Schema".+-}+module DataFrame.IO.Persistent.Schema.Common (+    -- * Options+    DeclareOptions (..),+    defaultDeclareOptions,++    -- * Compile-time introspection+    introspectQ,+    selectColumns,++    -- * Per-column resolution+    resolvedType,+    isNullable,++    -- * Type mapping+    thType,+    persistType,++    -- * Name helpers+    pascalCase,+    schemaTypeNameOf,+    entityNameOf,+    fieldIdentifier,++    -- * Warnings+    warnOnNumeric,+) where++import Control.Exception (SomeException, try)+import Control.Monad (when)+import Data.Char (isAlpha, isAlphaNum, toLower, toUpper)+import Data.Either (fromRight)+import Data.List (find, intercalate)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Time (Day, TimeOfDay, UTCTime)+import Language.Haskell.TH (Q, Type (ConT), reportWarning)+import Language.Haskell.TH.Syntax (addDependentFile, runIO)++import Data.ByteString (ByteString)+import DataFrame.IO.Persistent.Schema.Introspect++{- | Knobs shared by 'DataFrame.IO.Persistent.Schema.declareTable' and+'DataFrame.IO.Persistent.Schema.declareEntity'. Start from+'defaultDeclareOptions' and override fields with record syntax.+-}+data DeclareOptions = DeclareOptions+    { honorNotNull :: Bool+    {- ^ @True@ (default): @NOT NULL@ columns are non-null, others @Maybe@.+    @False@: every column is treated as nullable.+    -}+    , typeOverride :: Text -> Text -> Maybe HaskellType+    {- ^ Given @(rawColumnName, declaredSqliteType)@, optionally override the+    inferred Haskell type. Default: never override.+    -}+    , includeColumns :: Maybe [Text]+    -- ^ Restrict to these raw columns (@Nothing@ = all).+    , excludeColumns :: [Text]+    -- ^ Drop these raw columns (applied after 'includeColumns').+    , schemaTypeName :: Maybe String+    -- ^ Override the generated schema type-synonym name (default @\<Table\>Schema@).+    , entityName :: Maybe String+    -- ^ Override the generated entity name (default PascalCased table).+    }++-- | Sensible defaults: honor @NOT NULL@, no overrides, all columns, derived names.+defaultDeclareOptions :: DeclareOptions+defaultDeclareOptions =+    DeclareOptions+        { honorNotNull = True+        , typeOverride = \_ _ -> Nothing+        , includeColumns = Nothing+        , excludeColumns = []+        , schemaTypeName = Nothing+        , entityName = Nothing+        }++{- | Introspect a table at compile time: register the DB as a dependency (so a+schema change forces a rebuild), then fail helpfully if it can't be read.+-}+introspectQ :: FilePath -> String -> Q [ColumnInfo]+introspectQ path table = do+    addDependentFile path+    outcome <- runIO (try (introspectTable path table))+    case outcome of+        Left (e :: SomeException) -> fail (openError path e)+        Right [] -> failMissingTable path table+        Right cols -> pure cols++failMissingTable :: FilePath -> String -> Q a+failMissingTable path table = do+    names <-+        runIO (try (introspectTableNames path) :: IO (Either SomeException [Text]))+    fail (missingTableMessage path table (fromRight [] names))++openError :: FilePath -> SomeException -> String+openError path e =+    "declareTable/declareEntity: could not read " <> path <> ": " <> show e++missingTableMessage :: FilePath -> String -> [Text] -> String+missingTableMessage path table names =+    "declareTable/declareEntity: table "+        <> show table+        <> " not found in "+        <> path+        <> ".\n  Available tables: "+        <> intercalate ", " (map T.unpack names)+        <> maybe+            ""+            (\s -> "\n  (did you mean " <> show (T.unpack s) <> "?)")+            (didYouMean table names)++didYouMean :: String -> [Text] -> Maybe Text+didYouMean target = find ((== map toLower target) . map toLower . T.unpack)++-- | Apply 'includeColumns' / 'excludeColumns'.+selectColumns :: DeclareOptions -> [ColumnInfo] -> [ColumnInfo]+selectColumns opts = filter keep+  where+    keep c =+        maybe True (ciName c `elem`) (includeColumns opts)+            && ciName c `notElem` excludeColumns opts++-- | The Haskell type for a column, honoring 'typeOverride'.+resolvedType :: DeclareOptions -> ColumnInfo -> HaskellType+resolvedType opts c =+    fromMaybe+        (inferType (ciDeclType c))+        (typeOverride opts (ciName c) (ciDeclType c))++-- | Whether a column should be modelled as nullable.+isNullable :: DeclareOptions -> ColumnInfo -> Bool+isNullable opts c = not (honorNotNull opts) || not (ciNotNull c)++-- | The Template Haskell 'Type' for a 'HaskellType'.+thType :: HaskellType -> Type+thType HTInt = ConT ''Int+thType HTDouble = ConT ''Double+thType HTText = ConT ''Text+thType HTBool = ConT ''Bool+thType HTByteString = ConT ''ByteString+thType HTDay = ConT ''Day+thType HTUTCTime = ConT ''UTCTime+thType HTTimeOfDay = ConT ''TimeOfDay++-- | The @persistent@ DSL type name for a 'HaskellType'.+persistType :: HaskellType -> Text+persistType HTInt = "Int64"+persistType HTDouble = "Double"+persistType HTText = "Text"+persistType HTBool = "Bool"+persistType HTByteString = "ByteString"+persistType HTDay = "Day"+persistType HTUTCTime = "UTCTime"+persistType HTTimeOfDay = "TimeOfDay"++-- | Capitalize the first character (e.g. @"artists" -> "Artists"@).+pascalCase :: Text -> String+pascalCase t = case T.unpack t of+    (c : cs) -> toUpper c : cs+    [] -> []++schemaTypeNameOf :: DeclareOptions -> Text -> String+schemaTypeNameOf opts table = fromMaybe (pascalCase table <> "Schema") (schemaTypeName opts)++entityNameOf :: DeclareOptions -> Text -> String+entityNameOf opts table = fromMaybe (pascalCase table) (entityName opts)++-- | Turn a raw column name into a valid lowercase-initial @persistent@ field name.+fieldIdentifier :: Text -> Text+fieldIdentifier raw = T.pack (lowerFirst (ensureLetter cleaned))+  where+    cleaned = filter (\ch -> isAlphaNum ch || ch == '_') (T.unpack raw)+    lowerFirst (c : cs) = toLower c : cs+    lowerFirst [] = "field"+    ensureLetter s@(c : _) | isAlpha c = s+    ensureLetter s = 'f' : s++-- | Warn (at splice time) about @NUMERIC@/@DECIMAL@ columns mapped to 'Double'.+warnOnNumeric :: [ColumnInfo] -> Q ()+warnOnNumeric = mapM_ warn1+  where+    warn1 c = when (isNumeric (ciDeclType c)) (reportWarning (numericMessage c))+    isNumeric t = any (`T.isInfixOf` T.toUpper t) ["NUMERIC", "DECIMAL"]+    numericMessage c =+        "declareTable: column "+            <> show (T.unpack (ciName c))+            <> " has SQLite type "+            <> show (T.unpack (ciDeclType c))+            <> "; mapping to Double may lose precision "+            <> "(override with typeOverride)."
+ src/DataFrame/IO/Persistent/Schema/Introspect.hs view
@@ -0,0 +1,211 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : DataFrame.IO.Persistent.Schema.Introspect+License     : MIT++Compile-time-safe SQLite schema introspection. Everything here is plain 'IO'+(callable from a Template Haskell @runIO@ in "DataFrame.IO.Persistent.Schema")+plus a pure SQLite-affinity → 'HaskellType' mapping. No Template Haskell and no+DataFrame dependencies live here, so the logic can be unit-tested directly.+-}+module DataFrame.IO.Persistent.Schema.Introspect (+    -- * Column metadata+    ColumnInfo (..),+    HaskellType (..),++    -- * Introspection (IO)+    introspectTable,+    introspectTableConn,+    introspectTableNames,+    introspectTableNamesConn,++    -- * Type inference+    inferType,+    haskellTypeName,++    -- * Raw-query helper (shared with the runtime reader)+    runRawRows,+    quoteIdent,+) where++import Control.Monad.Trans.Reader (ReaderT)+import Control.Monad.Trans.Resource (MonadResource)+import Data.Conduit (runConduit, (.|))+import qualified Data.Conduit.List as CL+import Data.List (sortOn)+import Data.Text (Text)+import qualified Data.Text as T+import Database.Persist (PersistValue (..))+import Database.Persist.Sql (SqlBackend, rawQuery)+import Database.Persist.SqlBackend (getRDBMS)+import Database.Persist.Sqlite (runSqlite)++-- | A single column as reported by @PRAGMA table_info@.+data ColumnInfo = ColumnInfo+    { ciName :: Text+    -- ^ Raw column name as stored in SQLite (e.g. @"ArtistId"@).+    , ciDeclType :: Text+    -- ^ Declared type string (e.g. @"NVARCHAR(120)"@); may be empty.+    , ciNotNull :: Bool+    -- ^ Whether the column carries a @NOT NULL@ constraint.+    , ciPk :: Bool+    -- ^ Whether the column participates in the primary key.+    }+    deriving (Eq, Show)++{- | The closed set of Haskell element types we map SQLite columns onto. Every+constructor corresponds to a type that is both 'Database.Persist.PersistField'+and 'DataFrame.Internal.Column.Columnable'.+-}+data HaskellType+    = HTInt+    | HTDouble+    | HTText+    | HTBool+    | HTByteString+    | HTDay+    | HTUTCTime+    | HTTimeOfDay+    deriving (Eq, Show)++{- | Map a declared SQLite type to a 'HaskellType' using SQLite's own+(case-insensitive, substring) type-affinity rules, with a few semantic+refinements for dates/booleans. Unknown or empty declarations fall back the+same way SQLite does (BLOB affinity for empty, numeric otherwise).+-}+inferType :: Text -> HaskellType+inferType declared+    | "INT" `inUpper` declared = HTInt+    | anyIn ["CHAR", "CLOB", "TEXT"] declared = HTText+    | anyIn ["BLOB", "BYTEA"] declared || T.null (T.strip declared) = HTByteString+    | anyIn ["REAL", "FLOA", "DOUB"] declared = HTDouble+    | "BOOL" `inUpper` declared = HTBool+    | anyIn ["DATETIME", "TIMESTAMP"] declared = HTUTCTime+    | "DATE" `inUpper` declared = HTDay+    | "TIME" `inUpper` declared = HTTimeOfDay+    | otherwise = HTDouble++-- | A display name for a 'HaskellType' (the element type, without nullability).+haskellTypeName :: HaskellType -> Text+haskellTypeName HTInt = "Int"+haskellTypeName HTDouble = "Double"+haskellTypeName HTText = "Text"+haskellTypeName HTBool = "Bool"+haskellTypeName HTByteString = "ByteString"+haskellTypeName HTDay = "Day"+haskellTypeName HTUTCTime = "UTCTime"+haskellTypeName HTTimeOfDay = "TimeOfDay"++inUpper :: Text -> Text -> Bool+inUpper needle hay = needle `T.isInfixOf` T.toUpper hay++anyIn :: [Text] -> Text -> Bool+anyIn needles hay = any (`inUpper` hay) needles++{- | Read the columns of @table@ from the SQLite database at @path@, ordered by+their @PRAGMA table_info@ @cid@ (i.e. declaration order).+-}+introspectTable :: FilePath -> String -> IO [ColumnInfo]+introspectTable path table =+    runSqlite (T.pack path) (introspectTableConn (T.pack table))++{- | 'introspectTable' over an existing connection. Backend-agnostic: SQLite uses+@PRAGMA table_info@; every other backend (PostgreSQL, MySQL, etc.) uses the+standard @information_schema.columns@.+-}+introspectTableConn ::+    (MonadResource m) => Text -> ReaderT SqlBackend m [ColumnInfo]+introspectTableConn table = do+    rdbms <- getRDBMS+    if rdbms == "sqlite" then sqlitePragmaColumns table else infoSchemaColumns table++sqlitePragmaColumns ::+    (MonadResource m) => Text -> ReaderT SqlBackend m [ColumnInfo]+sqlitePragmaColumns table = do+    rows <- runRawRows ("PRAGMA table_info(" <> quoteIdent table <> ")") []+    pure (map snd (sortOn fst (map parsePragmaRow rows)))++infoSchemaColumns ::+    (MonadResource m) => Text -> ReaderT SqlBackend m [ColumnInfo]+infoSchemaColumns table = do+    rows <- runRawRows infoSchemaColumnQuery [PersistText table]+    pks <- runRawRows infoSchemaPkQuery [PersistText table]+    let pkNames = [pvText n | (n : _) <- pks]+    pure (map (parseInfoSchemaRow pkNames) rows)++infoSchemaColumnQuery :: Text+infoSchemaColumnQuery =+    "SELECT column_name, data_type, is_nullable FROM information_schema.columns \+    \WHERE table_name = ? AND table_schema NOT IN ('pg_catalog', 'information_schema') \+    \ORDER BY ordinal_position"++infoSchemaPkQuery :: Text+infoSchemaPkQuery =+    "SELECT kcu.column_name FROM information_schema.table_constraints tc \+    \JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name \+    \WHERE tc.table_name = ? AND tc.constraint_type = 'PRIMARY KEY'"++-- | List the user tables (excluding SQLite internal tables) in @path@.+introspectTableNames :: FilePath -> IO [Text]+introspectTableNames path = runSqlite (T.pack path) introspectTableNamesConn++-- | 'introspectTableNames' over an existing connection (backend-agnostic).+introspectTableNamesConn :: (MonadResource m) => ReaderT SqlBackend m [Text]+introspectTableNamesConn = do+    rdbms <- getRDBMS+    rows <-+        runRawRows+            (if rdbms == "sqlite" then sqliteTableQuery else infoSchemaTableQuery)+            []+    pure [pvText n | (n : _) <- rows]++sqliteTableQuery :: Text+sqliteTableQuery =+    "SELECT name FROM sqlite_master WHERE type = 'table' \+    \AND name NOT LIKE 'sqlite_%' ORDER BY name"++infoSchemaTableQuery :: Text+infoSchemaTableQuery =+    "SELECT table_name FROM information_schema.tables \+    \WHERE table_schema NOT IN ('pg_catalog', 'information_schema') \+    \AND table_type = 'BASE TABLE' ORDER BY table_name"++-- | Run a raw SQL query and collect every row's column values.+runRawRows ::+    (MonadResource m) =>+    Text -> [PersistValue] -> ReaderT SqlBackend m [[PersistValue]]+runRawRows sql params = runConduit (rawQuery sql params .| CL.consume)++parsePragmaRow :: [PersistValue] -> (Int, ColumnInfo)+parsePragmaRow [cid, name, ctype, notnull, _dflt, pk] =+    ( pvInt cid+    , ColumnInfo (pvText name) (pvText ctype) (pvInt notnull == 1) (pvInt pk > 0)+    )+parsePragmaRow other =+    error ("introspectTable: unexpected PRAGMA table_info row: " <> show other)++{- | Parse an @information_schema.columns@ row @(name, data_type, is_nullable)@,+marking 'ciPk' from the table's primary-key column names.+-}+parseInfoSchemaRow :: [Text] -> [PersistValue] -> ColumnInfo+parseInfoSchemaRow pkNames [name, dtype, nullable] =+    ColumnInfo nm (pvText dtype) (pvText nullable == "NO") (nm `elem` pkNames)+  where+    nm = pvText name+parseInfoSchemaRow _ other =+    error ("introspectTable: unexpected information_schema row: " <> show other)++pvText :: PersistValue -> Text+pvText (PersistText t) = t+pvText PersistNull = ""+pvText other = T.pack (show other)++pvInt :: PersistValue -> Int+pvInt (PersistInt64 i) = fromIntegral i+pvInt _ = 0++-- | Double-quote a SQLite identifier, escaping embedded quotes.+quoteIdent :: Text -> Text+quoteIdent t = "\"" <> T.replace "\"" "\"\"" t <> "\""
src/DataFrame/IO/Persistent/TH.hs view
@@ -14,20 +14,16 @@     derivePersistentDataFrame, ) where -import Control.Monad (forM, when)-import Data.List (foldl')-import Data.Text (Text)+import Control.Monad (forM)+import Data.Char import qualified Data.Text as T import qualified Data.Vector as V import DataFrame.Functions (col) import DataFrame.IO.Persistent-import qualified DataFrame.Internal.Column as DFCol import DataFrame.Internal.Expression import Database.Persist-import Database.Persist.Sql (fromSqlKey)-import Database.Persist.TH import Language.Haskell.TH-import Language.Haskell.TH.Syntax (Lift, lift)+import Language.Haskell.TH.Syntax (lift)  import Debug.Trace (trace) @@ -71,13 +67,13 @@             dataframeExprs <- forM fields $ \(raw, _, ty) -> do                 let nm = camelToSnake (nameBase raw)                 let colName = camelToSnake (drop (length entityNameStr) (nameBase raw))-                trace ((nm <> " :: Expr " <> (show ty))) pure ()+                trace (nm <> " :: Expr " <> show ty) pure ()                 let n = mkName nm                 sig <- sigD n [t|Expr $(pure ty)|]                 val <- valD (varP n) (normalB [|col $(lift colName)|]) []                 pure [sig, val] -            return ([instanceDec] ++ concat dataframeExprs)+            return (instanceDec : concat dataframeExprs)         _ ->             fail $                 "deriveEntityToDataFrame: " ++ show entityName ++ " must be a record type"@@ -190,5 +186,5 @@     go (c : cs)         | isUpper c = '_' : toLower c : go cs         | otherwise = c : go cs-    isUpper c = c >= 'A' && c <= 'Z'+    isUpper = isAsciiUpper     toLower c = if isUpper c then toEnum (fromEnum c + 32) else c
tests/Main.hs view
@@ -3,12 +3,13 @@ import qualified System.Exit as Exit  import PersistentTests+import SchemaTHTests  import Test.HUnit  main :: IO () main = do-    result <- runTestTT persistentTests+    result <- runTestTT (TestList [persistentTests, schemaThTests])     if failures result > 0 || errors result > 0         then Exit.exitFailure         else Exit.exitSuccess
tests/PersistentTests.hs view
@@ -13,6 +13,7 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}  module PersistentTests where@@ -36,7 +37,7 @@ import Test.HUnit import UnliftIO.Resource (ResourceT) -import DataFrame.Functions ((.<))+import DataFrame.Functions ((.<.))  -- Define test entities share@@ -109,7 +110,7 @@         assertBool "Has active column" ("active" `elem` cols)          -- Check data values-        let names = V.toList (DF.columnAsVector test_user_name df)+        let names = DF.columnAsList test_user_name df          assertEqual "Names match" ["Alice", "Bob", "Charlie", "Diana"] names @@ -125,7 +126,7 @@             print cols             assertBool "Has id column" ("id" `elem` cols)             assertBool "Has name column" ("name" `elem` cols)-            let names = V.toList (DF.columnAsVector artist_name (DF.take 5 df))+            let names = DF.columnAsList artist_name (DF.take 5 df)              assertEqual                 "Names match"@@ -144,7 +145,7 @@         assertEqual "Active users count" 3 (nRows df)          -- Check all loaded users are active-        let activeFlags = V.toList $ DF.columnAsVector test_user_active df+        let activeFlags = DF.columnAsList test_user_active df         assertBool "All active" (and activeFlags)  -- Test custom configuration@@ -196,15 +197,15 @@         assertEqual "Young users count" 2 (nRows youngUsers)          -- Sort operation-        let sorted = DF.sortBy [DF.Asc "age"] df-        let ages = V.toList $ DF.columnAsVector test_user_age sorted+        let sorted = DF.sortBy [DF.Asc (F.col @Int "age")] df+        let ages = DF.columnAsList test_user_age sorted         assertEqual "Ages sorted" [25, 28, 30, 35] ages          -- Derive column         let withAgeGroup =                 DF.derive @Text                     "age_group"-                    (F.ifThenElse (test_user_age .< 30) "young" "adult")+                    (F.ifThenElse (test_user_age .<. 30) "young" "adult")                     df         assertEqual "Has age_group column" 5 (length $ DF.columnNames withAgeGroup) @@ -239,7 +240,7 @@         assertEqual "Empty DataFrame" 0 (nRows df)         -- Should still have column names         let cols = DF.columnNames df-        assertBool "Has columns" (length cols > 0)+        assertBool "Has columns" (not (null cols))  -- Test persistFieldsToColumns function testPersistFieldsToColumns :: Test
+ tests/SchemaTHTests.hs view
@@ -0,0 +1,128 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++{- |+End-to-end tests for the compile-time SQLite schema splices and the runtime+readers, exercised against the committed @data/chinook.db@ fixture.+-}+module SchemaTHTests (schemaThTests) where++import Control.Monad.IO.Class (liftIO)+import Data.Function ((&))+import Data.Int (Int64)+import Data.Maybe (listToMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import Database.Persist (Filter, (==.))+import Database.Persist.Sqlite (runSqlite)+import Test.HUnit++import qualified DataFrame as DF+import DataFrame.IO.Persistent (nRows)+import DataFrame.IO.Persistent.Read+import DataFrame.IO.Persistent.Schema+import qualified DataFrame.Typed as DT++-- | Typed reader + schema for the @artists@ table (read at compile time).+$(declareTable "./data/chinook.db" "artists")++-- | A @persistent@ entity for the @albums@ table (generated from the live DB).+$(declareEntity "./data/chinook.db" "albums")++chinook :: T.Text+chinook = "./data/chinook.db"++-- Tier 0: runtime readers --------------------------------------------------++testReadTable :: Test+testReadTable = TestCase $ do+    df <- readTable "./data/chinook.db" "artists"+    assertEqual "row count" 275 (nRows df)+    let cols = DF.columnNames df+    assertBool "has raw ArtistId" ("ArtistId" `elem` cols)+    assertBool "has raw Name" ("Name" `elem` cols)++testReadTableWith :: Test+testReadTableWith = TestCase $ do+    df <- readTableWith "./data/chinook.db" "artists" (allRows & limit 5)+    assertEqual "limit pushed down" 5 (nRows df)++testReadSql :: Test+testReadSql = TestCase $ do+    df <- readSql "./data/chinook.db" "SELECT Name FROM artists LIMIT 5"+    assertEqual "raw query rows" 5 (nRows df)++testListTables :: Test+testListTables = TestCase $ do+    ts <- listTables "./data/chinook.db"+    assertBool "has artists" ("artists" `elem` ts)+    assertBool "has albums" ("albums" `elem` ts)++testDescribeTable :: Test+testDescribeTable = TestCase $ do+    d <- describeTable "./data/chinook.db" "artists"+    assertEqual+        "describe-style columns"+        ["Column Name", "Type", "SQLite Type", "Nullable", "Primary Key"]+        (DF.columnNames d)+    assertEqual "one row per column" 2 (nRows d)++-- Tier 1: typed splice -----------------------------------------------------++testDeclareTableTyped :: Test+testDeclareTableTyped = TestCase $ do+    -- declareTable emits only the ArtistsSchema type; read into it generically:+    tdf <- readTableTyped @ArtistsSchema "./data/chinook.db" "artists"+    assertEqual "typed row count" 275 (nRows (DT.thaw tdf))+    -- @col \@"Name"@ here is checked against the generated ArtistsSchema:+    let names = DT.columnAsList @"Name" tdf+    assertEqual "first artist" (Just (Just "AC/DC")) (listToMaybe names)++-- Tier 2: persistent entity generation -------------------------------------++testDeclareEntity :: Test+testDeclareEntity = TestCase $ runSqlite chinook $ do+    df <- selectToDataFrame ([] :: [Filter Albums]) []+    liftIO $ assertEqual "all albums" 347 (nRows df)++testDeclareEntityFilter :: Test+testDeclareEntityFilter = TestCase $ runSqlite chinook $ do+    df <- selectToDataFrame [AlbumsArtistId ==. 1] []+    liftIO $ assertEqual "AC/DC albums" 2 (nRows df)++-- Hand-off: raw read and entity read share one connection ------------------++testHandOff :: Test+testHandOff = TestCase $ runSqlite chinook $ do+    artists <- readTableConn "artists"+    albums <- selectToDataFrame ([] :: [Filter Albums]) []+    liftIO $ do+        assertEqual "artists via raw conn" 275 (nRows artists)+        assertEqual "albums via entity" 347 (nRows albums)++schemaThTests :: Test+schemaThTests =+    TestList+        [ TestLabel "readTable" testReadTable+        , TestLabel "readTableWith limit" testReadTableWith+        , TestLabel "readSql" testReadSql+        , TestLabel "listTables" testListTables+        , TestLabel "describeTable" testDescribeTable+        , TestLabel "declareTable (typed)" testDeclareTableTyped+        , TestLabel "declareEntity" testDeclareEntity+        , TestLabel "declareEntity filter" testDeclareEntityFilter+        , TestLabel "dataframe/persistent hand-off" testHandOff+        ]