From ea122fbe879656ff410e7f98856aed569129b4a9 Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Fri, 20 Nov 2026 16:25:34 +0000 Subject: [PATCH 1/5] Offline mode (ContextSchemaPath) improvements: Individuals to a separate json file, and add schema descriptions to another one. --- docs/RELEASE_NOTES.md | 11 + docs/content/core/parameters.fsx | 38 ++ src/SQLProvider.Common/SqlRuntime.Common.fs | 140 +++++++- src/SQLProvider.Common/Utils.fs | 12 + src/SQLProvider.DesignTime/SqlDesignTime.fs | 326 ++++++++++++++---- src/SQLProvider.Runtime/Providers.DuckDb.fs | 14 + src/SQLProvider.Runtime/Providers.Firebird.fs | 12 + .../Providers.MsSqlServer.Dynamic.fs | 17 + .../Providers.MsSqlServer.fs | 17 + src/SQLProvider.Runtime/Providers.MySql.fs | 14 + src/SQLProvider.Runtime/Providers.Oracle.fs | 14 + .../Providers.Postgresql.fs | 30 +- .../SqlProvider.Tests/SchemaCacheFileTests.fs | 224 ++++++++++++ .../SqlProvider.Tests.fsproj | 1 + 14 files changed, 785 insertions(+), 85 deletions(-) create mode 100644 tests/SqlProvider.Tests/SchemaCacheFileTests.fs diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 8e40f4f18..39de1b049 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,3 +1,14 @@ +### 1.5.34 - (unreleased) +- Offline mode (ContextSchemaPath) saves three files beside each other: schema.json for the schema, schema.descriptions.json for table and column descriptions (comments), schema.individuals.json for individuals. Builds read only the schema file; the descriptions file is read for the first tooltip and the individuals file when Individuals are first opened +- Offline tooltips show the saved table and column descriptions, instead of only "Offline mode." SaveContextSchema saves the descriptions of what you hovered over online +- A saved schema no longer carries individuals, so it stays small and loads fast. A schema file with individuals in it still loads them, and re-saving it moves them to the individuals file. Older versions can read the new schema files +- New design-time commands next to SaveContextSchema, online only, that read the whole database instead of what was used so far: SaveContextSchemaFull (every table, column, relationship and stored procedure, and every table and column description) and SaveContextSchemaIndividuals (individuals of every table with a single primary key) +- SaveContextSchemaFull reads the column descriptions of a table in one query instead of one per column (MS SQL Server, PostgreSQL, MySQL, Oracle, Firebird, DuckDB) +- OfflineTools.mergeCacheFiles merges descriptions and individuals files too +- Fix: after a failed SaveContextSchema, design-time commands no longer stop working until the IDE restarts +- Fix: saving individuals no longer fails on a column value such as a DateTimeOffset or an array; such values are saved as text +- Fix: PostgreSQL tables with capital letters in their name show their descriptions in tooltips; reading them failed before + ### 1.5.33 - 19.11.2026 - Fix: a saved schema (ContextSchemaPath) loads on both .NET and .NET Framework, whichever saved it. Visual Studio, whose editor and compiler run on .NET Framework, failed on a schema saved by dotnet with "Value cannot be null. Parameter name: key" diff --git a/docs/content/core/parameters.fsx b/docs/content/core/parameters.fsx index e98876be8..327d1a969 100644 --- a/docs/content/core/parameters.fsx +++ b/docs/content/core/parameters.fsx @@ -160,7 +160,45 @@ is saved, the outcome of the method execution is stored in memory so the file wi In case the database schema changes and the schema file must be updated, remove the outdated file, reload the solution and retype or uncomment a call to `SaveContextSchema` to regenerate the schema file. +The offline mode uses up to three files beside each other: + +| File | Contents | Read | +|---|---|---| +| `schema.json` (`ContextSchemaPath`) | Tables, columns, relationships, stored procedures | Every build | +| `schema.descriptions.json` | Table and column descriptions (comments), shown in tooltips | For the first tooltip | +| `schema.individuals.json` | Sample rows of the [Individuals](individuals.html) feature | When `Individuals` is first opened | + +Builds read only the schema file, so descriptions and individuals don't slow them down. + +To save the whole database instead of the parts used so far, use these commands while online (before the schema file +exists). Each reads the whole database and may take a while on a large one: + +```fsharp +// Every table, column, relationship and stored procedure, to schema.json, and every table +// and column description, to schema.descriptions.json. No rows of data. +ctx.``Design Time Commands``.SaveContextSchemaFull +// IndividualsAmount individuals of every table with a single primary key, to schema.individuals.json +ctx.``Design Time Commands``.SaveContextSchemaIndividuals +``` + +These two commands exist only while online. Remove the line after saving: once the schema file exists, the +solution is offline and a line that still calls one of them doesn't compile. + +Individuals are rows of your data, so mind GDPR/PII before committing the individuals file to version control. + +When the database schema changes, remove all three files, not only the schema file, before saving again. The +descriptions and individuals files are otherwise kept as they are, and may then describe tables and columns that +no longer exist. + +`SaveContextSchema` also saves the descriptions of the tables and columns you hovered over, and keeps the descriptions +already in the descriptions file. Offline, a table or column whose description wasn't saved shows "Offline mode." in +its tooltip. + +Schema files saved by older versions with individuals in them still work: re-saving such a file moves its individuals +to the individuals file. + There is a tool method FSharp.Data.Sql.Common.OfflineTools.mergeCacheFiles to merge multiple files together. +It merges their descriptions and individuals files as well. *) diff --git a/src/SQLProvider.Common/SqlRuntime.Common.fs b/src/SQLProvider.Common/SqlRuntime.Common.fs index 8c43ac72e..ebf4eab53 100644 --- a/src/SQLProvider.Common/SqlRuntime.Common.fs +++ b/src/SQLProvider.Common/SqlRuntime.Common.fs @@ -932,7 +932,13 @@ and SchemaCache = SprocsParams : ConcurrentDictionary //sproc name and params Packages : ResizeArray Individuals : ConcurrentDictionary) array> //table name and entities - IsOffline : bool } + IsOffline : bool + /// Table descriptions (comments) for tooltips, by table name. Saved in their own file (SaveDescriptions), not in the schema file. + [] + TableDescriptions : ConcurrentDictionary + /// Column descriptions (comments) for tooltips, by table name and column name. Saved like TableDescriptions. + [] + ColumnDescriptions : ConcurrentDictionary> } with static member Empty = { PrimaryKeys = ConcurrentDictionary() @@ -943,22 +949,124 @@ and SchemaCache = SprocsParams = ConcurrentDictionary() Packages = ResizeArray() Individuals = ConcurrentDictionary() - IsOffline = false } + IsOffline = false + TableDescriptions = ConcurrentDictionary() + ColumnDescriptions = ConcurrentDictionary>() } static member Load(filePath) = use ms = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText(filePath))) let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof) - { (ser.ReadObject(ms) :?> SchemaCache) with IsOffline = true } + // Schema files saved before 1.5.34 may carry individuals in the schema file itself: they're kept. + let loaded = ser.ReadObject(ms) :?> SchemaCache + { loaded with + IsOffline = true + Individuals = if isNull loaded.Individuals then ConcurrentDictionary() else loaded.Individuals + TableDescriptions = if isNull loaded.TableDescriptions then ConcurrentDictionary() else loaded.TableDescriptions + ColumnDescriptions = if isNull loaded.ColumnDescriptions then ConcurrentDictionary>() else loaded.ColumnDescriptions } static member LoadOrEmpty(filePath) = - if String.IsNullOrEmpty(filePath) || (not(File.Exists filePath)) then + if String.IsNullOrEmpty(filePath) || (not(File.Exists filePath)) then SchemaCache.Empty else SchemaCache.Load(filePath) - member this.Save(filePath) = + static member private BesideFilePath(filePath:string, kind:string) = + let ext = Path.GetExtension filePath + Path.Combine(Path.GetDirectoryName filePath, Path.GetFileNameWithoutExtension filePath + "." + kind + ext) + /// Individuals are saved beside the schema file: schema.json -> schema.individuals.json + static member IndividualsFilePath(filePath:string) = SchemaCache.BesideFilePath(filePath, "individuals") + /// Descriptions are saved beside the schema file: schema.json -> schema.descriptions.json + static member DescriptionsFilePath(filePath:string) = SchemaCache.BesideFilePath(filePath, "descriptions") + static member private WriteJson(filePath, value:obj) = use ms = new MemoryStream() - let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType()) - ser.WriteObject(ms, { this with IsOffline = true }); - let json = ms.ToArray(); + let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(value.GetType()) + ser.WriteObject(ms, value) + let json = ms.ToArray() File.WriteAllText(filePath, Encoding.UTF8.GetString(json, 0, json.Length)) + static member private ReadJson<'T>(filePath) = + use ms = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText filePath)) + System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof<'T>).ReadObject(ms) :?> 'T + /// Saves the schema, and the descriptions to their own file. Individuals are not in the schema file: + /// SaveIndividuals saves them to their own file. Individuals read from saved files (offline mode) are saved to + /// the individuals file, so a re-save doesn't lose them. + member this.Save(filePath) = + // The empty Individuals is kept so that older SQLProvider versions can read the file. + SchemaCache.WriteJson(filePath, { this with IsOffline = true; Individuals = ConcurrentDictionary() }) + this.SaveDescriptions filePath |> ignore + if this.IsOffline && this.HasIndividuals then + // An individuals file already there is newer than individuals of an old schema file + this.LoadIndividuals filePath + this.SaveIndividuals filePath |> ignore + member this.HasDescriptions = + this.TableDescriptions.Count > 0 || this.ColumnDescriptions.Count > 0 + /// Saves the descriptions to the descriptions file beside the schema file and returns its path; None when there + /// are none. Descriptions already in the file are kept unless read again, so a save of the parts used so far + /// doesn't drop the others. + member this.SaveDescriptions(filePath) = + this.LoadDescriptions filePath + if not this.HasDescriptions then None else + let descriptionsFile = SchemaCache.DescriptionsFilePath filePath + SchemaCache.WriteJson(descriptionsFile, { SchemaDescriptions.TableComments = this.TableDescriptions; ColumnComments = this.ColumnDescriptions }) + Some descriptionsFile + /// Reads the descriptions file beside the schema file, if there is one. Descriptions already read are kept. + member this.LoadDescriptions(filePath) = + if not(String.IsNullOrEmpty filePath) then + let descriptionsFile = SchemaCache.DescriptionsFilePath filePath + if File.Exists descriptionsFile then + let loaded = SchemaCache.ReadJson descriptionsFile + if not (isNull loaded.TableComments) then + for KeyValue(table, description) in loaded.TableComments do + this.TableDescriptions.TryAdd(table, description) |> ignore + if not (isNull loaded.ColumnComments) then + for KeyValue(table, columns) in loaded.ColumnComments do + let known = this.ColumnDescriptions.GetOrAdd(table, fun _ -> ConcurrentDictionary()) + for KeyValue(column, description) in columns do + known.TryAdd(column, description) |> ignore + member this.HasIndividuals = + this.Individuals |> Seq.exists (fun kv -> not (Array.isEmpty kv.Value)) + /// A column value as the individuals file can hold it. The serializer writes only some types when the value + /// is an obj: one DateTimeOffset or string array would fail the whole file. Offline the values of other + /// columns than the primary key are only shown as text, so the others are saved as their text. + static member private IndividualsFileValue(value:obj) : obj = + match value with + | null -> null + | :? string | :? bool | :? char | :? decimal | :? DateTime | :? Guid | :? TimeSpan | :? (byte[]) -> value + | _ when value.GetType().IsPrimitive -> value + | :? Array as items -> box [| for item in items -> SchemaCache.IndividualsFileValue item |] + | _ -> box (value.ToString()) + /// Saves the individuals to the individuals file beside the schema file and returns its path. + /// Tables without individuals are left out. + member this.SaveIndividuals(filePath) = + let individualsFile = SchemaCache.IndividualsFilePath filePath + let toSave = ConcurrentDictionary) array>() + for KeyValue(table, entities) in this.Individuals do + if not (Array.isEmpty entities) then + toSave.[table] <- + entities |> Array.map (fun (pk, columns) -> + SchemaCache.IndividualsFileValue pk, + dict [ for KeyValue(column, value) in columns -> column, SchemaCache.IndividualsFileValue value ]) + SchemaCache.WriteJson(individualsFile, toSave) + individualsFile + /// Reads the individuals file beside the schema file, if there is one. Its individuals replace the same tables' older ones. + member this.LoadIndividuals(filePath) = + if not(String.IsNullOrEmpty filePath) then + let individualsFile = SchemaCache.IndividualsFilePath filePath + if File.Exists individualsFile then + let loaded = SchemaCache.ReadJson) array>> individualsFile + if not (isNull loaded) then + for KeyValue(table, entities) in loaded do + this.Individuals.[table] <- entities + +/// Table and column descriptions as saved in the descriptions file beside the schema file +and SchemaDescriptions = + { /// Table name to description + TableComments : ConcurrentDictionary + /// Table name to column name to description + ColumnComments : ConcurrentDictionary> } + +/// A provider that can read the descriptions of all the columns of a table in one query implements this too. +/// Saving the descriptions of a whole database is then one query per table, not one per column. +type IColumnDescriptionsProvider = + /// Column name to description, for the columns of the table that have a description. + /// The descriptions are the same as ISqlProvider.GetColumnDescription gives. + abstract GetColumnDescriptions : IDbConnection * string -> IDictionary /// GroupResultItems is an item to create key-igrouping-structure. /// From the select group-by projection, aggregate operations like Enumerable.Count() @@ -1243,8 +1351,15 @@ module public OfflineTools = else if File.Exists targetfile then File.Delete targetfile + for besideFile in [ SchemaCache.IndividualsFilePath targetfile; SchemaCache.DescriptionsFilePath targetfile ] do + if File.Exists besideFile then + File.Delete besideFile let s1 = SchemaCache.Load sourcefile1 let s2 = SchemaCache.Load sourcefile2 + s1.LoadIndividuals sourcefile1 + s2.LoadIndividuals sourcefile2 + s1.LoadDescriptions sourcefile1 + s2.LoadDescriptions sourcefile2 let merged = { PrimaryKeys = ConcurrentDictionary( Seq.concat [|s1.PrimaryKeys ; s2.PrimaryKeys |] |> Seq.distinctBy(fun d -> d.Key)); @@ -1267,7 +1382,14 @@ module public OfflineTools = Packages = ResizeArray(Seq.concat [| s1.Packages ; s2.Packages |] |> Seq.distinctBy(fun s -> s.ToString())); Individuals = ConcurrentDictionary( Seq.concat [|s1.Individuals ; s2.Individuals |] |> Seq.distinctBy(fun d -> d.Key)); - IsOffline = s1.IsOffline || s2.IsOffline} + IsOffline = s1.IsOffline || s2.IsOffline + TableDescriptions = ConcurrentDictionary( + Seq.concat [|s1.TableDescriptions ; s2.TableDescriptions |] |> Seq.distinctBy(fun d -> d.Key)) + ColumnDescriptions = ConcurrentDictionary( + Seq.concat [|s1.ColumnDescriptions ; s2.ColumnDescriptions |] + |> Seq.groupBy(fun d -> d.Key) + |> Seq.map(fun (table, descs) -> + KeyValuePair(table, ConcurrentDictionary(descs |> Seq.collect(fun d -> d.Value) |> Seq.distinctBy(fun c -> c.Key))))) } merged.Save targetfile "Merge saved " + targetfile + " at " + DateTime.Now.ToString("hh:mm:ss") diff --git a/src/SQLProvider.Common/Utils.fs b/src/SQLProvider.Common/Utils.fs index c9698563d..d6d87f1d8 100644 --- a/src/SQLProvider.Common/Utils.fs +++ b/src/SQLProvider.Common/Utils.fs @@ -849,6 +849,18 @@ module Sql = let inline dbUnboxWithDefault<'a> def (v:obj) : 'a = if Convert.IsDBNull(v) then def else unbox v + /// Reads rows of a name and its description to a dictionary. Rows without a description are left out, + /// and of rows with the same name the first one counts. + let readDescriptions (reader:IDataReader) = + let descriptions = System.Collections.Generic.Dictionary() + while reader.Read() do + if not (reader.IsDBNull 0) && not (reader.IsDBNull 1) then + let name = reader.GetValue(0).ToString() + let description = reader.GetValue(1).ToString() + if description <> "" && not (descriptions.ContainsKey name) then + descriptions.[name] <- description + descriptions :> System.Collections.Generic.IDictionary + /// Note: SQLProvider reuses the connection through multiple instances, so you can't dispose it here. /// Instead it's created with ISQLProvider's CreateConnection method, and that is having always "use" to ensure it is disposed properly on "finally". let connect (con:IDbConnection) f = diff --git a/src/SQLProvider.DesignTime/SqlDesignTime.fs b/src/SQLProvider.DesignTime/SqlDesignTime.fs index c000e90e7..d6261a10f 100644 --- a/src/SQLProvider.DesignTime/SqlDesignTime.fs +++ b/src/SQLProvider.DesignTime/SqlDesignTime.fs @@ -139,19 +139,47 @@ module DesignTimeUtils = let transactionOptions = TransactionOptions.Default - let createIndividualsType (con:IDbConnection option) (prov:ISqlProvider) (table:Table) (designTimeDc:Lazy<_>) dbVendor individualsAmount tableTypeDef = - let t = ProvidedTypeDefinition($"{table.Schema}.{table.Name}.Individuals", Some typeof, isErased=true) - let individualsTypes = ResizeArray<_>() - individualsTypes.Add t - - t.AddXmlDocDelayed(fun _ -> $"A sample of %s{table.Name} individuals from the SQL object as supplied in the static parameters") - t.AddMember(ProvidedConstructor([ProvidedParameter("dataContext", typeof)], empty)) - t.AddMembersDelayed( fun _ -> + /// A table's description (comment). Online it's read from the database and kept in the schema cache, so a + /// save keeps it; offline it comes from the descriptions file, read on first use. None when it wasn't saved. + let tableDescription (con:IDbConnection option) (prov:ISqlProvider) (offlineDescriptions:Lazy) (tableName:string) = + let descriptions = prov.GetSchemaCache().TableDescriptions + match con with + | Some con -> + let description = match prov.GetTableDescription(con, tableName) with null -> "" | d -> d + descriptions.[tableName] <- description + Some description + | None -> + offlineDescriptions.Force() + match descriptions.TryGetValue tableName with + | true, description -> Some description + | false, _ -> None + + /// A column's description (comment), kept in the schema cache like tableDescription. + let columnDescription (con:IDbConnection option) (prov:ISqlProvider) (offlineDescriptions:Lazy) (tableName:string) (columnName:string) = + let descriptions = prov.GetSchemaCache().ColumnDescriptions + match con with + | Some con -> + let description = match prov.GetColumnDescription(con, tableName, columnName) with null -> "" | d -> d + descriptions.GetOrAdd(tableName, fun _ -> System.Collections.Concurrent.ConcurrentDictionary()).[columnName] <- description + Some description + | None -> + offlineDescriptions.Force() + match descriptions.TryGetValue tableName with + | true, columns -> + match columns.TryGetValue columnName with + | true, description -> Some description + | false, _ -> None + | false, _ -> None + + /// The primary key and individuals of a table with a single primary key. Read from the database once and kept + /// in the schema cache; offline they come from the individuals file. + let getIndividuals (con:IDbConnection option) (prov:ISqlProvider) (table:Table) (designTimeDc:Lazy<_>) (offlineIndividuals:Lazy) dbVendor individualsAmount = let columns = match con with | Some con -> prov.GetColumns(con,table) | None -> prov.GetSchemaCache().Columns.TryGetValue(table.FullName) |> function | true,cols -> cols | false, _ -> Map.empty match prov.GetPrimaryKey table with + | None -> None | Some pkName -> let rec (|FixedType|_|) (o:obj) = @@ -169,6 +197,7 @@ module DesignTimeUtils = | _, _ -> None let dcDone = designTimeDc.Force() + if con.IsNone then offlineIndividuals.Force() let entities = prov.GetSchemaCache().Individuals.GetOrAdd(($"{table.FullName}_{pkName}"), fun k -> match con with @@ -186,6 +215,18 @@ module DesignTimeUtils = mapped | None -> [||] ) + Some (pkName, entities) + + let createIndividualsType (con:IDbConnection option) (prov:ISqlProvider) (table:Table) (designTimeDc:Lazy<_>) (offlineIndividuals:Lazy) dbVendor individualsAmount tableTypeDef = + let t = ProvidedTypeDefinition($"{table.Schema}.{table.Name}.Individuals", Some typeof, isErased=true) + let individualsTypes = ResizeArray<_>() + individualsTypes.Add t + + t.AddXmlDocDelayed(fun _ -> $"A sample of %s{table.Name} individuals from the SQL object as supplied in the static parameters") + t.AddMember(ProvidedConstructor([ProvidedParameter("dataContext", typeof)], empty)) + t.AddMembersDelayed( fun _ -> + match getIndividuals con prov table designTimeDc offlineIndividuals dbVendor individualsAmount with + | Some (pkName, entities) -> if Array.isEmpty entities then [] else // for each column in the entity except the primary key, create a new type that will read ``As Column 1`` etc // inside that type the individuals will be listed again but with the text for the relevant column as the name @@ -227,13 +268,16 @@ module DesignTimeUtils = // this next bit is just side effect to populate the "As Column" types for the supported columns for colName, colValue in columnValues |> Seq.map(fun kvp -> kvp.Key, kvp.Value) do if colName <> pkName then - let colDefinition, _ = propertyMap.[colName] - colDefinition.AddMemberDelayed(fun() -> - ProvidedProperty( sprintf "%s, %s" (prettyPrint pkValue) (prettyPrint colValue) - , tableTypeDef - , getterCode = getterCode - ) - ) + // An individuals file saved before the schema changed may have columns the schema doesn't + match propertyMap.TryFind colName with + | Some (colDefinition, _) -> + colDefinition.AddMemberDelayed(fun() -> + ProvidedProperty( sprintf "%s, %s" (prettyPrint pkValue) (prettyPrint colValue) + , tableTypeDef + , getterCode = getterCode + ) + ) + | None -> () // return the primary key property Some <| ProvidedProperty(prettyPrint pkValue , tableTypeDef @@ -252,7 +296,7 @@ module DesignTimeUtils = | None -> []) individualsTypes :> seq<_> - let createColumnProperty (con:IDbConnection option) (prov:ISqlProvider) useOptionTypes key (c:Column) = + let createColumnProperty (con:IDbConnection option) (prov:ISqlProvider) (offlineDescriptions:Lazy) useOptionTypes key (c:Column) = let nullable = if c.IsNullable then useOptionTypes else NullableColumnType.NO_OPTION let ty = Utilities.getType c.TypeMapping.ClrType @@ -296,15 +340,13 @@ module DesignTimeUtils = let nfo = c.TypeInfo let typeInfo = match nfo with ValueNone -> "" | ValueSome x -> x.ToString() - match con with - | Some con -> - prop.AddXmlDocDelayed(fun () -> - let details = prov.GetColumnDescription(con, key, name).Replace("<","<").Replace(">",">") + prop.AddXmlDocDelayed(fun () -> + match columnDescription con prov offlineDescriptions key name with + | Some description -> + let details = description.Replace("<","<").Replace(">",">") let separator = if (String.IsNullOrWhiteSpace typeInfo) || (String.IsNullOrWhiteSpace details) then "" else "/" - sprintf "%s %s %s" (String.concat ": " [|name; details|]) separator typeInfo) - | None -> - prop.AddXmlDocDelayed(fun () -> $"Offline mode. %s{typeInfo}") - () + sprintf "%s %s %s" (String.concat ": " [|name; details|]) separator typeInfo + | None -> $"Offline mode. %s{typeInfo}") prop let generateSprocMethod (container:ProvidedTypeDefinition) (con:IDbConnection option) (prov:ISqlProvider) (sproc:CompileTimeSprocDefinition) = @@ -469,66 +511,89 @@ module DesignTimeUtils = |> Seq.map snd | sproc::rest -> generateTypeTree con prov (walkSproc con prov [] None createdTypes sproc) rest - let createDesignTimeCommands (prov:ISqlProvider) contextSchemaPath recreate (invalidate: _ -> Unit)= + let createDesignTimeCommands (prov:ISqlProvider) contextSchemaPath recreate (invalidate: _ -> Unit) (onlineCommands: (string * string * (unit -> string)) list) = let designTimeCommandsContainer = ProvidedTypeDefinition("DesignTimeCommands", Some typeof, isErased=true) let designTime = ProvidedProperty("Design Time Commands", designTimeCommandsContainer, getterCode = empty) designTime.AddXmlDocDelayed(fun () -> "Developer's design time commands to TypeProvider.") + /// Runs a design-time command, unless one is already running (None then). The flag is reset even if the command fails. + let runCommand (command: unit -> string) = + if saveInProcess then None else + lock mySaveLock (fun() -> + saveInProcess <- true + try Some (command()) + finally saveInProcess <- false) + + let commandResult result = + match result with + | Some message -> [ ProvidedProperty(message, typeof, getterCode = empty) :> MemberInfo ] + | None -> [] + let saveResponse = ProvidedTypeDefinition("SaveContextResponse", Some typeof, isErased=true) saveResponse.AddMember(ProvidedConstructor([], empty)) saveResponse.AddMembersDelayed(fun () -> - if not saveInProcess then - let result = - if not(String.IsNullOrEmpty contextSchemaPath) then - try - lock mySaveLock (fun() -> - saveInProcess <- true - prov.GetSchemaCache().Save contextSchemaPath - saveInProcess <- false - "Saved " + contextSchemaPath + " at " + DateTime.Now.ToString("hh:mm:ss") - ) - with - | e -> "Save failed: " + e.Message - else "ContextSchemaPath is not defined" - [ ProvidedProperty(result,typeof, getterCode = empty) :> MemberInfo ] - else [] + if String.IsNullOrEmpty contextSchemaPath then commandResult (Some "ContextSchemaPath is not defined") else + runCommand (fun () -> + try + prov.GetSchemaCache().Save contextSchemaPath + "Saved " + contextSchemaPath + " at " + DateTime.Now.ToString("hh:mm:ss") + with + | e -> "Save failed: " + e.Message) + |> commandResult ) let m = ProvidedProperty("SaveContextSchema", (saveResponse :> Type), getterCode = empty) let mOld = ProvidedMethod("SaveContextSchema", [], (saveResponse :> Type), invokeCode = empty) m.AddXmlDocComputed(fun () -> if String.IsNullOrEmpty contextSchemaPath then "ContextSchemaPath static parameter has to be defined to use this function." - else "Schema location: " + contextSchemaPath + ". Write dot after SaveContextSchema to save the schema at design time." + else "Schema location: " + contextSchemaPath + ". Write dot after SaveContextSchema to save the schema used so far at design time, " + + "and the descriptions read so far to " + SchemaCache.DescriptionsFilePath contextSchemaPath + ". " + + "Online, SaveContextSchemaFull saves the whole database schema and SaveContextSchemaIndividuals the individuals." ) let expirationMessage = "Expired, moved under: .``Design Time Commands``" mOld.AddXmlDocComputed(fun () -> expirationMessage) mOld.AddObsoleteAttribute expirationMessage + /// Adds a command: a property whose type gets its member when you type a dot after it. Computing the member + /// runs the command, and the member's name tells how it went. + let addCommand name (tooltip: string) (command: unit -> string) = + let response = ProvidedTypeDefinition(name + "Response", Some typeof, isErased=true) + response.AddMember(ProvidedConstructor([], empty)) + response.AddMembersDelayed(fun () -> + runCommand (fun () -> + try command() + with e -> name + " failed: " + e.Message) + |> commandResult) + let property = ProvidedProperty(name, (response :> Type), getterCode = empty) + property.AddXmlDocComputed(fun () -> tooltip) + designTimeCommandsContainer.AddMember response + designTimeCommandsContainer.AddMember property + + for name, tooltip, command in onlineCommands do + addCommand name tooltip command + // ClearDatabaseSchemaCache only in online-mode if String.IsNullOrEmpty contextSchemaPath then let invalidateActionResponse = ProvidedTypeDefinition("InvalidateResponse", Some typeof, isErased=true) invalidateActionResponse.AddMember(ProvidedConstructor([], empty)) invalidateActionResponse.AddMembersDelayed(fun () -> - if not saveInProcess then - let result = - lock mySaveLock (fun() -> - saveInProcess <- true - let schemacache = prov.GetSchemaCache() - schemacache.PrimaryKeys.Clear() - schemacache.Tables.Clear() - schemacache.Columns.Clear() - schemacache.Relationships.Clear() - schemacache.Sprocs.Clear() - schemacache.SprocsParams.Clear() - schemacache.Packages.Clear() - schemacache.Individuals.Clear() - invalidate() - let pf = recreate() - saveInProcess <- false - "Database schema cache cleared.") - [ProvidedProperty(result,typeof, getterCode = empty) :> MemberInfo] - else [] + runCommand (fun () -> + let schemacache = prov.GetSchemaCache() + schemacache.PrimaryKeys.Clear() + schemacache.Tables.Clear() + schemacache.Columns.Clear() + schemacache.Relationships.Clear() + schemacache.Sprocs.Clear() + schemacache.SprocsParams.Clear() + schemacache.Packages.Clear() + schemacache.Individuals.Clear() + schemacache.TableDescriptions.Clear() + schemacache.ColumnDescriptions.Clear() + invalidate() + recreate() + "Database schema cache cleared.") + |> commandResult ) let m2 = ProvidedProperty("ClearDatabaseSchemaCache", (invalidateActionResponse :> Type), getterCode = empty) m2.AddXmlDocComputed(fun () -> @@ -624,6 +689,20 @@ module DesignTimeUtils = | None -> prov.GetSchemaCache().Sprocs |> Seq.toList let getTableData name = tableColumns.Force().[name].Force() + // Offline, individuals are in their own file, read when an Individuals type is first expanded + let offlineIndividuals = + lazy + if con.IsNone then + // Individuals are optional: an unreadable individuals file just leaves them out + try prov.GetSchemaCache().LoadIndividuals contextSchemaPath + with _ -> () + // Offline, descriptions are in their own file, read for the first tooltip: builds never need them + let offlineDescriptions = + lazy + if con.IsNone then + // Descriptions are optional: an unreadable descriptions file just leaves them out + try prov.GetSchemaCache().LoadDescriptions contextSchemaPath + with _ -> () let designTimeDc = lazy SqlDataContext(rootTypeName, conString, dbVendor, resolutionPath, config.ReferencedAssemblies, config.RuntimeAssembly, owner, caseSensitivity, tableNames, contextSchemaPath, odbcquote, sqliteLibrary, transactionOptions, None, SelectOperations.DotNetSide, ssdtPath, true) // first create all the types so we are able to recursively reference them in each other's definitions let baseTypes = @@ -676,7 +755,7 @@ module DesignTimeUtils = let ct = ProvidedTypeDefinition(name, Some typeof,isErased=true) ct.AddInterfaceImplementationsDelayed( fun () -> [ProvidedTypeBuilder.MakeGenericType(typedefof>,[et :> Type]); typeof]) let tableTypeDef,_,_,_ = baseTypes.Force().[table.FullName] - let it = createIndividualsType con prov table designTimeDc dbVendor individualsAmount tableTypeDef + let it = createIndividualsType con prov table designTimeDc offlineIndividuals dbVendor individualsAmount tableTypeDef yield name,(ct,it) | false, _ -> ()] @@ -685,7 +764,7 @@ module DesignTimeUtils = t.AddMembersDelayed(fun () -> let (columns,(children,parents)) = getTableData key let attProps = - let createCols = createColumnProperty con prov useOptionTypes key + let createCols = createColumnProperty con prov offlineDescriptions useOptionTypes key List.map createCols (columns |> Seq.map (fun kvp -> kvp.Value) |> Seq.toList) let relProps = let getRelationshipName = Utilities.uniqueName() @@ -745,6 +824,113 @@ module DesignTimeUtils = let getOrAddSchema (name:string) = schemaTypes.GetOrAdd(name, fun nme -> ProvidedTypeDefinition(nme + "Schema", Some typeof, isErased=true)) + // Design-time commands that read the whole database at once, instead of what IntelliSense opened so far, + // and save it beside ContextSchemaPath. Only online: offline there's no database to read. + let onlineCommands = + match con with + | Some connection when not (String.IsNullOrEmpty contextSchemaPath) -> + let schemaCache () = prov.GetSchemaCache() + let savedAt file = "Saved " + file + " at " + DateTime.Now.ToString("hh:mm:ss") + ":" + let failures (failed: ResizeArray) = + if failed.Count = 0 then "" else $" {failed.Count} failed, the first: {failed.[0]}." + /// Runs read for every table; a table that fails doesn't stop the others. + let forTables (failed: ResizeArray) (read: Table -> bool) = + let mutable count = 0 + for table in tables.Force() do + try if read table then count <- count + 1 + with e -> failed.Add(table.FullName + ": " + e.Message) + count + + // A stored procedure's parameters and return columns are read when IntelliSense opens its type, and + // saved under the name of that type: overloads get different names. So open the types the same way. + let declared = BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Static ||| BindingFlags.DeclaredOnly + let rec openTypes (failed: ResizeArray) (t: Type) = + // Listing the nested types adds the stored procedures' types, which may show only in the next listing + let rec nestedTypes (known: Type[]) = + let listed = t.GetNestedTypes declared + if listed.Length = known.Length then listed else nestedTypes listed + let nested = + try nestedTypes [||] + with e -> + let name = if isNull t.DeclaringType then t.Name else t.DeclaringType.Name + "." + t.Name + failed.Add(name + ": " + e.Message) + [||] + for n in nested do + openTypes failed n + + let readFullSchema (failed: ResizeArray) = + // Columns, primary keys and relationships go to the schema cache as they're read + let tableCount = forTables failed (fun table -> getTableData table.FullName |> ignore; true) + for container in containers do + openTypes failed (container :> Type) + $" {tableCount} tables and {schemaCache().SprocsParams.Count} stored procedures." + + let readDescriptions (failed: ResizeArray) = + let tableCount = + forTables failed (fun table -> + let columns, _ = getTableData table.FullName + tableDescription con prov offlineDescriptions table.FullName |> ignore + match prov with + | :? IColumnDescriptionsProvider as allColumns -> + // One query for the table, instead of one for each column + let described = allColumns.GetColumnDescriptions(connection, table.FullName) + let known = schemaCache().ColumnDescriptions.GetOrAdd(table.FullName, fun _ -> System.Collections.Concurrent.ConcurrentDictionary()) + for KeyValue(_, column) in columns do + known.[column.Name] <- + match described.TryGetValue column.Name with + | true, description when not (isNull description) -> description + | _ -> "" + | _ -> + for KeyValue(_, column) in columns do + columnDescription con prov offlineDescriptions table.FullName column.Name |> ignore + true) + $" descriptions of {tableCount} tables." + + let readIndividuals (failed: ResizeArray) = + let tableCount = + forTables failed (fun table -> + match getIndividuals con prov table designTimeDc offlineIndividuals dbVendor individualsAmount with + | Some (_, entities) -> not (Array.isEmpty entities) + | None -> false) + $" individuals of {tableCount} tables." + + /// The whole schema and all the descriptions: metadata only, no rows. + let saveFull () = + let failed = ResizeArray() + let schema = readFullSchema failed + let descriptions = readDescriptions failed + let cache = schemaCache() + cache.Save contextSchemaPath + let files = + [ yield contextSchemaPath + if cache.HasDescriptions then yield SchemaCache.DescriptionsFilePath contextSchemaPath ] + savedAt (String.concat ", " files) + schema + descriptions + failures failed + + /// Rows of data: a step of its own, apart from the schema, because of GDPR/PII. + let saveIndividuals () = + let failed = ResizeArray() + let read = readIndividuals failed + if schemaCache().HasIndividuals then savedAt (schemaCache().SaveIndividuals contextSchemaPath) + read + failures failed + else "No individuals to save: no table with a single primary key has rows." + failures failed + + // SSDT reads a .dacpac: it has no rows + let hasIndividuals = dbVendor <> DatabaseProviderTypes.MSSQLSERVER_SSDT + + let individualsFile = SchemaCache.IndividualsFilePath contextSchemaPath + let descriptionsFile = SchemaCache.DescriptionsFilePath contextSchemaPath + [ yield "SaveContextSchemaFull", + "Saves every table, column, relationship and stored procedure of the database to " + contextSchemaPath + + ", not only the ones used so far, and the descriptions (comments) of every table and column to " + + descriptionsFile + ". No rows of data. Write dot after SaveContextSchemaFull to save. May take a while.", + saveFull + if hasIndividuals then + yield "SaveContextSchemaIndividuals", + "Saves IndividualsAmount individuals (rows) of every table with a single primary key to " + individualsFile + + ". Write dot after SaveContextSchemaIndividuals to save. May take a while. " + + "Individuals are rows of your data: mind GDPR/PII before committing the file.", + saveIndividuals ] + | _ -> [] + let addServiceTypeMembers (isReadonly:bool) = [ if not isReadonly then @@ -1002,15 +1188,13 @@ module DesignTimeUtils = let a0 = args.[0] <@@ ((%%a0 : obj) :?> ISqlDataContext).CreateEntities key @@> ) let tname = ct.Name - match con with - | Some con -> - prop.AddXmlDocDelayed (fun () -> - let details = prov.GetTableDescription(con, tname).Replace("<","<").Replace(">",">") + prop.AddXmlDocDelayed (fun () -> + match tableDescription con prov offlineDescriptions tname with + | Some description -> + let details = description.Replace("<","<").Replace(">",">") let separator = if (String.IsNullOrWhiteSpace desc) || (String.IsNullOrWhiteSpace details) then "" else "/" - $"%s{details} %s{separator} %s{desc}") - | None -> - prop.AddXmlDocDelayed (fun () -> "Offline mode.") - () + $"%s{details} %s{separator} %s{desc}" + | None -> $"Offline mode. %s{desc}") schemaType.AddMember ct if not (schemaType.DeclaredMembers |> Seq.exists(fun m -> m.Name = prop.Name)) then schemaType.AddMember prop @@ -1047,7 +1231,7 @@ module DesignTimeUtils = if not isReadonly then let recreate = fun () -> createTypes rootType serviceType readServiceType config sqlRuntimeInfo invalidate registerClose (connectionString, conStringName,dbVendor,resolutionPath,individualsAmount,useOptionTypes,owner,caseSensitivity, tableNames, contextSchemaPath, odbcquote, sqliteLibrary, ssdtPath, rootTypeName) let designTimeCommandsContainer, saveResponse, mOld, designTime, invalidateActionResponse = - createDesignTimeCommands prov contextSchemaPath recreate invalidate + createDesignTimeCommands prov contextSchemaPath recreate invalidate onlineCommands designTimeCommandsContainer.AddMember saveResponse designTimeCommandsContainer.AddMember templateContainer diff --git a/src/SQLProvider.Runtime/Providers.DuckDb.fs b/src/SQLProvider.Runtime/Providers.DuckDb.fs index e36115b30..8d33ec38a 100644 --- a/src/SQLProvider.Runtime/Providers.DuckDb.fs +++ b/src/SQLProvider.Runtime/Providers.DuckDb.fs @@ -538,6 +538,20 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re #if REFLECTIONLOAD DuckDb.referencedAssemblies <- referencedAssemblies #endif + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let sn = tableName.Substring(0,tableName.LastIndexOf('.')) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let baseQuery = @"SELECT COLUMN_NAME, COLUMN_COMMENT + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = $schema AND TABLE_NAME = $table" + use com = (this:>ISqlProvider).CreateCommand(con,baseQuery) + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("schema", 0), sn)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("table", 1), (DuckDb.ripQuotes tn))) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() + Sql.readDescriptions reader + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.Firebird.fs b/src/SQLProvider.Runtime/Providers.Firebird.fs index 0c40a6f23..308341ede 100644 --- a/src/SQLProvider.Runtime/Providers.Firebird.fs +++ b/src/SQLProvider.Runtime/Providers.Firebird.fs @@ -692,6 +692,18 @@ type internal FirebirdProvider(resolutionPath, contextSchemaPath, owner, referen #if REFLECTIONLOAD Firebird.referencedAssemblies <- referencedAssemblies #endif + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let baseQuery = @"SELECT trim(RDB$FIELD_NAME), RDB$DESCRIPTION + FROM RDB$RELATION_FIELDS + WHERE RDB$RELATION_NAME = @table" + use com = (this:>ISqlProvider).CreateCommand(con,baseQuery) + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@table", 1), (Firebird.ripQuotes tn))) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() + Sql.readDescriptions reader + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs index 09d1ac330..0e4a6ed21 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs @@ -579,6 +579,23 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe MSSqlServerDynamic.resolutionPath <- resolutionPath MSSqlServerDynamic.referencedAssemblies <- referencedAssemblies + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let baseq = + """select sc.name, sep.value + from sys.tables st + inner join sys.columns sc on st.object_id = sc.object_id + inner join sys.extended_properties sep on st.object_id = sep.major_id + and sc.column_id = sep.minor_id + and sep.name = 'MS_Description' + where st.name = @TableName""" + use com = (this:>ISqlProvider).CreateCommand(con,baseq) + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@TableName", 0), tn)) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() + Sql.readDescriptions reader + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs index 73326e857..1c3c6e5a8 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs @@ -500,6 +500,23 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = // Remembers the version of each instance it connects to let mssqlVersionCache = ConcurrentDictionary>() + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let baseq = + """select sc.name, sep.value + from sys.tables st + inner join sys.columns sc on st.object_id = sc.object_id + inner join sys.extended_properties sep on st.object_id = sep.major_id + and sc.column_id = sep.minor_id + and sep.name = 'MS_Description' + where st.name = @TableName""" + use com = new SqlCommand(baseq,con:?>SqlConnection) + com.Parameters.AddWithValue("@TableName",tn) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() + Sql.readDescriptions reader + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.MySql.fs b/src/SQLProvider.Runtime/Providers.MySql.fs index 1a5da092d..805ceaaef 100644 --- a/src/SQLProvider.Runtime/Providers.MySql.fs +++ b/src/SQLProvider.Runtime/Providers.MySql.fs @@ -594,6 +594,20 @@ type internal MySqlProvider(resolutionPath, contextSchemaPath, owner:string, ref #if REFLECTIONLOAD MySql.referencedAssemblies <- referencedAssemblies #endif + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let sn = tableName.Substring(0,tableName.LastIndexOf('.')) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let baseQuery = @"SELECT COLUMN_NAME, COLUMN_COMMENT + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table" + use com = (this:>ISqlProvider).CreateCommand(con,baseQuery) + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@schema", 0), sn)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@table", 1), (MySql.ripQuotes tn))) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() + Sql.readDescriptions reader + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.Oracle.fs b/src/SQLProvider.Runtime/Providers.Oracle.fs index c4e6c7a18..eec1ee48b 100644 --- a/src/SQLProvider.Runtime/Providers.Oracle.fs +++ b/src/SQLProvider.Runtime/Providers.Oracle.fs @@ -721,6 +721,20 @@ type internal OracleProvider(resolutionPath, contextSchemaPath, owner, reference #endif Oracle.resolutionPath <- resolutionPath + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + Sql.connect con (fun con -> + let query = + sprintf """SELECT COLUMN_NAME, COMMENTS + FROM user_col_comments + WHERE TABLE_NAME = '%s' + AND COMMENTS <> '-' + """ tn + use com = Oracle.createCommand query con + use reader = com.ExecuteReader() + Sql.readDescriptions reader) + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true diff --git a/src/SQLProvider.Runtime/Providers.Postgresql.fs b/src/SQLProvider.Runtime/Providers.Postgresql.fs index ce8558614..3db4586c2 100644 --- a/src/SQLProvider.Runtime/Providers.Postgresql.fs +++ b/src/SQLProvider.Runtime/Providers.Postgresql.fs @@ -822,6 +822,23 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer owner.Split(';', ',', ' ', '\n', '\r') |> Array.filter (not << String.IsNullOrWhiteSpace) + interface IColumnDescriptionsProvider with + member __.GetColumnDescriptions(con,tableName) = + Sql.connect con (fun _ -> + let sn = tableName.Substring(0,tableName.LastIndexOf('.')) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + use reader = + Sql.executeSql PostgreSQL.createCommand ( + sprintf """SELECT c.column_name, d.description + FROM pg_description d + LEFT JOIN information_schema.columns c + ON c.ordinal_position = d.objsubid + WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass + AND c.table_schema = '%s' + AND c.table_name = '%s'; + """ sn tn sn tn) con + Sql.readDescriptions reader) + interface ISqlProvider with member __.CloseConnectionAfterQuery = true member __.DesignConnection = true @@ -829,12 +846,15 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = Sql.connect con (fun _ -> - use reader = + // The names are quoted (%I), so that a table with capital letters in its name is found + let sn = tableName.Substring(0,tableName.LastIndexOf('.')) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + use reader = Sql.executeSql PostgreSQL.createCommand ( sprintf """SELECT description FROM pg_description - WHERE objoid = '%s'::regclass AND objsubid=0; - """ tableName) con + WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass AND objsubid=0; + """ sn tn) con if reader.Read() then let comment = Sql.dbUnbox reader.["description"] if isNull comment then "" else comment @@ -850,11 +870,11 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer FROM pg_description d LEFT JOIN information_schema.columns c ON c.ordinal_position = d.objsubid - WHERE objoid = '%s'::regclass + WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass AND c.table_schema = '%s' AND c.table_name = '%s' AND c.column_name = '%s'; - """ tableName sn tn columnName) con + """ sn tn sn tn columnName) con if reader.Read() then let comment = Sql.dbUnbox reader.["description"] if isNull comment then "" else comment diff --git a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs new file mode 100644 index 000000000..9b1c57e4e --- /dev/null +++ b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs @@ -0,0 +1,224 @@ +module SchemaCacheFileTests + +// The individuals of a saved schema (ContextSchemaPath) are in their own file beside it. + +open System +open System.IO +open System.Text +open System.Collections.Generic +open System.Collections.Concurrent +open FSharp.Data.Sql.Common +open NUnit.Framework + +let private tempSchemaPath () = + let dir = Path.Combine(Path.GetTempPath(), "SqlProviderSchemaTests", Guid.NewGuid().ToString("N")) + Directory.CreateDirectory dir |> ignore + Path.Combine(dir, "schema.json") + +let private customers () : (obj * IDictionary) array = + [| for i in 1 .. 3 -> box i, (dict [ "Id", box i; "Name", box (sprintf "Customer %d" i) ]) |] + +let private withCustomers (cache:SchemaCache) = + cache.Tables.["main.Customers"] <- { Schema = "main"; Name = "Customers"; Type = "TABLE" } + cache.Individuals.["main.Customers_Id"] <- customers () + cache + +/// A schema file as versions before 1.5.34 saved it: individuals in the schema file itself +let private saveOldFormat (cache:SchemaCache) (filePath:string) = + use ms = new MemoryStream() + let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof) + ser.WriteObject(ms, { cache with IsOffline = true }) + File.WriteAllText(filePath, Encoding.UTF8.GetString(ms.ToArray())) + +let private names (entities:(obj * IDictionary) array) = + entities |> Array.map (fun (_, cols) -> string cols.["Name"]) + +[] +let ``the individuals file is beside the schema file`` () = + Assert.AreEqual(Path.Combine("c:\\db", "schema.individuals.json"), SchemaCache.IndividualsFilePath(Path.Combine("c:\\db", "schema.json"))) + Assert.AreEqual("schema.individuals", SchemaCache.IndividualsFilePath "schema") + +[] +let ``saving the schema leaves out the individuals of an online cache`` () = + let path = tempSchemaPath () + let cache = withCustomers SchemaCache.Empty + cache.Save path + Assert.IsFalse(File.Exists(SchemaCache.IndividualsFilePath path)) + let loaded = SchemaCache.Load path + Assert.IsTrue(loaded.Tables.ContainsKey "main.Customers") + Assert.AreEqual(0, loaded.Individuals.Count) + StringAssert.DoesNotContain("Customer 1", File.ReadAllText path) + +[] +let ``saved individuals are read from their own file`` () = + let path = tempSchemaPath () + let cache = withCustomers SchemaCache.Empty + cache.Save path + let individualsFile = cache.SaveIndividuals path + Assert.AreEqual(SchemaCache.IndividualsFilePath path, individualsFile) + let loaded = SchemaCache.Load path + Assert.AreEqual(0, loaded.Individuals.Count) + loaded.LoadIndividuals path + CollectionAssert.AreEqual(names (customers ()), names loaded.Individuals.["main.Customers_Id"]) + +[] +let ``tables without individuals are not saved`` () = + let path = tempSchemaPath () + let cache = withCustomers SchemaCache.Empty + cache.Individuals.["main.Orders_Id"] <- [||] + cache.SaveIndividuals path |> ignore + let loaded = SchemaCache.Empty + loaded.LoadIndividuals path + Assert.IsFalse(loaded.Individuals.ContainsKey "main.Orders_Id") + Assert.IsTrue(loaded.Individuals.ContainsKey "main.Customers_Id") + +[] +let ``column values the file can't hold as such are saved as text`` () = + let path = tempSchemaPath () + let cache = SchemaCache.Empty + let changed = DateTimeOffset(2026, 11, 20, 12, 0, 0, TimeSpan.FromHours 2.) + cache.Individuals.["main.Customers_Id"] <- + [| box 1, (dict [ "Id", box 1; "Name", box "Customer 1"; "Changed", box changed + "Tags", box [| "a"; "b" |]; "Address", box (Net.IPAddress.Parse "10.0.0.1") + "Missing", box DBNull.Value; "Nothing", null ]) |] + cache.SaveIndividuals path |> ignore + let loaded = SchemaCache.Empty + loaded.LoadIndividuals path + let columns = snd loaded.Individuals.["main.Customers_Id"].[0] + Assert.AreEqual("Customer 1", columns.["Name"]) + Assert.AreEqual(changed.ToString(), columns.["Changed"]) + CollectionAssert.AreEqual([| "a"; "b" |], columns.["Tags"] :?> obj[]) + Assert.AreEqual("10.0.0.1", columns.["Address"]) + Assert.AreEqual("", columns.["Missing"]) + Assert.IsNull(columns.["Nothing"]) + // The cache itself keeps the values as they were read + Assert.AreEqual(box changed, (snd cache.Individuals.["main.Customers_Id"].[0]).["Changed"]) + +[] +let ``a schema file with individuals in it still loads them`` () = + let path = tempSchemaPath () + saveOldFormat (withCustomers SchemaCache.Empty) path + let loaded = SchemaCache.Load path + CollectionAssert.AreEqual(names (customers ()), names loaded.Individuals.["main.Customers_Id"]) + +[] +let ``re-saving an old schema file moves its individuals to their own file`` () = + let path = tempSchemaPath () + saveOldFormat (withCustomers SchemaCache.Empty) path + let loaded = SchemaCache.Load path + loaded.Save path + StringAssert.DoesNotContain("Customer 1", File.ReadAllText path) + let reloaded = SchemaCache.Load path + reloaded.LoadIndividuals path + CollectionAssert.AreEqual(names (customers ()), names reloaded.Individuals.["main.Customers_Id"]) + +[] +let ``the individuals file wins over individuals of an old schema file`` () = + let path = tempSchemaPath () + saveOldFormat (withCustomers SchemaCache.Empty) path + let newer = SchemaCache.Empty + newer.Individuals.["main.Customers_Id"] <- [| box 9, (dict [ "Id", box 9; "Name", box "Newer" ]) |] + newer.SaveIndividuals path |> ignore + let loaded = SchemaCache.Load path + loaded.Save path + let reloaded = SchemaCache.Load path + reloaded.LoadIndividuals path + CollectionAssert.AreEqual([| "Newer" |], names reloaded.Individuals.["main.Customers_Id"]) + +[] +let ``merging schema files merges their individuals files`` () = + let path1, path2, target = tempSchemaPath (), tempSchemaPath (), tempSchemaPath () + let cache1 = withCustomers SchemaCache.Empty + cache1.Save path1 + cache1.SaveIndividuals path1 |> ignore + let cache2 = SchemaCache.Empty + cache2.Individuals.["main.Orders_Id"] <- [| box 1, (dict [ "Id", box 1; "Name", box "Order 1" ]) |] + cache2.Save path2 + cache2.SaveIndividuals path2 |> ignore + OfflineTools.mergeCacheFiles(path1, path2, target) |> ignore + StringAssert.DoesNotContain("Customer 1", File.ReadAllText target) + let merged = SchemaCache.Load target + merged.LoadIndividuals target + Assert.IsTrue(merged.Individuals.ContainsKey "main.Customers_Id") + Assert.IsTrue(merged.Individuals.ContainsKey "main.Orders_Id") + +// Table and column descriptions (comments) are in their own file too, for tooltips in offline mode. + +let private columnDescriptions (pairs: (string * string) list) = + ConcurrentDictionary(pairs |> Seq.map (fun (k, v) -> KeyValuePair(k, v))) + +let private describedCustomers () = + let cache = withCustomers SchemaCache.Empty + cache.TableDescriptions.["main.Customers"] <- "People who buy" + cache.TableDescriptions.["main.Orders"] <- "" + cache.ColumnDescriptions.["main.Customers"] <- columnDescriptions [ "Name", "Full name"; "Id", "" ] + cache + +[] +let ``the descriptions file is beside the schema file`` () = + Assert.AreEqual(Path.Combine("c:\\db", "schema.descriptions.json"), SchemaCache.DescriptionsFilePath(Path.Combine("c:\\db", "schema.json"))) + +[] +let ``saving the schema saves the descriptions to their own file`` () = + let path = tempSchemaPath () + (describedCustomers ()).Save path + StringAssert.DoesNotContain("People who buy", File.ReadAllText path) + let loaded = SchemaCache.Load path + Assert.AreEqual(0, loaded.TableDescriptions.Count) + loaded.LoadDescriptions path + Assert.AreEqual("People who buy", loaded.TableDescriptions.["main.Customers"]) + Assert.AreEqual("", loaded.TableDescriptions.["main.Orders"]) + Assert.AreEqual("Full name", loaded.ColumnDescriptions.["main.Customers"].["Name"]) + Assert.AreEqual("", loaded.ColumnDescriptions.["main.Customers"].["Id"]) + +[] +let ``without descriptions there is no descriptions file`` () = + let path = tempSchemaPath () + (withCustomers SchemaCache.Empty).Save path + Assert.IsFalse(File.Exists(SchemaCache.DescriptionsFilePath path)) + Assert.AreEqual(None, SchemaCache.Empty.SaveDescriptions path) + +[] +let ``saving the descriptions read so far keeps the others in the file`` () = + let path = tempSchemaPath () + (describedCustomers ()).Save path + let later = SchemaCache.Empty + later.TableDescriptions.["main.Customers"] <- "Changed" + later.ColumnDescriptions.["main.Customers"] <- columnDescriptions [ "Phone", "Phone number" ] + later.SaveDescriptions path |> ignore + let loaded = SchemaCache.Empty + loaded.LoadDescriptions path + Assert.AreEqual("Changed", loaded.TableDescriptions.["main.Customers"]) + Assert.AreEqual("", loaded.TableDescriptions.["main.Orders"]) + Assert.AreEqual("Full name", loaded.ColumnDescriptions.["main.Customers"].["Name"]) + Assert.AreEqual("Phone number", loaded.ColumnDescriptions.["main.Customers"].["Phone"]) + +[] +let ``re-saving an offline schema keeps its descriptions`` () = + let path = tempSchemaPath () + (describedCustomers ()).Save path + // Offline, descriptions are read only for the first tooltip: a save before that must not lose them + (SchemaCache.Load path).Save path + let loaded = SchemaCache.Load path + loaded.LoadDescriptions path + Assert.AreEqual("People who buy", loaded.TableDescriptions.["main.Customers"]) + +[] +let ``merging schema files merges their descriptions files`` () = + let path1, path2, target = tempSchemaPath (), tempSchemaPath (), tempSchemaPath () + let cache1 = SchemaCache.Empty + cache1.TableDescriptions.["main.Customers"] <- "People who buy" + cache1.ColumnDescriptions.["main.Customers"] <- columnDescriptions [ "Name", "Full name" ] + cache1.Save path1 + let cache2 = SchemaCache.Empty + cache2.TableDescriptions.["main.Orders"] <- "What they buy" + cache2.ColumnDescriptions.["main.Customers"] <- columnDescriptions [ "Phone", "Phone number" ] + cache2.Save path2 + OfflineTools.mergeCacheFiles(path1, path2, target) |> ignore + let merged = SchemaCache.Load target + merged.LoadDescriptions target + Assert.AreEqual("People who buy", merged.TableDescriptions.["main.Customers"]) + Assert.AreEqual("What they buy", merged.TableDescriptions.["main.Orders"]) + Assert.AreEqual("Full name", merged.ColumnDescriptions.["main.Customers"].["Name"]) + Assert.AreEqual("Phone number", merged.ColumnDescriptions.["main.Customers"].["Phone"]) + diff --git a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj index d1f30559a..a8e728555 100644 --- a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj +++ b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj @@ -43,6 +43,7 @@ + Always From 2bd0822dcc8a09977ea053df718cbdf4d91b018d Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Fri, 20 Nov 2026 17:25:04 +0000 Subject: [PATCH 2/5] PR feedback addressed --- docs/RELEASE_NOTES.md | 4 +- src/SQLProvider.DesignTime/SqlDesignTime.fs | 12 ++-- .../Providers.MsSqlServer.Dynamic.fs | 19 ++++-- .../Providers.MsSqlServer.fs | 19 ++++-- src/SQLProvider.Runtime/Providers.Oracle.fs | 47 +++++++++------ .../Providers.Postgresql.fs | 60 +++++++++++-------- 6 files changed, 102 insertions(+), 59 deletions(-) diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 39de1b049..e493942c0 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -7,7 +7,9 @@ - OfflineTools.mergeCacheFiles merges descriptions and individuals files too - Fix: after a failed SaveContextSchema, design-time commands no longer stop working until the IDE restarts - Fix: saving individuals no longer fails on a column value such as a DateTimeOffset or an array; such values are saved as text -- Fix: PostgreSQL tables with capital letters in their name show their descriptions in tooltips; reading them failed before +- Fix: PostgreSQL tables with capital letters or an apostrophe in their name show their descriptions in tooltips; reading them failed before +- Fix: MS SQL Server descriptions of a table come from its own schema; with tables of the same name in two schemas, either could show the other's +- Fix: Oracle descriptions of tables owned by another schema (Owner) are read; only the current user's tables had them before ### 1.5.33 - 19.11.2026 - Fix: a saved schema (ContextSchemaPath) loads on both .NET and .NET Framework, whichever saved it. Visual Studio, whose editor and compiler run on .NET Framework, failed on a schema saved by dotnet with "Value cannot be null. Parameter name: key" diff --git a/src/SQLProvider.DesignTime/SqlDesignTime.fs b/src/SQLProvider.DesignTime/SqlDesignTime.fs index d6261a10f..abb81eb0d 100644 --- a/src/SQLProvider.DesignTime/SqlDesignTime.fs +++ b/src/SQLProvider.DesignTime/SqlDesignTime.fs @@ -517,13 +517,17 @@ module DesignTimeUtils = designTime.AddXmlDocDelayed(fun () -> "Developer's design time commands to TypeProvider.") - /// Runs a design-time command, unless one is already running (None then). The flag is reset even if the command fails. + /// Runs a design-time command, unless one is already running (None then): another thread holds the lock, + /// or the command itself asks for a command on this thread (the lock is re-entrant, so the flag tells). + /// The lock and the flag are released even if the command fails. let runCommand (command: unit -> string) = - if saveInProcess then None else - lock mySaveLock (fun() -> + if not (System.Threading.Monitor.TryEnter mySaveLock) then None else + try + if saveInProcess then None else saveInProcess <- true try Some (command()) - finally saveInProcess <- false) + finally saveInProcess <- false + finally System.Threading.Monitor.Exit mySaveLock let commandResult result = match result with diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs index 0e4a6ed21..24bad5cd2 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs @@ -582,6 +582,7 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sc.name, sep.value from sys.tables st @@ -589,9 +590,11 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe inner join sys.extended_properties sep on st.object_id = sep.major_id and sc.column_id = sep.minor_id and sep.name = 'MS_Description' - where st.name = @TableName""" + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName)""" use com = (this:>ISqlProvider).CreateCommand(con,baseq) com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@TableName", 0), tn)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@SchemaName", 2), sn)) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() Sql.readDescriptions reader @@ -602,16 +605,19 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe member __.StoredProcedures = true member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sep.value from sys.tables st left join sys.extended_properties sep on st.object_id = sep.major_id and (sep.minor_id is null or sep.minor_id =0) and sep.name = 'MS_Description' - where st.name = @TableName""" + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName)""" use com = (this:>ISqlProvider).CreateCommand(con,baseq) com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@TableName", 0), tn)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@SchemaName", 2), sn)) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() @@ -622,7 +628,8 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe else "" member __.GetColumnDescription(con,tableName,columnName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sep.value from sys.tables st @@ -630,10 +637,12 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe left join sys.extended_properties sep on st.object_id = sep.major_id and sc.column_id = sep.minor_id and sep.name = 'MS_Description' - where st.name = @TableName + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName) and sc.name = @ColumnName""" use com = (this:>ISqlProvider).CreateCommand(con,baseq) com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@TableName", 0), tn)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@SchemaName", 2), sn)) |> ignore com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("@ColumnName", 1), columnName)) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs index 1c3c6e5a8..dafaa7abb 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs @@ -503,6 +503,7 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sc.name, sep.value from sys.tables st @@ -510,9 +511,11 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = inner join sys.extended_properties sep on st.object_id = sep.major_id and sc.column_id = sep.minor_id and sep.name = 'MS_Description' - where st.name = @TableName""" + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName)""" use com = new SqlCommand(baseq,con:?>SqlConnection) com.Parameters.AddWithValue("@TableName",tn) |> ignore + com.Parameters.AddWithValue("@SchemaName",sn) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() Sql.readDescriptions reader @@ -523,16 +526,19 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = member __.StoredProcedures = true member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sep.value from sys.tables st left join sys.extended_properties sep on st.object_id = sep.major_id and (sep.minor_id is null or sep.minor_id =0) and sep.name = 'MS_Description' - where st.name = @TableName""" + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName)""" use com = new SqlCommand(baseq,con:?>SqlConnection) com.Parameters.AddWithValue("@TableName",tn) |> ignore + com.Parameters.AddWithValue("@SchemaName",sn) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() if reader.Read() then @@ -542,7 +548,8 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = else "" member __.GetColumnDescription(con,tableName,columnName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" let baseq = """select sep.value from sys.tables st @@ -550,10 +557,12 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = left join sys.extended_properties sep on st.object_id = sep.major_id and sc.column_id = sep.minor_id and sep.name = 'MS_Description' - where st.name = @TableName + inner join sys.schemas ss on st.schema_id = ss.schema_id + where st.name = @TableName and (@SchemaName = '' or ss.name = @SchemaName) and sc.name = @ColumnName""" use com = new SqlCommand(baseq,con:?>SqlConnection) com.Parameters.AddWithValue("@TableName",tn) |> ignore + com.Parameters.AddWithValue("@SchemaName",sn) |> ignore com.Parameters.AddWithValue("@ColumnName",columnName) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() diff --git a/src/SQLProvider.Runtime/Providers.Oracle.fs b/src/SQLProvider.Runtime/Providers.Oracle.fs index eec1ee48b..5b2f591c3 100644 --- a/src/SQLProvider.Runtime/Providers.Oracle.fs +++ b/src/SQLProvider.Runtime/Providers.Oracle.fs @@ -221,6 +221,16 @@ module internal Oracle = new Oracle.ManagedDataAccess.Client.OracleCommand(commandText, (connection :?> Oracle.ManagedDataAccess.Client.OracleConnection) ) :> IDbCommand #endif + /// A value for inside '...' in SQL text: an apostrophe in it doubled. + let sqlText (value: string) = value.Replace("'", "''") + + /// The owner and name of a table, from OWNER.TABLE, for the comments queries. The owner is "" without one: the + /// queries then read the current user's. + let descriptionOwnerAndTable (tableName: string) = + let dot = tableName.LastIndexOf '.' + let owner = if dot < 0 then "" else tableName.Substring(0, dot) + sqlText owner, sqlText (tableName.Substring(dot + 1)) + let readParameter (parameter:IDbDataParameter) = #if REFLECTIONLOAD let parameterType = parameterType.Value @@ -723,14 +733,15 @@ type internal OracleProvider(resolutionPath, contextSchemaPath, owner, reference interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn, tn = Oracle.descriptionOwnerAndTable tableName Sql.connect con (fun con -> let query = sprintf """SELECT COLUMN_NAME, COMMENTS - FROM user_col_comments - WHERE TABLE_NAME = '%s' + FROM all_col_comments + WHERE OWNER = NVL('%s', USER) + AND TABLE_NAME = '%s' AND COMMENTS <> '-' - """ tn + """ sn tn use com = Oracle.createCommand query con use reader = com.ExecuteReader() Sql.readDescriptions reader) @@ -741,15 +752,15 @@ type internal OracleProvider(resolutionPath, contextSchemaPath, owner, reference member __.StoredProcedures = true member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = - let sn = tableName.Substring(0,tableName.LastIndexOf('.')) - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - Sql.connect con (fun con -> + let sn, tn = Oracle.descriptionOwnerAndTable tableName + Sql.connect con (fun con -> let comment = - sprintf """SELECT COMMENTS - FROM user_tab_comments - WHERE TABLE_NAME = '%s' + sprintf """SELECT COMMENTS + FROM all_tab_comments + WHERE OWNER = NVL('%s', USER) + AND TABLE_NAME = '%s' AND COMMENTS <> '-' - """ tn + """ sn tn |> Oracle.read con (fun row -> Sql.dbUnbox row.[0]) |> Seq.toList @@ -759,16 +770,16 @@ type internal OracleProvider(resolutionPath, contextSchemaPath, owner, reference "" ) member __.GetColumnDescription(con,tableName,columnName) = - let sn = tableName.Substring(0,tableName.LastIndexOf('.')) - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - Sql.connect con (fun con -> + let sn, tn = Oracle.descriptionOwnerAndTable tableName + Sql.connect con (fun con -> let comment = - sprintf """SELECT COMMENTS - FROM user_col_comments - WHERE TABLE_NAME = '%s' + sprintf """SELECT COMMENTS + FROM all_col_comments + WHERE OWNER = NVL('%s', USER) + AND TABLE_NAME = '%s' AND COLUMN_NAME = '%s' AND COMMENTS <> '-' - """ tn columnName + """ sn tn (Oracle.sqlText columnName) |> Oracle.read con (fun row -> Sql.dbUnbox row.[0]) |> Seq.toList diff --git a/src/SQLProvider.Runtime/Providers.Postgresql.fs b/src/SQLProvider.Runtime/Providers.Postgresql.fs index 3db4586c2..f8a8060e7 100644 --- a/src/SQLProvider.Runtime/Providers.Postgresql.fs +++ b/src/SQLProvider.Runtime/Providers.Postgresql.fs @@ -323,6 +323,13 @@ module PostgreSQL = new Npgsql.NpgsqlCommand(commandText, connection :?> Npgsql.NpgsqlConnection) :> IDbCommand #endif + /// Runs a query with the values as parameters instead of in the SQL text, so that any name works in it. + let executeSqlWith commandText (parameters: (string * obj) list) (connection:IDbConnection) = + use com = createCommand commandText connection + parameters |> List.iteri (fun i (name, value) -> + createCommandParameter (QueryParameter.Create(name, i)) value |> com.Parameters.Add |> ignore) + com.ExecuteReader() + let readParameter (parameter:IDbDataParameter) = #if REFLECTIONLOAD match parameter.DbType, (dbTypeGetter.Value.Invoke(parameter, [||]) :?> int) with @@ -828,15 +835,15 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer let sn = tableName.Substring(0,tableName.LastIndexOf('.')) let tn = tableName.Substring(tableName.LastIndexOf('.')+1) use reader = - Sql.executeSql PostgreSQL.createCommand ( - sprintf """SELECT c.column_name, d.description - FROM pg_description d - LEFT JOIN information_schema.columns c - ON c.ordinal_position = d.objsubid - WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass - AND c.table_schema = '%s' - AND c.table_name = '%s'; - """ sn tn sn tn) con + PostgreSQL.executeSqlWith + """SELECT c.column_name, d.description + FROM pg_description d + LEFT JOIN information_schema.columns c + ON c.ordinal_position = d.objsubid + WHERE objoid = format('%I.%I', @schema, @table)::regclass + AND c.table_schema = @schema + AND c.table_name = @table;""" + [ "@schema", box sn; "@table", box tn ] con Sql.readDescriptions reader) interface ISqlProvider with @@ -846,15 +853,16 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = Sql.connect con (fun _ -> - // The names are quoted (%I), so that a table with capital letters in its name is found + // The names are quoted (%I), so that a table with capital letters in its name is found. They are + // parameters, so that a name with an apostrophe in it works too. let sn = tableName.Substring(0,tableName.LastIndexOf('.')) let tn = tableName.Substring(tableName.LastIndexOf('.')+1) use reader = - Sql.executeSql PostgreSQL.createCommand ( - sprintf """SELECT description - FROM pg_description - WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass AND objsubid=0; - """ sn tn) con + PostgreSQL.executeSqlWith + """SELECT description + FROM pg_description + WHERE objoid = format('%I.%I', @schema, @table)::regclass AND objsubid=0;""" + [ "@schema", box sn; "@table", box tn ] con if reader.Read() then let comment = Sql.dbUnbox reader.["description"] if isNull comment then "" else comment @@ -864,17 +872,17 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer Sql.connect con (fun _ -> let sn = tableName.Substring(0,tableName.LastIndexOf('.')) let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - use reader = - Sql.executeSql PostgreSQL.createCommand ( - sprintf """SELECT description - FROM pg_description d - LEFT JOIN information_schema.columns c - ON c.ordinal_position = d.objsubid - WHERE objoid = format('%%I.%%I', '%s', '%s')::regclass - AND c.table_schema = '%s' - AND c.table_name = '%s' - AND c.column_name = '%s'; - """ sn tn sn tn columnName) con + use reader = + PostgreSQL.executeSqlWith + """SELECT description + FROM pg_description d + LEFT JOIN information_schema.columns c + ON c.ordinal_position = d.objsubid + WHERE objoid = format('%I.%I', @schema, @table)::regclass + AND c.table_schema = @schema + AND c.table_name = @table + AND c.column_name = @column;""" + [ "@schema", box sn; "@table", box tn; "@column", box columnName ] con if reader.Read() then let comment = Sql.dbUnbox reader.["description"] if isNull comment then "" else comment From 2d084122eb5d18f46d2763d7b9a2efb0a24b0c6f Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sat, 21 Nov 2026 08:49:18 +0000 Subject: [PATCH 3/5] code review fixes --- docs/RELEASE_NOTES.md | 3 + src/SQLProvider.Common/SqlRuntime.Common.fs | 66 +++++++++++++-- src/SQLProvider.Common/Utils.fs | 14 ++++ .../Providers.MsSqlServer.Dynamic.fs | 9 +- .../Providers.MsSqlServer.fs | 9 +- src/SQLProvider.Runtime/Providers.Oracle.fs | 10 +-- .../Providers.Postgresql.fs | 22 +++-- .../SqlProvider.Tests/SchemaCacheFileTests.fs | 82 ++++++++++++++++++- 8 files changed, 186 insertions(+), 29 deletions(-) diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index e493942c0..e856cbcbc 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -7,6 +7,9 @@ - OfflineTools.mergeCacheFiles merges descriptions and individuals files too - Fix: after a failed SaveContextSchema, design-time commands no longer stop working until the IDE restarts - Fix: saving individuals no longer fails on a column value such as a DateTimeOffset or an array; such values are saved as text +- Fix: offline individuals with a smallint, bigint or decimal primary key have the key in its own type, as they do online; it came back from the saved file in whatever number type fitted the value +- Fix: PostgreSQL individuals of a table with a uuid primary key can be got; getting one failed, as the key was sent as text +- Fix: tables with a space in their name show their descriptions in tooltips (MS SQL Server, PostgreSQL, Oracle) - Fix: PostgreSQL tables with capital letters or an apostrophe in their name show their descriptions in tooltips; reading them failed before - Fix: MS SQL Server descriptions of a table come from its own schema; with tables of the same name in two schemas, either could show the other's - Fix: Oracle descriptions of tables owned by another schema (Owner) are read; only the current user's tables had them before diff --git a/src/SQLProvider.Common/SqlRuntime.Common.fs b/src/SQLProvider.Common/SqlRuntime.Common.fs index ebf4eab53..091df49ea 100644 --- a/src/SQLProvider.Common/SqlRuntime.Common.fs +++ b/src/SQLProvider.Common/SqlRuntime.Common.fs @@ -957,11 +957,14 @@ and SchemaCache = let ser = System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof) // Schema files saved before 1.5.34 may carry individuals in the schema file itself: they're kept. let loaded = ser.ReadObject(ms) :?> SchemaCache - { loaded with - IsOffline = true - Individuals = if isNull loaded.Individuals then ConcurrentDictionary() else loaded.Individuals - TableDescriptions = if isNull loaded.TableDescriptions then ConcurrentDictionary() else loaded.TableDescriptions - ColumnDescriptions = if isNull loaded.ColumnDescriptions then ConcurrentDictionary>() else loaded.ColumnDescriptions } + let cache = + { loaded with + IsOffline = true + Individuals = if isNull loaded.Individuals then ConcurrentDictionary() else loaded.Individuals + TableDescriptions = if isNull loaded.TableDescriptions then ConcurrentDictionary() else loaded.TableDescriptions + ColumnDescriptions = if isNull loaded.ColumnDescriptions then ConcurrentDictionary>() else loaded.ColumnDescriptions } + if not cache.Individuals.IsEmpty then cache.RestorePrimaryKeyTypes() + cache static member LoadOrEmpty(filePath) = if String.IsNullOrEmpty(filePath) || (not(File.Exists filePath)) then SchemaCache.Empty @@ -1030,7 +1033,59 @@ and SchemaCache = | :? string | :? bool | :? char | :? decimal | :? DateTime | :? Guid | :? TimeSpan | :? (byte[]) -> value | _ when value.GetType().IsPrimitive -> value | :? Array as items -> box [| for item in items -> SchemaCache.IndividualsFileValue item |] + // Round-trip text, so that a primary key of this type can be read back (PrimaryKeyValue) + | :? DateTimeOffset as d -> box (d.ToString("o", Globalization.CultureInfo.InvariantCulture)) + | :? IFormattable as f -> box (f.ToString(null, Globalization.CultureInfo.InvariantCulture)) | _ -> box (value.ToString()) + /// A DateTime as the serializer writes it: /Date(milliseconds since 1970 UTC, then maybe an offset)/ + static member private SerializerDate(text:string) = + let m = Text.RegularExpressions.Regex.Match(text, @"^/Date\((-?\d+)([+-]\d{4})?\)/$") + if not m.Success then None else + let utc = DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(float (Int64.Parse m.Groups.[1].Value)) + if not m.Groups.[2].Success then Some utc else + // The offset is that of the machine that saved the file. With it the date is as the database gave it, + // whatever the time zone of the machine that reads the file. + let offset = m.Groups.[2].Value + let minutes = Int32.Parse(offset.Substring(1, 2)) * 60 + Int32.Parse(offset.Substring(3, 2)) + let saved = utc.AddMinutes(float (if offset.[0] = '-' then -minutes else minutes)) + Some (DateTime.SpecifyKind(saved, DateTimeKind.Unspecified)) + /// A primary key value read from a file, as the design time has it online: in the type of its column. The file + /// gives a DateTime or a DateTimeOffset back as text, and a number in a type that fits it. A Guid stays text: + /// online it's kept as text too, because a Guid can't be a constant in a provided quotation. + /// A value that doesn't convert is kept as it is. + static member private PrimaryKeyValue(clrType:Type, value:obj) : obj = + if isNull value || isNull clrType || value.GetType() = clrType || clrType = typeof then value else + let invariant = Globalization.CultureInfo.InvariantCulture + try + match value with + | :? string as text -> + if clrType = typeof then box (DateTimeOffset.Parse(text, invariant)) + elif clrType = typeof then + match SchemaCache.SerializerDate text with + | Some date -> box date + | None -> box (DateTime.Parse(text, invariant, Globalization.DateTimeStyles.RoundtripKind)) + elif clrType = typeof then box (TimeSpan.Parse(text, invariant)) + else Convert.ChangeType(text, clrType, invariant) + | :? IConvertible -> Convert.ChangeType(value, clrType, invariant) + | _ -> value + with _ -> value + /// Gives the primary keys of individuals read from a file the type of their column, as the schema has it. + member private this.RestorePrimaryKeyTypes() = + for KeyValue(table, keys) in this.PrimaryKeys do + match keys with + | [ pk ] -> + let key = table + "_" + pk + match this.Individuals.TryGetValue key, this.Columns.TryGetValue table with + | (true, entities), (true, columns) when not (isNull entities) -> + match columns.TryFind pk with + | Some column -> + let clrType = try Utilities.getType column.TypeMapping.ClrType with _ -> null + if not (isNull clrType) then + this.Individuals.[key] <- + entities |> Array.map (fun (pkValue, values) -> SchemaCache.PrimaryKeyValue(clrType, pkValue), values) + | None -> () + | _ -> () + | _ -> () /// Saves the individuals to the individuals file beside the schema file and returns its path. /// Tables without individuals are left out. member this.SaveIndividuals(filePath) = @@ -1053,6 +1108,7 @@ and SchemaCache = if not (isNull loaded) then for KeyValue(table, entities) in loaded do this.Individuals.[table] <- entities + this.RestorePrimaryKeyTypes() /// Table and column descriptions as saved in the descriptions file beside the schema file and SchemaDescriptions = diff --git a/src/SQLProvider.Common/Utils.fs b/src/SQLProvider.Common/Utils.fs index d6d87f1d8..34b7d4c95 100644 --- a/src/SQLProvider.Common/Utils.fs +++ b/src/SQLProvider.Common/Utils.fs @@ -861,6 +861,20 @@ module Sql = descriptions.[name] <- description descriptions :> System.Collections.Generic.IDictionary + /// The schema ("" without one) and the name of a table from its FullName, schema.name. A name with a space in + /// it is in quotes in FullName (quoteWhiteSpace): those quotes are left out, so the name is as the database has it. + let tableSchemaAndName (fullName:string) = + let unquote (name:string) = + if name.Length > 1 && name.StartsWith "\"" && name.EndsWith "\"" && name.Contains " " then name.Substring(1, name.Length - 2) + else name + if fullName.Length > 1 && fullName.StartsWith "\"" && fullName.EndsWith "\"" then "", unquote fullName else + // A quoted name may have a dot in it: it starts after the schema's ." + let dot = + match (if fullName.EndsWith "\"" then fullName.IndexOf ".\"" else -1) with + | -1 -> fullName.LastIndexOf '.' + | quoted -> quoted + (if dot < 0 then "" else fullName.Substring(0, dot)), unquote (fullName.Substring(dot + 1)) + /// Note: SQLProvider reuses the connection through multiple instances, so you can't dispose it here. /// Instead it's created with ISQLProvider's CreateConnection method, and that is having always "use" to ensure it is disposed properly on "finally". let connect (con:IDbConnection) f = diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs index 24bad5cd2..24a92e27b 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs @@ -581,8 +581,7 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sc.name, sep.value from sys.tables st @@ -605,8 +604,7 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe member __.StoredProcedures = true member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sep.value from sys.tables st @@ -628,8 +626,7 @@ type internal MSSqlServerDynamicProvider(resolutionPath, contextSchemaPath, refe else "" member __.GetColumnDescription(con,tableName,columnName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sep.value from sys.tables st diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs index dafaa7abb..4eee4250d 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs @@ -502,8 +502,7 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sc.name, sep.value from sys.tables st @@ -526,8 +525,7 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = member __.StoredProcedures = true member __.GetLockObject() = myLock member __.GetTableDescription(con,tableName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sep.value from sys.tables st @@ -548,8 +546,7 @@ type internal MSSqlServerProvider(contextSchemaPath, tableNames:string) = else "" member __.GetColumnDescription(con,tableName,columnName) = - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) - let sn = if tableName.Contains "." then tableName.Substring(0, tableName.LastIndexOf('.')) else "" + let sn, tn = Sql.tableSchemaAndName tableName let baseq = """select sep.value from sys.tables st diff --git a/src/SQLProvider.Runtime/Providers.Oracle.fs b/src/SQLProvider.Runtime/Providers.Oracle.fs index 5b2f591c3..e081c9bac 100644 --- a/src/SQLProvider.Runtime/Providers.Oracle.fs +++ b/src/SQLProvider.Runtime/Providers.Oracle.fs @@ -224,12 +224,12 @@ module internal Oracle = /// A value for inside '...' in SQL text: an apostrophe in it doubled. let sqlText (value: string) = value.Replace("'", "''") - /// The owner and name of a table, from OWNER.TABLE, for the comments queries. The owner is "" without one: the - /// queries then read the current user's. + /// The owner and name of a table, from OWNER.TABLE, for inside '...' in the comments queries: without the quotes + /// of a name with a space in it, apostrophes doubled. The owner is "" without one: the queries then read the + /// current user's. let descriptionOwnerAndTable (tableName: string) = - let dot = tableName.LastIndexOf '.' - let owner = if dot < 0 then "" else tableName.Substring(0, dot) - sqlText owner, sqlText (tableName.Substring(dot + 1)) + let owner, name = Sql.tableSchemaAndName tableName + sqlText owner, sqlText name let readParameter (parameter:IDbDataParameter) = #if REFLECTIONLOAD diff --git a/src/SQLProvider.Runtime/Providers.Postgresql.fs b/src/SQLProvider.Runtime/Providers.Postgresql.fs index f8a8060e7..59d2814ad 100644 --- a/src/SQLProvider.Runtime/Providers.Postgresql.fs +++ b/src/SQLProvider.Runtime/Providers.Postgresql.fs @@ -96,6 +96,9 @@ module PostgreSQL = #endif with _ -> None + /// The value of Npgsql's type enumeration for a uuid + let uuidProviderDbType = lazy (parseDbType "Uuid") + let tryReadValueProperty instance = let typ = instance.GetType() let prop = typ.GetProperty "Value" @@ -113,6 +116,16 @@ module PostgreSQL = if not (isOptionValue value) then (if isNull value || (Type.(=) (value.GetType(), typeof)) then box DBNull.Value else value) else match tryReadValueProperty value with Some v -> v | None -> box DBNull.Value + // Npgsql doesn't write text to a uuid. The key of an individual with a uuid key is text: a Guid can't be + // a constant in a provided quotation. + let normalizedValue = + match normalizedValue, param.TypeMapping.ProviderType, uuidProviderDbType.Value with + | (:? string as text), ValueSome dbType, Some uuid when dbType = uuid -> + match Guid.TryParse text with + | true, guid -> box guid + | false, _ -> normalizedValue + | _ -> normalizedValue + let isAnonymousParam = param.Direction <> ParameterDirection.Output && param.Name.StartsWith ANONYMOUS_PARAMETER_NAME && @@ -832,8 +845,7 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer interface IColumnDescriptionsProvider with member __.GetColumnDescriptions(con,tableName) = Sql.connect con (fun _ -> - let sn = tableName.Substring(0,tableName.LastIndexOf('.')) - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn, tn = Sql.tableSchemaAndName tableName use reader = PostgreSQL.executeSqlWith """SELECT c.column_name, d.description @@ -855,8 +867,7 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer Sql.connect con (fun _ -> // The names are quoted (%I), so that a table with capital letters in its name is found. They are // parameters, so that a name with an apostrophe in it works too. - let sn = tableName.Substring(0,tableName.LastIndexOf('.')) - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn, tn = Sql.tableSchemaAndName tableName use reader = PostgreSQL.executeSqlWith """SELECT description @@ -870,8 +881,7 @@ type internal PostgresqlProvider(resolutionPath, contextSchemaPath, owner, refer "") member __.GetColumnDescription(con,tableName,columnName) = Sql.connect con (fun _ -> - let sn = tableName.Substring(0,tableName.LastIndexOf('.')) - let tn = tableName.Substring(tableName.LastIndexOf('.')+1) + let sn, tn = Sql.tableSchemaAndName tableName use reader = PostgreSQL.executeSqlWith """SELECT description diff --git a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs index 9b1c57e4e..c2df90e67 100644 --- a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs +++ b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs @@ -8,6 +8,7 @@ open System.Text open System.Collections.Generic open System.Collections.Concurrent open FSharp.Data.Sql.Common +open FSharp.Data.Sql.Schema open NUnit.Framework let private tempSchemaPath () = @@ -86,7 +87,8 @@ let ``column values the file can't hold as such are saved as text`` () = loaded.LoadIndividuals path let columns = snd loaded.Individuals.["main.Customers_Id"].[0] Assert.AreEqual("Customer 1", columns.["Name"]) - Assert.AreEqual(changed.ToString(), columns.["Changed"]) + // Round-trip text, the same on every machine + Assert.AreEqual("2026-11-20T12:00:00.0000000+02:00", columns.["Changed"]) CollectionAssert.AreEqual([| "a"; "b" |], columns.["Tags"] :?> obj[]) Assert.AreEqual("10.0.0.1", columns.["Address"]) Assert.AreEqual("", columns.["Missing"]) @@ -222,3 +224,81 @@ let ``merging schema files merges their descriptions files`` () = Assert.AreEqual("Full name", merged.ColumnDescriptions.["main.Customers"].["Name"]) Assert.AreEqual("Phone number", merged.ColumnDescriptions.["main.Customers"].["Phone"]) + +// A primary key comes back from the individuals file as the design time has it online: in its column's type, but a +// Guid as text, because a Guid can't be a constant in a provided quotation. + +let private keyed (table:string) (pkType:Type) (keys:obj list) = + let cache = SchemaCache.Empty + let column = + { Name = "Id"; TypeMapping = TypeMapping.Create(clrType = pkType.AssemblyQualifiedName); IsPrimaryKey = true + IsNullable = false; IsAutonumber = false; HasDefault = false; IsComputed = false; TypeInfo = ValueNone } + cache.Tables.[table] <- { Schema = "main"; Name = table.Substring 5; Type = "TABLE" } + cache.PrimaryKeys.[table] <- [ "Id" ] + cache.Columns.[table] <- Map.ofList [ "Id", column ] + cache.Individuals.[table + "_Id"] <- [| for key in keys -> key, dict [ "Id", key; "Name", box (string key) ] |] + cache + +[] +let ``primary keys of individuals are read back as they are online`` () = + // Online a Guid key is kept as text, so it's given here as the design time gives it + let guid = Guid.NewGuid().ToString() + let offset = DateTimeOffset(2024, 5, 6, 7, 8, 9, 123, TimeSpan.FromHours 3.) + let cases : (string * Type * obj) list = + [ "main.Guids", typeof, box guid + "main.Offsets", typeof, box offset + "main.UtcDates", typeof, box (DateTime(2024, 5, 6, 7, 8, 9, DateTimeKind.Utc)) + "main.Dates", typeof, box (DateTime(2024, 5, 6, 7, 8, 9)) + "main.Shorts", typeof, box 12s + "main.Longs", typeof, box 1234567890123L + "main.SmallLongs", typeof, box 7L + "main.Decimals", typeof, box 42M ] + for table, columnType, key in cases do + let path = tempSchemaPath () + let cache = keyed table columnType [ key ] + cache.Save path + cache.SaveIndividuals path |> ignore + let loaded = SchemaCache.Load path + loaded.LoadIndividuals path + let pk, _ = loaded.Individuals.[table + "_Id"].[0] + Assert.AreEqual(key.GetType(), pk.GetType(), table) + Assert.AreEqual(key, pk, table) + +[] +let ``a date key saved in another time zone is read back as it was saved`` () = + let date = DateTime(2024, 5, 6, 7, 8, 9) + for offset, hours in [ "+0500", 5.; "-0930", -9.5 ] do + let path = tempSchemaPath () + let cache = keyed "main.Dates" typeof [ box date ] + cache.Save path + let file = cache.SaveIndividuals path + // The same moment as a machine in that time zone saves it + File.WriteAllText(file, RegularExpressions.Regex.Replace(File.ReadAllText file, @"[+-]\d{4}\)", offset + ")")) + let loaded = SchemaCache.Load path + loaded.LoadIndividuals path + let pk, _ = loaded.Individuals.["main.Dates_Id"].[0] + Assert.AreEqual(date.ToUniversalTime().AddHours hours, unbox pk, offset) + +[] +let ``primary keys of individuals in an old schema file are read back as they are online`` () = + let path = tempSchemaPath () + let guid = Guid.NewGuid().ToString() + saveOldFormat (keyed "main.Guids" typeof [ box guid ]) path + let pk, _ = (SchemaCache.Load path).Individuals.["main.Guids_Id"].[0] + Assert.AreEqual(box guid, pk) + let path = tempSchemaPath () + saveOldFormat (keyed "main.Longs" typeof [ box 7L ]) path + let pk, _ = (SchemaCache.Load path).Individuals.["main.Longs_Id"].[0] + Assert.AreEqual(box 7L, pk) + +// A table's FullName has a name with a space in quotes: the metadata queries need it as the database has it. + +[] +let ``a table's schema and name come from its full name without the quotes`` () = + let full schema name = Table.CreateFullName(schema, name) + Assert.AreEqual(("dbo", "Customers"), Sql.tableSchemaAndName (full "dbo" "Customers")) + Assert.AreEqual(("dbo", "Order Details"), Sql.tableSchemaAndName (full "dbo" "Order Details")) + Assert.AreEqual(("dbo", "v1.2 Orders"), Sql.tableSchemaAndName (full "dbo" "v1.2 Orders")) + Assert.AreEqual(("", "Order Details"), Sql.tableSchemaAndName (full "" "Order Details")) + Assert.AreEqual(("", "Customers"), Sql.tableSchemaAndName (full "" "Customers")) + Assert.AreEqual(("public", "customer'archive"), Sql.tableSchemaAndName (full "public" "customer'archive")) From 743f023ff8fa16702fec903c8b3569ae6b0215eb Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sat, 21 Nov 2026 13:14:29 +0000 Subject: [PATCH 4/5] MySQL and DuckDB fixes --- docs/RELEASE_NOTES.md | 10 ++- src/SQLProvider.Common/SqlRuntime.Common.fs | 56 ++++++++++---- src/SQLProvider.Common/Utils.fs | 47 ++++++++++- src/SQLProvider.DesignTime/SqlDesignTime.fs | 16 ++-- src/SQLProvider.Runtime/Providers.DuckDb.fs | 77 +++++++++++-------- .../Providers.MsSqlServer.Dynamic.fs | 2 + .../Providers.MsSqlServer.fs | 2 + src/SQLProvider.Runtime/Providers.MySql.fs | 2 +- .../Providers.Postgresql.fs | 10 +-- tests/SqlProvider.Tests/ColumnValueTests.fs | 66 ++++++++++++++++ .../SqlProvider.Tests/SchemaCacheFileTests.fs | 44 +++++++++++ .../SqlProvider.Tests.fsproj | 1 + 12 files changed, 267 insertions(+), 66 deletions(-) create mode 100644 tests/SqlProvider.Tests/ColumnValueTests.fs diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index e856cbcbc..1859c179a 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -8,7 +8,15 @@ - Fix: after a failed SaveContextSchema, design-time commands no longer stop working until the IDE restarts - Fix: saving individuals no longer fails on a column value such as a DateTimeOffset or an array; such values are saved as text - Fix: offline individuals with a smallint, bigint or decimal primary key have the key in its own type, as they do online; it came back from the saved file in whatever number type fitted the value -- Fix: PostgreSQL individuals of a table with a uuid primary key can be got; getting one failed, as the key was sent as text +- Fix: individuals of a table with a uuid (PostgreSQL) or uniqueidentifier (MS SQL Server) primary key can be got; getting one failed, as the key was sent as text +- Fix: MySQL, DuckDB and Firebird tables have their columns and relationships in offline mode; they had none, as these databases save the schema under other names than the offline mode looked for +- Fix: MySQL and DuckDB individuals can be got; the query quoted the table name twice, and DuckDB also never got the key +- Fix: DuckDB tables with a foreign key can be used, and have their relationships; opening one failed with "Index was outside the bounds of the array" +- Fix: DuckDB columns of a type with a precision, such as DECIMAL(18,3), are no longer left out +- Fix: DuckDB Owner can list several schemas; no tables were found with more than one +- Fix: DuckDB DATE columns can be read on .NET 6 and later; the driver gives a DateOnly there, and reading it as the DateTime of the column failed +- Fix: DuckDB TIME columns can be read, as a TimeSpan; they were typed DateTime, and reading one always failed +- Fix: DuckDB TIMESTAMP_S, TIMESTAMP_MS, TIMESTAMP_NS and TIMETZ columns are no longer left out - Fix: tables with a space in their name show their descriptions in tooltips (MS SQL Server, PostgreSQL, Oracle) - Fix: PostgreSQL tables with capital letters or an apostrophe in their name show their descriptions in tooltips; reading them failed before - Fix: MS SQL Server descriptions of a table come from its own schema; with tables of the same name in two schemas, either could show the other's diff --git a/src/SQLProvider.Common/SqlRuntime.Common.fs b/src/SQLProvider.Common/SqlRuntime.Common.fs index 091df49ea..d8eea3eb8 100644 --- a/src/SQLProvider.Common/SqlRuntime.Common.fs +++ b/src/SQLProvider.Common/SqlRuntime.Common.fs @@ -355,6 +355,10 @@ type SqlEntity(dc: ISqlDataContext, tableName, columns: ColumnLookup, activeColu Type.(<>)(typeof<'T>, typeof) && (data :? IConvertible) -> unbox <| Convert.ChangeType(data, typeof<'T>) + | data when Type.(<>)(typeof<'T>, data.GetType()) && Type.(<>)(typeof<'T>, typeof) -> + match Utilities.tryConvertDateOrTime data typeof<'T> with + | ValueSome converted -> unbox converted + | ValueNone -> unbox data | data -> unbox data member __.GetColumnOption<'T>(key) : Option<'T> = @@ -364,7 +368,10 @@ type SqlEntity(dc: ISqlDataContext, tableName, columns: ColumnLookup, activeColu match dataitem with | null -> None | :? DBNull -> None - | data when Type.(<>)(data.GetType(), typeof<'T>) && Type.(<>)(typeof<'T>, typeof) -> Some(unbox<'T> <| Convert.ChangeType(data, typeof<'T>)) + | data when Type.(<>)(data.GetType(), typeof<'T>) && Type.(<>)(typeof<'T>, typeof) -> + match Utilities.tryConvertDateOrTime data typeof<'T> with + | ValueSome converted -> Some(unbox<'T> converted) + | ValueNone -> Some(unbox<'T> <| Convert.ChangeType(data, typeof<'T>)) | data -> Some(unbox data) member __.GetColumnValueOption<'T>(key) : ValueOption<'T> = @@ -374,7 +381,10 @@ type SqlEntity(dc: ISqlDataContext, tableName, columns: ColumnLookup, activeColu match dataitem with | null -> ValueNone | :? DBNull -> ValueNone - | data when Type.(<>)(data.GetType(), typeof<'T>) && Type.(<>)(typeof<'T>, typeof) -> ValueSome(unbox<'T> <| Convert.ChangeType(data, typeof<'T>)) + | data when Type.(<>)(data.GetType(), typeof<'T>) && Type.(<>)(typeof<'T>, typeof) -> + match Utilities.tryConvertDateOrTime data typeof<'T> with + | ValueSome converted -> ValueSome(unbox<'T> converted) + | ValueNone -> ValueSome(unbox<'T> <| Convert.ChangeType(data, typeof<'T>)) | data -> ValueSome(unbox data) member this.GetPkColumnOption<'T>(keys: string list) : 'T list = @@ -1069,21 +1079,37 @@ and SchemaCache = | :? IConvertible -> Convert.ChangeType(value, clrType, invariant) | _ -> value with _ -> value + /// The first of the keys that has an entry. + static member private TryFindKeyed(entries: ConcurrentDictionary, keys: string list) = + keys |> List.tryPick (fun key -> + match entries.TryGetValue key with + | true, entry -> Some entry + | false, _ -> None) + /// The entry of a table in Columns, PrimaryKeys or Relationships. Not every provider keys these by the table's + /// FullName: MySQL and DuckDB key them, and Tables, by a quoted name, Firebird by the name alone, and Oracle + /// its primary keys by the name alone. + member this.TryFindByTable(entries: ConcurrentDictionary, table: Table) = + match entries.TryGetValue table.FullName with + | true, entry -> Some entry + | false, _ -> + let tableKeys = + [ for KeyValue(key, known) in this.Tables do + if known.Schema = table.Schema && known.Name = table.Name then yield key ] + SchemaCache.TryFindKeyed(entries, tableKeys @ [ table.Name ]) /// Gives the primary keys of individuals read from a file the type of their column, as the schema has it. member private this.RestorePrimaryKeyTypes() = - for KeyValue(table, keys) in this.PrimaryKeys do - match keys with - | [ pk ] -> - let key = table + "_" + pk - match this.Individuals.TryGetValue key, this.Columns.TryGetValue table with - | (true, entities), (true, columns) when not (isNull entities) -> - match columns.TryFind pk with - | Some column -> - let clrType = try Utilities.getType column.TypeMapping.ClrType with _ -> null - if not (isNull clrType) then - this.Individuals.[key] <- - entities |> Array.map (fun (pkValue, values) -> SchemaCache.PrimaryKeyValue(clrType, pkValue), values) - | None -> () + for KeyValue(tableKey, table) in this.Tables do + // Individuals are keyed by the table's FullName and its primary key; the others as TryFindByTable tells + let keys = [ table.FullName; tableKey; table.Name ] + match SchemaCache.TryFindKeyed(this.PrimaryKeys, keys), SchemaCache.TryFindKeyed(this.Columns, keys) with + | Some [ pk ], Some columns -> + let key = table.FullName + "_" + pk + match this.Individuals.TryGetValue key, columns.TryFind pk with + | (true, entities), Some column when not (isNull entities) -> + let clrType = try Utilities.getType column.TypeMapping.ClrType with _ -> null + if not (isNull clrType) then + this.Individuals.[key] <- + entities |> Array.map (fun (pkValue, values) -> SchemaCache.PrimaryKeyValue(clrType, pkValue), values) | _ -> () | _ -> () /// Saves the individuals to the individuals file beside the schema file and returns its path. diff --git a/src/SQLProvider.Common/Utils.fs b/src/SQLProvider.Common/Utils.fs index 34b7d4c95..ea15e6c79 100644 --- a/src/SQLProvider.Common/Utils.fs +++ b/src/SQLProvider.Common/Utils.fs @@ -125,6 +125,33 @@ module Utilities = let private makeSomeOf (optionType:Type) (value:obj) = Microsoft.FSharp.Reflection.FSharpValue.MakeUnion(Microsoft.FSharp.Reflection.FSharpType.GetUnionCases(optionType).[1], [|value|]) + /// A date or a time that the driver gave in another type than the column is mapped to, as the mapped type. + /// DuckDB gives a DATE as DateOnly and a TIME as TimeOnly on .NET 6 and later, and a TIME as its own DuckDBTimeOnly before that. + let internal tryConvertDateOrTime (value:obj) (targetType:Type) : obj voption = + if isNull value then ValueNone else + let int64Property (name:string) = + match value.GetType().GetProperty name with + | null -> ValueNone + | property -> ValueSome (Convert.ToInt64 (property.GetValue(value, null))) + if Type.(=) (targetType, typeof) then + match value with +#if NET6_0_OR_GREATER + | :? DateOnly as date -> ValueSome (box (date.ToDateTime TimeOnly.MinValue)) +#endif + // An assembly built for an older .NET doesn't know DateOnly, but may run with a driver that does + | _ when value.GetType().FullName = "System.DateOnly" -> + int64Property "DayNumber" |> ValueOption.map (fun days -> box (DateTime(days * TimeSpan.TicksPerDay))) + | _ -> ValueNone + elif Type.(=) (targetType, typeof) then + match value with +#if NET6_0_OR_GREATER + | :? TimeOnly as time -> ValueSome (box (time.ToTimeSpan())) +#endif + | _ when value.GetType().Name.EndsWith "TimeOnly" -> + int64Property "Ticks" |> ValueOption.map (fun ticks -> box (TimeSpan ticks)) + | _ -> ValueNone + else ValueNone + let rec internal convertTypes (itm:obj) (returnType:Type) = if not(isNull itm) && Type.(=) (itm.GetType(), returnType) then itm elif isCOpt returnType && returnType.GenericTypeArguments.Length = 1 then @@ -204,12 +231,18 @@ module Utilities = elif Type.(=) (returnType, typeof) then Convert.ToUInt64 itm |> box elif Type.(=) (returnType, typeof) then Convert.ToInt16 itm |> box elif Type.(=) (returnType, typeof) then Convert.ToUInt16 itm |> box - elif Type.(=) (returnType, typeof) then Convert.ToDateTime itm |> box + elif Type.(=) (returnType, typeof) then + match tryConvertDateOrTime itm returnType with + | ValueSome date -> date + | ValueNone -> Convert.ToDateTime itm |> box elif Type.(=) (returnType, typeof) then Convert.ToBoolean itm |> box elif Type.(=) (returnType, typeof) then Convert.ToByte itm |> box elif Type.(=) (returnType, typeof) then Convert.ToSByte itm |> box elif Type.(=) (returnType, typeof) then Convert.ToChar itm |> box - else itm |> box + else + match tryConvertDateOrTime itm returnType with + | ValueSome time -> time + | ValueNone -> itm |> box elif Type.(=) (returnType, typeof) then s |> box elif Type.(=) (returnType, typeof) then let ok, x = Int32.TryParse s @@ -861,6 +894,16 @@ module Sql = descriptions.[name] <- description descriptions :> System.Collections.Generic.IDictionary + /// The Guid of a text that is one; any other value as it is. The key of an individual with a Guid key is text, + /// because a Guid can't be a constant in a provided quotation, and not every database takes text for a Guid parameter. + let guidOfText (value:obj) : obj = + match value with + | :? string as text -> + match Guid.TryParse text with + | true, guid -> box guid + | false, _ -> value + | _ -> value + /// The schema ("" without one) and the name of a table from its FullName, schema.name. A name with a space in /// it is in quotes in FullName (quoteWhiteSpace): those quotes are left out, so the name is as the database has it. let tableSchemaAndName (fullName:string) = diff --git a/src/SQLProvider.DesignTime/SqlDesignTime.fs b/src/SQLProvider.DesignTime/SqlDesignTime.fs index abb81eb0d..407eddc8a 100644 --- a/src/SQLProvider.DesignTime/SqlDesignTime.fs +++ b/src/SQLProvider.DesignTime/SqlDesignTime.fs @@ -177,7 +177,7 @@ module DesignTimeUtils = let columns = match con with | Some con -> prov.GetColumns(con,table) - | None -> prov.GetSchemaCache().Columns.TryGetValue(table.FullName) |> function | true,cols -> cols | false, _ -> Map.empty + | None -> prov.GetSchemaCache().TryFindByTable(prov.GetSchemaCache().Columns, table) |> Option.defaultValue Map.empty match prov.GetPrimaryKey table with | None -> None | Some pkName -> @@ -236,7 +236,7 @@ module DesignTimeUtils = let propertyMap = match con with | Some con -> prov.GetColumns(con,table) - | None -> prov.GetSchemaCache().Columns.TryGetValue(table.FullName) |> function | true,cols -> cols | false, _ -> Map.empty + | None -> prov.GetSchemaCache().TryFindByTable(prov.GetSchemaCache().Columns, table) |> Option.defaultValue Map.empty |> Seq.choose(fun col -> if col.Key = pkName then None else let name = table.Schema + "." + table.Name + "." + col.Key + "Individuals" @@ -676,14 +676,10 @@ module DesignTimeUtils = let rel = prov.GetRelationships(con,t) (cols,rel) | None -> - let cols = - match prov.GetSchemaCache().Columns.TryGetValue t.FullName with - | true,cols -> cols - | false,_ -> Map.empty - let rel = - match prov.GetSchemaCache().Relationships.TryGetValue t.FullName with - | true,rel -> rel - | false,_ -> ([||],[||]) + // Not every provider keys its schema cache by the table's FullName + let cache = prov.GetSchemaCache() + let cols = cache.TryFindByTable(cache.Columns, t) |> Option.defaultValue Map.empty + let rel = cache.TryFindByTable(cache.Relationships, t) |> Option.defaultValue ([||],[||]) (cols,rel))] let sprocData = diff --git a/src/SQLProvider.Runtime/Providers.DuckDb.fs b/src/SQLProvider.Runtime/Providers.DuckDb.fs index 8d33ec38a..535e334cc 100644 --- a/src/SQLProvider.Runtime/Providers.DuckDb.fs +++ b/src/SQLProvider.Runtime/Providers.DuckDb.fs @@ -107,11 +107,16 @@ module DuckDb = "System.String","BPCHAR",16,false "System.String","TEXT",16,false "System.String","STRING",16,false + "System.TimeSpan","TIME",6,false "System.TimeSpan","INTERVAL",6,false + "System.DateTimeOffset","TIMETZ",6,false + "System.DateTimeOffset","TIME WITH TIME ZONE",6,false "System.DateTime","DATETIME",6,false "System.DateTime","DATE",6,false - "System.DateTime","TIME",6,false "System.DateTime","TIMESTAMP",6,false + "System.DateTime","TIMESTAMP_S",6,false + "System.DateTime","TIMESTAMP_MS",6,false + "System.DateTime","TIMESTAMP_NS",6,false "System.DateTime","TIMESTAMPTZ",6,false "System.DateTime","TIMESTAMP WITH TIME ZONE",6,false "System.DateTime","TIMESTAMPTZ",6,false @@ -131,13 +136,15 @@ module DuckDb = let createCommandParameter sprocCommand (param:QueryParameter) value = let mapping = if not (isNull value || sprocCommand) then (findClrType (value.GetType().ToString())) else None let value = if isNull value then (box DBNull.Value) else value + // DuckDB names a parameter without a prefix: the name of $id is id, and the key of an individual comes as @id + let name = param.Name.TrimStart('@') #if REFLECTIONLOAD let parameterType = parameterType.Value - let p = Activator.CreateInstance(parameterType,[|box param.Name;value|]) :?> IDbDataParameter + let p = Activator.CreateInstance(parameterType,[|box name;value|]) :?> IDbDataParameter #else - let p = DuckDB.NET.Data.DuckDBParameter(param.Name, value) :> IDbDataParameter + let p = DuckDB.NET.Data.DuckDBParameter(name, value) :> IDbDataParameter #endif p.Direction <- param.Direction @@ -377,6 +384,7 @@ module DuckDb = type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, referencedAssemblies) as this = let schemaCache = SchemaCache.LoadOrEmpty(contextSchemaPath) let myLock = Object() + let ownerSchemas = owner.Split(';', ',', ' ', '\n', '\r') |> Array.filter (not << String.IsNullOrWhiteSpace) let quotedTableName (table: Table) = let quotedFullName = table.QuotedFullName("\"", "\"") @@ -534,7 +542,7 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re do DuckDb.resolutionPath <- resolutionPath - DuckDb.schemas <- owner.Split(';', ',', ' ', '\n', '\r') |> Array.filter (not << String.IsNullOrWhiteSpace) + DuckDb.schemas <- ownerSchemas #if REFLECTIONLOAD DuckDb.referencedAssemblies <- referencedAssemblies #endif @@ -597,7 +605,9 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re member __.GetSchemaCache() = schemaCache member __.GetTables(con,cs) = - let dbName = if String.IsNullOrEmpty owner then "'main'" else $"'{owner}'" + let dbName = + if Array.isEmpty ownerSchemas then "'main'" + else String.Join(",", ownerSchemas |> Array.map (fun schema -> "'" + schema.Replace("'", "''") + "'")) let caseChane = match cs with | Common.CaseSensitivityChange.TOUPPER -> "UPPER(TABLE_SCHEMA)" @@ -610,7 +620,7 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re [ while reader.Read() do let table ={ Schema = reader.GetString 0; Name = reader.GetString 1; Type=reader.GetString 2 } yield schemaCache.Tables.GetOrAdd(table |> quotedTableName,table) ] |> List.toArray - executeSql DuckDb.createCommand (sprintf "select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE from INFORMATION_SCHEMA.TABLES where %s in (%s)" caseChane (String.Join(",", dbName))) con) + executeSql DuckDb.createCommand (sprintf "select TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE from INFORMATION_SCHEMA.TABLES where %s in (%s)" caseChane dbName) con) member __.GetPrimaryKey(table) = match schemaCache.PrimaryKeys.TryGetValue (table |> quotedTableName) with @@ -656,7 +666,12 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re #else let isUnsigned = not(reader.IsDBNull 6) && reader.GetString(6).ToUpperInvariant().Contains("UNSIGNED") #endif - let udt = if isUnsigned then dt + " unsigned" else dt + // A type with a precision, as DECIMAL(18,3), is mapped by its name alone + let typeName = + match dt.IndexOf '(' with + | i when i > 0 && dt.EndsWith ")" -> dt.Substring(0, i) + | _ -> dt + let udt = if isUnsigned then typeName + " unsigned" else typeName match DuckDb.findDbType udt with | Some(m) -> let col = @@ -684,43 +699,45 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re member __.GetRelationships(con,table) = schemaCache.Relationships.GetOrAdd(table |> quotedTableName, fun name -> + // DuckDb's KEY_COLUMN_USAGE doesn't tell the referenced table: it is the table of the unique constraint the foreign key points to let baseQuery = @"SELECT KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME ,KCU1.TABLE_NAME AS FK_TABLE_NAME ,KCU1.TABLE_SCHEMA AS FK_SCHEMA_NAME ,KCU1.COLUMN_NAME AS FK_COLUMN_NAME + ,KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME + ,KCU2.TABLE_SCHEMA AS REFERENCED_SCHEMA_NAME + ,KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 - WHERE POSITION_IN_UNIQUE_CONSTRAINT is not null" - - // DuckDb doesn't have built-in constraint navigation - //,KCU1.REFERENCED_TABLE_NAME AS REFERENCED_TABLE_NAME - //,KCU1.REFERENCED_TABLE_SCHEMA AS REFERENCED_SCHEMA_NAME - //,KCU1.REFERENCED_COLUMN_NAME AS FK_CONSTRAINT_SCHEMA + JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC + ON RC.CONSTRAINT_CATALOG = KCU1.CONSTRAINT_CATALOG + AND RC.CONSTRAINT_SCHEMA = KCU1.CONSTRAINT_SCHEMA + AND RC.CONSTRAINT_NAME = KCU1.CONSTRAINT_NAME + JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 + ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG + AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA + AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME + AND KCU2.ORDINAL_POSITION = KCU1.POSITION_IN_UNIQUE_CONSTRAINT + WHERE KCU1.POSITION_IN_UNIQUE_CONSTRAINT is not null" let res = Sql.connect con (fun con -> - use com = (this:>ISqlProvider).CreateCommand(con,$"%s{baseQuery} AND KCU1.TABLE_NAME = $table") - com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("table", 0), (DuckDb.ripQuotes table.Name))) |> ignore - if con.State <> ConnectionState.Open then con.Open() - use reader = com.ExecuteReader() - let children = + let read (tableAlias:string) = + use com = (this:>ISqlProvider).CreateCommand(con,$"%s{baseQuery} AND %s{tableAlias}.TABLE_SCHEMA = $schema AND %s{tableAlias}.TABLE_NAME = $table") + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("schema", 0), table.Schema)) |> ignore + com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("table", 1), (DuckDb.ripQuotes table.Name))) |> ignore + if con.State <> ConnectionState.Open then con.Open() + use reader = com.ExecuteReader() [ while reader.Read() do - yield { Name = reader.GetString 0; PrimaryTable=Table.CreateQuotedFullName(reader.GetString(2),reader.GetString(1), "\"", "\""); PrimaryKey=reader.GetString 3 - ForeignTable=Table.CreateQuotedFullName(reader.GetString(5),reader.GetString(4), "\"", "\""); ForeignKey=reader.GetString 6 } ] |> List.toArray - reader.Dispose() - //use com = (this:>ISqlProvider).CreateCommand(con,(sprintf "%s AND KCU1.REFERENCED_TABLE_NAME = $table" baseQuery)) - //com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("table", 0), (DuckDb.ripQuotes table.Name))) |> ignore - //if con.State <> ConnectionState.Open then con.Open() - //use reader = com.ExecuteReader() - let parents = Array.empty - //[ while reader.Read() do - // yield { Name = reader.GetString(0); PrimaryTable=Table.CreateQuotedFullName(reader.GetString(2),reader.GetString(1), "\"", "\""); PrimaryKey=reader.GetString(3) - // ForeignTable= Table.CreateQuotedFullName(reader.GetString(5),reader.GetString(4), "\"", "\""); ForeignKey=reader.GetString(6) } ] + yield { Name = reader.GetString 0; PrimaryTable=Table.CreateFullName(reader.GetString(2),reader.GetString(1)); PrimaryKey=reader.GetString 3 + ForeignTable=Table.CreateFullName(reader.GetString(5),reader.GetString(4)); ForeignKey=reader.GetString 6 } ] |> List.toArray + let children = read "KCU1" + let parents = read "KCU2" (children,parents)) res) member __.GetSprocs(con) = Sql.connect con DuckDb.getSprocs member __.GetIndividualsQueryText(table,amount) = sprintf "SELECT * FROM %s LIMIT %i;" (table |> quotedTableName) amount - member __.GetIndividualQueryText(table,column) = sprintf "SELECT * FROM \"%s\" WHERE \"%s\".\"%s\" = $id" (table |> quotedTableName) (table |> quotedTableName) column + member __.GetIndividualQueryText(table,column) = sprintf "SELECT * FROM %s WHERE %s.\"%s\" = $id" (table |> quotedTableName) (table |> quotedTableName) column member this.GenerateQueryText(sqlQuery,baseAlias,baseTable,projectionColumns,isDeleteScript, con) = if sqlQuery.ForUpdate then failwith "DuckDB has no row locks, so Seq.lockForUpdate can't be used with it." diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs index 24a92e27b..53f4a0bd8 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.Dynamic.fs @@ -210,6 +210,8 @@ module MSSqlServerDynamic = let udtTypeSetter = parameterType.GetProperty("UdtTypeName").GetSetMethod() + // SqlClient doesn't convert text to a uniqueidentifier, and the key of an individual with such a key is text + let value = if param.TypeMapping.DbType = DbType.Guid then Sql.guidOfText value else value let p = Activator.CreateInstance(parameterType,[|box param.Name;value|]) :?> IDbDataParameter p.DbType <- param.TypeMapping.DbType ValueOption.iter (fun (t:int) -> diff --git a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs index 4eee4250d..52b771df8 100644 --- a/src/SQLProvider.Runtime/Providers.MsSqlServer.fs +++ b/src/SQLProvider.Runtime/Providers.MsSqlServer.fs @@ -134,6 +134,8 @@ module MSSqlServer = p let createCommandParameter (param:QueryParameter) (value:obj) = + // SqlClient doesn't convert text to a uniqueidentifier, and the key of an individual with such a key is text + let value = if param.TypeMapping.DbType = DbType.Guid then Sql.guidOfText value else value let p = SqlParameter(param.Name,value, DbType = param.TypeMapping.DbType) ValueOption.iter (fun (t:int) -> p.SqlDbType <- Enum.ToObject(typeof, t) :?> SqlDbType) param.TypeMapping.ProviderType p.Direction <- param.Direction diff --git a/src/SQLProvider.Runtime/Providers.MySql.fs b/src/SQLProvider.Runtime/Providers.MySql.fs index 805ceaaef..01040ab80 100644 --- a/src/SQLProvider.Runtime/Providers.MySql.fs +++ b/src/SQLProvider.Runtime/Providers.MySql.fs @@ -771,7 +771,7 @@ type internal MySqlProvider(resolutionPath, contextSchemaPath, owner:string, ref member __.GetSprocs(con) = Sql.connect con MySql.getSprocs member __.GetIndividualsQueryText(table,amount) = sprintf "SELECT * FROM %s LIMIT %i;" (table |> quotedTableName) amount - member __.GetIndividualQueryText(table,column) = sprintf "SELECT * FROM `%s` WHERE `%s`.`%s` = @id" (table |> quotedTableName) (table |> quotedTableName) column + member __.GetIndividualQueryText(table,column) = sprintf "SELECT * FROM %s WHERE %s.`%s` = @id" (table |> quotedTableName) (table |> quotedTableName) column member this.GenerateQueryText(sqlQuery,baseAlias,baseTable,projectionColumns,isDeleteScript, con) = let parameters = ResizeArray<_>() diff --git a/src/SQLProvider.Runtime/Providers.Postgresql.fs b/src/SQLProvider.Runtime/Providers.Postgresql.fs index 59d2814ad..f1cba3f2e 100644 --- a/src/SQLProvider.Runtime/Providers.Postgresql.fs +++ b/src/SQLProvider.Runtime/Providers.Postgresql.fs @@ -116,14 +116,10 @@ module PostgreSQL = if not (isOptionValue value) then (if isNull value || (Type.(=) (value.GetType(), typeof)) then box DBNull.Value else value) else match tryReadValueProperty value with Some v -> v | None -> box DBNull.Value - // Npgsql doesn't write text to a uuid. The key of an individual with a uuid key is text: a Guid can't be - // a constant in a provided quotation. + // Npgsql doesn't write text to a uuid, and the key of an individual with a uuid key is text let normalizedValue = - match normalizedValue, param.TypeMapping.ProviderType, uuidProviderDbType.Value with - | (:? string as text), ValueSome dbType, Some uuid when dbType = uuid -> - match Guid.TryParse text with - | true, guid -> box guid - | false, _ -> normalizedValue + match param.TypeMapping.ProviderType, uuidProviderDbType.Value with + | ValueSome dbType, Some uuid when dbType = uuid -> Sql.guidOfText normalizedValue | _ -> normalizedValue let isAnonymousParam = diff --git a/tests/SqlProvider.Tests/ColumnValueTests.fs b/tests/SqlProvider.Tests/ColumnValueTests.fs new file mode 100644 index 000000000..e5e80f1e4 --- /dev/null +++ b/tests/SqlProvider.Tests/ColumnValueTests.fs @@ -0,0 +1,66 @@ +module ColumnValueTests + +// A driver may give a date or a time in another type than the column is mapped to: +// DuckDB gives a DATE as DateOnly and a TIME as TimeOnly on .NET 6 and later, and a TIME as its own DuckDBTimeOnly before that. + +open System +open FSharp.Data.Sql.Common +open NUnit.Framework + +/// Stands for a driver's own time type, such as DuckDBTimeOnly +[] +type DriverTimeOnly(ticks: int64) = + member __.Ticks = ticks + +type DayAndTime = + { Day: DateTime + Time: TimeSpan + MaybeDay: DateTime option + MaybeTime: TimeSpan voption } + +let private entityOf (values: (string * obj) list) = + let entity = SqlEntity(Unchecked.defaultof<_>, "main.events", Map.empty, values.Length) + entity.SetData values + entity + +let private day = DateTime(2024, 2, 29) +let private time = TimeSpan(0, 13, 45, 10, 123) + +[] +let ``a time in a driver's own type is read as a TimeSpan`` () = + let row = entityOf [ "time", box (DriverTimeOnly time.Ticks) ] :> IColumnHolder + Assert.AreEqual(time, row.GetColumn "time") + Assert.AreEqual(Some time, row.GetColumnOption "time") + Assert.AreEqual(ValueSome time, row.GetColumnValueOption "time") + +[] +let ``a date and a time in their mapped types are read as they are`` () = + let row = entityOf [ "day", box day; "time", box time; "nothing", null ] :> IColumnHolder + Assert.AreEqual(day, row.GetColumn "day") + Assert.AreEqual(time, row.GetColumn "time") + Assert.AreEqual(Some day, row.GetColumnOption "day") + Assert.AreEqual(ValueSome time, row.GetColumnValueOption "time") + Assert.AreEqual(None, row.GetColumnOption "nothing") + Assert.AreEqual(DateTime.MinValue, row.GetColumn "nothing") + +#if NET6_0_OR_GREATER +[] +let ``a DateOnly is read as a DateTime and a TimeOnly as a TimeSpan`` () = + let row = entityOf [ "day", box (DateOnly.FromDateTime day); "time", box (TimeOnly.FromTimeSpan time) ] :> IColumnHolder + Assert.AreEqual(day, row.GetColumn "day") + Assert.AreEqual(time, row.GetColumn "time") + Assert.AreEqual(Some day, row.GetColumnOption "day") + Assert.AreEqual(Some time, row.GetColumnOption "time") + Assert.AreEqual(ValueSome day, row.GetColumnValueOption "day") + Assert.AreEqual(ValueSome time, row.GetColumnValueOption "time") + // As it is, when that is what was asked for + Assert.AreEqual(DateOnly.FromDateTime day, row.GetColumn "day") + Assert.AreEqual(box (TimeOnly.FromTimeSpan time), row.GetColumn "time") + +[] +let ``a DateOnly and a TimeOnly map to DateTime and TimeSpan fields`` () = + let row = + entityOf [ "day", box (DateOnly.FromDateTime day); "time", box (TimeOnly.FromTimeSpan time) + "maybe_day", box (DateOnly.FromDateTime day); "maybe_time", box (TimeOnly.FromTimeSpan time) ] + Assert.AreEqual({ Day = day; Time = time; MaybeDay = Some day; MaybeTime = ValueSome time }, row.MapTo()) +#endif diff --git a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs index c2df90e67..7a3c2aa34 100644 --- a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs +++ b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs @@ -291,6 +291,50 @@ let ``primary keys of individuals in an old schema file are read back as they ar let pk, _ = (SchemaCache.Load path).Individuals.["main.Longs_Id"].[0] Assert.AreEqual(box 7L, pk) +// Not every provider keys its schema cache by the table's FullName: MySQL and DuckDB key it by a quoted name, +// Firebird by the name alone, and Oracle its primary keys by the name alone. + +let private rekeyed (entries: ConcurrentDictionary) (key: string) = + let entry = entries.["main.Longs"] + entries.Clear() + entries.[key] <- entry + +let private providerKeys () = + // The provider, then its key of the table in Tables, in PrimaryKeys and in Columns + [ "PostgreSQL", "main.Longs", "main.Longs", "main.Longs" + "MySQL", "`main`.`Longs`", "`main`.`Longs`", "`main`.`Longs`" + "DuckDB", "\"main\".\"Longs\"", "\"main\".\"Longs\"", "\"main\".\"Longs\"" + "Firebird", "Longs", "Longs", "Longs" + "Oracle", "main.Longs", "Longs", "main.Longs" ] + +let private keyedAs (tableKey, primaryKeyKey, columnKey) = + let cache = keyed "main.Longs" typeof [ box 7L ] + rekeyed cache.Tables tableKey + rekeyed cache.PrimaryKeys primaryKeyKey + rekeyed cache.Columns columnKey + cache + +[] +let ``a table's columns and primary key are found however the provider keys them`` () = + let table = { Schema = "main"; Name = "Longs"; Type = "TABLE" } + for provider, tableKey, primaryKeyKey, columnKey in providerKeys () do + let cache = keyedAs (tableKey, primaryKeyKey, columnKey) + Assert.AreEqual(Some [ "Id" ], cache.TryFindByTable(cache.PrimaryKeys, table), provider) + Assert.IsTrue((cache.TryFindByTable(cache.Columns, table) |> Option.exists (fun columns -> columns.ContainsKey "Id")), provider) + Assert.AreEqual(None, cache.TryFindByTable(cache.Columns, { table with Name = "Others" }), provider) + +[] +let ``primary keys of individuals are read back as they are online however the provider keys the schema`` () = + for provider, tableKey, primaryKeyKey, columnKey in providerKeys () do + let path = tempSchemaPath () + let cache = keyedAs (tableKey, primaryKeyKey, columnKey) + cache.Save path + cache.SaveIndividuals path |> ignore + let loaded = SchemaCache.Load path + loaded.LoadIndividuals path + let pk, _ = loaded.Individuals.["main.Longs_Id"].[0] + Assert.AreEqual(box 7L, pk, provider) + // A table's FullName has a name with a space in quotes: the metadata queries need it as the database has it. [] diff --git a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj index a8e728555..dc71b56b3 100644 --- a/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj +++ b/tests/SqlProvider.Tests/SqlProvider.Tests.fsproj @@ -43,6 +43,7 @@ + From bbba9a4ebddadf4b59bf15d75bf044062f337b61 Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Sat, 21 Nov 2026 14:24:52 +0000 Subject: [PATCH 5/5] duckdb fixes --- docs/RELEASE_NOTES.md | 4 +- docs/content/core/parameters.fsx | 4 ++ src/SQLProvider.Common/SqlRuntime.Common.fs | 30 ++++++---- src/SQLProvider.DesignTime/SqlDesignTime.fs | 9 ++- src/SQLProvider.Runtime/Providers.DuckDb.fs | 11 ++-- .../SqlProvider.Tests/SchemaCacheFileTests.fs | 60 ++++++++++++++++++- 6 files changed, 97 insertions(+), 21 deletions(-) diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 1859c179a..f65af0767 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -1,7 +1,7 @@ ### 1.5.34 - (unreleased) - Offline mode (ContextSchemaPath) saves three files beside each other: schema.json for the schema, schema.descriptions.json for table and column descriptions (comments), schema.individuals.json for individuals. Builds read only the schema file; the descriptions file is read for the first tooltip and the individuals file when Individuals are first opened - Offline tooltips show the saved table and column descriptions, instead of only "Offline mode." SaveContextSchema saves the descriptions of what you hovered over online -- A saved schema no longer carries individuals, so it stays small and loads fast. A schema file with individuals in it still loads them, and re-saving it moves them to the individuals file. Older versions can read the new schema files +- A saved schema no longer carries individuals, so it stays small and loads fast. SaveContextSchema saves the individuals opened so far to the individuals file instead: a table opened again replaces its saved individuals, and the other tables in the file are kept. A schema file with individuals in it still loads them, and re-saving it moves them to the individuals file. Older versions can read the new schema files - New design-time commands next to SaveContextSchema, online only, that read the whole database instead of what was used so far: SaveContextSchemaFull (every table, column, relationship and stored procedure, and every table and column description) and SaveContextSchemaIndividuals (individuals of every table with a single primary key) - SaveContextSchemaFull reads the column descriptions of a table in one query instead of one per column (MS SQL Server, PostgreSQL, MySQL, Oracle, Firebird, DuckDB) - OfflineTools.mergeCacheFiles merges descriptions and individuals files too @@ -11,7 +11,7 @@ - Fix: individuals of a table with a uuid (PostgreSQL) or uniqueidentifier (MS SQL Server) primary key can be got; getting one failed, as the key was sent as text - Fix: MySQL, DuckDB and Firebird tables have their columns and relationships in offline mode; they had none, as these databases save the schema under other names than the offline mode looked for - Fix: MySQL and DuckDB individuals can be got; the query quoted the table name twice, and DuckDB also never got the key -- Fix: DuckDB tables with a foreign key can be used, and have their relationships; opening one failed with "Index was outside the bounds of the array" +- Fix: DuckDB tables with a foreign key can be used, and have their relationships, the same way round as SQL Server and PostgreSQL have them; opening one failed with "Index was outside the bounds of the array" - Fix: DuckDB columns of a type with a precision, such as DECIMAL(18,3), are no longer left out - Fix: DuckDB Owner can list several schemas; no tables were found with more than one - Fix: DuckDB DATE columns can be read on .NET 6 and later; the driver gives a DateOnly there, and reading it as the DateTime of the column failed diff --git a/docs/content/core/parameters.fsx b/docs/content/core/parameters.fsx index 327d1a969..d07446e1b 100644 --- a/docs/content/core/parameters.fsx +++ b/docs/content/core/parameters.fsx @@ -194,6 +194,10 @@ no longer exist. already in the descriptions file. Offline, a table or column whose description wasn't saved shows "Offline mode." in its tooltip. +Likewise, `SaveContextSchema` saves the individuals of the tables whose `Individuals` you opened to the individuals +file. A table is in the file once: saving it again replaces its individuals, and the other tables already in the file +are kept. + Schema files saved by older versions with individuals in them still work: re-saving such a file moves its individuals to the individuals file. diff --git a/src/SQLProvider.Common/SqlRuntime.Common.fs b/src/SQLProvider.Common/SqlRuntime.Common.fs index d8eea3eb8..d1053df41 100644 --- a/src/SQLProvider.Common/SqlRuntime.Common.fs +++ b/src/SQLProvider.Common/SqlRuntime.Common.fs @@ -996,16 +996,16 @@ and SchemaCache = static member private ReadJson<'T>(filePath) = use ms = new MemoryStream(Encoding.UTF8.GetBytes(File.ReadAllText filePath)) System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof<'T>).ReadObject(ms) :?> 'T - /// Saves the schema, and the descriptions to their own file. Individuals are not in the schema file: - /// SaveIndividuals saves them to their own file. Individuals read from saved files (offline mode) are saved to - /// the individuals file, so a re-save doesn't lose them. + /// Saves the schema, and the descriptions and the individuals read so far to their own files. Individuals are + /// not in the schema file, and each table is in the individuals file once: see SaveIndividuals. member this.Save(filePath) = // The empty Individuals is kept so that older SQLProvider versions can read the file. SchemaCache.WriteJson(filePath, { this with IsOffline = true; Individuals = ConcurrentDictionary() }) this.SaveDescriptions filePath |> ignore - if this.IsOffline && this.HasIndividuals then - // An individuals file already there is newer than individuals of an old schema file - this.LoadIndividuals filePath + if this.HasIndividuals then + if this.IsOffline then + // An individuals file already there is newer than individuals of an old schema file + this.LoadIndividuals filePath this.SaveIndividuals filePath |> ignore member this.HasDescriptions = this.TableDescriptions.Count > 0 || this.ColumnDescriptions.Count > 0 @@ -1112,17 +1112,27 @@ and SchemaCache = entities |> Array.map (fun (pkValue, values) -> SchemaCache.PrimaryKeyValue(clrType, pkValue), values) | _ -> () | _ -> () - /// Saves the individuals to the individuals file beside the schema file and returns its path. + /// Saves the individuals to the individuals file beside the schema file and returns its path. A table read now + /// replaces its individuals in the file, and the file's other tables are kept, so a table is there once. /// Tables without individuals are left out. member this.SaveIndividuals(filePath) = let individualsFile = SchemaCache.IndividualsFilePath filePath let toSave = ConcurrentDictionary) array>() - for KeyValue(table, entities) in this.Individuals do - if not (Array.isEmpty entities) then + let add table (entities: (obj * IDictionary) array) = + if not (isNull entities || Array.isEmpty entities) then toSave.[table] <- entities |> Array.map (fun (pk, columns) -> SchemaCache.IndividualsFileValue pk, - dict [ for KeyValue(column, value) in columns -> column, SchemaCache.IndividualsFileValue value ]) + dict [ if not (isNull columns) then + for KeyValue(column, value) in columns -> column, SchemaCache.IndividualsFileValue value ]) + if File.Exists individualsFile then + // An unreadable file is just replaced + let saved = try SchemaCache.ReadJson) array>> individualsFile with _ -> null + if not (isNull saved) then + for KeyValue(table, entities) in saved do + if not (this.Individuals.ContainsKey table) then add table entities + for KeyValue(table, entities) in this.Individuals do + add table entities SchemaCache.WriteJson(individualsFile, toSave) individualsFile /// Reads the individuals file beside the schema file, if there is one. Its individuals replace the same tables' older ones. diff --git a/src/SQLProvider.DesignTime/SqlDesignTime.fs b/src/SQLProvider.DesignTime/SqlDesignTime.fs index 407eddc8a..3f981475d 100644 --- a/src/SQLProvider.DesignTime/SqlDesignTime.fs +++ b/src/SQLProvider.DesignTime/SqlDesignTime.fs @@ -552,7 +552,8 @@ module DesignTimeUtils = m.AddXmlDocComputed(fun () -> if String.IsNullOrEmpty contextSchemaPath then "ContextSchemaPath static parameter has to be defined to use this function." else "Schema location: " + contextSchemaPath + ". Write dot after SaveContextSchema to save the schema used so far at design time, " + - "and the descriptions read so far to " + SchemaCache.DescriptionsFilePath contextSchemaPath + ". " + + "the descriptions read so far to " + SchemaCache.DescriptionsFilePath contextSchemaPath + " " + + "and the individuals opened so far to " + SchemaCache.IndividualsFilePath contextSchemaPath + ". " + "Online, SaveContextSchemaFull saves the whole database schema and SaveContextSchemaIndividuals the individuals." ) let expirationMessage = "Expired, moved under: .``Design Time Commands``" @@ -903,7 +904,8 @@ module DesignTimeUtils = cache.Save contextSchemaPath let files = [ yield contextSchemaPath - if cache.HasDescriptions then yield SchemaCache.DescriptionsFilePath contextSchemaPath ] + if cache.HasDescriptions then yield SchemaCache.DescriptionsFilePath contextSchemaPath + if cache.HasIndividuals then yield SchemaCache.IndividualsFilePath contextSchemaPath ] savedAt (String.concat ", " files) + schema + descriptions + failures failed /// Rows of data: a step of its own, apart from the schema, because of GDPR/PII. @@ -921,7 +923,8 @@ module DesignTimeUtils = [ yield "SaveContextSchemaFull", "Saves every table, column, relationship and stored procedure of the database to " + contextSchemaPath + ", not only the ones used so far, and the descriptions (comments) of every table and column to " + - descriptionsFile + ". No rows of data. Write dot after SaveContextSchemaFull to save. May take a while.", + descriptionsFile + ". Reads no rows of data; individuals already opened are saved as SaveContextSchema saves them. " + + "Write dot after SaveContextSchemaFull to save. May take a while.", saveFull if hasIndividuals then yield "SaveContextSchemaIndividuals", diff --git a/src/SQLProvider.Runtime/Providers.DuckDb.fs b/src/SQLProvider.Runtime/Providers.DuckDb.fs index 535e334cc..3282842dd 100644 --- a/src/SQLProvider.Runtime/Providers.DuckDb.fs +++ b/src/SQLProvider.Runtime/Providers.DuckDb.fs @@ -727,11 +727,14 @@ type internal DuckDbProvider(resolutionPath, contextSchemaPath, owner:string, re com.Parameters.Add((this:>ISqlProvider).CreateCommandParameter(QueryParameter.Create("table", 1), (DuckDb.ripQuotes table.Name))) |> ignore if con.State <> ConnectionState.Open then con.Open() use reader = com.ExecuteReader() + // As SQL Server and PostgreSQL have it: the primary side is the referenced table, the foreign side + // the table with the foreign key [ while reader.Read() do - yield { Name = reader.GetString 0; PrimaryTable=Table.CreateFullName(reader.GetString(2),reader.GetString(1)); PrimaryKey=reader.GetString 3 - ForeignTable=Table.CreateFullName(reader.GetString(5),reader.GetString(4)); ForeignKey=reader.GetString 6 } ] |> List.toArray - let children = read "KCU1" - let parents = read "KCU2" + yield { Name = reader.GetString 0; PrimaryTable=Table.CreateFullName(reader.GetString(5),reader.GetString(4)); PrimaryKey=reader.GetString 6 + ForeignTable=Table.CreateFullName(reader.GetString(2),reader.GetString(1)); ForeignKey=reader.GetString 3 } ] |> List.toArray + // Children are the rows of other tables that refer to this table, parents the rows this table refers to + let children = read "KCU2" + let parents = read "KCU1" (children,parents)) res) diff --git a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs index 7a3c2aa34..56f88e4b0 100644 --- a/tests/SqlProvider.Tests/SchemaCacheFileTests.fs +++ b/tests/SqlProvider.Tests/SchemaCacheFileTests.fs @@ -40,15 +40,71 @@ let ``the individuals file is beside the schema file`` () = Assert.AreEqual("schema.individuals", SchemaCache.IndividualsFilePath "schema") [] -let ``saving the schema leaves out the individuals of an online cache`` () = +let ``saving the schema saves the individuals read so far to their own file`` () = let path = tempSchemaPath () let cache = withCustomers SchemaCache.Empty cache.Save path - Assert.IsFalse(File.Exists(SchemaCache.IndividualsFilePath path)) let loaded = SchemaCache.Load path Assert.IsTrue(loaded.Tables.ContainsKey "main.Customers") Assert.AreEqual(0, loaded.Individuals.Count) StringAssert.DoesNotContain("Customer 1", File.ReadAllText path) + loaded.LoadIndividuals path + CollectionAssert.AreEqual(names (customers ()), names loaded.Individuals.["main.Customers_Id"]) + +[] +let ``without individuals saving the schema makes no individuals file`` () = + let path = tempSchemaPath () + let cache = SchemaCache.Empty + cache.Tables.["main.Customers"] <- { Schema = "main"; Name = "Customers"; Type = "TABLE" } + cache.Individuals.["main.Customers_Id"] <- [||] + cache.Save path + Assert.IsFalse(File.Exists(SchemaCache.IndividualsFilePath path)) + +[] +let ``saving again doesn't double the individuals`` () = + let path = tempSchemaPath () + let cache = withCustomers SchemaCache.Empty + cache.Save path + cache.Save path + cache.SaveIndividuals path |> ignore + let loaded = SchemaCache.Load path + loaded.LoadIndividuals path + loaded.Save path + let reloaded = SchemaCache.Load path + reloaded.LoadIndividuals path + Assert.AreEqual(1, reloaded.Individuals.Count) + CollectionAssert.AreEqual(names (customers ()), names reloaded.Individuals.["main.Customers_Id"]) + +[] +let ``saving individuals replaces the tables read now and keeps the others in the file`` () = + let path = tempSchemaPath () + let everything = withCustomers SchemaCache.Empty + everything.Individuals.["main.Orders_Id"] <- [| box 1, (dict [ "Id", box 1; "Name", box "Order 1" ]) |] + everything.SaveIndividuals path |> ignore + // A later session opened only Customers, and its rows have changed since + let later = SchemaCache.Empty + later.Tables.["main.Customers"] <- { Schema = "main"; Name = "Customers"; Type = "TABLE" } + later.Individuals.["main.Customers_Id"] <- [| box 9, (dict [ "Id", box 9; "Name", box "Newer" ]) |] + later.Save path + let loaded = SchemaCache.Empty + loaded.LoadIndividuals path + CollectionAssert.AreEqual([| "Newer" |], names loaded.Individuals.["main.Customers_Id"]) + CollectionAssert.AreEqual([| "Order 1" |], names loaded.Individuals.["main.Orders_Id"]) + // The cache itself still has only what it read + Assert.IsFalse(later.Individuals.ContainsKey "main.Orders_Id") + +[] +let ``a table read now without rows is left out of the file`` () = + let path = tempSchemaPath () + (withCustomers SchemaCache.Empty).SaveIndividuals path |> ignore + let later = SchemaCache.Empty + later.Individuals.["main.Customers_Id"] <- [||] + later.Individuals.["main.Orders_Id"] <- [| box 1, (dict [ "Id", box 1; "Name", box "Order 1" ]) |] + later.SaveIndividuals path |> ignore + let loaded = SchemaCache.Empty + loaded.LoadIndividuals path + Assert.IsFalse(loaded.Individuals.ContainsKey "main.Customers_Id") + Assert.IsTrue(loaded.Individuals.ContainsKey "main.Orders_Id") [] let ``saved individuals are read from their own file`` () =