diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index c44f8fc842ba..f2000ebf09c0 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -55,7 +55,7 @@ jobs: run: ./run git-clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - run: ./run backend benchmark runtime enso + - run: ./run backend benchmark runtime env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - if: failure() && runner.os == 'Windows' diff --git a/CHANGELOG.md b/CHANGELOG.md index 0346125f0b28..169f10cc8742 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -136,6 +136,9 @@ such as dropdown can now be placed in the node and affect the code text flow. - [The IDE UI element for selecting the execution mode of the project is now sending messages to the backend.][6341]. +- [Feedback when renaming a project][6366]. When the user tries to rename the + project to an invalid name, a helpful error message is shown and the text + field stays the same as to give the user the opportunity to fix the mistake. - [Area selectionof nodes no longer takes into account the visualisation that belongs to the node.][6487]. - [List Editor Widget][6470]. Now you can edit lists by clicking buttons on @@ -143,9 +146,17 @@ - [Fixed text visualisations which were being cut off at the last line.][6421] - [Fixed a bug where, when scrolling or dragging on a full-screen visualization, the view of the graph changed as well.][6530] +- [Changed the shortcut for restoring to the last saved version of a project + from cmd+r to + cmd+shift+r][6620] to make it less likely + that it would be triggered by accident. As a consequence, the program + execution shortcuts changed from + cmd+shift+t/r to + cmd+alt+t/r. [6421]: https://github.com/enso-org/enso/pull/6421 [6530]: https://github.com/enso-org/enso/pull/6530 +[6620]: https://github.com/enso-org/enso/pull/6620 #### EnsoGL (rendering engine) @@ -209,6 +220,7 @@ [6035]: https://github.com/enso-org/enso/pull/6035 [6097]: https://github.com/enso-org/enso/pull/6097 [6097]: https://github.com/enso-org/enso/pull/6341 +[6366]: https://github.com/enso-org/enso/pull/6366 [6487]: https://github.com/enso-org/enso/pull/6487 [6341]: https://github.com/enso-org/enso/pull/6341 [6470]: https://github.com/enso-org/enso/pull/6470 @@ -415,6 +427,8 @@ `Text.write`.][6459] - [Implemented `create_database_table` allowing saving queries as database tables.][6467] +- [Implemented `Column.format` for in-memory `Column`s.][6538] +- [Added `at_least_one` flag to `Table.tokenize_to_rows`.][6539] - [Moved `Redshift` connector into a separate `AWS` library.][6550] [debug-shortcuts]: @@ -622,6 +636,8 @@ [6429]: https://github.com/enso-org/enso/pull/6429 [6459]: https://github.com/enso-org/enso/pull/6459 [6467]: https://github.com/enso-org/enso/pull/6467 +[6538]: https://github.com/enso-org/enso/pull/6538 +[6539]: https://github.com/enso-org/enso/pull/6539 [6550]: https://github.com/enso-org/enso/pull/6550 #### Enso Compiler diff --git a/Cargo.lock b/Cargo.lock index ad4c0a5a1be2..97367fa5e9a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -148,7 +148,7 @@ dependencies = [ "enso-macro-utils", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -278,7 +278,7 @@ checksum = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -295,7 +295,7 @@ checksum = "1cd7fce9ba8c3c042128ce72d8b2ddbf3a05747efb67ea0313c635e10bda47a2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -961,7 +961,7 @@ dependencies = [ "cached_proc_macro_types", "darling", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1055,7 +1055,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1399,7 +1399,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" dependencies = [ "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1426,7 +1426,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn", + "syn 1.0.107", ] [[package]] @@ -1443,7 +1443,7 @@ checksum = "357f40d1f06a24b60ae1fe122542c1fb05d28d32acb2aed064e84bc2ad1e252e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1467,7 +1467,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 1.0.107", ] [[package]] @@ -1478,7 +1478,7 @@ checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" dependencies = [ "darling_core", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1658,7 +1658,7 @@ checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1671,7 +1671,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version 0.4.0", - "syn", + "syn 1.0.107", ] [[package]] @@ -1962,7 +1962,7 @@ dependencies = [ "enso-build-macros-lib", "itertools", "proc-macro2", - "syn", + "syn 1.0.107", ] [[package]] @@ -1978,7 +1978,7 @@ dependencies = [ "quote", "regex", "serde_yaml", - "syn", + "syn 1.0.107", ] [[package]] @@ -2019,6 +2019,7 @@ dependencies = [ "enso-prelude", "ensogl", "semver 1.0.16", + "thiserror", ] [[package]] @@ -2218,7 +2219,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2227,7 +2228,7 @@ version = "0.2.0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2323,7 +2324,7 @@ dependencies = [ "enso-macro-utils", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2416,7 +2417,7 @@ dependencies = [ "Inflector", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2434,7 +2435,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2462,7 +2463,7 @@ dependencies = [ "paste", "proc-macro2", "quote", - "syn", + "syn 1.0.107", "wasm-bindgen-test", ] @@ -2634,7 +2635,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -3266,7 +3267,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -3327,7 +3328,7 @@ checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", "synstructure", ] @@ -3426,7 +3427,7 @@ checksum = "236b4e4ae2b8be5f7a5652f6108c4a0f2627c569db4e7923333d31c7dbfed0fb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -3558,7 +3559,7 @@ checksum = "95a73af87da33b5acf53acfebdc339fe592ecf5357ac7c0a7734ab9d8c876a70" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -3730,7 +3731,7 @@ dependencies = [ "quote", "serde", "serde_json", - "syn", + "syn 1.0.107", ] [[package]] @@ -3741,7 +3742,7 @@ checksum = "a755cc59cda2641ea3037b4f9f7ef40471c329f55c1fa2db6fa0bb7ae6c1f7ce" dependencies = [ "graphql_client_codegen", "proc-macro2", - "syn", + "syn 1.0.107", ] [[package]] @@ -4149,7 +4150,7 @@ dependencies = [ "sha2", "strum", "symlink", - "syn", + "syn 1.0.107", "sysinfo", "tar", "tempfile", @@ -4342,6 +4343,7 @@ dependencies = [ "js-sys", "nalgebra", "ordered-float", + "parser", "serde", "serde-wasm-bindgen", "serde_json", @@ -4652,7 +4654,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -4782,7 +4784,7 @@ dependencies = [ "cfg-if 0.1.10", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5024,7 +5026,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5106,7 +5108,7 @@ checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5163,7 +5165,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5331,7 +5333,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5362,7 +5364,7 @@ checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5510,7 +5512,7 @@ dependencies = [ "proc-macro-error-attr", "proc-macro2", "quote", - "syn", + "syn 1.0.107", "version_check", ] @@ -5533,9 +5535,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.50" +version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2" +checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" dependencies = [ "unicode-ident", ] @@ -5560,7 +5562,7 @@ dependencies = [ "itertools", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -5602,9 +5604,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" -version = "1.0.23" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" dependencies = [ "proc-macro2", ] @@ -6136,7 +6138,7 @@ checksum = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -6342,7 +6344,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -6430,7 +6432,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn", + "syn 1.0.107", ] [[package]] @@ -6450,6 +6452,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "2.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "0.1.1" @@ -6464,7 +6477,7 @@ checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", "unicode-xid", ] @@ -6553,22 +6566,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.38" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" +checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.38" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" +checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.15", ] [[package]] @@ -6682,7 +6695,7 @@ checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -6888,7 +6901,7 @@ checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -7280,7 +7293,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.107", "wasm-bindgen-shared", ] @@ -7314,7 +7327,7 @@ checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/Cargo.toml b/Cargo.toml index b22bd852415d..e00b7ac0e0e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -134,3 +134,5 @@ syn = { version = "1.0", features = [ "visit-mut", ] } quote = { version = "1.0.23" } +semver = { version = "1.0.0", features = ["serde"] } +thiserror = "1.0.40" diff --git a/app/gui/Cargo.toml b/app/gui/Cargo.toml index 5a57c3454fcd..500fe57b4ad2 100644 --- a/app/gui/Cargo.toml +++ b/app/gui/Cargo.toml @@ -50,7 +50,7 @@ itertools = { workspace = true } js-sys = { workspace = true } mockall = { version = "0.7.1", features = ["nightly"] } nalgebra = { workspace = true } -semver = { version = "1.0.0", features = ["serde"] } +semver = { workspace = true } serde = { version = "1.0", features = ["derive"] } serde_json = { workspace = true } sha3 = { version = "0.8.2" } diff --git a/app/gui/config.yaml b/app/gui/config.yaml index e6ca0802fd42..08ece4c7e1b0 100644 --- a/app/gui/config.yaml +++ b/app/gui/config.yaml @@ -20,8 +20,8 @@ minimumSupportedVersion": "2.0.0-alpha.6" # The minimum engine version supported by the application. The projects opened with the older versions # will have the "Unsupported engine version" message displayed. -engineVersionSupported: "2023.1.1-nightly.2023.2.8" +engineVersionSupported: "2023.1.1" # The minimum language edition supported by the application. It will be displayed as edition user # should put in their package.yaml file to have project compatible with the IDE. -languageEditionSupported: "2023.1.1-nightly.2023.2.8" +languageEditionSupported: "2023.1.1" diff --git a/app/gui/config/Cargo.toml b/app/gui/config/Cargo.toml index 6b574e3c7dae..bb4bc0343e6c 100644 --- a/app/gui/config/Cargo.toml +++ b/app/gui/config/Cargo.toml @@ -8,7 +8,8 @@ edition = "2021" ensogl = { path = "../../../lib/rust/ensogl" } enso-prelude = { path = "../../../lib/rust/prelude" } enso-json-to-struct = { path = "../../../lib/rust/json-to-struct" } -semver = "1.0.0" +semver = { workspace = true } +thiserror = { workspace = true } [build-dependencies] config-reader = { path = "../../../lib/rust/config-reader" } diff --git a/app/gui/config/src/lib.rs b/app/gui/config/src/lib.rs index ca71959078b0..b01b31c494bb 100644 --- a/app/gui/config/src/lib.rs +++ b/app/gui/config/src/lib.rs @@ -20,15 +20,74 @@ use enso_json_to_struct::json_to_struct; // ============== -// === Config === +// === Errors === // ============== +///Error type with information that the Engine version does not meet the requirements. +#[derive(Clone, Debug, thiserror::Error)] +#[error("Unsupported Engine version: required {required} (or newer), found {found}.")] +pub struct UnsupportedEngineVersion { + /// The version of the Engine that is required. + pub required: semver::Version, + /// The version of the Engine that was found. + pub found: semver::Version, +} + + + +// =============== +// === Version === +// =============== + include!(concat!(env!("OUT_DIR"), "/config.rs")); pub use generated::*; -pub fn engine_version_requirement() -> semver::VersionReq { - semver::VersionReq::parse(&format!(">={engine_version_supported}")).unwrap() +/// The minimum supported engine version. +pub fn engine_version_required() -> semver::Version { + // Safe to unwrap, as `engine_version_supported` compile-time and is validated by the test. + semver::Version::parse(engine_version_supported).unwrap() +} + +/// Check if the given Engine version meets the requirements. +/// +/// Effectively, this checks if the given version is greater or equal to the minimum supported. +/// "Greater or equal" is defined by the [Semantic Versioning specification](https://semver.org/) +/// term of precedence. +pub fn check_engine_version_requirement( + required_version: &semver::Version, + tested_version: &semver::Version, +) -> Result<(), UnsupportedEngineVersion> { + // We don't want to rely on the `semver::VersionReq` semantics here. Unfortunately the + // [Semantic Versioning specification](https://semver.org/) does not define the semantics of + // the version requirement operators, so different implementations may behave differently. + // + // The `semver::VersionReq` implementation follows the Cargo's implementation, namely: + // ``` + // In particular, in order for any VersionReq to match a pre-release version, the VersionReq + // must contain at least one Comparator that has an explicit major, minor, and patch version + // identical to the pre-release being matched, and that has a nonempty pre-release component. + // ``` + // See: https://docs.rs/semver/latest/semver/struct.VersionReq.html#associatedconstant.STAR + // This leads to counter-intuitive behavior, where `2023.0.0-dev` does not fulfill the + // `>= 2022.0.0-dev` requirement. + if tested_version < required_version { + Err(UnsupportedEngineVersion { + required: required_version.clone(), + found: tested_version.clone(), + }) + } else { + Ok(()) + } +} + +/// Check if the given Engine version meets the requirements for this build. +/// +/// See [`check_engine_version_requirement`] for more details. +pub fn check_engine_version( + engine_version: &semver::Version, +) -> Result<(), UnsupportedEngineVersion> { + check_engine_version_requirement(&engine_version_required(), engine_version) } @@ -64,3 +123,37 @@ pub fn read_args() -> Args { lazy_static! { pub static ref ARGS: Args = read_args(); } + + + +// ============= +// === Tests === +// ============= + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_that_version_requirement_parses() { + // We just expect that it won't panic. + let _ = engine_version_required(); + } + + #[test] + fn new_project_engine_version_fills_requirements() { + // Sanity check: required version must be supported. + assert!(check_engine_version(&engine_version_required()).is_ok()); + } + + #[test] + fn newer_prerelease_matches() -> anyhow::Result<()> { + // Whatever version we have currently defined with `-dev` prerelease. + let current = + semver::Version { pre: semver::Prerelease::new("dev")?, ..engine_version_required() }; + let newer = semver::Version { major: current.major + 1, ..current.clone() }; + + check_engine_version_requirement(¤t, &newer)?; + Ok(()) + } +} diff --git a/app/gui/controller/engine-protocol/src/common/error.rs b/app/gui/controller/engine-protocol/src/common/error.rs index ea842f8c46c6..adbe8c46aadd 100644 --- a/app/gui/controller/engine-protocol/src/common/error.rs +++ b/app/gui/controller/engine-protocol/src/common/error.rs @@ -30,4 +30,7 @@ pub mod code { /// Signals that requested project is already under version control. pub const VCS_ALREADY_EXISTS: i64 = 1005; + + /// Signals that project name is invalid. + pub const PROJECT_NAME_INVALID: i64 = 4001; } diff --git a/app/gui/docs/product/shortcuts.md b/app/gui/docs/product/shortcuts.md index e1a649759797..815a2257e19b 100644 --- a/app/gui/docs/product/shortcuts.md +++ b/app/gui/docs/product/shortcuts.md @@ -40,6 +40,7 @@ broken and require further investigation. | ctrl+` | Show Code Editor. Please note that the Code Editor implementation is in a very early stage and you should not use it. Even just openning it can cause errors in the IDE. Do not try using the graph editor while having the code editor tab openned. | | cmd+o | Open project | | cmd+s | Save module | +| cmd+shift+r | Restore module from last save | | cmd+z | Undo last action | | cmd+y or cmd + shift + z | Redo last undone action | | cmd+q | Close the application (MacOS) | @@ -48,8 +49,8 @@ broken and require further investigation. | ctrl+w | Close the application (Windows, Linux) | | :warning: ctrl+p | Toggle profiling mode | | escape | Cancel current action. For example, drop currently dragged connection. | -| cmd+shift+t | Terminate the program execution | -| cmd+shift+r | Re-execute the program | +| cmd+alt+t | Terminate the program execution | +| cmd+alt+r | Re-execute the program | | cmd+shift+k | Switch the execution environment to Design. | | cmd+shift+l | Switch the execution environment to Live. | diff --git a/app/gui/src/controller/project.rs b/app/gui/src/controller/project.rs index 6c9c205b754a..e78384ead0cd 100644 --- a/app/gui/src/controller/project.rs +++ b/app/gui/src/controller/project.rs @@ -214,16 +214,8 @@ impl Project { } fn display_warning_on_unsupported_engine_version(&self) { - let requirement = enso_config::engine_version_requirement(); - let version = self.model.engine_version(); - if !requirement.matches(&version) { - let message = format!( - "Unsupported Engine version. Please update edition in {} \ - to {}.", - package_yaml_path(&self.model.name()), - enso_config::language_edition_supported - ); - self.status_notifications.publish_event(message); + if let Err(e) = enso_config::check_engine_version(&self.model.engine_version()) { + self.status_notifications.publish_event(e.to_string()); } } } @@ -273,19 +265,6 @@ mod tests { use engine_protocol::language_server; use std::assert_matches::assert_matches; - #[test] - fn parse_supported_engine_version() { - // Should not panic. - enso_config::engine_version_requirement(); - } - - #[test] - fn new_project_engine_version_fills_requirements() { - let requirements = enso_config::engine_version_requirement(); - let version = semver::Version::parse(enso_config::engine_version_supported).unwrap(); - assert!(requirements.matches(&version)) - } - #[wasm_bindgen_test] fn adding_missing_main() { let _ctx = TestWithLocalPoolExecutor::set_up(); diff --git a/app/gui/src/model/project/synchronized.rs b/app/gui/src/model/project/synchronized.rs index 4967efe096b5..62e92a6ba246 100644 --- a/app/gui/src/model/project/synchronized.rs +++ b/app/gui/src/model/project/synchronized.rs @@ -224,6 +224,13 @@ async fn update_modules_on_file_change( #[fail(display = "Project Manager is unavailable.")] pub struct ProjectManagerUnavailable; +/// An error signalling the project name was invalid. +#[derive(Clone, Debug, Fail)] +#[fail(display = "The project name is not allowed: {}", cause)] +pub struct ProjectNameInvalid { + cause: String, +} + #[allow(missing_docs)] #[derive(Clone, Copy, Debug, Fail)] #[fail(display = "Project renaming is not available in read-only mode.")] @@ -233,8 +240,9 @@ pub struct RenameInReadOnly; /// engine's version (which is likely the cause of the problems). #[derive(Debug, Fail)] pub struct UnsupportedEngineVersion { - project_name: String, - root_cause: failure::Error, + project_name: String, + version_mismatch: enso_config::UnsupportedEngineVersion, + root_cause: failure::Error, } impl UnsupportedEngineVersion { @@ -242,10 +250,13 @@ impl UnsupportedEngineVersion { let engine_version = properties.engine_version.clone(); let project_name = properties.name.project.as_str().to_owned(); move |root_cause| { - let requirement = enso_config::engine_version_requirement(); - if !requirement.matches(&engine_version) { - let project_name = project_name.clone(); - UnsupportedEngineVersion { project_name, root_cause }.into() + if let Err(version_mismatch) = enso_config::check_engine_version(&engine_version) { + UnsupportedEngineVersion { + project_name: project_name.clone(), + version_mismatch, + root_cause, + } + .into() } else { root_cause } @@ -720,7 +731,14 @@ impl model::project::API for Project { self.project_manager.as_ref().ok_or(ProjectManagerUnavailable)?; let project_id = self.properties.borrow().id; let project_name = ProjectName::new_unchecked(name); - project_manager.rename_project(&project_id, &project_name).await?; + project_manager.rename_project(&project_id, &project_name).await.map_err( + |error| match error { + RpcError::RemoteError(cause) + if cause.code == code::PROJECT_NAME_INVALID => + failure::Error::from(ProjectNameInvalid { cause: cause.message }), + error => error.into(), + }, + )?; self.properties.borrow_mut().name.project = referent_name.clone_ref(); self.execution_contexts.rename_project(old_name, referent_name); Ok(()) diff --git a/app/gui/src/presenter/project.rs b/app/gui/src/presenter/project.rs index 2805043bf9b5..01ed7c3efddb 100644 --- a/app/gui/src/presenter/project.rs +++ b/app/gui/src/presenter/project.rs @@ -4,6 +4,7 @@ use crate::prelude::*; use crate::executor::global::spawn_stream_handler; +use crate::model::project::synchronized::ProjectNameInvalid; use crate::presenter; use crate::presenter::graph::ViewNodeId; @@ -159,11 +160,23 @@ impl Model { if self.controller.model.name() != name.as_ref() { let project = self.controller.model.clone_ref(); let breadcrumbs = self.view.graph().model.breadcrumbs.clone_ref(); + let popup = self.view.popup().clone_ref(); let name = name.into(); executor::global::spawn(async move { - if let Err(e) = project.rename_project(name).await { - error!("The project couldn't be renamed: {e}"); - breadcrumbs.cancel_project_name_editing.emit(()); + if let Err(error) = project.rename_project(name).await { + let error_message = match error.downcast::() { + Ok(error) => error.to_string(), + Err(error) => { + // Other errors aren't geared towards users, so display a generic + // message. + let prefix = "The project couldn't be renamed".to_string(); + error!("{prefix}: {error}"); + prefix + } + }; + popup.set_label.emit(error_message); + // Reset name to old, valid value + breadcrumbs.input.project_name.emit(project.name()); } }); } diff --git a/app/gui/view/documentation/src/html.rs b/app/gui/view/documentation/src/html.rs index 4d28ce1de4b9..802a7c3a1416 100644 --- a/app/gui/view/documentation/src/html.rs +++ b/app/gui/view/documentation/src/html.rs @@ -63,16 +63,29 @@ fn svg_icon(content: &'static str) -> impl Render { /// Render entry documentation to HTML code with Tailwind CSS styles. #[profile(Detail)] pub fn render(docs: EntryDocumentation) -> String { - match docs { + let html = match docs { EntryDocumentation::Placeholder(placeholder) => match placeholder { Placeholder::NoDocumentation => String::from("No documentation available."), Placeholder::VirtualComponentGroup { name } => render_virtual_component_group_docs(name), }, EntryDocumentation::Docs(docs) => render_documentation(docs), + }; + match validate_utf8(&html) { + Ok(_) => html, + Err(_) => { + error!("Internal error. Generated HTML is not valid utf-8. This is bug #5813."); + String::from("Failed to load documentation.") + } } } +#[profile(Debug)] +fn validate_utf8(s: &str) -> Result<&str, std::str::Utf8Error> { + let bytes = s.as_bytes(); + std::str::from_utf8(bytes) +} + fn render_documentation(docs: Documentation) -> String { match docs { Documentation::Module(module_docs) => render_module_documentation(&module_docs, None), diff --git a/app/gui/view/documentation/src/lib.rs b/app/gui/view/documentation/src/lib.rs index a1f827815cf3..1436b07675a7 100644 --- a/app/gui/view/documentation/src/lib.rs +++ b/app/gui/view/documentation/src/lib.rs @@ -18,21 +18,12 @@ //! [`Tailwind CSS`]: https://tailwindcss.com/ // === Features === -#![feature(associated_type_bounds)] -#![feature(associated_type_defaults)] #![feature(drain_filter)] -#![feature(fn_traits)] #![feature(option_result_contains)] -#![feature(specialization)] -#![feature(trait_alias)] -#![feature(type_alias_impl_trait)] -#![feature(unboxed_closures)] // === Standard Linter Configuration === #![deny(non_ascii_idents)] -#![warn(unsafe_code)] #![allow(clippy::bool_to_int_with_if)] #![allow(clippy::let_and_return)] -#![allow(incomplete_features)] // To be removed, see: https://github.com/enso-org/ide/issues/1559 #![warn(missing_copy_implementations)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] @@ -64,10 +55,8 @@ use ensogl::Animation; use ensogl_component::shadow; use ensogl_derive_theme::FromTheme; use ensogl_hardcoded_theme::application::component_browser::documentation as theme; -use web::Closure; use web::HtmlElement; use web::JsCast; -use web::MouseEvent; pub mod html; @@ -89,6 +78,7 @@ const MIN_CAPTION_HEIGHT: f32 = 1.0; /// Delay before updating the displayed documentation. const DISPLAY_DELAY_MS: i32 = 0; + // === Style === #[derive(Debug, Clone, Copy, Default, FromTheme)] @@ -108,24 +98,20 @@ pub struct Style { // === Model === // ============= -type CodeCopyClosure = Closure; - /// Model of Native visualization that generates documentation for given Enso code and embeds /// it in a HTML container. #[derive(Clone, CloneRef, Debug)] #[allow(missing_docs)] pub struct Model { - outer_dom: DomSymbol, - caption_dom: DomSymbol, - inner_dom: DomSymbol, + outer_dom: DomSymbol, + caption_dom: DomSymbol, + inner_dom: DomSymbol, /// The purpose of this overlay is stop propagating mouse events under the documentation panel /// to EnsoGL shapes, and pass them to the DOM instead. - overlay: overlay::View, - display_object: display::object::Instance, - code_copy_closures: Rc>>, + overlay: overlay::View, + display_object: display::object::Instance, } - impl Model { /// Constructor. fn new(scene: &Scene) -> Self { @@ -164,9 +150,7 @@ impl Model { scene.dom.layers.node_searcher.manage(&inner_dom); scene.dom.layers.node_searcher.manage(&caption_dom); - let code_copy_closures = default(); - Model { outer_dom, inner_dom, caption_dom, overlay, display_object, code_copy_closures } - .init() + Model { outer_dom, inner_dom, caption_dom, overlay, display_object }.init() } fn init(self) -> Self { diff --git a/app/gui/view/examples/interface/src/lib.rs b/app/gui/view/examples/interface/src/lib.rs index d8a9639068be..a8c275ebb1ff 100644 --- a/app/gui/view/examples/interface/src/lib.rs +++ b/app/gui/view/examples/interface/src/lib.rs @@ -19,6 +19,7 @@ use ensogl::prelude::*; use enso_frp as frp; use ensogl::application::Application; +use ensogl::control::io::mouse; use ensogl::display::object::ObjectOps; use ensogl::display::shape::StyleWatch; use ensogl::gui::text; @@ -260,6 +261,23 @@ fn init(app: &Application) { graph_editor.set_available_execution_environments(make_dummy_execution_environments()); + // === Pop-up === + + // Create node to trigger a pop-up. + let node_id = graph_editor.model.add_node(); + graph_editor.frp.set_node_position.emit((node_id, Vector2(-300.0, -100.0))); + let expression = expression_mock_string("Click me to show a pop-up"); + graph_editor.frp.set_node_expression.emit((node_id, expression)); + let node = graph_editor.nodes().all.get_cloned_ref(&node_id).unwrap(); + + let popup = project_view.popup(); + let network = node.network(); + let node_clicked = node.on_event::(); + frp::extend! { network + eval_ node_clicked (popup.set_label.emit("This is a test pop-up.")); + } + + // === Rendering === // let tgt_type = dummy_type_generator.get_dummy_type(); diff --git a/app/gui/view/graph-editor/Cargo.toml b/app/gui/view/graph-editor/Cargo.toml index 5566d5961139..6b4bd34dc32f 100644 --- a/app/gui/view/graph-editor/Cargo.toml +++ b/app/gui/view/graph-editor/Cargo.toml @@ -29,6 +29,7 @@ indexmap = "1.9.2" js-sys = { workspace = true } nalgebra = { workspace = true } ordered-float = { workspace = true } +parser = { path = "../../language/parser" } serde = { version = "1.0", features = ["derive"] } serde-wasm-bindgen = { workspace = true } serde_json = { workspace = true } diff --git a/app/gui/view/graph-editor/src/component/breadcrumbs.rs b/app/gui/view/graph-editor/src/component/breadcrumbs.rs index d30ad663a546..17ba6ff12ff3 100644 --- a/app/gui/view/graph-editor/src/component/breadcrumbs.rs +++ b/app/gui/view/graph-editor/src/component/breadcrumbs.rs @@ -81,12 +81,6 @@ ensogl::define_endpoints! { /// Signalizes a mouse press happened outside the breadcrumb panel. It's used to finish /// project renaming, committing the name in text field. outside_press (), - /// Signalizes we want to cancel project name renaming, bringing back the project name - /// before editing. - cancel_project_name_editing (), - /// Signalizes we want to start editing the project name. Adds a cursor to the text edit - /// field at the mouse position. - start_project_name_editing (), /// Sets the project name. project_name (String), /// Select the breadcrumb by its index. @@ -126,6 +120,8 @@ ensogl::define_endpoints! { project_name_hovered (bool), /// Indicates whether the project name was clicked. project_mouse_down (), + /// Signalizes an error if the user tried to rename the project to an invalid name. + project_name_error (String), /// Indicates if the read-only mode is enabled. read_only(bool), } @@ -478,7 +474,6 @@ impl Breadcrumbs { eval frp.input.project_name((name) model.project_name.set_name.emit(name)); frp.source.project_name <+ model.project_name.output.name; - eval_ frp.input.start_project_name_editing( model.project_name.start_editing.emit(()) ); eval frp.ide_text_edit_mode((value) model.project_name.ide_text_edit_mode.emit(value) ); frp.source.project_name_hovered <+ model.project_name.is_hovered; @@ -486,10 +481,12 @@ impl Breadcrumbs { eval frp.input.set_project_changed((v) model.project_name.set_project_changed(v)); + frp.source.project_name_error <+ model.project_name.error; + + // === User Interaction === frp.select_breadcrumb <+ model.project_name.frp.output.mouse_down.constant(0); - model.project_name.frp.cancel_editing <+ frp.cancel_project_name_editing; model.project_name.frp.outside_press <+ frp.outside_press; popped_count <= frp.output.breadcrumb_select.map(|selected| (0..selected.0).collect_vec()); diff --git a/app/gui/view/graph-editor/src/component/breadcrumbs/project_name.rs b/app/gui/view/graph-editor/src/component/breadcrumbs/project_name.rs index 2f5e39beb61f..431d374ffbd5 100644 --- a/app/gui/view/graph-editor/src/component/breadcrumbs/project_name.rs +++ b/app/gui/view/graph-editor/src/component/breadcrumbs/project_name.rs @@ -19,6 +19,7 @@ use ensogl::DEPRECATED_Animation; use ensogl_component::text; use ensogl_component::text::formatting::Size as TextSize; use ensogl_hardcoded_theme::graph_editor::breadcrumbs as breadcrumbs_theme; +use parser::Parser; @@ -66,8 +67,8 @@ ensogl::define_endpoints_2! { cancel_editing (), /// Enable editing the project name field and add a cursor at the mouse position. start_editing (), - /// Commit current project name. - commit (), + /// Try committing current project name. + try_commit (), outside_press (), /// Indicates that this is the currently active breadcrumb. select (), @@ -90,6 +91,7 @@ ensogl::define_endpoints_2! { edit_mode (bool), selected (bool), is_hovered (bool), + error (String), read_only (bool), } } @@ -217,6 +219,24 @@ impl ProjectNameModel { self.commit(name); } + /// Confirm the given name as the current project name if it's valid. + fn try_commit(&self, name: impl Str) -> Result<(), String> { + let name = name.into(); + Self::validate(&name) + .map_err(|error| format!("The project couldn't be renamed. {error}"))?; + self.commit(name); + Ok(()) + } + + /// Check whether the given name is a valid project name. + fn validate(name: impl Str) -> Result<(), String> { + let parser = Parser::new(); + match parser.parse_line_ast(name).map(|ast| ast.shape().clone()) { + Ok(ast::Shape::Cons(_)) => Ok(()), + _ => Err("The project name should use the 'Upper_Snake' case.".to_owned()), + } + } + /// Confirm the given name as the current project name. fn commit>(&self, name: T) { let name = name.into(); @@ -323,11 +343,15 @@ impl ProjectName { // === Commit === - do_commit <- any(&frp.commit,&frp.outside_press).gate(&frp.output.edit_mode); - commit_text <- text_content.sample(&do_commit); - output.name <+ commit_text; - eval commit_text((text) model.commit(text)); - on_commit <- commit_text.constant(()); + try_commit <- any(&frp.try_commit, &frp.outside_press).gate(&frp.output.edit_mode); + commit_result <- try_commit.map2(&text_content, f!([model] (_, text) { + let result = model.try_commit(text); + (result.as_ref().ok().copied(), result.err()) + })); + commit_success <- commit_result.filter_map(|(ok, _)| *ok); + commit_failure <- commit_result.filter_map(|(_, error)| error.clone()); + output.name <+ text_content.sample(&commit_success); + output.error <+ commit_failure; not_selected <- frp.output.selected.map(|selected| !selected); on_deselect <- not_selected.gate(¬_selected).constant(()); @@ -337,7 +361,7 @@ impl ProjectName { // === Selection === output.selected <+ frp.select.to_true(); - set_inactive <- any(&frp.deselect,&on_commit); + set_inactive <- any(&frp.deselect, &commit_success); eval_ set_inactive ([text,model] { text.deprecated_set_focus(false); text.remove_all_cursors(); @@ -409,7 +433,7 @@ impl View for ProjectName { fn default_shortcuts() -> Vec { use shortcut::ActionType::*; [ - (Press, "!read_only", "enter", "commit"), + (Press, "!read_only", "enter", "try_commit"), (Release, "", "escape", "cancel_editing"), (DoublePress, "is_hovered & !read_only", "left-mouse-button", "start_editing"), ] diff --git a/app/gui/view/graph-editor/src/component/visualization/container.rs b/app/gui/view/graph-editor/src/component/visualization/container.rs index 5d713495cca5..cfdbeb15ce49 100644 --- a/app/gui/view/graph-editor/src/component/visualization/container.rs +++ b/app/gui/view/graph-editor/src/component/visualization/container.rs @@ -315,6 +315,15 @@ impl ContainerModel { impl ContainerModel { fn set_visibility(&self, visibility: bool) { + // This is a workaround for #6600. It ensures the action bar is removed + // and receive no further mouse events. + if visibility { + self.view.add_child(&self.action_bar); + } else { + self.action_bar.unset_parent(); + } + + // Show or hide the visualization. if visibility { self.drag_root.add_child(&self.view); self.show_visualisation(); diff --git a/app/gui/view/src/debug_mode_popup.rs b/app/gui/view/src/debug_mode_popup.rs index 65adbcf74b09..f7e2bebab084 100644 --- a/app/gui/view/src/debug_mode_popup.rs +++ b/app/gui/view/src/debug_mode_popup.rs @@ -1,15 +1,13 @@ -//! Text message on top of the screen that signals about enabling/disabling Debug Mode of Graph -//! Editor. +//! A pop-up that signals about enabling/disabling Debug Mode of Graph Editor. use crate::prelude::*; -use ensogl::display::shape::*; -use enso_frp as frp; -use ensogl::animation::delayed::DelayedAnimation; +use crate::popup; + use ensogl::application::Application; use ensogl::display; -use ensogl::Animation; -use ensogl_component::label::Label; +use frp::stream::EventOutput; +use frp::HasLabel; @@ -28,110 +26,7 @@ macro_rules! define_debug_mode_shortcut { } define_debug_mode_shortcut!("ctrl shift d"); const DEBUG_MODE_DISABLED: &str = "Debug Mode disabled."; - const LABEL_VISIBILITY_DELAY_MS: f32 = 3_000.0; -const LABEL_PADDING_TOP: f32 = 50.0; - - - -// ================== -// === PopupLabel === -// ================== - -/// Text label that disappears after a predefined delay. -#[derive(Debug, Clone, CloneRef)] -pub struct PopupLabel { - label: Label, - network: frp::Network, - delay_animation: DelayedAnimation, - /// Show the Popup with the given message. - pub show: frp::Source, -} - -impl display::Object for PopupLabel { - fn display_object(&self) -> &display::object::Instance { - self.label.display_object() - } -} - -impl PopupLabel { - /// Constructor. - pub fn new(app: &Application) -> Self { - let network = frp::Network::new("PopupLabel"); - let label = Label::new(app); - label.set_opacity(0.0); - let background_layer = &app.display.default_scene.layers.panel; - let text_layer = &app.display.default_scene.layers.panel_text; - label.set_layers(background_layer, text_layer); - - let opacity_animation = Animation::new(&network); - network.store(&opacity_animation); - let delay_animation = DelayedAnimation::new(&network); - delay_animation.set_delay(0.0); - delay_animation.set_duration(0.0); - network.store(&delay_animation); - - frp::extend! { network - show <- source::(); - - eval show ([label, delay_animation](text) { - label.set_content(text); - delay_animation.reset(); - delay_animation.start(); - }); - - opacity_animation.target <+ show.constant(1.0); - opacity_animation.target <+ delay_animation.on_end.constant(0.0); - label.set_opacity <+ opacity_animation.value; - } - - Self { label, network, show, delay_animation } - } - - /// Set a delay in milliseconds after which the label will disappear. - pub fn set_delay(&self, delay: f32) { - self.delay_animation.set_delay(delay); - } -} - - - -// ============= -// === Model === -// ============= - -#[derive(Debug, Clone, CloneRef)] -struct Model { - display_object: display::object::Instance, - label: PopupLabel, -} - -impl Model { - /// Constructor. - pub fn new(app: &Application) -> Self { - let display_object = display::object::Instance::new(); - let label = PopupLabel::new(app); - label.set_delay(LABEL_VISIBILITY_DELAY_MS); - display_object.add_child(&label); - - Self { display_object, label } - } - - /// Show "Debug Mode enabled" label. - pub fn show_enabled_label(&self) { - self.label.show.emit(String::from(DEBUG_MODE_ENABLED)); - } - - /// Show "Debug Mode disabled" label. - pub fn show_disabled_label(&self) { - self.label.show.emit(String::from(DEBUG_MODE_DISABLED)); - } - - /// Return the height of the label. - pub fn label_height(&self) -> f32 { - self.label.label.size.value().y - } -} @@ -155,48 +50,39 @@ ensogl::define_endpoints! { // === View === // ============ -/// Text message on top of the screen that signals about enabling/disabling Debug Mode of Graph -/// Editor. +/// A pop-up that signals about enabling/disabling Debug Mode of Graph Editor. #[derive(Debug, Clone, CloneRef)] pub struct View { frp: Frp, - model: Model, + popup: popup::View, } impl View { /// Constructor. pub fn new(app: &Application) -> Self { let frp = Frp::new(); - let model = Model::new(app); let network = &frp.network; + let popup = popup::View::new(app); + + popup.set_delay(LABEL_VISIBILITY_DELAY_MS); frp::extend! { network - init <- source_(); - let shape = app.display.default_scene.shape(); - _eval <- all_with(shape, &init, f!([model](scene_size, _init) { - let half_height = scene_size.height / 2.0; - let label_height = model.label_height(); - let pos_y = half_height - LABEL_PADDING_TOP - label_height / 2.0; - model.display_object.set_y(pos_y); - })); - - eval_ frp.enabled(model.show_enabled_label()); - eval_ frp.disabled(model.show_disabled_label()); + eval_ frp.enabled (popup.set_label(DEBUG_MODE_ENABLED.to_string())); + eval_ frp.disabled (popup.set_label(DEBUG_MODE_DISABLED.to_string())); } - init.emit(()); - Self { frp, model } + Self { frp, popup } } - /// Get the label of the popup. - pub fn label(&self) -> &PopupLabel { - &self.model.label + /// Get the FRP node for the content of the pop-up, for testing purposes. + pub fn content_frp_node(&self) -> impl EventOutput + HasLabel { + self.popup.content_frp_node() } } impl display::Object for View { fn display_object(&self) -> &display::object::Instance { - &self.model.display_object + self.popup.display_object() } } diff --git a/app/gui/view/src/lib.rs b/app/gui/view/src/lib.rs index ab816ae54bc7..96853628a874 100644 --- a/app/gui/view/src/lib.rs +++ b/app/gui/view/src/lib.rs @@ -32,6 +32,7 @@ #[allow(clippy::option_map_unit_fn)] pub mod code_editor; pub mod debug_mode_popup; +pub mod popup; pub mod project; pub mod project_list; pub mod root; diff --git a/app/gui/view/src/popup.rs b/app/gui/view/src/popup.rs new file mode 100644 index 000000000000..a7b8ec556869 --- /dev/null +++ b/app/gui/view/src/popup.rs @@ -0,0 +1,143 @@ +//! A temporary text message on top of the screen. + +use crate::prelude::*; + +use ensogl::animation::delayed::DelayedAnimation; +use ensogl::application::Application; +use ensogl::display; +use ensogl::Animation; +use ensogl_component::label::Label; +use frp::stream::EventOutput; +use frp::HasLabel; + + + +// ================= +// === Constants === +// ================= + +const PADDING_TOP: f32 = 50.0; +const DEFAULT_DELAY_MS: f32 = 5_000.0; + + + +// ============= +// === Model === +// ============= + +/// Text label that disappears after a predefined delay. +#[derive(Debug, Clone, CloneRef)] +struct Model { + label: Label, + opacity_animation: Animation, + delay_animation: DelayedAnimation, +} + +impl Model { + /// Constructor. + fn new(app: &Application, network: &frp::Network) -> Self { + let label = Label::new(app); + label.set_opacity(0.0); + // Add the pop-up to the panel layer so its position is fixed. The default for Label is the + // tooltip layer, which moves when panning. + let scene = &app.display.default_scene; + let background_layer = &scene.layers.panel; + let text_layer = &scene.layers.panel_text; + label.set_layers(background_layer, text_layer); + + let opacity_animation = Animation::new(network); + network.store(&opacity_animation); + let delay_animation = DelayedAnimation::new(network); + delay_animation.set_delay(DEFAULT_DELAY_MS); + delay_animation.set_duration(0.0); + network.store(&delay_animation); + + Self { label, opacity_animation, delay_animation } + } + + /// Set the message. + fn set_label(&self, content: String) { + self.label.set_content(content); + self.delay_animation.reset(); + self.delay_animation.start(); + } + + /// Set the position of the label based on the height of the scene. + fn set_label_position(&self, scene_height: f32) { + let half_height = scene_height / 2.0; + let label_height = self.label.size.value().y; + let pos_y = half_height - PADDING_TOP - label_height / 2.0; + self.label.display_object().set_y(pos_y); + } + + /// Set a delay in milliseconds after which the label will disappear. + fn set_delay(&self, delay: f32) { + self.delay_animation.set_delay(delay); + } +} + + + +// =========== +// === FRP === +// =========== + +ensogl::define_endpoints! { + Input { + set_label (String), + set_delay (f32), + } + Output {} +} + + + +// ============ +// === View === +// ============ + +/// A temporary text message on top of the screen. +#[derive(Debug, Clone, CloneRef, Deref)] +pub struct View { + #[deref] + frp: Frp, + model: Model, +} + +impl View { + /// Constructor. + pub fn new(app: &Application) -> Self { + let frp = Frp::new(); + let network = &frp.network; + let model = Model::new(app, network); + + frp::extend! { network + init <- source_(); + let scene_shape = app.display.default_scene.shape(); + _eval <- all_with(scene_shape, &init, f!((scene_shape, _init) + model.set_label_position(scene_shape.height); + )); + + model.opacity_animation.target <+ frp.set_label.constant(1.0); + model.opacity_animation.target <+ model.delay_animation.on_end.constant(0.0); + model.label.set_opacity <+ model.opacity_animation.value; + + eval frp.set_label ((content) model.set_label(content.clone())); + eval frp.set_delay ((delay) model.set_delay(*delay)); + } + init.emit(()); + + Self { frp, model } + } + + /// Get the FRP node for the content of the pop-up, for testing purposes. + pub fn content_frp_node(&self) -> impl EventOutput + HasLabel { + self.frp.set_label.clone_ref() + } +} + +impl display::Object for View { + fn display_object(&self) -> &display::object::Instance { + self.model.label.display_object() + } +} diff --git a/app/gui/view/src/project.rs b/app/gui/view/src/project.rs index acf620d2c0a0..b92539147cc8 100644 --- a/app/gui/view/src/project.rs +++ b/app/gui/view/src/project.rs @@ -13,6 +13,7 @@ use crate::graph_editor::component::node::Expression; use crate::graph_editor::component::visualization; use crate::graph_editor::GraphEditor; use crate::graph_editor::NodeId; +use crate::popup; use crate::project_list::ProjectList; use crate::searcher; @@ -147,6 +148,7 @@ struct Model { fullscreen_vis: Rc>>, project_list: Rc, debug_mode_popup: debug_mode_popup::View, + popup: popup::View, } impl Model { @@ -158,6 +160,7 @@ impl Model { let code_editor = app.new_view::(); let fullscreen_vis = default(); let debug_mode_popup = debug_mode_popup::View::new(app); + let popup = popup::View::new(app); let runs_in_web = ARGS.groups.startup.options.platform.value == "web"; let window_control_buttons = runs_in_web.as_some_from(|| { let window_control_buttons = app.new_view::(); @@ -172,6 +175,7 @@ impl Model { display_object.add_child(&code_editor); display_object.add_child(&searcher); display_object.add_child(&debug_mode_popup); + display_object.add_child(&popup); display_object.remove_child(&searcher); let app = app.clone_ref(); @@ -186,6 +190,7 @@ impl Model { fullscreen_vis, project_list, debug_mode_popup, + popup, } } @@ -371,10 +376,7 @@ impl View { // FIXME[WD]: Think how to refactor it, as it needs to be done before model, as we do not // want shader recompilation. Model uses styles already. model.set_style(theme); - // TODO[WD]: This should not be needed after the theme switching issue is implemented. - // See: https://github.com/enso-org/ide/issues/795 let input_change_delay = frp::io::timer::Timeout::new(network); - let searcher_open_delay = frp::io::timer::Timeout::new(network); if let Some(window_control_buttons) = &*model.window_control_buttons { let initial_size = &window_control_buttons.size.value(); @@ -477,8 +479,7 @@ impl View { existing_node_edited <- graph.node_expression_edited.gate_not(&frp.is_searcher_opened); open_searcher <- existing_node_edited.map2(&node_edited_by_user, |(id, _, _), edited| edited.map_or(false, |edited| *id == edited) - ).on_true(); - searcher_open_delay.restart <+ open_searcher.constant(0); + ).on_true().debounce(); cursor_position <- existing_node_edited.map2( &node_edited_by_user, |(node_id, _, selections), edited| { @@ -490,7 +491,7 @@ impl View { ).filter_map(|pos| *pos); edited_node <- node_edited_by_user.filter_map(|node| *node); position_and_edited_node <- cursor_position.map2(&edited_node, |pos, id| (*pos, *id)); - prepare_params <- position_and_edited_node.sample(&searcher_open_delay.on_expired); + prepare_params <- position_and_edited_node.sample(&open_searcher); frp.source.searcher <+ prepare_params.map(|(pos, node_id)| { Some(SearcherParams::new_for_edited_node(*node_id, *pos)) }); @@ -505,7 +506,7 @@ impl View { update_searcher_input_on_commit <- frp.output.editing_committed.constant(()); input_change_delay.cancel <+ update_searcher_input_on_commit; update_searcher_input <- any(&input_change_delay.on_expired, &update_searcher_input_on_commit); - input_change_and_searcher <- map2(&searcher_input_change, &frp.searcher, + input_change_and_searcher <- all_with(&searcher_input_change, &frp.searcher, |c, s| (c.clone(), *s) ); updated_input <- input_change_and_searcher.sample(&update_searcher_input); @@ -624,6 +625,10 @@ impl View { model.debug_mode_popup.enabled <+ frp.enable_debug_mode; model.debug_mode_popup.disabled <+ frp.disable_debug_mode; + + // === Error Pop-up === + + model.popup.set_label <+ model.graph_editor.model.breadcrumbs.project_name_error; } init.emit(()); @@ -655,6 +660,11 @@ impl View { pub fn debug_mode_popup(&self) -> &debug_mode_popup::View { &self.model.debug_mode_popup } + + /// Pop-up + pub fn popup(&self) -> &popup::View { + &self.model.popup + } } impl display::Object for View { @@ -691,14 +701,14 @@ impl application::View for View { (Press, "", "cmd alt shift t", "toggle_style"), (Press, "", "cmd alt p", "toggle_component_browser_private_entries_visibility"), (Press, "", "cmd s", "save_project_snapshot"), - (Press, "", "cmd r", "restore_project_snapshot"), + (Press, "", "cmd shift r", "restore_project_snapshot"), (Press, "", "cmd z", "undo"), (Press, "", "cmd y", "redo"), (Press, "", "cmd shift z", "redo"), (Press, "!debug_mode", DEBUG_MODE_SHORTCUT, "enable_debug_mode"), (Press, "debug_mode", DEBUG_MODE_SHORTCUT, "disable_debug_mode"), - (Press, "", "cmd shift t", "execution_context_interrupt"), - (Press, "", "cmd shift r", "execution_context_restart"), + (Press, "", "cmd alt t", "execution_context_interrupt"), + (Press, "", "cmd alt r", "execution_context_restart"), // TODO(#6179): Remove this temporary shortcut when Play button is ready. (Press, "", "ctrl shift b", "toggle_read_only"), ] diff --git a/app/ide-desktop/lib/client/src/file-associations.ts b/app/ide-desktop/lib/client/src/file-associations.ts index 4a6e1c67c330..02dc0bfbfd3c 100644 --- a/app/ide-desktop/lib/client/src/file-associations.ts +++ b/app/ide-desktop/lib/client/src/file-associations.ts @@ -104,7 +104,7 @@ export function isFileOpenable(path: string): boolean { * we manually start a new instance of the application and pass the file path to it (using the * Windows-style command). */ -export function onFileOpened(event: Event, path: string): string | null { +export function onFileOpened(event: Event, path: string): string | void { logger.log(`Received 'open-file' event for path '${path}'.`) if (isFileOpenable(path)) { logger.log(`The file '${path}' is openable.`) @@ -114,6 +114,7 @@ export function onFileOpened(event: Event, path: string): string | null { if (!electron.app.isReady() && CLIENT_ARGUMENTS.length === 0) { event.preventDefault() logger.log(`Opening file '${path}'.`) + // eslint-disable-next-line no-restricted-syntax return handleOpenFile(path) } else { // We need to start another copy of the application, as the first one is already running. @@ -127,11 +128,9 @@ export function onFileOpened(event: Event, path: string): string | null { }) // Prevent parent (this) process from waiting for the child to exit. child.unref() - return null } } else { logger.log(`The file '${path}' is not openable, ignoring the 'open-file' event.`) - return null } } diff --git a/app/ide-desktop/lib/content-config/src/index.ts b/app/ide-desktop/lib/content-config/src/index.ts index 1a68e317199a..c2aed90d433f 100644 --- a/app/ide-desktop/lib/content-config/src/index.ts +++ b/app/ide-desktop/lib/content-config/src/index.ts @@ -2,7 +2,7 @@ import * as semver from 'semver' -import * as linkedDist from '../../../../../target/ensogl-pack/linked-dist' +import * as linkedDist from '../../../../../target/ensogl-pack/linked-dist/index' import BUILD_INFO from '../../../build.json' assert { type: 'json' } // Aliases with the same name as the original. diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/components/setUsername.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/components/setUsername.tsx index 903fad09e884..7aff6c16d8c4 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/components/setUsername.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/components/setUsername.tsx @@ -3,7 +3,9 @@ import * as react from 'react' import * as auth from '../providers/auth' +import * as backendProvider from '../../providers/backend' import * as svg from '../../components/svg' + import Input from './input' import SvgIcon from './svgIcon' @@ -14,6 +16,7 @@ import SvgIcon from './svgIcon' function SetUsername() { const { setUsername: authSetUsername } = auth.useAuth() const { email } = auth.usePartialUserSession() + const { backend } = backendProvider.useBackend() const [username, setUsername] = react.useState('') @@ -32,7 +35,7 @@ function SetUsername() { { event.preventDefault() - await authSetUsername(username, email) + await authSetUsername(backend, username, email) }} > diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/providers/auth.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/providers/auth.tsx index 1f18c902bd5a..e1adaee206f6 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/providers/auth.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/authentication/providers/auth.tsx @@ -86,7 +86,11 @@ export interface PartialUserSession { interface AuthContextType { signUp: (email: string, password: string) => Promise confirmSignUp: (email: string, code: string) => Promise - setUsername: (username: string, email: string) => Promise + setUsername: ( + backend: backendProvider.AnyBackendAPI, + username: string, + email: string + ) => Promise signInWithGoogle: () => Promise signInWithGitHub: () => Promise signInWithPassword: (email: string, password: string) => Promise @@ -166,7 +170,7 @@ export function AuthProvider(props: AuthProviderProps) { const client = new http.Client(headers) const backend = new remoteBackend.RemoteBackend(client, logger) setBackend(backend) - const organization = await backend.usersMe() + const organization = await backend.usersMe().catch(() => null) let newUserSession: UserSession if (!organization) { newUserSession = { @@ -257,10 +261,14 @@ export function AuthProvider(props: AuthProviderProps) { return result.ok }) - const setUsername = async (username: string, email: string) => { - const { backend } = backendProvider.useBackend() + const setUsername = async ( + backend: backendProvider.AnyBackendAPI, + username: string, + email: string + ) => { if (backend.platform === platform.Platform.desktop) { - throw new Error('') + toast.error('You cannot set your username on the local backend.') + return false } else { try { await backend.createUser({ @@ -270,7 +278,8 @@ export function AuthProvider(props: AuthProviderProps) { navigate(app.DASHBOARD_PATH) toast.success(MESSAGES.setUsernameSuccess) return true - } catch { + } catch (e) { + toast.error('Could not set your username.') return false } } @@ -377,6 +386,22 @@ export function ProtectedLayout() { if (!session) { return + } else if (session.variant === 'partial') { + return + } else { + return + } +} + +// =========================== +// === SemiProtectedLayout === +// =========================== + +export function SemiProtectedLayout() { + const { session } = useAuth() + + if (session?.variant === 'full') { + return } else { return } diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/components/app.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/components/app.tsx index d5f5fa458679..cc1f34e22ffc 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/components/app.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/components/app.tsx @@ -144,6 +144,9 @@ function AppRouter(props: AppProps) { path={DASHBOARD_PATH} element={showDashboard && } /> + + {/* Semi-protected pages are visible to users currently registering. */} + }> } /> {/* Other pages are visible to unauthenticated and authenticated users. */} diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/changePasswordModal.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/changePasswordModal.tsx index 8964a327ff61..74a4ebaa8a03 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/changePasswordModal.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/changePasswordModal.tsx @@ -33,11 +33,15 @@ function ChangePasswordModal() { } return ( - + { event.stopPropagation() }} + onSubmit={async event => { + event.preventDefault() + await onSubmit() + }} className="flex flex-col bg-white shadow-md px-4 sm:px-6 md:px-8 lg:px-10 py-8 rounded-md w-full max-w-md" > @@ -63,6 +67,8 @@ function ChangePasswordModal() { { + unsetModal() + await toast.promise(doDelete(), { + loading: `Deleting ${assetType}...`, + success: `Deleted ${assetType}.`, + error: `Could not delete ${assetType}.`, + }) + onSuccess() + } + return ( - + { event.stopPropagation() }} + onSubmit={async event => { + event.preventDefault() + // Consider not calling `onSubmit()` here to make it harder to accidentally + // delete an important asset. + await onSubmit() + }} + className="relative bg-white shadow-soft rounded-lg w-96 p-2" > {svg.CLOSE_ICON} @@ -35,15 +52,7 @@ function ConfirmDeleteModal(props: ConfirmDeleteModalProps) { { - unsetModal() - await toast.promise(doDelete(), { - loading: `Deleting ${assetType}...`, - success: `Deleted ${assetType}.`, - error: `Could not delete ${assetType}.`, - }) - onSuccess() - }} + onClick={onSubmit} > Delete diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/createForm.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/createForm.tsx index b99273ee142a..535566efdd3d 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/createForm.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/createForm.tsx @@ -31,10 +31,10 @@ function CreateForm(props: CreateFormProps) { } return ( - + { event.stopPropagation() diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/dashboard.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/dashboard.tsx index 416e8def13bf..81fd843c3930 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/dashboard.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/dashboard.tsx @@ -355,6 +355,14 @@ function Dashboard(props: DashboardProps) { Promise.resolve()} onSuccess={doRefresh} @@ -525,8 +533,8 @@ function Dashboard(props: DashboardProps) { const CreateForm = ASSET_TYPE_CREATE_FORM[assetType] setModal(() => ( @@ -645,7 +653,7 @@ function Dashboard(props: DashboardProps) { return ( { @@ -679,20 +687,22 @@ function Dashboard(props: DashboardProps) { } }} setBackendPlatform={newBackendPlatform => { - setProjectAssets([]) - setDirectoryAssets([]) - setSecretAssets([]) - setFileAssets([]) - switch (newBackendPlatform) { - case platformModule.Platform.desktop: - setBackend(new localBackend.LocalBackend()) - break - case platformModule.Platform.cloud: { - const headers = new Headers() - headers.append('Authorization', `Bearer ${accessToken}`) - const client = new http.Client(headers) - setBackend(new remoteBackendModule.RemoteBackend(client, logger)) - break + if (newBackendPlatform !== backend.platform) { + setProjectAssets([]) + setDirectoryAssets([]) + setSecretAssets([]) + setFileAssets([]) + switch (newBackendPlatform) { + case platformModule.Platform.desktop: + setBackend(new localBackend.LocalBackend()) + break + case platformModule.Platform.cloud: { + const headers = new Headers() + headers.append('Authorization', `Bearer ${accessToken}`) + const client = new http.Client(headers) + setBackend(new remoteBackendModule.RemoteBackend(client, logger)) + break + } } } }} @@ -725,6 +735,7 @@ function Dashboard(props: DashboardProps) { ? 'opacity-50' : '' }`} + disabled={backend.platform === platformModule.Platform.desktop} onClick={event => { event.stopPropagation() setModal(() => ( @@ -738,8 +749,8 @@ function Dashboard(props: DashboardProps) { {svg.UPLOAD_ICON} { event.stopPropagation() /* TODO */ @@ -848,9 +859,21 @@ function Dashboard(props: DashboardProps) { Promise.resolve()} + {...(backend.platform === platformModule.Platform.desktop + ? { + namePattern: '[A-Z][a-z]*(?:_\\d+|_[A-Z][a-z]*)*', + title: + 'Names must be in Upper_Snake_Case. ' + + '(Numbers (_0, _1) are also allowed.)', + } + : {})} + doRename={async name => { + await backend.projectUpdate(projectAsset.id, { + ami: null, + ideVersion: null, + projectName: name, + }) + }} onSuccess={doRefresh} /> )) @@ -858,18 +881,14 @@ function Dashboard(props: DashboardProps) { // This is not a React component even though it contains JSX. // eslint-disable-next-line no-restricted-syntax function doDelete() { - // The button is disabled when using the desktop backend, - // so this condition should never be `false`. - if (backend.platform === platformModule.Platform.cloud) { - setModal(() => ( - backend.deleteProject(projectAsset.id)} - onSuccess={doRefresh} - /> - )) - } + setModal(() => ( + backend.deleteProject(projectAsset.id)} + onSuccess={doRefresh} + /> + )) } setModal(() => ( @@ -879,15 +898,8 @@ function Dashboard(props: DashboardProps) { Open as folder - - Rename - - + Rename + Delete diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/modal.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/modal.tsx index 954e3ee31af3..28bedcebb00e 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/modal.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/modal.tsx @@ -8,17 +8,19 @@ import * as modalProvider from '../../providers/modal' // ================= export interface ModalProps extends react.PropsWithChildren { + centered?: boolean className?: string } function Modal(props: ModalProps) { - const { children } = props + const { children, centered, className } = props const { unsetModal } = modalProvider.useSetModal() + return ( { if (event.currentTarget === event.target) { unsetModal() diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/renameModal.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/renameModal.tsx index 41fed6f6a660..e9d4ce260892 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/renameModal.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/renameModal.tsx @@ -10,60 +10,75 @@ import Modal from './modal' export interface RenameModalProps { assetType: string name: string + namePattern?: string + title?: string doRename: (newName: string) => Promise onSuccess: () => void } function RenameModal(props: RenameModalProps) { - const { assetType, name, doRename, onSuccess } = props + const { assetType, name, namePattern, title, doRename, onSuccess } = props const { unsetModal } = modalProvider.useSetModal() + const [newName, setNewName] = react.useState(null) + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault() + if (newName == null) { + toast.error('Please provide a new name.') + } else { + unsetModal() + await toast.promise(doRename(newName), { + loading: `Renaming ${assetType}...`, + success: `Renamed ${assetType}.`, + // This is UNSAFE, as the original function's parameter is of type `any`. + error: (promiseError: Error) => + `Error renaming ${assetType}: ${promiseError.message}`, + }) + onSuccess() + } + } + + console.log('what', namePattern, title) + return ( - + { event.stopPropagation() }} + onSubmit={onSubmit} + className="relative bg-white shadow-soft rounded-lg w-96 p-2" > {svg.CLOSE_ICON} What do you want to rename the {assetType} '{name}' to? - + File name { setNewName(event.target.value) }} - defaultValue={newName ?? ''} + defaultValue={newName ?? name} /> - { - if (newName == null) { - toast.error('Please provide a new name.') - } else { - unsetModal() - await toast.promise(doRename(newName), { - loading: `Deleting ${assetType}...`, - success: `Deleted ${assetType}.`, - error: `Could not delete ${assetType}.`, - }) - onSuccess() - } - }} > Rename - + { + if (userMenuVisible) { + setModal(() => ) + } else { + unsetModal() + } + }, [userMenuVisible]) + return ( @@ -114,7 +125,7 @@ function TopBar(props: TopBarProps) { className="rounded-full w-8 h-8 bg-cover cursor-pointer" onClick={event => { event.stopPropagation() - setModal(() => ) + setUserMenuVisible(!userMenuVisible) }} /> diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/uploadFileModal.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/uploadFileModal.tsx index 0f0f9aaa7ce8..8a7bf254d107 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/uploadFileModal.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/components/uploadFileModal.tsx @@ -46,12 +46,16 @@ function UploadFileModal(props: UploadFileModalProps) { } return ( - + { event.stopPropagation() }} + onSubmit={async event => { + event.preventDefault() + await onSubmit() + }} + className="relative bg-white shadow-soft rounded-lg w-96 h-72 p-2" > { setName(event.target.value) @@ -85,6 +89,7 @@ function UploadFileModal(props: UploadFileModalProps) { { } async closeProject(projectId: backend.ProjectId): Promise { + if (LocalBackend.currentlyOpeningProjectId === projectId) { + LocalBackend.currentlyOpeningProjectId = null + } await this.projectManager.closeProject({ projectId }) if (projectId === LocalBackend.currentlyOpeningProjectId) { LocalBackend.currentlyOpeningProjectId = null @@ -150,4 +153,53 @@ export class LocalBackend implements Partial { }) LocalBackend.currentlyOpenProject = { id: projectId, project } } + + async projectUpdate( + projectId: backend.ProjectId, + body: backend.ProjectUpdateRequestBody + ): Promise { + if (body.ami != null) { + throw new Error('Cannot change project AMI on local backend.') + } else { + if (body.projectName != null) { + await this.projectManager.renameProject({ + projectId, + name: newtype.asNewtype(body.projectName), + }) + } + const result = await this.projectManager.listProjects({}) + const project = result.projects.find(listedProject => listedProject.id === projectId) + const engineVersion = project?.engineVersion + if (project == null) { + throw new Error(`The project ID '${projectId}' is invalid.`) + } else if (engineVersion == null) { + throw new Error(`The project '${projectId}' does not have an engine version.`) + } else { + return { + ami: null, + engineVersion: { + lifecycle: backend.VersionLifecycle.stable, + value: engineVersion, + }, + ideVersion: { + lifecycle: backend.VersionLifecycle.stable, + value: engineVersion, + }, + name: project.name, + organizationId: '', + projectId, + } + } + } + } + + async deleteProject(projectId: backend.ProjectId): Promise { + if (LocalBackend.currentlyOpeningProjectId === projectId) { + LocalBackend.currentlyOpeningProjectId = null + } + await this.projectManager.deleteProject({ projectId }) + if (LocalBackend.currentlyOpenProject?.id === projectId) { + LocalBackend.currentlyOpenProject = null + } + } } diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/remoteBackend.ts b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/remoteBackend.ts index f4246626961e..009c6f9ecca8 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/remoteBackend.ts +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/dashboard/remoteBackend.ts @@ -14,13 +14,28 @@ import * as platformModule from '../platform' // ================= /** HTTP status indicating that the request was successful. */ -const STATUS_OK = 200 +const STATUS_SUCCESS_FIRST = 200 +/** HTTP status indicating that the request was successful. */ +const STATUS_SUCCESS_LAST = 299 /** Default HTTP body for an "open project" request. */ const DEFAULT_OPEN_PROJECT_BODY: backend.OpenProjectRequestBody = { forceCreate: false, } +// ======================== +// === Helper functions === +// ======================== + +/** Returns true if and only if a response has a success HTTP status code (200-299). */ +function responseIsSuccessful(response: Response) { + return response.status >= STATUS_SUCCESS_FIRST && response.status <= STATUS_SUCCESS_LAST +} + +// ============= +// === Paths === +// ============= + /** Relative HTTP path to the "set username" endpoint of the Cloud backend API. */ const CREATE_USER_PATH = 'users' /** Relative HTTP path to the "get user" endpoint of the Cloud backend API. */ @@ -162,7 +177,7 @@ export class RemoteBackend implements backend.Backend { * @returns `null` if status code 401 or 404 was received. */ async usersMe(): Promise { const response = await this.get(USERS_ME_PATH) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return null } else { return await response.json() @@ -182,7 +197,7 @@ export class RemoteBackend implements backend.Backend { ...(query.parentId ? { parent_id: query.parentId } : {}), }).toString() ) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { if (query.parentId) { return this.throw(`Unable to list directory with ID '${query.parentId}'.`) } else { @@ -202,7 +217,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async createDirectory(body: backend.CreateDirectoryRequestBody): Promise { const response = await this.post(CREATE_DIRECTORY_PATH, body) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to create directory with name '${body.title}'.`) } else { return await response.json() @@ -215,7 +230,7 @@ export class RemoteBackend implements backend.Backend { */ async listProjects(): Promise { const response = await this.get(LIST_PROJECTS_PATH) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw('Unable to list projects.') } else { return (await response.json()).projects.map(project => ({ @@ -237,7 +252,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async createProject(body: backend.CreateProjectRequestBody): Promise { const response = await this.post(CREATE_PROJECT_PATH, body) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to create project with name '${body.projectName}'.`) } else { return await response.json() @@ -249,7 +264,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async closeProject(projectId: backend.ProjectId): Promise { const response = await this.post(closeProjectPath(projectId), {}) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to close project with ID '${projectId}'.`) } else { return @@ -261,7 +276,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async getProjectDetails(projectId: backend.ProjectId): Promise { const response = await this.get(getProjectDetailsPath(projectId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to get details of project with ID '${projectId}'.`) } else { const project = await response.json() @@ -287,7 +302,7 @@ export class RemoteBackend implements backend.Backend { body: backend.OpenProjectRequestBody = DEFAULT_OPEN_PROJECT_BODY ): Promise { const response = await this.post(openProjectPath(projectId), body) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to open project with ID '${projectId}'.`) } else { return @@ -299,7 +314,7 @@ export class RemoteBackend implements backend.Backend { body: backend.ProjectUpdateRequestBody ): Promise { const response = await this.put(projectUpdatePath(projectId), body) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to update project with ID '${projectId}'.`) } else { return await response.json() @@ -311,7 +326,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async deleteProject(projectId: backend.ProjectId): Promise { const response = await this.delete(deleteProjectPath(projectId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to delete project with ID '${projectId}'.`) } else { return @@ -323,7 +338,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async checkResources(projectId: backend.ProjectId): Promise { const response = await this.get(checkResourcesPath(projectId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to get resource usage for project with ID '${projectId}'.`) } else { return await response.json() @@ -335,7 +350,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async listFiles(): Promise { const response = await this.get(LIST_FILES_PATH) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw('Unable to list files.') } else { return (await response.json()).files @@ -363,7 +378,7 @@ export class RemoteBackend implements backend.Backend { }).toString(), body ) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { if (params.fileName) { return this.throw(`Unable to upload file with name '${params.fileName}'.`) } else if (params.fileId) { @@ -381,7 +396,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async deleteFile(fileId: backend.FileId): Promise { const response = await this.delete(deleteFilePath(fileId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to delete file with ID '${fileId}'.`) } else { return @@ -393,7 +408,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async createSecret(body: backend.CreateSecretRequestBody): Promise { const response = await this.post(CREATE_SECRET_PATH, body) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to create secret with name '${body.secretName}'.`) } else { return await response.json() @@ -405,7 +420,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async getSecret(secretId: backend.SecretId): Promise { const response = await this.get(getSecretPath(secretId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to get secret with ID '${secretId}'.`) } else { return await response.json() @@ -417,7 +432,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async listSecrets(): Promise { const response = await this.get(LIST_SECRETS_PATH) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw('Unable to list secrets.') } else { return (await response.json()).secrets @@ -429,7 +444,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async deleteSecret(secretId: backend.SecretId): Promise { const response = await this.delete(deleteSecretPath(secretId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to delete secret with ID '${secretId}'.`) } else { return @@ -448,7 +463,7 @@ export class RemoteBackend implements backend.Backend { object_id: body.objectId, /* eslint-enable @typescript-eslint/naming-convention */ }) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to create create tag with name '${body.name}'.`) } else { return await response.json() @@ -467,7 +482,7 @@ export class RemoteBackend implements backend.Backend { tag_type: params.tagType, }).toString() ) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to list tags of type '${params.tagType}'.`) } else { return (await response.json()).tags @@ -479,7 +494,7 @@ export class RemoteBackend implements backend.Backend { * @throws An error if a 401 or 404 status code was received. */ async deleteTag(tagId: backend.TagId): Promise { const response = await this.delete(deleteTagPath(tagId)) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to delete tag with ID '${tagId}'.`) } else { return @@ -501,7 +516,7 @@ export class RemoteBackend implements backend.Backend { default: String(params.default), }).toString() ) - if (response.status !== STATUS_OK) { + if (!responseIsSuccessful(response)) { return this.throw(`Unable to list versions of type '${params.versionType}'.`) } else { return (await response.json()).versions diff --git a/app/ide-desktop/lib/dashboard/src/authentication/src/providers/backend.tsx b/app/ide-desktop/lib/dashboard/src/authentication/src/providers/backend.tsx index 5a1e3adf238c..7dba7e2a04a9 100644 --- a/app/ide-desktop/lib/dashboard/src/authentication/src/providers/backend.tsx +++ b/app/ide-desktop/lib/dashboard/src/authentication/src/providers/backend.tsx @@ -10,7 +10,7 @@ import * as remoteBackend from '../dashboard/remoteBackend' // ============= /** A type representing a backend API that may be of any type. */ -type AnyBackendAPI = localBackend.LocalBackend | remoteBackend.RemoteBackend +export type AnyBackendAPI = localBackend.LocalBackend | remoteBackend.RemoteBackend // ====================== // === BackendContext === diff --git a/app/ide-desktop/lib/types/modules.d.ts b/app/ide-desktop/lib/types/modules.d.ts index 58762fe78f19..3c68a6e47708 100644 --- a/app/ide-desktop/lib/types/modules.d.ts +++ b/app/ide-desktop/lib/types/modules.d.ts @@ -2,23 +2,6 @@ * * This file MUST NOT `export {}` for the modules to be visible to other files. */ -declare module '*/build.json' { - interface BuildInfo { - commit: string - version: string - engineVersion: string - name: string - } - - const BUILD_INFO: BuildInfo - export default BUILD_INFO -} - -declare module '*/ensogl-pack/linked-dist' { - // eslint-disable-next-line no-restricted-syntax - export * from '../../../../lib/rust/ensogl/pack/js/src/runner/index' -} - declare module '*/gui/config.yaml' { interface Config { windowAppScopeName: string diff --git a/build-config.yaml b/build-config.yaml index d71082a4c23d..bf84c332d939 100644 --- a/build-config.yaml +++ b/build-config.yaml @@ -1,6 +1,6 @@ # Options intended to be common for all developers. -wasm-size-limit: 15.83 MiB +wasm-size-limit: 15.85 MiB required-versions: # NB. The Rust version is pinned in rust-toolchain.toml. diff --git a/build/build/Cargo.toml b/build/build/Cargo.toml index e621630144d9..f6c2bc623d74 100644 --- a/build/build/Cargo.toml +++ b/build/build/Cargo.toml @@ -58,7 +58,7 @@ regex = { workspace = true } reqwest = { version = "0.11.5", default-features = false, features = [ "stream" ] } -semver = { version = "1.0.4", features = ["serde"] } +semver = { workspace = true } serde = { version = "1.0.130", features = ["derive"] } serde_json = { workspace = true } serde_yaml = { workspace = true } diff --git a/build/build/src/ci_gen.rs b/build/build/src/ci_gen.rs index 57ee9ffa733a..afc25ad0f175 100644 --- a/build/build/src/ci_gen.rs +++ b/build/build/src/ci_gen.rs @@ -488,7 +488,7 @@ pub fn benchmark() -> Result { ); let mut benchmark_job = - plain_job(&BenchmarkRunner, "Benchmark Engine", "backend benchmark runtime enso"); + plain_job(&BenchmarkRunner, "Benchmark Engine", "backend benchmark runtime"); benchmark_job.timeout_minutes = Some(60 * 8); workflow.add_job(benchmark_job); Ok(workflow) diff --git a/build/ci_utils/Cargo.toml b/build/ci_utils/Cargo.toml index 4ec09d4079c7..3180a18f567c 100644 --- a/build/ci_utils/Cargo.toml +++ b/build/ci_utils/Cargo.toml @@ -59,7 +59,7 @@ regex = { workspace = true } reqwest = { version = "0.11.5", default-features = false, features = [ "stream" ] } -semver = { version = "1.0.4", features = ["serde"] } +semver = { workspace = true } serde = { version = "1.0.130", features = ["derive"] } serde_json = { workspace = true } serde_yaml = { workspace = true } diff --git a/build/cli/src/lib.rs b/build/cli/src/lib.rs index c6fc4f497cc7..7ab115122e0f 100644 --- a/build/cli/src/lib.rs +++ b/build/cli/src/lib.rs @@ -86,8 +86,6 @@ use ide_ci::programs::git; use ide_ci::programs::git::clean; use ide_ci::programs::rustc; use ide_ci::programs::Cargo; -use ide_ci::programs::Npm; -use ide_ci::programs::Npx; use std::time::Duration; use tempfile::tempdir; use tokio::process::Child; @@ -837,10 +835,6 @@ pub async fn main_internal(config: Option) -> Result .await?; prettier::check(&ctx.repo_root).await?; - let js_modules_root = ctx.repo_root.join("app/ide-desktop"); - Npm.cmd()?.current_dir(&js_modules_root).args(["install"]).run_ok().await?; - Npm.cmd()?.current_dir(&js_modules_root).args(["run", "typecheck"]).run_ok().await?; - Npx.cmd()?.current_dir(&js_modules_root).args(["eslint", "."]).run_ok().await?; } Target::Fmt => { let prettier = prettier::write(&ctx.repo_root); diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso index e5d742c9d493..70a5e1668893 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso @@ -438,6 +438,8 @@ type Array flatten : Vector Any flatten self = Vector.flatten self + ## PRIVATE + ADVANCED short_display_text : Integer -> Text short_display_text self max_entries=10 = Vector.short_display_text self max_entries @@ -641,9 +643,15 @@ type Array join : Text -> Text -> Text -> Text join self separator="" prefix="" suffix="" = Vector.join self separator prefix suffix + ## PRIVATE + Generates a human-readable text representation of the array. to_text : Text to_text self = self.map .to_text . join ", " "[" "]" + ## PRIVATE + to_display_text : Text + to_display_text self = self.short_display_text max_entries=40 + ## Combines all the elements of a non-empty array using a binary operation. If the array is empty, it returns `if_empty`. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso index 108115c8c1a0..10767ffea671 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso @@ -1,13 +1,16 @@ +import project.Any.Any import project.Data.Numbers.Integer import project.Data.Vector.Vector import project.Data.Pair.Pair import project.Data.Text.Extensions import project.Data.Text.Text +import project.Error.Error import project.Errors.Illegal_Argument.Illegal_Argument import project.Errors.No_Such_Key.No_Such_Key +import project.Nothing.Nothing +import project.Panic.Panic from project.Data.Boolean import Boolean, True, False -from project import Error, Nothing, Any, Panic ## A key-value store. It is possible to use any type as keys and values and mix them in one Map. Keys are checked for equality based on their hash code and `==` operator, which diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso index c36c4ba34b72..fc2c1c6d3b5f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Extensions.enso @@ -900,7 +900,7 @@ Text.repeat : Integer -> Text Text.repeat self count=1 = 0.up_to count . fold "" acc-> _-> acc + self -## ALIAS first, last, left, right, mid, substring +## ALIAS first, last, left, right, mid, substring, slice Creates a new Text by selecting the specified range of the input. This can select a section of text from the beginning, end, or middle of the diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Helpers.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Helpers.enso index ef6c323d6386..9b046dced946 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Helpers.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Helpers.enso @@ -1,8 +1,6 @@ -from Standard.Base import all - import project.Any.Any -import project.Data.Locale.Locale -import project.Data.Text.Case_Sensitivity.Case_Sensitivity +import project.Data.Text.Text +import project.Error.Error import project.Errors.Common.Type_Error import project.Meta diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index 34907d65c092..a1f2d1d7c44c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -314,6 +314,54 @@ type Date end_of : Date_Period -> Date end_of self period=Date_Period.Month = period.adjust_end self + ## Returns the next date adding the `Date_Period` to self. + + Produces a warning for a Date that is before epoch start. + See `Date_Time.enso_epoch_start`. + + Arguments: + - period: the period to add to self. + next : Date_Period -> Date + next self period=Date_Period.Day = self + period.to_period + + ## Returns the previous date subtracting the `Date_Period` from self. + + Produces a warning for a Date that is before epoch start. + See `Date_Time.enso_epoch_start`. + + Arguments: + - period: the period to add to self. + previous : Date_Period -> Date + previous self period=Date_Period.Day = self - period.to_period + + ## Creates a `Period` between self and the provided end date. + + Produces a warning for a Date that is before epoch start. + See `Date_Time.enso_epoch_start`. + + Arguments: + - end: the end date of the interval to count workdays in. + until : Date -> Period + until self end = + ensure_in_epoch self <| ensure_in_epoch end <| + Period.between self end + + ## Counts the days between self (inclusive) and the provided end date + (exclusive, or inclusive if include_end_date=True). + + Produces a warning for a Date that is before epoch start. + See `Date_Time.enso_epoch_start`. + + Arguments: + - end: the end date of the interval to count workdays in. + - include_end_date: whether to include the end date in the count. + By default the end date is not included in the interval. + days_until : Date -> Boolean -> Integer + days_until self end include_end_date=False = + if end < self then -(end.days_until self include_end_date) else + ensure_in_epoch self <| ensure_in_epoch end <| + (Time_Utils.days_between self end) + if include_end_date then 1 else 0 + ## Counts workdays between self (inclusive) and the provided end date (exclusive). @@ -331,7 +379,7 @@ type Date end-exclusive manner), by default the end date is not included in the count. This has the nice property that for example to count the work days within the next week you can do - `date.work_days_until (date + (Period.new days=7)` and it will look at + `date.work_days_until (date + (Period.new days=7))` and it will look at the 7 days starting from the current `date` and not 8 days. This also gives us a property that `date.work_days_until (date.add_work_days N) == N` for any non-negative @@ -566,6 +614,8 @@ type Date Arguments: - pattern: The text specifying the format for formatting the date. + - locale: The locale in which the format should be interpreted. + (Defaults to Locale.default.) ? Pattern Syntax A custom pattern string consists of one or more custom date and time @@ -574,19 +624,19 @@ type Date for a complete format specification. > Example - Format "2020-06-02" as "2 June 2020" + Format "2020-06-02" as "2 Jun 2020" from Standard.Base import Date example_format = Date.new 2020 6 2 . format "d MMMM yyyy" > Example - Format "2020-06-02" as "2 June 20" + Format "2020-06-02" as "2 Jun 20" example_format = Date.new 2020 6 2 . format "d MMMM yy" > Example - Format "2020-06-02" as "Tuesday, 02 June 2020" + Format "2020-06-02" as "Tuesday, 02 Jun 2020" example_format = Date.new 2020 6 2 . format "EEEE, dd MMMM yyyy" @@ -599,8 +649,15 @@ type Date Format "2020-06-02" as "2020AD" example_format = Date.new 2020 6 2 . format "yyyyGG" - format : Text -> Text - format self pattern = Time_Utils.local_date_format self pattern + + > Example + Format "2020-06-21" with French locale as "21. juin 2020" + + example_format = Date.new 2020 6 21 . format "d. MMMM yyyy" (Locale.new "fr") + format : Text -> Locale -> Text + format self pattern locale=Locale.default = case locale of + Nothing -> Time_Utils.local_date_format self pattern + _ -> Time_Utils.local_date_format_with_locale self pattern locale.java_locale ## PRIVATE week_days_between start end = diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Period.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Period.enso index 0df833bbeb18..4eab0356cb2d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Period.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Period.enso @@ -1,4 +1,5 @@ import project.Data.Time.Date.Date +import project.Data.Time.Period.Period import project.Data.Time.Date_Time.Date_Time import project.Data.Time.Day_Of_Week.Day_Of_Week from project.Data.Boolean import Boolean, True, False @@ -22,6 +23,8 @@ type Date_Period to any other day. Week (first_day:Day_Of_Week = Day_Of_Week.Monday) + Day + ## PRIVATE This method could be replaced with matching on `Date_Period` supertype if/when that is supported. @@ -36,14 +39,25 @@ type Date_Period Date_Period.Quarter -> Date_Period_Utils.quarter_start Date_Period.Month -> TemporalAdjusters.firstDayOfMonth Date_Period.Week first_day -> TemporalAdjusters.previousOrSame first_day.to_java + Date_Period.Day -> Date_Period_Utils.day_start (Time_Utils.utils_for date).apply_adjuster date adjuster ## PRIVATE adjust_end : (Date | Date_Time) -> (Date | Date_Time) - adjust_end self date = + adjust_end self date = if self == Date_Period.Day then date else adjuster = case self of Date_Period.Year -> TemporalAdjusters.lastDayOfYear Date_Period.Quarter -> Date_Period_Utils.quarter_end Date_Period.Month -> TemporalAdjusters.lastDayOfMonth Date_Period.Week first_day -> Date_Period_Utils.end_of_week first_day.to_java + Date_Period.Day -> Date_Period_Utils.day_end (Time_Utils.utils_for date).apply_adjuster date adjuster + + ## PRIVATE + to_period : Period + to_period self = case self of + Date_Period.Year -> Period.new years=1 + Date_Period.Quarter -> Period.new months=3 + Date_Period.Month -> Period.new months=1 + Date_Period.Week _ -> Period.new days=7 + Date_Period.Day -> Period.new days=1 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Time.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Time.enso index e41da2a2f81d..3a85f9d09849 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Time.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date_Time.enso @@ -613,6 +613,8 @@ type Date_Time Arguments: - pattern: The pattern that specifies how to format the time. + - locale: The locale in which the format should be interpreted. + (Defaults to Locale.default.) ? Pattern Syntax A custom pattern string consists of one or more custom date and time @@ -645,6 +647,16 @@ type Date_Time example_format = Date_Time.parse "2020-10-08T16:41:13+03:00[Europe/Moscow]" . format "EEE MMM d (HH:mm)" - format : Text -> Text - format self pattern = @Builtin_Method "Date_Time.format" + > Example + Format "2020-06-21T16:41:13+03:00" with French locale as "21. juin 2020" + + from Standard.Base import Date_Time + import Standard.Base.Data.Locale.Locale + + example_format = + Date_Time.parse "2020-06-21T16:41:13+03:00" . format "d. MMMM yyyy" (Locale.new "fr") + format : Text -> Locale -> Text + format self pattern locale=Locale.default = case locale of + Nothing -> Time_Utils.date_time_format self pattern + _ -> Time_Utils.date_time_format_with_locale self pattern locale.java_locale diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Period.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Period.enso index ed1daadba25c..cc2fbab1670a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Period.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Period.enso @@ -1,10 +1,12 @@ import project.Any.Any +import project.Data.Json.JS_Object import project.Data.Numbers.Integer import project.Data.Ordering.Comparable import project.Data.Text.Extensions import project.Data.Text.Text import project.Data.Time.Date.Date import project.Data.Time.Duration.Duration +import project.Data.Vector.Vector import project.Error.Error import project.Errors.Illegal_Argument.Illegal_Argument import project.Errors.Time_Error.Time_Error @@ -144,3 +146,20 @@ type Period m = if months == 0 && (y=="" || d=="") then "" else months.to_text + "M " (y + m + d) . trim + + ## PRIVATE + Convert to a JavaScript Object representing a Period. + + > Example + Convert a period of 10 months to a JS_Object. + + example_to_json = (Period.new months=10).to_js_object + to_js_object : JS_Object + to_js_object self = + b = Vector.new_builder 7 + b.append ["type", "Period"] + b.append ["constructor", "new"] + if self.years==0 . not then b.append ["years", self.years] + if self.months==0 . not then b.append ["months", self.months] + if self.days==0 . not then b.append ["days", self.days] + JS_Object.from_pairs b.to_vector diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso index 74f107a536f0..1086b067191b 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso @@ -311,6 +311,8 @@ type Time_Of_Day Arguments: - pattern: The pattern specifying how to format the time of day. + - locale: The locale in which the format should be interpreted. + (Defaults to Locale.default.) ? Pattern Syntax A custom pattern string consists of one or more custom date and time @@ -352,5 +354,7 @@ type Time_Of_Day from Standard.Base import Time_Of_Day example_format = Time_Of_Day.new 16 21 10 . format "'hour:'h" - format : Text -> Text - format self pattern = @Builtin_Method "Time_Of_Day.format" + format : Text -> Locale -> Text + format self pattern locale=Locale.default = case locale of + Nothing -> Time_Utils.time_of_day_format self pattern + _ -> Time_Utils.time_of_day_format_with_locale self pattern locale.java_locale diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso index 9fc87fa0c070..656270126a5f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Vector.enso @@ -618,6 +618,10 @@ type Vector a to_text : Text to_text self = self.map .to_text . join ", " "[" "]" + ## PRIVATE + to_display_text : Text + to_display_text self = self.short_display_text max_entries=40 + ## PRIVATE ADVANCED diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso index 47a26123ffba..20e6bac5eb56 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File.enso @@ -245,7 +245,8 @@ type File @format format_widget read : File_Format -> Problem_Behavior -> Any ! File_Error read self format=Auto_Detect (on_problems=Problem_Behavior.Report_Warning) = - format.read self on_problems + if self.exists.not then Error.throw (File_Error.Not_Found self) else + format.read self on_problems ## ALIAS Load Bytes, Open Bytes Reads all bytes in this file into a byte vector. @@ -612,6 +613,14 @@ type File resource = Managed_Resource.register stream close_stream Input_Stream.Value self resource + ## PRIVATE + Reads first `n` bytes from the file (or less if the file is too small) + and returns a vector of bytes. + read_first_bytes : Integer -> Vector ! File_Error + read_first_bytes self n = + opts = [File_Access.Read] + self.with_input_stream opts (_.read_n_bytes n) + ## PRIVATE Reads last `n` bytes from the file (or less if the file is too small) and returns a vector of bytes. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File_Format.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File_Format.enso index 292b55027061..41a38ab188bd 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File_Format.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File_Format.enso @@ -45,7 +45,7 @@ format_widget : Single_Choice format_widget = all_types = [Auto_Detect] + format_types make_ctor type_obj = - type_name = Meta.get_qualified_type_name type_obj + type_name = Meta.get_simple_type_name type_obj ctors = Meta.meta type_obj . constructors is_singleton_type = ctors.length == 0 if is_singleton_type then type_name else @@ -58,14 +58,26 @@ type Auto_Detect Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any ! File_Error read self file on_problems = - reader = Auto_Detect.get_format file + reader = Auto_Detect.get_reading_format file if reader == Nothing then Error.throw (File_Error.Unsupported_Type file) else reader.read file on_problems ## PRIVATE - get_format : File -> Any | Nothing - get_format file = - get_format f-> f.for_file file + Finds a matching format for reading the file. + + It assumes that `file` already exists. + get_reading_format : File -> Any | Nothing + get_reading_format file = + get_format f-> f.for_file_read file + + ## PRIVATE + Finds a matching format for reading the file. + + It may not assume that the `file` exists, so it must only rely on the + file path (extension in particular), but not the contents. + get_writing_format : File -> Any | Nothing + get_writing_format file = + get_format f-> f.for_file_write file ## PRIVATE get_web_parser : Text -> URI -> Any | Nothing @@ -91,13 +103,18 @@ type Plain_Text_Format ## PRIVATE If the File_Format supports reading from the file, return a configured instance. - for_file : File -> Plain_Text_Format | Nothing - for_file file = + for_file_read : File -> Plain_Text_Format | Nothing + for_file_read file = case file.extension of ".txt" -> Plain_Text_Format.Plain_Text ".log" -> Plain_Text_Format.Plain_Text _ -> Nothing + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> Plain_Text_Format | Nothing + for_file_write file = Plain_Text_Format.for_file_read file + ## PRIVATE If the File_Format supports reading from the web response, return a configured instance. for_web : Text -> URI -> Plain_Text_Format | Nothing @@ -127,12 +144,17 @@ type Plain_Text_Format type Bytes ## PRIVATE If the File_Format supports reading from the file, return a configured instance. - for_file : File -> Bytes | Nothing - for_file file = + for_file_read : File -> Bytes | Nothing + for_file_read file = case file.extension of ".dat" -> Bytes _ -> Nothing + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> Bytes | Nothing + for_file_write file = Bytes.for_file_read file + ## PRIVATE If the File_Format supports reading from the web response, return a configured instance. As `Bytes`, does not support reading from the web returns `Nothing`. @@ -148,13 +170,18 @@ type Bytes type JSON_Format ## PRIVATE If the File_Format supports reading from the file, return a configured instance. - for_file : File -> JSON_Format | Nothing - for_file file = + for_file_read : File -> JSON_Format | Nothing + for_file_read file = case file.extension of ".json" -> JSON_Format ".geojson" -> JSON_Format _ -> Nothing + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> JSON_Format | Nothing + for_file_write file = JSON_Format.for_file_read file + ## PRIVATE If the File_Format supports reading from the web response, return a configured instance. for_web : Text -> URI -> JSON_Format | Nothing diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite_Format.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite_Format.enso index 05b46d7796fe..3bd0f90864e8 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite_Format.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite_Format.enso @@ -11,8 +11,16 @@ type SQLite_Format ## PRIVATE If the File_Format supports reading from the file, return a configured instance. - for_file : File -> SQLite_Format | Nothing - for_file file = + for_file_read : File -> SQLite_Format | Nothing + for_file_read file = + expected_header = magic_header_string + got_header = file.read_first_bytes expected_header.length + if got_header == expected_header then SQLite_Format.For_File else Nothing + + ## PRIVATE + If the File_Format supports writing to the file, return a configured instance. + for_file_write : File -> SQLite_Format | Nothing + for_file_write file = case file.extension of ".db" -> SQLite_Format.For_File ".sqlite" -> SQLite_Format.For_File @@ -31,3 +39,8 @@ type SQLite_Format read self file on_problems = _ = [on_problems] Database.connect (SQLite_Details.SQLite file) + +## PRIVATE + Based on the File Format definition at: https://www.sqlite.org/fileformat.html +magic_header_string = + "SQLite format 3".utf_8 + [0] diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso index 0eb08a1e1f9b..e12484b17da8 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso @@ -994,6 +994,12 @@ type Column _ = [type, format, on_problems] Error.throw <| Unsupported_Database_Operation.Error "`Column.parse` is not implemented yet for the Database backends." + ## Formatting values is not supported in database columns. + format : Text | Column -> Locale -> Column ! Illegal_Argument + format self format=Nothing locale=Locale.default = + _ = [format, locale] + Error.throw <| Unsupported_Database_Operation.Error "`Column.format` is not implemented yet for the Database backends." + ## PRIVATE UNSTABLE Cast the column to a specific type. diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index b2ddb208ca0f..7173af43bc86 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -8,7 +8,7 @@ import Standard.Base.Errors.Illegal_Argument.Illegal_Argument import Standard.Base.Errors.Illegal_State.Illegal_State import Standard.Base.Errors.Unimplemented.Unimplemented -from Standard.Table import Auto_Detect, Aggregate_Column, Data_Formatter, Column_Selector, Sort_Column, Match_Columns, Position, Set_Mode, Auto, Value_Type +from Standard.Table import Aggregate_Column, Data_Formatter, Column_Selector, Sort_Column, Match_Columns, Position, Set_Mode, Auto, Value_Type import Standard.Table.Data.Expression.Expression import Standard.Table.Data.Expression.Expression_Error import Standard.Table.Data.Join_Condition.Join_Condition @@ -23,6 +23,7 @@ import Standard.Table.Internal.Java_Exports import Standard.Table.Internal.Table_Helpers import Standard.Table.Internal.Table_Helpers.Table_Column_Helper import Standard.Table.Internal.Problem_Builder.Problem_Builder +import Standard.Table.Internal.Unique_Name_Strategy.Unique_Name_Strategy import Standard.Table.Internal.Widget_Helpers from Standard.Table.Data.Column import get_item_string, normalize_string_for_display from Standard.Table.Data.Table import print_table @@ -187,6 +188,7 @@ type Table table.select_columns [-1, 0, 1] reorder=True Icon: select_column + @columns Widget_Helpers.make_column_name_vector_selector select_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Boolean -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range select_columns self (columns = [0]) (reorder = False) (error_on_missing_columns = True) (on_problems = Report_Warning) = new_columns = self.columns_helper.select_columns selectors=columns reorder=reorder error_on_missing_columns=error_on_missing_columns on_problems=on_problems @@ -239,6 +241,7 @@ type Table Remove the first two columns and the last column. table.remove_columns [-1, 0, 1] + @columns Widget_Helpers.make_column_name_vector_selector remove_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range remove_columns self (columns = [0]) (error_on_missing_columns = False) (on_problems = Report_Warning) = new_columns = self.columns_helper.remove_columns selectors=columns error_on_missing_columns=error_on_missing_columns on_problems=on_problems @@ -294,6 +297,7 @@ type Table Move the first column to back. table.reorder_columns [0] position=Position.After_Other_Columns + @columns Widget_Helpers.make_column_name_vector_selector reorder_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Position -> Boolean -> Problem_Behavior -> Table ! Missing_Input_Columns | Column_Indexes_Out_Of_Range reorder_columns self (columns = [0]) (position = Position.Before_Other_Columns) (error_on_missing_columns = False) (on_problems = Report_Warning) = new_columns = self.columns_helper.reorder_columns selectors=columns position=position error_on_missing_columns on_problems=on_problems @@ -617,6 +621,7 @@ type Table double_inventory = table.at "total_stock" * 2 table.set double_inventory new_name="total_stock" table.set "2 * [total_stock]" new_name="total_stock_expr" + @new_name Widget_Helpers.make_column_name_selector set : Column | Text -> Text | Nothing -> Set_Mode -> Problem_Behavior -> Table ! Unsupported_Name | Existing_Column | Missing_Column | No_Such_Column | Expression_Error set self column new_name=Nothing set_mode=Set_Mode.Add_Or_Update on_problems=Report_Warning = resolved = case column of @@ -794,6 +799,7 @@ type Table Sort the table by columns whose names start with letter `a`. table.order_by [(Sort_Column.Select_By_Name "a.*" use_regex=True case_sensitivity=Case_Sensitivity.Insensitive)] + @columns Widget_Helpers.make_order_by_selector order_by : Text | Sort_Column | Vector (Text | Sort_Column) -> Text_Ordering -> Boolean -> Problem_Behavior -> Table ! Incomparable_Values | No_Input_Columns_Selected | Missing_Input_Columns | Column_Indexes_Out_Of_Range order_by self (columns = ([(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering.Default error_on_missing_columns=True on_problems=Problem_Behavior.Report_Warning = Panic.handle_wrapped_dataflow_error <| problem_builder = Problem_Builder.new error_on_missing_columns=error_on_missing_columns types_to_always_throw=[No_Input_Columns_Selected] @@ -843,6 +849,7 @@ type Table - If floating points values are present in the distinct columns, a `Floating_Point_Equality` is reported according to the `on_problems` setting. + @columns Widget_Helpers.make_column_name_vector_selector distinct : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Case_Sensitivity -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | No_Input_Columns_Selected | Floating_Point_Equality distinct self columns=self.column_names case_sensitivity=Case_Sensitivity.Default error_on_missing_columns=True on_problems=Report_Warning = key_columns = self.columns_helper.select_columns selectors=columns reorder=True error_on_missing_columns=error_on_missing_columns on_problems=on_problems . catch No_Output_Columns _-> @@ -855,12 +862,15 @@ type Table Arguments: - right: The table to join with. - - join_kind: The `Join_Kind` for the joining the two tables. + - join_kind: The `Join_Kind` for the joining the two tables. It defaults + to `Left_Outer`. - on: A single condition or a common column name, or a list thereof, on which to correlate rows from the two tables. If multiple conditions are supplied, rows are correlated only if all are true. If common column names are provided, these columns should be present in both tables and an equality condition is added for each of them. + By default, the join is performed on the first column of the left table + correlated with a column in the right table with the same name. - right_prefix: The prefix added to right table column names in case of name conflict. - on_problems: Specifies how to handle problems if they occur, reporting @@ -908,10 +918,9 @@ type Table allows to join the two tables on equality of corresponding columns with the same name. So `table.join other on=["A", "B"]` is a shorthand for: table.join other on=[Join_Condition.Equals "A" "A", Join_Condition.Equals "B" "B"] - @join_kind Widget_Helpers.join_kind_selector @on Widget_Helpers.make_column_name_selector join : Table -> Join_Kind -> Join_Condition | Text | Vector (Join_Condition | Text) -> Text -> Problem_Behavior -> Table - join self right join_kind=Join_Kind.Inner on=[Join_Condition.Equals 0 0] right_prefix="Right_" on_problems=Report_Warning = + join self right join_kind=Join_Kind.Left_Outer on=[Join_Condition.Equals self.column_names.first] right_prefix="Right " on_problems=Report_Warning = can_proceed = if Table_Helpers.is_table right . not then Error.throw (Type_Error.Error Table right "right") else same_backend = case right of _ : Table -> True @@ -996,7 +1005,7 @@ type Table example, by sorting the table; in-memory tables will keep the memory layout order while for database tables the order may be unspecified). cross_join : Table -> Integer | Nothing -> Text -> Problem_Behavior -> Table - cross_join self right right_row_limit=100 right_prefix="Right_" on_problems=Report_Warning = + cross_join self right right_row_limit=100 right_prefix="Right " on_problems=Report_Warning = _ = [right, right_row_limit, right_prefix, on_problems] Error.throw (Unsupported_Database_Operation.Error "Table.cross_join is not implemented yet for the Database backends.") @@ -1045,7 +1054,7 @@ type Table order of columns is undefined and the operation will fail, reporting a `Undefined_Column_Order` problem and returning an empty table. zip : Table -> Boolean | Report_Unmatched -> Text -> Problem_Behavior -> Table - zip self right keep_unmatched=Report_Unmatched right_prefix="Right_" on_problems=Report_Warning = + zip self right keep_unmatched=Report_Unmatched right_prefix="Right " on_problems=Report_Warning = _ = [right, keep_unmatched, right_prefix, on_problems] Error.throw (Unsupported_Database_Operation.Error "Table.zip is not implemented yet for the Database backends.") @@ -1340,6 +1349,7 @@ type Table - If any column names in the new table are clashing, a `Duplicate_Output_Column_Names` is reported according to the `on_problems` setting. + @id_fields Widget_Helpers.make_column_name_vector_selector transpose : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Text -> Text -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range | Duplicate_Output_Column_Names transpose self id_fields=[] (name_field="Name") (value_field="Value") (error_on_missing_columns=True) (on_problems = Report_Warning) = ## Avoid unused arguments warning. We cannot rename arguments to `_`, @@ -1382,6 +1392,9 @@ type Table an `Unquoted_Delimiter` - If there are more than 10 issues with a single column, an `Additional_Warnings`. + @group_by Widget_Helpers.make_column_name_vector_selector + @name_column Widget_Helpers.make_column_name_selector + @values (Widget_Helpers.make_aggregate_column_selector include_group_by=False) cross_tab : Aggregate_Column | Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector | Aggregate_Column) -> (Text | Integer | Column) -> Vector Aggregate_Column -> Problem_Behavior -> Table ! Missing_Input_Columns | Column_Indexes_Out_Of_Range | Invalid_Aggregate_Column | Floating_Point_Equality | Invalid_Aggregation | Unquoted_Delimiter | Additional_Warnings cross_tab self group_by=[] name_column=self.column_names.first values=Aggregate_Column.Count (on_problems=Report_Warning) = ## Avoid unused arguments warning. We cannot rename arguments to `_`, @@ -1392,6 +1405,8 @@ type Table ## Parsing values is not supported in database tables, the table has to be loaded into memory first with `read`. + @type Widget_Helpers.parse_type_selector + @columns Widget_Helpers.make_column_name_vector_selector parse : Text | Integer | Column_Selector | Vector (Text | Integer | Column_Selector) -> Value_Type | Auto -> Text | Data_Formatter -> Boolean -> Problem_Behavior -> Table parse columns=(self.columns . filter (c-> c.value_type.is_text) . map .name) type=Auto format=Data_Formatter.Value error_on_missing_columns=True on_problems=Report_Warning = ## Avoid unused arguments warning. We cannot rename arguments to `_`, @@ -1415,6 +1430,7 @@ type Table ! Error Conditions If the data exceeds the `column_count`, a `Column_Count_Exceeded` will be reported according to the `on_problems` behavior. + @column Widget_Helpers.make_column_name_selector split_to_columns : Text | Integer -> Text -> Integer | Nothing -> Problem_Behavior -> Table split_to_columns self column delimiter="," column_count=Nothing on_problems=Report_Error = _ = [column delimiter column_count on_problems] @@ -1426,7 +1442,7 @@ type Table Arguments: - column: The name or index of the column to split the text of. - delimiter: The term or terms used to split the text. - - on_problems: Specifies the behavior when a problem occurs. + @column Widget_Helpers.make_column_name_selector split_to_rows : Text | Integer -> Text -> Table split_to_rows self column delimiter="," = _ = [column delimiter] @@ -1452,6 +1468,7 @@ type Table ! Error Conditions If the data exceeds the `column_count`, a `Column_Count_Exceeded` will be reported according to the `on_problems` behavior. + @column Widget_Helpers.make_column_name_selector tokenize_to_columns : Text | Integer -> Text -> Case_Sensitivity -> Integer | Nothing -> Problem_Behavior -> Table tokenize_to_columns self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive column_count=Nothing on_problems=Report_Error = _ = [column pattern case_sensitivity column_count on_problems] @@ -1468,10 +1485,13 @@ type Table - pattern: The pattern used to find within the text. - case_sensitivity: Specifies if the text values should be compared case sensitively. - - on_problems: Specifies the behavior when a problem occurs. - tokenize_to_rows : Text | Integer -> Text -> Case_Sensitivity -> Table - tokenize_to_rows self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive = - _ = [column pattern case_sensitivity] + - at_least_one_row: If True, a tokenization that returns no values will still + produce at least one row, with `Nothing` for the output column values. + Equivalent to converting a tokenization output of [] to [Nothing]. + @column Widget_Helpers.make_column_name_selector + tokenize_to_rows : Text | Integer -> Text -> Case_Sensitivity -> Boolean -> Table + tokenize_to_rows self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive at_least_one_row=False = + _ = [column, pattern, case_sensitivity, at_least_one_row] Error.throw (Unsupported_Database_Operation.Error "Table.tokenize_to_rows is not implemented yet for the Database backends.") ## Converts a Text column into new columns using a regular expression @@ -1498,6 +1518,7 @@ type Table will be named ` ` where `N` is the number of the marked group. If the new name is already in use it will be renamed following the normal suffixing strategy. + @column Widget_Helpers.make_column_name_selector parse_to_columns : Text | Integer -> Text -> Case_Sensitivity -> Boolean -> Problem_Behavior -> Table parse_to_columns self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive parse_values=True on_problems=Report_Error = _ = [column, pattern, case_sensitivity, parse_values, on_problems] @@ -1553,6 +1574,7 @@ type Table If the backend does not support the requested target type, the closest supported type is chosen and a `Inexact_Type_Coercion` problem is reported. + @columns Widget_Helpers.make_column_name_vector_selector cast : (Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector)) -> Value_Type -> Problem_Behavior -> Table ! Illegal_Argument | Inexact_Type_Coercion | Lossy_Conversion cast self columns=[0] value_type=Value_Type.Char on_problems=Problem_Behavior.Report_Warning = selected = self.select_columns columns @@ -1592,9 +1614,7 @@ type Table table = self.connection.read_statement sql table.at column_name . at 0 - ## UNSTABLE - - Returns a materialized dataframe containing rows of this table. + ## Returns a materialized dataframe containing rows of this table. Arguments: - max_rows: specifies a maximum amount of rows to fetch; if not set, all @@ -1858,16 +1878,9 @@ display_dataframe df indices_count all_rows_count format_terminal = is, otherwise numerical suffixes are added. fresh_names : Vector Text -> Vector Text -> Vector Text fresh_names used_names preferred_names = - freshen currently_used name ix = - new_name = if ix == 0 then name else name+"_"+ix.to_text - case currently_used.contains new_name of - False -> new_name - True -> freshen currently_used name ix+1 - res = preferred_names . fold [used_names, []] acc-> name-> - used = acc.first - new_name = freshen used name 0 - [used_names + [new_name], acc.second + [new_name]] - res.second + unique = Unique_Name_Strategy.new + unique.mark_used used_names + unique.make_all_unique preferred_names ## PRIVATE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Errors.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Errors.enso index e39dc95c35fb..a12bca5a15df 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Errors.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Errors.enso @@ -155,10 +155,14 @@ type Non_Unique_Primary_Key Arguments: - primary_key: The primary key that is not unique. - Error (primary_key : Vector Text) + - clashing_primary_key: The values of an example key that corresponds to + more than one row. + - clashing_example_row_count: The number of rows that correspond to the + example key. + Error (primary_key : Vector Text) (clashing_primary_key : Vector Any) (clashing_example_row_count : Integer) ## PRIVATE Pretty print the non-unique primary key error. to_display_text : Text to_display_text self = - "The primary key " + self.primary_key.to_display_text + " is not unique." + "The primary key " + self.primary_key.to_display_text + " is not unique. The key "+self.clashing_primary_key.to_display_text+" corresponds to "+self.clashing_example_row_count.to_text+" rows." diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Extensions/Upload_Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Extensions/Upload_Table.enso index dedd832ffd53..7f2130e0f416 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Extensions/Upload_Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Extensions/Upload_Table.enso @@ -62,7 +62,7 @@ In_Memory_Table.create_database_table self connection table_name=Nothing primary continue. Otherwise, they could 'leak' to `Panic.rethrow` and be wrongly raised as panics. upload_status = create_table_statement.if_not_error <| - translate_known_upload_errors connection resolved_primary_key <| + translate_known_upload_errors self connection resolved_primary_key <| connection.jdbc_connection.run_within_transaction <| Panic.rethrow <| connection.execute_update create_table_statement if structure_only.not then @@ -119,7 +119,7 @@ Database_Table.create_database_table self connection table_name=Nothing primary_ Error.throw (Unsupported_Database_Operation.Error "The Database table to be uploaded must be coming from the same connection as the connection on which the new table is being created. Cross-connection uploads are currently not supported. To work around this, you can first `.read` the table into memory and then upload it from memory to a different connection.") upload_status = connection_check.if_not_error <| create_table_statement.if_not_error <| - translate_known_upload_errors connection resolved_primary_key <| + translate_known_upload_errors self connection resolved_primary_key <| connection.jdbc_connection.run_within_transaction <| Panic.rethrow <| connection.execute_update create_table_statement if structure_only.not then @@ -144,15 +144,35 @@ resolve_primary_key table primary_key = case primary_key of ## PRIVATE Inspects any `SQL_Error` thrown and replaces it with a more precise error type when available. -translate_known_upload_errors connection primary_key ~action = +translate_known_upload_errors source_table connection primary_key ~action = handler caught_panic = error_mapper = connection.dialect.get_error_mapper sql_error = caught_panic.payload case error_mapper.is_primary_key_violation sql_error of - True -> Error.throw (Non_Unique_Primary_Key.Error primary_key) + True -> raise_duplicated_primary_key_error source_table primary_key caught_panic False -> Panic.throw caught_panic Panic.catch SQL_Error action handler +## PRIVATE + Creates a `Non_Unique_Primary_Key` error containing information about an + example group violating the uniqueness constraint. +raise_duplicated_primary_key_error source_table primary_key original_panic = + agg = source_table.aggregate [Aggregate_Column.Count]+(primary_key.map Aggregate_Column.Group_By) + filtered = agg.filter column=0 (Filter_Condition.Greater than=1) + materialized = filtered.read max_rows=1 + case materialized.row_count == 0 of + ## If we couldn't find a duplicated key, we give up the translation and + rethrow the original panic containing the SQL error. This could + happen if the constraint violation is on some non-trivial key, like + case insensitive. + True -> Panic.throw original_panic + False -> + row = materialized.first_row.to_vector + example_count = row.first + example_entry = row.drop 1 + Error.throw (Non_Unique_Primary_Key.Error primary_key example_entry example_count) + + ## PRIVATE Creates a statement that will create a table with structure determined by the provided columns. diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso index 6986f97ec3a0..66e8fec763ba 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso @@ -6,6 +6,7 @@ import project.Connection.Database import project.Connection.Postgres_Details.Postgres_Details import project.Connection.SQLite_Details.SQLite_Details import project.Connection.SQLite_Details.In_Memory +import project.Connection.SQLite_Format.SQLite_Format import project.Connection.SSL_Mode.SSL_Mode import project.Data.SQL_Query.SQL_Query import project.Extensions.Upload_Table @@ -21,6 +22,7 @@ export project.Connection.Database export project.Connection.Postgres_Details.Postgres_Details export project.Connection.SQLite_Details.SQLite_Details export project.Connection.SQLite_Details.In_Memory +export project.Connection.SQLite_Format.SQLite_Format export project.Connection.SSL_Mode.SSL_Mode export project.Data.SQL_Query.SQL_Query export project.Extensions.Upload_Table diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Image_File_Format.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Image_File_Format.enso index d5e80347ff50..80acec43a217 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Image_File_Format.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Image_File_Format.enso @@ -14,11 +14,16 @@ type Image_File_Format ## PRIVATE If the File_Format supports reading from the file, return a configured instance. - for_file : File -> Image_File_Format | Nothing - for_file file = + for_file_read : File -> Image_File_Format | Nothing + for_file_read file = extension = file.extension if supported.contains extension then Image_File_Format.For_File else Nothing + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> Image_File_Format | Nothing + for_file_write file = Image_File_Format.for_file_read file + ## PRIVATE If the File_Format supports reading from the web response, return a configured instance. for_web : Text -> URI -> Image_File_Format | Nothing diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso index cbeaa6ca1c8d..7af78ca3648f 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso @@ -1,5 +1,6 @@ from Standard.Base import all -from Standard.Base import all +from project.Data.Column_Format import all + import Standard.Base.Data.Array_Proxy.Array_Proxy import Standard.Base.Errors.Common.Index_Out_Of_Bounds import Standard.Base.Errors.Illegal_Argument.Illegal_Argument @@ -21,6 +22,7 @@ import project.Data.Type.Value_Type_Helpers from project.Data.Table import print_table from project.Data.Type.Value_Type import Value_Type, Auto from project.Errors import No_Index_Set_Error, Floating_Point_Equality, Invalid_Value_Type, Inexact_Type_Coercion +from project.Internal.Java_Exports import make_string_builder polyglot java import org.enso.table.data.column.operation.map.MapOperationProblemBuilder polyglot java import org.enso.table.data.column.storage.Storage as Java_Storage @@ -1175,6 +1177,108 @@ type Column output = Column.Value (Java_Column.new self.name new_storage) on_problems.attach_problems_after output problems + ## Format a `Column` using a format string (or `Column` of format strings). + + Arguments: + - format: The type-dependent format string to use to format the values. + If `format` is `""` or `Nothing`, .to_text is used to format the value. + - locale: The locale in which the format should be interpreted. + + ! Error Conditions + + - If the format is incorrectly formed, or if some values in the column + did not match the expected datatype format, an `Illegal_Argument` + error is thrown. + + ? Supported Types + - `Value_Type.Date` + - `Value_Type.Date_Time` + - `Value_Type.Time` + - `Value_Type.Integer` + - `Value_Type.Float` + - `Value_Type.Boolean` + + ? `Value_Type.Date`, `Value_Type.Date_Time`, `Value_Type.Time` format strings + + A custom pattern string consists of one or more custom date and time + format specifiers. For example, "d MMM yyyy" will format "2011-12-03" + as "3 Dec 2011". See https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/time/format/DateTimeFormatter.html + for a complete format specification. + + Note that the format string can specify decimal point and digit + separators, but these characters are interpreted in the context of the + Locale used. The format string specifies their location, but the Locale + has the final decision about which characters are used. + + ? `Value_Type.Integer`, `Value_Type.Float` format strings + + Numeric format strings are specified by the Java DecimalFormat class. + See https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html + for a complete format specification. + + ? `Value_Type.Boolean` format strings + + Format strings for `Boolean` consist of two values that represent true + and false, separated by a `|`. + + > Example + Format a `Column` of `Dates` in the format `"yyyyMMdd"`. + + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + input.format "yyyyMMdd" + # ==> ["20201221", "20230425"] + + > Example + Format `Column` of `Dates`, using format strings in a second column. + + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + formats = Column.from_vector "formats" ["yyyyMMdd", "dd-MM-yyyy"] + input.format formats + # ==> ["20201221", "25-04-2023"] + + > Example + Format a `Column` of `Integers` in the format `"#,##0.00"`. + + input = Column.from_vector "values" [100000000, 2222, 3] + input.format "#,##0.00" + # ==> ["100,000,000.00", "2,222.00", "3.00"] + + > Example + Format a `Column` of `Booleans` in the format `"t|f"`. + + input = Column.from_vector "values" [True, False] + input.format "t|f" + # ==> ["t", "f"] + + > Example + Format a `Column` of numbers, using both decimal point / digit + separators and a Locale. + + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + input.format "#,##0.00" locale=(Locale.new "fr") + # ==> ["100 000 000,00", "2 222,00", "3,00"] + format : Text | Column -> Locale -> Column ! Illegal_Argument + format self format=Nothing locale=Locale.default = + create_formatter = make_value_formatter_for_value_type self.value_type locale + + new_column = case format of + "" -> + formatter = .to_text + map_over_storage self formatter make_string_builder + Nothing -> + formatter = .to_text + map_over_storage self formatter make_string_builder + _ : Text -> + formatter = create_formatter + formatter.if_not_error <| + map_over_storage self (formatter format=format) make_string_builder + format_column : Column -> Value_Type.expect_text format_column <| + formatter = create_formatter + formatter.if_not_error <| + map_2_over_storage self format_column formatter make_string_builder + _ -> Error.throw <| Illegal_Argument.Error <| "Unsupported format type: " + format.to_text + new_column + ## ALIAS Transform Column Applies `function` to each item in this column and returns the column diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Format.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Format.enso new file mode 100644 index 000000000000..48625a8dcc8c --- /dev/null +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Format.enso @@ -0,0 +1,114 @@ +from Standard.Base import all +import Standard.Base.Errors.Illegal_Argument.Illegal_Argument +import Standard.Base.Errors.Illegal_State.Illegal_State +import project.Data.Column.Column +import project.Data.Data_Formatter.Data_Formatter +import project.Data.Type.Storage +import project.Data.Type.Value_Type.Value_Type + +from project.Internal.Java_Exports import make_string_builder + +polyglot java import java.lang.IllegalArgumentException +polyglot java import java.time.temporal.UnsupportedTemporalTypeException +polyglot java import org.enso.table.data.column.operation.map.MapOperationProblemBuilder +polyglot java import org.enso.table.data.column.storage.Storage as Java_Storage +polyglot java import org.enso.table.data.table.Column as Java_Column +polyglot java import org.enso.table.operations.OrderBuilder + +## PRIVATE + Create a formatter for the specified `Value_Type`. +make_value_formatter_for_value_type : Value_Type -> Locale -> (Any -> Text) +make_value_formatter_for_value_type value_type locale = case value_type of + Value_Type.Date -> make_value_formatter locale + Value_Type.Date_Time _ -> make_value_formatter locale + Value_Type.Time -> make_value_formatter locale + Value_Type.Boolean -> make_boolean_formatter + Value_Type.Integer _ -> make_value_formatter locale + Value_Type.Float _ -> make_value_formatter locale + bad_type -> + msg = "Cannot format a Column of type " + bad_type.to_text + Error.throw (Illegal_Argument.Error msg) + +## PRIVATE + Create a formatter for the given format string. + The `value` parameter has to have a `format` method that takes a format and + locale. +make_value_formatter : Locale -> (Any -> Text) +make_value_formatter locale = value-> format-> + handle_illegal_argument_exception format <| + if format.is_nothing || format.is_empty then value.to_text else + value.format format locale +## PRIVATE + Create a `Boolean` formatter that takes the format string as the second + parameter. +make_boolean_formatter : (Boolean -> Text -> Text) +make_boolean_formatter = bool-> format-> + if format.is_nothing || format.is_empty then bool.to_text else + data_formatter = Data_Formatter.Value.with_format Value_Type.Boolean format + data_formatter.format bool + +## PRIVATE + Rethrow a Java IllegalArgumentException as an Illegal_Argument. +handle_illegal_argument_exception : Text -> Any -> Any +handle_illegal_argument_exception format_string ~action = + handler cause = + msg = cause.payload.getMessage + ' in \"' + format_string + '\"' + Error.throw (Illegal_Argument.Error msg) + Panic.catch IllegalArgumentException handler=handler <| + Panic.catch UnsupportedTemporalTypeException handler=handler action + +## PRIVATE + Iterate over a range, exiting early if the body produces an `Error`. +each_propagate : Range -> (Number -> Any) -> Nothing ! Error +each_propagate range function = + if range.step == 0 then Error.throw (Illegal_State.Error "A range with step = 0 is ill-formed.") else + end_condition = if range.step > 0 then (>=) else (<=) + go current = + if end_condition current range.end then Nothing else + result = function current + result.if_not_error <| + @Tail_Call go current+range.step + go range.start + +## PRIVATE + Map a text-returning function over the column values, using Storage directly. + The output column has the same name as the input. +map_over_storage : Column -> (Any -> Text) -> (Integer -> Any) -> Boolean -> Column +map_over_storage input_column function builder skip_nothing=True = + input_storage = input_column.java_column.getStorage + num_input_rows = input_storage.size + output_storage_builder = builder num_input_rows + ok = each_propagate (0.up_to num_input_rows) i-> + input_value = input_storage.getItemBoxed i + if skip_nothing && input_value.is_nothing then output_storage_builder.append Nothing else + output_value = function input_value + output_value.if_not_error + output_storage_builder.append output_value + ok.if_not_error <| + output_storage = output_storage_builder.seal + Column.from_storage input_column.name output_storage + +## PRIVATE + Map a text-returning function over the values of two columns, using Storage + directly. The output column has the same name as the first input column. + `skip_nothing` applies to the first input to the function, not both inputs. +map_2_over_storage : Column -> Column -> (Any -> Any -> Text) -> (Integer -> Any) -> Boolean -> Column +map_2_over_storage input_column_0 input_column_1 function builder skip_nothing=True = + input_storage_0 = input_column_0.java_column.getStorage + input_storage_1 = input_column_1.java_column.getStorage + case input_storage_0.size != input_storage_1.size of + True -> + msg = "Column lengths differ: " + input_storage_0.size.to_text + " != " + input_storage_1.size.to_text + Error.throw (Illegal_Argument.Error msg) + False -> + num_input_rows = input_storage_0.size + output_storage_builder = builder num_input_rows + ok = each_propagate (0.up_to num_input_rows) i-> + input_value_0 = input_storage_0.getItemBoxed i + input_value_1 = input_storage_1.getItemBoxed i + if skip_nothing && input_value_0.is_nothing then output_storage_builder.append Nothing else + output_value = function input_value_0 input_value_1 + output_storage_builder.append output_value + ok.if_not_error <| + output_storage = output_storage_builder.seal + Column.from_storage input_column_0.name output_storage diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index c4a844e69c8f..ec9f272aa79f 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -311,6 +311,7 @@ type Table table.select_columns [-1, 0, 1] reorder=True Icon: select_column + @columns Widget_Helpers.make_column_name_vector_selector select_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Boolean -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range select_columns self columns=[0] (reorder = False) (error_on_missing_columns = True) (on_problems = Report_Warning) = new_columns = self.columns_helper.select_columns selectors=columns reorder=reorder error_on_missing_columns=error_on_missing_columns on_problems=on_problems @@ -363,7 +364,7 @@ type Table Remove the first two columns and the last column. table.remove_columns [-1, 0, 1] - + @columns Widget_Helpers.make_column_name_vector_selector remove_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range remove_columns self (columns=[0]) (error_on_missing_columns = False) (on_problems = Report_Warning) = new_columns = self.columns_helper.remove_columns selectors=columns error_on_missing_columns=error_on_missing_columns on_problems=on_problems @@ -419,7 +420,7 @@ type Table Move the first column to back. table.reorder_columns [0] position=Position.After_Other_Columns - + @columns Widget_Helpers.make_column_name_vector_selector reorder_columns : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Position -> Boolean -> Problem_Behavior -> Table ! Missing_Input_Columns | Column_Indexes_Out_Of_Range reorder_columns self (columns = [0]) (position = Position.Before_Other_Columns) (error_on_missing_columns = False) (on_problems = Report_Warning) = new_columns = self.columns_helper.reorder_columns selectors=columns position=position error_on_missing_columns=error_on_missing_columns on_problems=on_problems @@ -681,6 +682,7 @@ type Table Sort the table by columns whose names start with letter `a`. table.order_by [(Sort_Column.Select_By_Name "a.*" use_regex=True case_sensitivity=Case_Sensitivity.Insensitive)] + @columns Widget_Helpers.make_order_by_selector order_by : Text | Sort_Column | Vector (Text | Sort_Column) -> Text_Ordering -> Boolean -> Problem_Behavior -> Table ! Incomparable_Values | No_Input_Columns_Selected | Missing_Input_Columns | Column_Indexes_Out_Of_Range order_by self (columns = ([(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering.Default error_on_missing_columns=True on_problems=Problem_Behavior.Report_Warning = problem_builder = Problem_Builder.new error_on_missing_columns=error_on_missing_columns types_to_always_throw=[No_Input_Columns_Selected] @@ -739,6 +741,7 @@ type Table - If floating points values are present in the distinct columns, a `Floating_Point_Equality` is reported according to the `on_problems` setting. + @columns Widget_Helpers.make_column_name_vector_selector distinct : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Case_Sensitivity -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | No_Input_Columns_Selected | Floating_Point_Equality distinct self (columns = self.column_names) case_sensitivity=Case_Sensitivity.Default error_on_missing_columns=True on_problems=Report_Warning = key_columns = self.columns_helper.select_columns selectors=columns reorder=True error_on_missing_columns=error_on_missing_columns on_problems=on_problems . catch No_Output_Columns _-> @@ -833,6 +836,8 @@ type Table Parse all columns inferring their types, using `,` as the decimal point for numbers. table.parse format=(Data_Formatter.Value.with_number_formatting decimal_point=',') + @type Widget_Helpers.parse_type_selector + @columns Widget_Helpers.make_column_name_vector_selector parse : Text | Integer | Column_Selector | Vector (Text | Integer | Column_Selector) -> Value_Type | Auto -> Text | Data_Formatter -> Boolean -> Problem_Behavior -> Table parse self columns=(self.columns . filter (c-> c.value_type.is_text) . map .name) type=Auto format=Data_Formatter.Value error_on_missing_columns=True on_problems=Report_Warning = formatter = case format of @@ -918,6 +923,7 @@ type Table If the backend does not support the requested target type, the closest supported type is chosen and a `Inexact_Type_Coercion` problem is reported. + @columns Widget_Helpers.make_column_name_vector_selector cast : (Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector)) -> Value_Type -> Problem_Behavior -> Table ! Illegal_Argument | Inexact_Type_Coercion | Lossy_Conversion cast self columns=[0] value_type=Value_Type.Char on_problems=Problem_Behavior.Report_Warning = _ = [columns, value_type, on_problems] @@ -939,6 +945,7 @@ type Table ! Error Conditions If the data exceeds the `column_count`, a `Column_Count_Exceeded` will be reported according to the `on_problems` behavior. + @column Widget_Helpers.make_column_name_selector split_to_columns : Text | Integer -> Text -> Integer | Nothing -> Problem_Behavior -> Table split_to_columns self column delimiter="," column_count=Nothing on_problems=Report_Error = Split_Tokenize.split_to_columns self column delimiter column_count on_problems @@ -949,7 +956,7 @@ type Table Arguments: - column: The name or index of the column to split the text of. - delimiter: The term or terms used to split the text. - - on_problems: Specifies the behavior when a problem occurs. + @column Widget_Helpers.make_column_name_selector split_to_rows : Text | Integer -> Text -> Table split_to_rows self column delimiter="," = Split_Tokenize.split_to_rows self column delimiter @@ -974,6 +981,7 @@ type Table ! Error Conditions If the data exceeds the `column_count`, a `Column_Count_Exceeded` will be reported according to the `on_problems` behavior. + @column Widget_Helpers.make_column_name_selector tokenize_to_columns : Text | Integer -> Text -> Case_Sensitivity -> Integer | Nothing -> Problem_Behavior -> Table tokenize_to_columns self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive column_count=Nothing on_problems=Report_Error = Split_Tokenize.tokenize_to_columns self column pattern case_sensitivity column_count on_problems @@ -989,10 +997,13 @@ type Table - pattern: The pattern used to find within the text. - case_sensitivity: Specifies if the text values should be compared case sensitively. - - on_problems: Specifies the behavior when a problem occurs. - tokenize_to_rows : Text | Integer -> Text -> Case_Sensitivity -> Table - tokenize_to_rows self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive = - Split_Tokenize.tokenize_to_rows self column pattern case_sensitivity + - at_least_one_row: If True, a tokenization that returns no values will still + produce at least one row, with `Nothing` for the output column values. + Equivalent to converting a tokenization output of [] to [Nothing]. + @column Widget_Helpers.make_column_name_selector + tokenize_to_rows : Text | Integer -> Text -> Case_Sensitivity -> Boolean -> Table + tokenize_to_rows self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive at_least_one_row=False = + Split_Tokenize.tokenize_to_rows self column pattern case_sensitivity at_least_one_row ## Converts a Text column into new columns using a regular expression pattern. @@ -1018,6 +1029,7 @@ type Table will be named ` ` where `N` is the number of the marked group. If the new name is already in use it will be renamed following the normal suffixing strategy. + @column Widget_Helpers.make_column_name_selector parse_to_columns : Text | Integer -> Text -> Case_Sensitivity -> Boolean -> Problem_Behavior -> Table parse_to_columns self column pattern="." case_sensitivity=Case_Sensitivity.Sensitive parse_values=True on_problems=Report_Error = Split_Tokenize.parse_to_columns self column pattern case_sensitivity parse_values on_problems @@ -1207,6 +1219,7 @@ type Table double_inventory = table.at "total_stock" * 2 table.set double_inventory new_name="total_stock" table.set "2 * [total_stock]" new_name="total_stock_expr" + @new_name Widget_Helpers.make_column_name_selector set : Column | Text -> Text | Nothing -> Set_Mode -> Problem_Behavior -> Table ! Existing_Column | Missing_Column | No_Such_Column | Expression_Error set self column new_name=Nothing set_mode=Set_Mode.Add_Or_Update on_problems=Report_Warning = resolved = case column of @@ -1321,12 +1334,15 @@ type Table Arguments: - right: The table to join with. - - join_kind: The `Join_Kind` for the joining the two tables. + - join_kind: The `Join_Kind` for the joining the two tables. It defaults + to `Left_Outer`. - on: A single condition or a common column name, or a list thereof, on which to correlate rows from the two tables. If multiple conditions are supplied, rows are correlated only if all are true. If common column names are provided, these columns should be present in both tables and an equality condition is added for each of them. + By default, the join is performed on the first column of the left table + correlated with a column in the right table with the same name. - right_prefix: The prefix added to right table column names in case of name conflict. - on_problems: Specifies how to handle problems if they occur, reporting @@ -1374,10 +1390,9 @@ type Table allows to join the two tables on equality of corresponding columns with the same name. So `table.join other on=["A", "B"]` is a shorthand for: table.join other on=[Join_Condition.Equals "A" "A", Join_Condition.Equals "B" "B"] - @join_kind Widget_Helpers.join_kind_selector @on Widget_Helpers.make_column_name_selector join : Table -> Join_Kind -> Join_Condition | Text | Vector (Join_Condition | Text) -> Text -> Problem_Behavior -> Table - join self right join_kind=Join_Kind.Inner on=[Join_Condition.Equals 0 0] right_prefix="Right_" on_problems=Report_Warning = + join self right join_kind=Join_Kind.Left_Outer on=[Join_Condition.Equals self.column_names.first] right_prefix="Right " on_problems=Report_Warning = if check_table "right" right then # [left_unmatched, matched, right_unmatched] rows_to_keep = case join_kind of @@ -1438,7 +1453,7 @@ type Table example, by sorting the table; in-memory tables will keep the memory layout order while for database tables the order may be unspecified). cross_join : Table -> Integer | Nothing -> Text -> Problem_Behavior -> Table - cross_join self right right_row_limit=100 right_prefix="Right_" on_problems=Report_Warning = + cross_join self right right_row_limit=100 right_prefix="Right " on_problems=Report_Warning = if check_table "right" right then limit_problems = case right_row_limit.is_nothing.not && (right.row_count > right_row_limit) of True -> @@ -1494,7 +1509,7 @@ type Table order of columns is undefined and the operation will fail, reporting a `Undefined_Column_Order` problem and returning an empty table. zip : Table -> Boolean | Report_Unmatched -> Text -> Problem_Behavior -> Table - zip self right keep_unmatched=Report_Unmatched right_prefix="Right_" on_problems=Report_Warning = + zip self right keep_unmatched=Report_Unmatched right_prefix="Right " on_problems=Report_Warning = if check_table "right" right then keep_unmatched_bool = case keep_unmatched of Report_Unmatched -> True @@ -1645,6 +1660,21 @@ type Table row_count : Integer row_count self = self.java_table.rowCount + ## Returns a materialized dataframe containing rows of this table. + + In the in-memory backend, this returns the same table, truncated to + `max_rows`. This is only kept for API compatibility between database and + in-memory tables. The `read` operation can be used to ensure that the + table is now in-memory, regardless of its origin. + + Arguments: + - max_rows: specifies a maximum amount of rows to fetch; if not set, all + available rows are fetched. + read : (Integer | Nothing) -> Table + read self max_rows=Nothing = case max_rows of + Nothing -> self + _ : Integer -> self.take (First max_rows) + ## Returns a Table describing this table's contents. The table lists all columns, counts of non-null items and value types of @@ -1693,6 +1723,7 @@ type Table - If any column names in the new table are clashing, a `Duplicate_Output_Column_Names` is reported according to the `on_problems` setting. + @id_fields Widget_Helpers.make_column_name_vector_selector transpose : Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector) -> Text -> Text -> Boolean -> Problem_Behavior -> Table ! No_Output_Columns | Missing_Input_Columns | Column_Indexes_Out_Of_Range | Duplicate_Output_Column_Names transpose self (id_fields = []) (name_field="Name") (value_field="Value") (error_on_missing_columns=True) (on_problems = Report_Warning) = columns_helper = self.columns_helper @@ -1748,7 +1779,10 @@ type Table an `Unquoted_Delimiter` - If there are more than 10 issues with a single column, an `Additional_Warnings`. - cross_tab : Aggregate_Column | Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector | Aggregate_Column) -> (Text | Integer) -> Vector Aggregate_Column -> Problem_Behavior -> Table ! Missing_Input_Columns | Column_Indexes_Out_Of_Range | Invalid_Aggregate_Column | Floating_Point_Equality | Invalid_Aggregation | Unquoted_Delimiter | Additional_Warnings + @group_by Widget_Helpers.make_column_name_vector_selector + @name_column Widget_Helpers.make_column_name_selector + @values (Widget_Helpers.make_aggregate_column_selector include_group_by=False) + cross_tab : Aggregate_Column | Text | Integer | Column_Selector | Vector (Integer | Text | Column_Selector | Aggregate_Column) -> (Text | Integer) -> Aggregate_Column | Vector Aggregate_Column -> Problem_Behavior -> Table ! Missing_Input_Columns | Column_Indexes_Out_Of_Range | Invalid_Aggregate_Column | Floating_Point_Equality | Invalid_Aggregation | Unquoted_Delimiter | Additional_Warnings cross_tab self group_by=[] name_column=self.column_names.first values=Aggregate_Column.Count (on_problems=Report_Warning) = columns_helper = self.columns_helper problem_builder = Problem_Builder.new error_on_missing_columns=True @@ -1894,7 +1928,7 @@ type Table file = File.new path case format of _ : Auto_Detect -> - base_format = format.get_format file + base_format = format.get_writing_format file if base_format == Nothing then Error.throw (File_Error.Unsupported_Output_Type file Table) else self.write file format=base_format on_existing_file match_columns on_problems _ -> diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Delimited/Delimited_Format.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Delimited/Delimited_Format.enso index d2b8799dc71e..0b2f35252bd6 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Delimited/Delimited_Format.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Delimited/Delimited_Format.enso @@ -49,19 +49,24 @@ type Delimited_Format character if it anywhere else than at the beginning of the line. This option is only applicable for read mode and does not affect writing. It defaults to `Nothing` which means that comments are disabled. - Delimited (delimiter:Text) (encoding:Encoding=Encoding.utf_8) (skip_rows:Integer=0) (row_limit:Integer|Nothing=Nothing) (quote_style:Quote_Style=Quote_Style.With_Quotes) (headers:Boolean|Infer=Infer) (value_formatter:Data_Formatter|Nothing=Data_Formatter.Value) (keep_invalid_rows:Boolean=True) (line_endings:Line_Ending_Style=Infer) (comment_character:Text|Nothing=Nothing) + Delimited (delimiter:Text=',') (encoding:Encoding=Encoding.utf_8) (skip_rows:Integer=0) (row_limit:Integer|Nothing=Nothing) (quote_style:Quote_Style=Quote_Style.With_Quotes) (headers:Boolean|Infer=Infer) (value_formatter:Data_Formatter|Nothing=Data_Formatter.Value) (keep_invalid_rows:Boolean=True) (line_endings:Line_Ending_Style=Infer) (comment_character:Text|Nothing=Nothing) ## PRIVATE ADVANCED If the File_Format supports reading from the file, return a configured instance. - for_file : File -> Delimited_Format | Nothing - for_file file = + for_file_read : File -> Delimited_Format | Nothing + for_file_read file = case file.extension of ".csv" -> Delimited_Format.Delimited ',' ".tab" -> Delimited_Format.Delimited '\t' ".tsv" -> Delimited_Format.Delimited '\t' _ -> Nothing + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> Delimited_Format | Nothing + for_file_write file = Delimited_Format.for_file_read file + ## PRIVATE ADVANCED If the File_Format supports reading from the web response, return a configured instance. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso index 2cef60b1cc26..8ace594b0be2 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso @@ -12,14 +12,24 @@ polyglot java import org.enso.table.error.EmptySheetException type Missing_Input_Columns ## PRIVATE One or more columns not found in the input table. - Error (criteria : [Text]) + + Arguments: + - criteria: the names of the columns or regular expressions that did not + have any matches. + - where: an optional text describing to which object this error is + related to (for example in join, whether the reported error is for the + left or right table). + Error (criteria : [Text]) (where:Text|Nothing = Nothing) ## PRIVATE Convert a missing input error to a human-readable form. to_display_text : Text to_display_text self = - "The criteria "+self.criteria.to_text+" did not match any columns." + where = case self.where of + Nothing -> "." + location : Text -> " in "+location+"." + "The criteria "+self.criteria.to_text+" did not match any columns"+where type Column_Indexes_Out_Of_Range ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Excel/Excel_Format.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Excel/Excel_Format.enso index 84c75121f3bf..4d7c6adc44d6 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Excel/Excel_Format.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Excel/Excel_Format.enso @@ -48,12 +48,17 @@ type Excel_Format ## PRIVATE ADVANCED If the File_Format supports reading from the file, return a configured instance. - for_file : File -> Excel_Format | Nothing - for_file file = + for_file_read : File -> Excel_Format | Nothing + for_file_read file = is_xls = should_treat_as_xls_format Infer file if is_xls.is_error then Nothing else Excel_Format.Excel xls_format=is_xls + ## PRIVATE + If this File_Format should be used for writing to that file, return a configured instance. + for_file_write : File -> Excel_Format | Nothing + for_file_write file = Excel_Format.for_file_read file + ## PRIVATE ADVANCED If the File_Format supports reading from the web response, return a configured instance. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Join_Helpers.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Join_Helpers.enso index 313ac6a9c705..abdd958ea67d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Join_Helpers.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Join_Helpers.enso @@ -23,9 +23,10 @@ type Join_Condition_Resolver resolve : Join_Condition | Text | Vector (Join_Condition | Text) -> Problem_Behavior -> Join_Condition_Resolution resolve self conditions on_problems = redundant_names = Vector.new_builder - problem_builder = Problem_Builder.new types_to_always_throw=[Missing_Input_Columns, Column_Indexes_Out_Of_Range] + left_problem_builder = Problem_Builder.new missing_input_columns_location="the left table" types_to_always_throw=[Missing_Input_Columns, Column_Indexes_Out_Of_Range] + right_problem_builder = Problem_Builder.new missing_input_columns_location="the right table" types_to_always_throw=[Missing_Input_Columns, Column_Indexes_Out_Of_Range] - resolve_selector resolver selector = + resolve_selector problem_builder resolver selector = r_1 = resolver selector r_2 = r_1.catch No_Such_Column _-> problem_builder.report_missing_input_columns [selector] @@ -33,9 +34,10 @@ type Join_Condition_Resolver r_2.catch Index_Out_Of_Bounds _-> problem_builder.report_oob_indices [selector] Nothing - resolve_left = resolve_selector self.left_at - resolve_right = resolve_selector self.right_at + resolve_left = resolve_selector left_problem_builder self.left_at + resolve_right = resolve_selector right_problem_builder self.right_at + problem_builder = Problem_Builder.new is_nothing column = case column of Nothing -> True _ -> False @@ -70,7 +72,12 @@ type Join_Condition_Resolver Value_Type.expect_comparable left right_lower <| Value_Type.expect_comparable left right_upper <| self.make_between problem_builder left right_lower right_upper - problem_builder.attach_problems_before on_problems <| + attach_problems ~result = + left_problem_builder.attach_problems_before on_problems <| + right_problem_builder.attach_problems_before on_problems <| + problem_builder.attach_problems_before on_problems <| + result + attach_problems <| if converted.contains Nothing then Panic.throw (Illegal_State.Error "Impossible: unresolved columns remaining in the join resolution. This should have raised a dataflow error. This is a bug in the Table library.") else Join_Condition_Resolution.Result converted redundant_names.to_vector diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso index c90d924b2779..2c668f40a801 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso @@ -8,7 +8,7 @@ from project.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, D ## PRIVATE type Problem_Builder ## PRIVATE - Value types_to_always_throw oob_indices missing_input_columns other + Value types_to_always_throw oob_indices missing_input_columns missing_input_columns_location other ## PRIVATE report_oob_indices self indices = @@ -39,7 +39,7 @@ type Problem_Builder if vec.not_empty then problems.append (problem_creator vec) - build_vector_and_append self.missing_input_columns Missing_Input_Columns.Error + build_vector_and_append self.missing_input_columns (Missing_Input_Columns.Error _ where=self.missing_input_columns_location) build_vector_and_append self.oob_indices Column_Indexes_Out_Of_Range.Error self.other.to_vector.each problems.append @@ -91,10 +91,12 @@ type Problem_Builder methods regardless of the `Problem_Behavior` used. Defaults to `False`. Setting this to `True` is essentially a shorthand for adding these two problem types to `types_to_always_throw`. + - missing_input_columns_location: The location to add to the missing + input column error to make it more informative. Defaults to `Nothing`. new : Vector -> Boolean -> Problem_Builder - new types_to_always_throw=[] error_on_missing_columns=False = + new types_to_always_throw=[] error_on_missing_columns=False missing_input_columns_location=Nothing = additional_types_to_throw = if error_on_missing_columns then [Missing_Input_Columns, Column_Indexes_Out_Of_Range, Invalid_Aggregate_Column] else [] - Problem_Builder.Value types_to_always_throw+additional_types_to_throw (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) other=Vector.new_builder + Problem_Builder.Value types_to_always_throw+additional_types_to_throw (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) missing_input_columns_location other=Vector.new_builder ## PRIVATE Appends a `Vector` to a `Vector_Builder` stored in a `Ref`. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Split_Tokenize.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Split_Tokenize.enso index dfd842cd3972..2a65ee6f0670 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Split_Tokenize.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Split_Tokenize.enso @@ -47,11 +47,11 @@ tokenize_to_columns table input_column_id pattern case_sensitivity column_count Tokenizes a column of text into a set of new rows using a regular expression. See `Table.tokenize_to_rows`. -tokenize_to_rows : Table -> Text | Integer -> Text -> Case_Sensitivity -> Table -tokenize_to_rows table input_column_id pattern="." case_sensitivity=Case_Sensitivity.Sensitive = +tokenize_to_rows : Table -> Text | Integer -> Text -> Case_Sensitivity -> Boolean -> Table +tokenize_to_rows table input_column_id pattern="." case_sensitivity=Case_Sensitivity.Sensitive at_least_one_row=False = column = table.at input_column_id Value_Type.expect_text column - fan_out_to_rows table input_column_id (handle_nothing (_.tokenize pattern case_sensitivity)) + fan_out_to_rows table input_column_id (handle_nothing (_.tokenize pattern case_sensitivity)) at_least_one_row=at_least_one_row ## PRIVATE Converts a Text column into new columns using a regular expression @@ -68,7 +68,7 @@ parse_to_columns table input_column_id pattern="." case_sensitivity=Case_Sensiti column = table.at input_column_id new_table = Value_Type.expect_text column <| - fan_out_to_rows_and_columns table input_column_id fun column_names on_problems + fan_out_to_rows_and_columns table input_column_id fun column_names on_problems=on_problems if parse_values then new_table.parse on_problems=on_problems else new_table ## PRIVATE @@ -123,7 +123,7 @@ fan_out_to_columns table input_column_id function column_count=Nothing on_proble input_column = table.get input_column_id problem_builder = Problem_Builder.new new_columns_unrenamed = map_columns_to_multiple input_column function column_count problem_builder - new_columns = rename_new_columns table new_columns_unrenamed problem_builder + new_columns = rename_new_columns table input_column.name new_columns_unrenamed problem_builder new_table = replace_column_with_columns table input_column new_columns problem_builder.attach_problems_after on_problems new_table @@ -138,14 +138,14 @@ fan_out_to_columns table input_column_id function column_count=Nothing on_proble - input_column: The column to transform. - function: A function that transforms a single element of `input_column` to multiple values. -fan_out_to_rows : Table -> Text | Integer -> (Any -> Vector Any) -> Problem_Behavior -> Table -fan_out_to_rows table input_column_id function on_problems=Report_Error = +fan_out_to_rows : Table -> Text | Integer -> (Any -> Vector Any) -> Boolean -> Problem_Behavior -> Table +fan_out_to_rows table input_column_id function at_least_one_row=False on_problems=Report_Error = ## Treat this as a special case of fan_out_to_rows_and_columns, with one column. Wrap the provided function to convert each value to a singleton `Vector`. wrapped_function x = function x . map y-> [y] column_names = [input_column_id] - fan_out_to_rows_and_columns table input_column_id wrapped_function column_names on_problems + fan_out_to_rows_and_columns table input_column_id wrapped_function column_names at_least_one_row=at_least_one_row on_problems=on_problems ## PRIVATE Transform a column by applying the given function to the values in the @@ -173,7 +173,7 @@ fan_out_to_rows table input_column_id function on_problems=Report_Error = x | 12 34 56 | y ===> ... | ... | ... - foo | bar 0 | bar 1 | baz + foo | bar 1 | bar 2 | baz ----+-------+-------+---- x | 1 | 2 | y x | 3 | 4 | y @@ -187,8 +187,8 @@ fan_out_to_rows table input_column_id function on_problems=Report_Error = to a `Vector` of `Vector` of values. - column_names: The names for the generated columns. - on_problems: Specifies the behavior when a problem occurs. -fan_out_to_rows_and_columns : Table -> Text | Integer -> (Any -> Vector (Vector Any)) -> Vector Text -> Problem_Behavior -> Table -fan_out_to_rows_and_columns table input_column_id function column_names on_problems=Report_Error = +fan_out_to_rows_and_columns : Table -> Text | Integer -> (Any -> Vector (Vector Any)) -> Vector Text -> Boolean -> Problem_Behavior -> Table +fan_out_to_rows_and_columns table input_column_id function column_names at_least_one_row=False on_problems=Report_Error = problem_builder = Problem_Builder.new unique = Unique_Name_Strategy.new @@ -205,9 +205,15 @@ fan_out_to_rows_and_columns table input_column_id function column_names on_probl # Accumulates repeated position indices for the order mask. order_mask_positions = Vector.new_builder initial_size + maybe_add_empty_row vecs = + should_add_empty_row = vecs.is_empty && at_least_one_row + if should_add_empty_row.not then vecs else + empty_row = Vector.fill num_output_columns Nothing + [empty_row] + 0.up_to num_input_rows . each i-> input_value = input_storage.getItemBoxed i - output_values = function input_value + output_values = function input_value |> maybe_add_empty_row # Append each group of values to the builder. output_values.each row_unchecked-> row = uniform_length num_output_columns row_unchecked problem_builder @@ -315,17 +321,22 @@ map_columns_to_multiple input_column function column_count problem_builder = builders + # Name columns. If there's only one, use the original column name. + new_column_names = case builders.length of + 1 -> [input_column.name] + _ -> 0.up_to builders.length . map i-> default_column_namer input_column.name i + # Build Columns. - builders.map .seal . map_with_index i-> storage-> - name = default_column_namer input_column.name i - Column.from_storage name storage + storages = builders.map .seal + new_column_names.zip storages Column.from_storage ## PRIVATE Rename a vector of columns to be unique when added to a table. -rename_new_columns : Table -> Vector Column -> Problem_Builder -> Vector Column -rename_new_columns table columns problem_builder = +rename_new_columns : Table -> Text -> Vector Column -> Problem_Builder -> Vector Column +rename_new_columns table removed_column_name columns problem_builder = unique = Unique_Name_Strategy.new - unique.mark_used <| table.columns.map .name + remaining_columns = table.columns . filter (c-> c.name != removed_column_name) . map .name + unique.mark_used remaining_columns new_columns = columns.map column-> new_name = unique.make_unique column.name column.rename new_name @@ -355,12 +366,13 @@ handle_nothing function = x-> case x of ## PRIVATE Repeat a computation n times. +repeat_each : Integer -> Any -> Any repeat_each n ~action = 0.up_to n . each _-> action ## PRIVATE Name a column by appending an integer to a base column name. default_column_namer : Text -> Integer -> Text -default_column_namer base_name i = base_name + " " + i.to_text +default_column_namer base_name i = base_name + " " + (i+1).to_text ## PRIVATE Pad or truncate a vector to be a specified length; if altered, report diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso index 867c80966e09..853836a51891 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Unique_Name_Strategy.enso @@ -56,10 +56,10 @@ type Unique_Name_Strategy > Example Rename names from a second list to avoid clashing with the first one. - first = ["A", "B", "second_A"] - second = ["A", "B", "second_A_1", "C"] + first = ["A", "B", "second A"] + second = ["A", "B", "second A 1", "C"] unique_second = Unique_Name_Strategy.combine_with_prefix first second "second_" - unique_second == ["second_A_2", "second_B", "second_A_1", "C"] + unique_second == ["second A 2", "second_B", "second A 1", "C"] combine_with_prefix : Vector Text -> Vector Text -> Text -> Unique_Name_Strategy combine_with_prefix self first second second_prefix = Vector.from_polyglot_array <| @@ -110,7 +110,7 @@ type Unique_Name_Strategy > Example strategy = Unique_Name_Strategy.new strategy.make_unique "A" # returns "A" - strategy.make_unique "A" # returns "A_1" + strategy.make_unique "A" # returns "A 1" make_unique : Text -> Text make_unique self name = self.deduplicator.makeUnique name diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Widget_Helpers.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Widget_Helpers.enso index c6274fca3cb7..b1bfae4ab6ec 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Widget_Helpers.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Widget_Helpers.enso @@ -1,16 +1,72 @@ from Standard.Base import all - -from Standard.Base.Metadata.Widget import Single_Choice +from Standard.Base.Metadata.Widget import Single_Choice, Vector_Editor from Standard.Base.Metadata.Choice import Option import Standard.Base.Metadata.Display -from project.Data.Table import Table +import project.Data.Table.Table +import project.Data.Aggregate_Column.Aggregate_Column + +## PRIVATE + Make an aggregate column selector. +make_aggregate_column_selector : Table -> Display -> Boolean -> Single_Choice +make_aggregate_column_selector table display=Display.Always include_group_by=True = + col_names_selector = make_column_name_selector table display=Display.Always + column_widget = Pair.new "column" col_names_selector + + col_list_selector = make_column_name_vector_selector table display=Display.Always + + group_by = if include_group_by then [Option "Group By" "(Aggregate_Column.Group_By)" [column_widget]] else [] + count = Option "Count" "Aggregate_Column.Count" + count_distinct = Option "Count Distinct" "(Aggregate_Column.Count_Distinct)" [Pair.new "columns" (col_list_selector)] + first = Option "First" "(Aggregate_Column.First)" [column_widget, Pair.new "order_by" (col_list_selector)] + last = Option "Last" "(Aggregate_Column.Last)" [column_widget, Pair.new "order_by" (col_list_selector)] + + count_not_nothing = Option "Count Not Nothing" "(Aggregate_Column.Count_Not_Nothing)" [column_widget] + count_nothing = Option "Count Nothing" "(Aggregate_Column.Count_Nothing)" [column_widget] + + ## Should be a list of Text columns only + count_not_empty = Option "Count Not Empty" "(Aggregate_Column.Count_Not_Empty)" [column_widget] + count_empty = Option "Count Empty" "(Aggregate_Column.Count_Empty)" [column_widget] + concatenate = Option "Concatenate" "(Aggregate_Column.Concatenate)" [column_widget] + shortest = Option "Shortest" "(Aggregate_Column.Shortest)" [column_widget] + longest = Option "Longest" "(Aggregate_Column.Longest)" [column_widget] + + ## Should be a list of Numeric columns only + sum = Option "Sum" "(Aggregate_Column.Sum)" [column_widget] + average = Option "Average" "(Aggregate_Column.Average)" [column_widget] + median = Option "Median" "(Aggregate_Column.Median)" [column_widget] + percentile = Option "Percentile" "(Aggregate_Column.Percentile)" [column_widget] + mode = Option "Mode" "(Aggregate_Column.Mode)" [column_widget] + standard_deviation = Option "Standard Deviation" "(Aggregate_Column.Standard_Deviation)" [column_widget] + + # Should be a list of comparable columns only + maximum = Option "Maximum" "(Aggregate_Column.Maximum)" [column_widget] + minimum = Option "Minimum" "(Aggregate_Column.Minimum)" [column_widget] + + Single_Choice display=display values=(group_by+[count, count_distinct, first, last, count_not_nothing, count_nothing, count_not_empty, count_empty, concatenate, shortest, longest, sum, average, median, percentile, mode, standard_deviation, maximum, minimum]) ## PRIVATE Make a column name selector. make_column_name_selector : Table -> Display -> Single_Choice make_column_name_selector table display=Display.Always = - Single_Choice display=display values=(table.column_names.map n->(Option n n.pretty)) + col_names = table.column_names + names = col_names.map n-> Option n n.pretty + Single_Choice display=display values=names + +## PRIVATE + Make a multiple column name selector. +make_column_name_vector_selector : Table -> Display -> Vector_Editor +make_column_name_vector_selector table display=Display.Always = + item_editor = make_column_name_selector table display=Display.Always + Vector_Editor item_editor=item_editor item_default=table.column_names.first.pretty display=display + +## PRIVATE + Make a column name selector. +make_order_by_selector : Table -> Display -> Single_Choice +make_order_by_selector table display=Display.Always = + col_names = table.column_names + names = col_names.fold [] c-> n-> c + [Option n+" (Asc)" n.pretty, Option n+" (Desc)" "(Sort_Column.Name "+n.pretty+" Sort_Direction.Descending)"] + Single_Choice display=display values=names ## PRIVATE Selector for type argument on `Column.parse`. @@ -21,11 +77,3 @@ parse_type_selector = options = names.zip choice . map pair-> Option pair.first pair.second Single_Choice display=Display.Always values=options -## PRIVATE - Selector for type argument on `Column.parse`. -join_kind_selector : Single_Choice -join_kind_selector = - choice = ['Join_Kind.Inner','Join_Kind.Left_Outer','Join_Kind.Right_Outer','Join_Kind.Full','Join_Kind.Left_Exclusive','Join_Kind.Right_Exclusive'] - names = ['Inner', 'Left Outer', 'Right Outer', 'Full', 'Left Exclusive', 'Right Exclusive'] - options = names.zip choice . map pair-> Option pair.first pair.second - Single_Choice display=Display.Always values=options diff --git a/distribution/lib/Standard/Test/0.0.0-dev/src/Extensions.enso b/distribution/lib/Standard/Test/0.0.0-dev/src/Extensions.enso index 5c7793bbc78f..96638e976f23 100644 --- a/distribution/lib/Standard/Test/0.0.0-dev/src/Extensions.enso +++ b/distribution/lib/Standard/Test/0.0.0-dev/src/Extensions.enso @@ -284,7 +284,8 @@ Error.should_succeed self frames_to_skip=0 = ## Handles an unexpected dataflow error. Error.should_be_a : Integer -> Any -Error.should_be_a self frames_to_skip=0 = +Error.should_be_a self typ frames_to_skip=0 = + _ = typ Test.fail_match_on_unexpected_error self 1+frames_to_skip ## Asserts that the given `Boolean` is `True` diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java index d5bcc46b7015..7ff5dce76c05 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java @@ -194,13 +194,6 @@ public Text toText() { return Text.create(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(dateTime)); } - @Builtin.Method(description = "Return this datetime to the datetime in the provided time zone.") - @Builtin.Specialize - @CompilerDirectives.TruffleBoundary - public Text format(String pattern) { - return Text.create(DateTimeFormatter.ofPattern(pattern).format(dateTime)); - } - @ExportMessage boolean isDate() { return true; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java index 454b0b755373..0ef6954a3379 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java @@ -125,13 +125,6 @@ public Text toText() { return Text.create(DateTimeFormatter.ISO_LOCAL_TIME.format(localTime)); } - @Builtin.Method(description = "Return this datetime to the datetime in the provided time zone.") - @Builtin.Specialize - @CompilerDirectives.TruffleBoundary - public Text format(String pattern) { - return Text.create(DateTimeFormatter.ofPattern(pattern).format(localTime)); - } - @ExportMessage boolean isTime() { return true; diff --git a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index 791c124e0c97..d27ae396f747 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala @@ -23,7 +23,7 @@ import scala.annotation.unused */ @SerialVersionUID( - 5568L // stable serialization of bindings + 5569L // removes special handling of `enso_project` method ) case class BindingsMap( definedEntities: List[DefinedEntity], diff --git a/integration-test/tests/graph_editor.rs b/integration-test/tests/graph_editor.rs index 8f1a15d9077b..d98acee76838 100644 --- a/integration-test/tests/graph_editor.rs +++ b/integration-test/tests/graph_editor.rs @@ -52,7 +52,7 @@ async fn debug_mode() { // Turning On let expect_mode = project.debug_mode.next_event(); - let expect_popup_message = project.debug_mode_popup().label().show.next_event(); + let expect_popup_message = project.debug_mode_popup().content_frp_node().next_event(); project.enable_debug_mode(); assert!(expect_mode.expect()); let message = expect_popup_message.expect(); @@ -68,7 +68,7 @@ async fn debug_mode() { // Turning Off let expect_mode = project.debug_mode.next_event(); - let expect_popup_message = project.debug_mode_popup().label().show.next_event(); + let expect_popup_message = project.debug_mode_popup().content_frp_node().next_event(); project.disable_debug_mode(); assert!(!expect_mode.expect()); let message = expect_popup_message.expect(); diff --git a/lib/rust/ensogl/core/Cargo.toml b/lib/rust/ensogl/core/Cargo.toml index b6b5648be8b3..3311e4167c26 100644 --- a/lib/rust/ensogl/core/Cargo.toml +++ b/lib/rust/ensogl/core/Cargo.toml @@ -40,7 +40,7 @@ num_enum = { version = "0.5.1" } num-traits = { version = "0.2" } ordered-float = { workspace = true } rustc-hash = { version = "1.0.1" } -semver = { version = "1.0.9" } +semver = { workspace = true } serde = { version = "1" } smallvec = { workspace = true } typenum = { version = "1.11.2" } diff --git a/std-bits/base/src/main/java/org/enso/base/Time_Utils.java b/std-bits/base/src/main/java/org/enso/base/Time_Utils.java index a00e02761888..5a80e3bc76fc 100644 --- a/std-bits/base/src/main/java/org/enso/base/Time_Utils.java +++ b/std-bits/base/src/main/java/org/enso/base/Time_Utils.java @@ -95,6 +95,26 @@ public static String local_date_format(LocalDate date, Object format) { return DateTimeFormatter.ofPattern(format.toString()).format(date); } + public static String local_date_format_with_locale(LocalDate date, Object format, Locale locale) { + return DateTimeFormatter.ofPattern(format.toString()).withLocale(locale).format(date); + } + + public static String date_time_format(ZonedDateTime dateTime, Object format) { + return DateTimeFormatter.ofPattern(format.toString()).format(dateTime); + } + + public static String date_time_format_with_locale(ZonedDateTime dateTime, Object format, Locale locale) { + return DateTimeFormatter.ofPattern(format.toString()).withLocale(locale).format(dateTime); + } + + public static String time_of_day_format_with_locale(LocalTime localTime, Object format, Locale locale) { + return DateTimeFormatter.ofPattern(format.toString()).withLocale(locale).format(localTime); + } + + public static String time_of_day_format(LocalTime localTime, Object format) { + return DateTimeFormatter.ofPattern(format.toString()).format(localTime); + } + public static LocalDate date_adjust(LocalDate date, AdjustOp op, Period period) { return switch (op) { case PLUS -> date.plus(period); diff --git a/std-bits/base/src/main/java/org/enso/base/time/Date_Period_Utils.java b/std-bits/base/src/main/java/org/enso/base/time/Date_Period_Utils.java index bf4b5f882638..48902640e92b 100644 --- a/std-bits/base/src/main/java/org/enso/base/time/Date_Period_Utils.java +++ b/std-bits/base/src/main/java/org/enso/base/time/Date_Period_Utils.java @@ -5,6 +5,20 @@ import java.time.temporal.*; public class Date_Period_Utils implements TimeUtilsBase { + private static final long NANOSECONDS_IN_DAY = 86_400_000_000_000L; + public static TemporalAdjuster day_start = + (Temporal temporal) -> { + return temporal.isSupported(ChronoField.NANO_OF_DAY) + ? temporal.with(ChronoField.NANO_OF_DAY, 0) + : temporal; + }; + + public static TemporalAdjuster day_end = + (Temporal temporal) -> { + return temporal.isSupported(ChronoField.NANO_OF_DAY) + ? temporal.with(ChronoField.NANO_OF_DAY, NANOSECONDS_IN_DAY - 1) + : temporal; + }; public static TemporalAdjuster quarter_start = (Temporal temporal) -> { diff --git a/std-bits/table/src/main/java/org/enso/table/read/DelimitedReader.java b/std-bits/table/src/main/java/org/enso/table/read/DelimitedReader.java index 82103f7c2946..ff90cf4facf2 100644 --- a/std-bits/table/src/main/java/org/enso/table/read/DelimitedReader.java +++ b/std-bits/table/src/main/java/org/enso/table/read/DelimitedReader.java @@ -334,7 +334,7 @@ private WithProblems> headersFromRow(String[] row) { private WithProblems> generateDefaultHeaders(int columnCount) { List headerNames = new ArrayList<>(columnCount); for (int i = 0; i < columnCount; ++i) { - headerNames.add(COLUMN_NAME + "_" + (i + 1)); + headerNames.add(COLUMN_NAME + " " + (i + 1)); } return new WithProblems<>(headerNames, Collections.emptyList()); } diff --git a/std-bits/table/src/main/java/org/enso/table/util/NameDeduplicator.java b/std-bits/table/src/main/java/org/enso/table/util/NameDeduplicator.java index 73f8486e9eec..b5fa13f3046e 100644 --- a/std-bits/table/src/main/java/org/enso/table/util/NameDeduplicator.java +++ b/std-bits/table/src/main/java/org/enso/table/util/NameDeduplicator.java @@ -87,7 +87,7 @@ private static String getName(String name, int index) { if (index == 0) { return name; } - return name + "_" + index; + return name + " " + index; } public String[] getInvalidNames() { @@ -134,7 +134,7 @@ public List combineWithPrefix( String name = second.get(i); if (output.get(i) == null) { var prefixed = secondPrefix + name; - output.set(i, makeUnique(secondPrefix + name)); + output.set(i, makeUnique(prefixed)); } } return output; diff --git a/test/Image_Tests/src/Image_Read_Write_Spec.enso b/test/Image_Tests/src/Image_Read_Write_Spec.enso index 273c9ecb22fe..b69eb09695c5 100644 --- a/test/Image_Tests/src/Image_Read_Write_Spec.enso +++ b/test/Image_Tests/src/Image_Read_Write_Spec.enso @@ -69,9 +69,9 @@ spec = Test.group "Image File_Format" <| Test.specify "should recognise image files" <| - Auto_Detect.get_format (enso_project.data / "data.jpg") . should_be_a Image_File_Format - Auto_Detect.get_format (enso_project.data / "data.png") . should_be_a Image_File_Format - Auto_Detect.get_format (enso_project.data / "data.bmp") . should_be_a Image_File_Format + Auto_Detect.get_reading_format (enso_project.data / "data.jpg") . should_be_a Image_File_Format + Auto_Detect.get_reading_format (enso_project.data / "data.png") . should_be_a Image_File_Format + Auto_Detect.get_reading_format (enso_project.data / "data.bmp") . should_be_a Image_File_Format Test.specify "should allow reading an Image" <| img = Data.read rgba_file diff --git a/test/Table_Tests/src/Common_Table_Operations/Aggregate_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Aggregate_Spec.enso index 95a75f0b7c52..8f691bdeefdb 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Aggregate_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Aggregate_Spec.enso @@ -111,9 +111,9 @@ spec setup = materialized.columns.at 0 . at 0 . should_equal 56.708660 epsilon=0.000001 materialized.columns.at 1 . name . should_equal "Standard Deviation ValueWithNothing" materialized.columns.at 1 . at 0 . should_equal 58.588610 epsilon=0.000001 - materialized.columns.at 2 . name . should_equal "Standard Deviation Value_1" + materialized.columns.at 2 . name . should_equal "Standard Deviation Value 1" materialized.columns.at 2 . at 0 . should_equal 56.697317 epsilon=0.000001 - materialized.columns.at 3 . name . should_equal "Standard Deviation ValueWithNothing_1" + materialized.columns.at 3 . name . should_equal "Standard Deviation ValueWithNothing 1" materialized.columns.at 3 . at 0 . should_equal 58.575554 epsilon=0.000001 Test.specify "should be able to create median, mode and percentile values" (pending = resolve_pending test_selection.advanced_stats) <| @@ -153,7 +153,7 @@ spec setup = materialized.column_count . should_equal 3 materialized.columns.at 0 . name . should_equal "First TextWithNothing" materialized.columns.at 0 . at 0 . should_equal "riwaiqq1io" - materialized.columns.at 1 . name . should_equal "First TextWithNothing_1" + materialized.columns.at 1 . name . should_equal "First TextWithNothing 1" materialized.columns.at 1 . at 0 . should_equal "j4i2ua7uft" materialized.columns.at 2 . name . should_equal "Last ValueWithNothing" materialized.columns.at 2 . at 0 . should_equal -38.56 epsilon=0.000001 @@ -236,7 +236,7 @@ spec setup = materialized.column_count . should_equal 2 materialized.columns.at 0 . name . should_equal "Count Distinct Code" materialized.columns.at 0 . at 0 . should_equal 0 - materialized.columns.at 1 . name . should_equal "Count Distinct Code_1" + materialized.columns.at 1 . name . should_equal "Count Distinct Code 1" materialized.columns.at 1 . at 0 . should_equal 0 Test.specify "should be able to compute sum and average of values" <| @@ -527,9 +527,9 @@ spec setup = materialized.columns.at 1 . at idx . should_equal 60.272158 epsilon=0.000001 materialized.columns.at 2 . name . should_equal "Standard Deviation ValueWithNothing" materialized.columns.at 2 . at idx . should_equal 56.798691 epsilon=0.000001 - materialized.columns.at 3 . name . should_equal "Standard Deviation Value_1" + materialized.columns.at 3 . name . should_equal "Standard Deviation Value 1" materialized.columns.at 3 . at idx . should_equal 60.156583 epsilon=0.000001 - materialized.columns.at 4 . name . should_equal "Standard Deviation ValueWithNothing_1" + materialized.columns.at 4 . name . should_equal "Standard Deviation ValueWithNothing 1" materialized.columns.at 4 . at idx . should_equal 56.677714 epsilon=0.000001 Test.specify "should be able to create median values" (pending = resolve_pending test_selection.advanced_stats) <| @@ -735,9 +735,9 @@ spec setup = materialized.columns.at 2 . at idx . should_equal 58.979275 epsilon=0.000001 materialized.columns.at 3 . name . should_equal "Standard Deviation ValueWithNothing" materialized.columns.at 3 . at idx . should_equal 57.561756 epsilon=0.000001 - materialized.columns.at 4 . name . should_equal "Standard Deviation Value_1" + materialized.columns.at 4 . name . should_equal "Standard Deviation Value 1" materialized.columns.at 4 . at idx . should_equal 58.746614 epsilon=0.000001 - materialized.columns.at 5 . name . should_equal "Standard Deviation ValueWithNothing_1" + materialized.columns.at 5 . name . should_equal "Standard Deviation ValueWithNothing 1" materialized.columns.at 5 . at idx . should_equal 57.306492 epsilon=0.000001 Test.specify "should be able to create median values" (pending = resolve_pending test_selection.advanced_stats) <| @@ -1366,25 +1366,25 @@ spec setup = Test.specify "should raise a warning when an invalid output name" <| action = table.aggregate [Group_By "Index" ""] on_problems=_ problems = [Invalid_Output_Column_Names.Error [""]] - tester = expect_column_names ["Column_1"] + tester = expect_column_names ["Column 1"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when a duplicate column name" <| action = table.aggregate [Group_By "Index", Group_By 0] on_problems=_ problems = [Duplicate_Output_Column_Names.Error ["Index"]] - tester = expect_column_names ["Index", "Index_1"] + tester = expect_column_names ["Index", "Index 1"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when a duplicate column name and rename default names first" <| action = table.aggregate [Group_By "Value", Group_By "Index" "Value"] on_problems=_ problems = [Duplicate_Output_Column_Names.Error ["Value"]] - tester = expect_column_names ["Value_1", "Value"] + tester = expect_column_names ["Value 1", "Value"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when duplicate column names" <| action = table.aggregate [Sum "Value" new_name="AGG1", Count new_name="AGG1"] on_problems=_ problems = [Duplicate_Output_Column_Names.Error ["AGG1"]] - tester = expect_column_names ["AGG1", "AGG1_1"] + tester = expect_column_names ["AGG1", "AGG1 1"] Problems.test_problem_handling action problems tester Test.specify "should allow partial matches on Count_Distinct" <| diff --git a/test/Table_Tests/src/Common_Table_Operations/Core_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Core_Spec.enso index 6091137b646b..ae7842786fb0 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Core_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Core_Spec.enso @@ -21,8 +21,8 @@ spec setup = col1 = ["foo", [1,2,3]] col2 = ["bar", [4,5,6]] col3 = ["Baz", [7,8,9]] - col4 = ["foo_1", [10,11,12]] - col5 = ["foo_2", [13,14,15]] + col4 = ["foo 1", [10,11,12]] + col5 = ["foo 2", [13,14,15]] col6 = ["ab.+123", [16,17,18]] col7 = ["abcd123", [19,20,21]] table_builder [col1, col2, col3, col4, col5, col6, col7] @@ -100,11 +100,11 @@ spec setup = Test.specify "should allow adding a column" <| bar2 = table.get "bar" . rename "bar2" t2 = table.set bar2 - t2.column_names . should_equal ["foo", "bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "bar2"] + t2.column_names . should_equal ["foo", "bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "bar2"] t2.get "bar2" . to_vector . should_equal [4, 5, 6] t3 = t2.set bar2 "bar3" - t3.column_names . should_equal ["foo", "bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "bar2", "bar3"] + t3.column_names . should_equal ["foo", "bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "bar2", "bar3"] Test.specify "should not allow illegal column names" <| table.set (table.get "bar") new_name="" . should_fail_with Illegal_Argument @@ -113,11 +113,11 @@ spec setup = Test.specify "should allow replacing a column" <| foo = table.get "bar" . rename "foo" t2 = table.set foo - t2.column_names . should_equal ["foo", "bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] + t2.column_names . should_equal ["foo", "bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] t2.get "foo" . to_vector . should_equal [4, 5, 6] t3 = t2.set foo "bar3" - t3.column_names . should_equal ["foo", "bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "bar3"] + t3.column_names . should_equal ["foo", "bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "bar3"] Test.specify "should allow adding a column" <| bar2 = table.get "bar" . rename "bar2" @@ -166,7 +166,7 @@ spec setup = Test.group prefix+"Table.column_names" <| Test.specify "should return the names of all columns" <| - table.column_names . should_equal ["foo", "bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] + table.column_names . should_equal ["foo", "bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] Test.specify "should allow weird column names in all backends" <| columns = weird_names.map_with_index ix-> name-> diff --git a/test/Table_Tests/src/Common_Table_Operations/Cross_Tab_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Cross_Tab_Spec.enso index d45c83be88f9..bfe835b49b98 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Cross_Tab_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Cross_Tab_Spec.enso @@ -149,14 +149,14 @@ spec setup = Test.specify "should gracefully handle duplicate aggregate names" <| action = table.cross_tab [] "Key" values=[Count new_name="Agg1", Sum "Value" new_name="Agg1"] on_problems=_ tester table = - table.column_names . should_equal ["x Agg1", "x Agg1_1", "y Agg1", "y Agg1_1", "z Agg1", "z Agg1_1"] + table.column_names . should_equal ["x Agg1", "x Agg1 1", "y Agg1", "y Agg1 1", "z Agg1", "z Agg1 1"] problems = [Duplicate_Output_Column_Names.Error ["x Agg1", "y Agg1", "z Agg1"]] Problems.test_problem_handling action problems tester table3 = table2.rename_columns (Map.from_vector [["Group", "x"]]) action3 = table3.cross_tab ["x"] "Key" on_problems=_ tester3 table = - table.column_names . should_equal ["x", "x_1", "y", "z"] + table.column_names . should_equal ["x", "x 1", "y", "z"] problems3 = [Duplicate_Output_Column_Names.Error ["x"]] Problems.test_problem_handling action3 problems3 tester3 diff --git a/test/Table_Tests/src/Common_Table_Operations/Integration_Tests.enso b/test/Table_Tests/src/Common_Table_Operations/Integration_Tests.enso index 94eafeba889b..8ae48df0538e 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Integration_Tests.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Integration_Tests.enso @@ -37,7 +37,7 @@ spec setup = t3 = t2.aggregate [Group_By "Letter", Count] t4 = t3.join t1 on="Count" join_kind=Join_Kind.Left_Outer |> materialize |> _.order_by "Letter" - t4.columns.map .name . should_equal ["Letter", "Count", "Right_Count", "Class"] + t4.columns.map .name . should_equal ["Letter", "Count", "Right Count", "Class"] rows = t4.rows . map .to_vector rows.at 0 . should_equal ["A", 4, Nothing, Nothing] rows.at 1 . should_equal ["B", 3, 3, "Z"] diff --git a/test/Table_Tests/src/Common_Table_Operations/Join/Cross_Join_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Join/Cross_Join_Spec.enso index ba11a64b515e..3f60df4ca93a 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Join/Cross_Join_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Join/Cross_Join_Spec.enso @@ -94,7 +94,7 @@ spec setup = t1 = table_builder [["X", [1, 2]], ["Y", [4, 5]]] t2 = t1.cross_join t1 - expect_column_names ["X", "Y", "Right_X", "Right_Y"] t2 + expect_column_names ["X", "Y", "Right X", "Right Y"] t2 t2.row_count . should_equal 4 r = materialize t2 . rows . map .to_vector r.length . should_equal 4 @@ -108,26 +108,26 @@ spec setup = False -> r.should_equal expected_rows Test.specify "should rename columns of the right table to avoid duplicates" <| - t1 = table_builder [["X", [1]], ["Y", [5]], ["Right_Y", [10]]] + t1 = table_builder [["X", [1]], ["Y", [5]], ["Right Y", [10]]] t2 = table_builder [["X", ['a']], ["Y", ['d']]] t3 = t1.cross_join t2 - expect_column_names ["X", "Y", "Right_Y", "Right_X", "Right_Y_1"] t3 - Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right_Y"]] + expect_column_names ["X", "Y", "Right Y", "Right X", "Right Y 1"] t3 + Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right Y"]] t3.row_count . should_equal 1 t3.at "X" . to_vector . should_equal [1] t3.at "Y" . to_vector . should_equal [5] - t3.at "Right_Y" . to_vector . should_equal [10] - t3.at "Right_X" . to_vector . should_equal ['a'] - t3.at "Right_Y_1" . to_vector . should_equal ['d'] + t3.at "Right Y" . to_vector . should_equal [10] + t3.at "Right X" . to_vector . should_equal ['a'] + t3.at "Right Y 1" . to_vector . should_equal ['d'] t1.cross_join t2 on_problems=Problem_Behavior.Report_Error . should_fail_with Duplicate_Output_Column_Names - expect_column_names ["X", "Y", "Right_Y", "X_1", "Y_1"] (t1.cross_join t2 right_prefix="") + expect_column_names ["X", "Y", "Right Y", "X 1", "Y 1"] (t1.cross_join t2 right_prefix="") - t4 = table_builder [["X", [1]], ["Right_X", [5]]] - expect_column_names ["X", "Y", "Right_Y", "Right_X_1", "Right_X"] (t1.cross_join t4) - expect_column_names ["X", "Right_X", "Right_X_1", "Y", "Right_Y"] (t4.cross_join t1) + t4 = table_builder [["X", [1]], ["Right X", [5]]] + expect_column_names ["X", "Y", "Right Y", "Right X 1", "Right X"] (t1.cross_join t4) + expect_column_names ["X", "Right X", "Right X 1", "Y", "Right Y"] (t4.cross_join t1) Test.specify "should respect the column ordering" <| t1 = table_builder [["X", [100, 2]], ["Y", [4, 5]]] diff --git a/test/Table_Tests/src/Common_Table_Operations/Join/Join_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Join/Join_Spec.enso index b0b56bfffd65..910080636bea 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Join/Join_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Join/Join_Spec.enso @@ -34,9 +34,18 @@ spec setup = Test.group prefix+"Table.join" <| t1 = table_builder [["X", [1, 2, 3]], ["Y", [4, 5, 6]]] t2 = table_builder [["Z", [2, 3, 2, 4]], ["W", [4, 5, 6, 7]]] - Test.specify "should allow to Inner join on equality of a the first column by default" <| - t3 = t1.join t2 + Test.specify "should by default do a Left Outer join on equality of first column in the left table, correlated with column of the same name in the right one" <| + t3 = table_builder [["Z", [4, 5, 6, 7]], ["X", [2, 3, 2, 4]]] + t4 = t1.join t3 |> materialize |> _.order_by ["X", "Z"] + expect_column_names ["X", "Y", "Z", "Right X"] t4 + t4.at "X" . to_vector . should_equal [1, 2, 2, 3] + t4.at "Y" . to_vector . should_equal [4, 5, 5, 6] + t4.at "Right X" . to_vector . should_equal [Nothing, 2, 2, 3] + t4.at "Z" . to_vector . should_equal [Nothing, 4, 6, 5] + + Test.specify "should allow Inner join" <| + t3 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals 0 0) expect_column_names ["X", "Y", "Z", "W"] t3 t4 = t3 |> materialize |> _.order_by ["X", "W"] t4.at "X" . to_vector . should_equal [2, 2, 3] @@ -45,23 +54,15 @@ spec setup = t4.at "W" . to_vector . should_equal [4, 6, 5] Test.specify "should allow Full join" <| - t3 = t1.join t2 join_kind=Join_Kind.Full |> materialize |> _.order_by ["X", "W"] + t3 = t1.join t2 join_kind=Join_Kind.Full on=(Join_Condition.Equals 0 0) |> materialize |> _.order_by ["X", "W"] expect_column_names ["X", "Y", "Z", "W"] t3 t3.at "X" . to_vector . should_equal [Nothing, 1, 2, 2, 3] t3.at "Y" . to_vector . should_equal [Nothing, 4, 5, 5, 6] t3.at "Z" . to_vector . should_equal [4, Nothing, 2, 2, 3] t3.at "W" . to_vector . should_equal [7, Nothing, 4, 6, 5] - Test.specify "should allow Left Outer join" <| - t4 = t1.join t2 join_kind=Join_Kind.Left_Outer |> materialize |> _.order_by ["X", "W"] - expect_column_names ["X", "Y", "Z", "W"] t4 - t4.at "X" . to_vector . should_equal [1, 2, 2, 3] - t4.at "Y" . to_vector . should_equal [4, 5, 5, 6] - t4.at "Z" . to_vector . should_equal [Nothing, 2, 2, 3] - t4.at "W" . to_vector . should_equal [Nothing, 4, 6, 5] - Test.specify "should allow Right Outer join" <| - t5 = t1.join t2 join_kind=Join_Kind.Right_Outer |> materialize |> _.order_by ["X", "W"] + t5 = t1.join t2 join_kind=Join_Kind.Right_Outer on=(Join_Condition.Equals 0 0) |> materialize |> _.order_by ["X", "W"] expect_column_names ["X", "Y", "Z", "W"] t5 t5.at "X" . to_vector . should_equal [Nothing, 2, 2, 3] t5.at "Y" . to_vector . should_equal [Nothing, 5, 5, 6] @@ -69,12 +70,12 @@ spec setup = t5.at "W" . to_vector . should_equal [7, 4, 6, 5] Test.specify "should allow to perform anti-joins" <| - t6 = t1.join t2 join_kind=Join_Kind.Left_Exclusive |> materialize |> _.order_by ["X"] + t6 = t1.join t2 join_kind=Join_Kind.Left_Exclusive on=(Join_Condition.Equals 0 0) |> materialize |> _.order_by ["X"] t6.columns.map .name . should_equal ["X", "Y"] t6.at "X" . to_vector . should_equal [1] t6.at "Y" . to_vector . should_equal [4] - t7 = t1.join t2 join_kind=Join_Kind.Right_Exclusive |> materialize |> _.order_by ["Z"] + t7 = t1.join t2 join_kind=Join_Kind.Right_Exclusive on=(Join_Condition.Equals 0 0) |> materialize |> _.order_by ["Z"] t7.columns.map .name . should_equal ["Z", "W"] t7.at "Z" . to_vector . should_equal [4] t7.at "W" . to_vector . should_equal [7] @@ -82,39 +83,39 @@ spec setup = t3 = table_builder [["X", [1, 1, 1, 2, 2, 2]], ["Y", ["A", "B", "B", "C", "C", "A"]], ["Z", [1, 2, 3, 4, 5, 6]]] t4 = table_builder [["X", [1, 1, 3, 2, 2, 4]], ["Y", ["B", "B", "C", "C", "D", "A"]], ["Z", [1, 2, 3, 4, 5, 6]]] check_xy_joined r = - expect_column_names ["X", "Y", "Z", "Right_Z"] r + expect_column_names ["X", "Y", "Z", "Right Z"] r r.at "X" . to_vector . should_equal [1, 1, 1, 1, 2, 2] r.at "Y" . to_vector . should_equal ["B", "B", "B", "B", "C", "C"] r.at "Z" . to_vector . should_equal [2, 2, 3, 3, 4, 5] - r.at "Right_Z" . to_vector . should_equal [1, 2, 1, 2, 4, 4] + r.at "Right Z" . to_vector . should_equal [1, 2, 1, 2, 4, 4] Test.specify "should allow to join on equality of multiple columns and drop redundant columns if Inner join" <| conditions = [Join_Condition.Equals "Y" "Y", Join_Condition.Equals "X" "X"] - r = t3.join t4 on=conditions |> materialize |> _.order_by ["X", "Y", "Z", "Right_Z"] + r = t3.join t4 join_kind=Join_Kind.Inner on=conditions |> materialize |> _.order_by ["X", "Y", "Z", "Right Z"] check_xy_joined r [Join_Kind.Full, Join_Kind.Left_Outer, Join_Kind.Right_Outer].each kind-> r2 = t3.join t4 join_kind=kind on=conditions - expect_column_names ["X", "Y", "Z", "Right_X", "Right_Y", "Right_Z"] r2 + expect_column_names ["X", "Y", "Z", "Right X", "Right Y", "Right Z"] r2 Test.specify "should support same-name column join shorthand" <| - r = t3.join t4 on=["X", "Y"] |> materialize |> _.order_by ["X", "Y", "Z", "Right_Z"] + r = t3.join t4 join_kind=Join_Kind.Inner on=["X", "Y"] |> materialize |> _.order_by ["X", "Y", "Z", "Right Z"] check_xy_joined r Test.specify "should allow to join on text equality ignoring case" <| t1 = table_builder [["X", ["a", "B"]], ["Y", [1, 2]]] t2 = table_builder [["X", ["A", "a", "b"]], ["Z", [1, 2, 3]]] - r1 = t1.join t2 + r1 = t1.join t2 join_kind=Join_Kind.Inner expect_column_names ["X", "Y", "Z"] r1 r1 . at "X" . to_vector . should_equal ["a"] r1 . at "Y" . to_vector . should_equal [1] r1 . at "Z" . to_vector . should_equal [2] - r2 = t1.join t2 on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Z"] - expect_column_names ["X", "Y", "Right_X", "Z"] r2 + r2 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Z"] + expect_column_names ["X", "Y", "Right X", "Z"] r2 r2 . at "X" . to_vector . should_equal ["a", "a", "B"] - r2 . at "Right_X" . to_vector . should_equal ["A", "a", "b"] + r2 . at "Right X" . to_vector . should_equal ["A", "a", "b"] r2 . at "Y" . to_vector . should_equal [1, 1, 2] r2 . at "Z" . to_vector . should_equal [1, 2, 3] @@ -123,16 +124,16 @@ spec setup = t1 = table_builder [["X", ['s\u0301', 'S\u0301']], ["Y", [1, 2]]] t2 = table_builder [["X", ['s', 'S', 'ś']], ["Z", [1, 2, 3]]] - r1 = t1.join t2 + r1 = t1.join t2 join_kind=Join_Kind.Inner expect_column_names ["X", "Y", "Z"] r1 r1 . at "X" . to_vector . should_equal ['ś'] r1 . at "Y" . to_vector . should_equal [1] r1 . at "Z" . to_vector . should_equal [3] - r2 = t1.join t2 on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Y"] - expect_column_names ["X", "Y", "Right_X", "Z"] r2 + r2 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Y"] + expect_column_names ["X", "Y", "Right X", "Z"] r2 r2 . at "X" . to_vector . should_equal ['s\u0301', 'S\u0301'] - r2 . at "Right_X" . to_vector . should_equal ['ś', 'ś'] + r2 . at "Right X" . to_vector . should_equal ['ś', 'ś'] r2 . at "Y" . to_vector . should_equal [1, 2] r2 . at "Z" . to_vector . should_equal [3, 3] @@ -141,7 +142,7 @@ spec setup = t1 = table_builder [["X", [1, 2]], ["Y", [10, 20]]] t2 = table_builder [["X", [2.0, 2.1, 0.0]], ["Z", [1, 2, 3]]] - r1 = t1.join t2 + r1 = t1.join t2 join_kind=Join_Kind.Inner expect_column_names ["X", "Y", "Z"] r1 r1 . at "X" . to_vector . should_equal [2] r1 . at "Y" . to_vector . should_equal [20] @@ -152,14 +153,14 @@ spec setup = t1 = table_builder [["X", [My_Type.Value 1 2, My_Type.Value 2 3]], ["Y", [1, 2]]] t2 = table_builder [["X", [My_Type.Value 5 0, My_Type.Value 2 1]], ["Z", [10, 20]]] - r1 = t1.join t2 |> materialize |> _.order_by ["Y"] + r1 = t1.join t2 join_kind=Join_Kind.Inner |> materialize |> _.order_by ["Y"] expect_column_names ["X", "Y", "Z"] r1 r1 . at "X" . to_vector . should_equal [My_Type.Value 1 2, My_Type.Value 2 3] ## We don't keep the other column, because the values in both are equal. However, with custom comparators, they may not be the same values, so we may consider keeping it. For not it is dropped though for consistency. - # r1 . at "Right_X" . to_vector . should_equal [My_Type.Value 1 2, My_Type.Value 2 3] + # r1 . at "Right X" . to_vector . should_equal [My_Type.Value 1 2, My_Type.Value 2 3] r1 . at "Y" . to_vector . should_equal [1, 2] r1 . at "Z" . to_vector . should_equal [20, 10] @@ -167,7 +168,7 @@ spec setup = t1 = table_builder [["X", [1, 10, 12]], ["Y", [1, 2, 3]]] t2 = table_builder [["lower", [1, 10, 8, 12]], ["upper", [1, 12, 30, 0]], ["Z", [1, 2, 3, 4]]] - r1 = t1.join t2 on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["X", "Z"] + r1 = t1.join join_kind=Join_Kind.Inner t2 on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["X", "Z"] expect_column_names ["X", "Y", "lower", "upper", "Z"] r1 r1 . at "X" . to_vector . should_equal [1, 10, 10, 12, 12] r1 . at "Y" . to_vector . should_equal [1, 2, 2, 3, 3] @@ -179,7 +180,7 @@ spec setup = t1 = table_builder [["X", ["a", "b", "c"]], ["Y", [1, 2, 3]]] t2 = table_builder [["lower", ["a", "b"]], ["upper", ["a", "ccc"]], ["Z", [10, 20]]] - r1 = t1.join t2 on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["X", "Z"] + r1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["X", "Z"] expect_column_names ["X", "Y", "lower", "upper", "Z"] r1 r1 . at "X" . to_vector . should_equal ["a", "b", "c"] r1 . at "Y" . to_vector . should_equal [1, 2, 3] @@ -192,7 +193,7 @@ spec setup = t1 = table_builder [["X", ['s\u0301', 's']], ["Y", [1, 2]]] t2 = table_builder [["lower", ['s', 'ś']], ["upper", ['sa', 'ś']], ["Z", [10, 20]]] - r1 = t1.join t2 on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["Y"] + r1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["Y"] expect_column_names ["X", "Y", "lower", "upper", "Z"] r1 r1 . at "X" . to_vector . should_equal ['s\u0301', 's'] r1 . at "Y" . to_vector . should_equal [1, 2] @@ -205,7 +206,7 @@ spec setup = t1 = table_builder [["X", [My_Type.Value 20 30, My_Type.Value 1 2]], ["Y", [1, 2]]] t2 = table_builder [["lower", [My_Type.Value 3 0, My_Type.Value 10 10]], ["upper", [My_Type.Value 2 1, My_Type.Value 100 0]], ["Z", [10, 20]]] - r1 = t1.join t2 on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["Z"] + r1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Between "X" "lower" "upper") |> materialize |> _.order_by ["Z"] expect_column_names ["X", "Y", "lower", "upper", "Z"] r1 r1 . at "X" . to_vector . to_text . should_equal "[(My_Type.Value 1 2), (My_Type.Value 20 30)]" r1 . at "Y" . to_vector . should_equal [2, 1] @@ -217,25 +218,25 @@ spec setup = t1 = table_builder [["X", [1, 12, 12, 0]], ["Y", [1, 2, 3, 4]], ["Z", ["a", "A", "a", "ą"]], ["W", [1, 2, 3, 4]]] t2 = table_builder [["X", [12, 12, 1]], ["l", [0, 100, 100]], ["u", [10, 100, 100]], ["Z", ["A", "A", "A"]], ["W'", [10, 20, 30]]] - r1 = t1.join t2 on=[Join_Condition.Between "Y" "l" "u", Join_Condition.Equals_Ignore_Case "Z" "Z", Join_Condition.Equals "X" "X"] |> materialize |> _.order_by ["Y"] - expect_column_names ["X", "Y", "Z", "W", "l", "u", "Right_Z", "W'"] r1 + r1 = t1.join t2 join_kind=Join_Kind.Inner on=[Join_Condition.Between "Y" "l" "u", Join_Condition.Equals_Ignore_Case "Z" "Z", Join_Condition.Equals "X" "X"] |> materialize |> _.order_by ["Y"] + expect_column_names ["X", "Y", "Z", "W", "l", "u", "Right Z", "W'"] r1 r1.at "X" . to_vector . should_equal [12, 12] r1.at "Y" . to_vector . should_equal [2, 3] r1.at "Z" . to_vector . should_equal ["A", "a"] r1.at "W" . to_vector . should_equal [2, 3] r1.at "l" . to_vector . should_equal [0, 0] r1.at "u" . to_vector . should_equal [10, 10] - r1.at "Right_Z" . to_vector . should_equal ["A", "A"] + r1.at "Right Z" . to_vector . should_equal ["A", "A"] r1.at "W'" . to_vector . should_equal [10, 10] Test.specify "should work fine if the same condition is specified multiple times" <| - r = t3.join t4 on=["X", "X", "Y", "X", "Y"] |> materialize |> _.order_by ["X", "Y", "Z", "Right_Z"] + r = t3.join t4 join_kind=Join_Kind.Inner on=["X", "X", "Y", "X", "Y"] |> materialize |> _.order_by ["X", "Y", "Z", "Right Z"] check_xy_joined r t5 = table_builder [["X", [1, 10, 12]], ["Y", [1, 2, 3]]] t6 = table_builder [["lower", [1, 10, 8, 12]], ["upper", [1, 12, 30, 0]], ["Z", [1, 2, 3, 4]]] - r1 = t5.join t6 on=[Join_Condition.Between "X" "lower" "upper", Join_Condition.Between "X" "lower" "upper", Join_Condition.Between "X" "lower" "upper"] |> materialize |> _.order_by ["X", "Z"] + r1 = t5.join t6 join_kind=Join_Kind.Inner on=[Join_Condition.Between "X" "lower" "upper", Join_Condition.Between "X" "lower" "upper", Join_Condition.Between "X" "lower" "upper"] |> materialize |> _.order_by ["X", "Z"] r1 . at "X" . to_vector . should_equal [1, 10, 10, 12, 12] r1 . at "Y" . to_vector . should_equal [1, 2, 2, 3, 3] r1 . at "Z" . to_vector . should_equal [1, 2, 3, 2, 3] @@ -243,64 +244,71 @@ spec setup = t7 = table_builder [["X", ["a", "B"]], ["Y", [1, 2]]] t8 = table_builder [["X", ["A", "a", "b"]], ["Z", [1, 2, 3]]] - r2 = t7.join t8 on=[Join_Condition.Equals_Ignore_Case "X", Join_Condition.Equals_Ignore_Case "X", Join_Condition.Equals_Ignore_Case "X" "X"] |> materialize |> _.order_by ["Z"] + r2 = t7.join t8 join_kind=Join_Kind.Inner on=[Join_Condition.Equals_Ignore_Case "X", Join_Condition.Equals_Ignore_Case "X", Join_Condition.Equals_Ignore_Case "X" "X"] |> materialize |> _.order_by ["Z"] r2 . at "X" . to_vector . should_equal ["a", "a", "B"] - r2 . at "Right_X" . to_vector . should_equal ["A", "a", "b"] + r2 . at "Right X" . to_vector . should_equal ["A", "a", "b"] r2 . at "Z" . to_vector . should_equal [1, 2, 3] Test.specify "should correctly handle joining a table with itself" <| t1 = table_builder [["X", [0, 1, 2, 3, 2]], ["Y", [1, 2, 3, 4, 100]], ["A", ["B", "C", "D", "E", "X"]]] - t2 = t1.join t1 on=(Join_Condition.Equals left="X" right="Y") |> materialize |> _.order_by ["X", "Y"] + t2 = t1.join t1 join_kind=Join_Kind.Inner on=(Join_Condition.Equals left="X" right="Y") |> materialize |> _.order_by ["X", "Y"] - expect_column_names ["X", "Y", "A", "Right_X", "Right_Y", "Right_A"] t2 + expect_column_names ["X", "Y", "A", "Right X", "Right Y", "Right A"] t2 t2.at "X" . to_vector . should_equal [1, 2, 2, 3] - t2.at "Right_Y" . to_vector . should_equal [1, 2, 2, 3] + t2.at "Right Y" . to_vector . should_equal [1, 2, 2, 3] t2.at "Y" . to_vector . should_equal [2, 3, 100, 4] t2.at "A" . to_vector . should_equal ["C", "D", "X", "E"] - t2.at "Right_X" . to_vector . should_equal [0, 1, 1, 2] - t2.at "Right_A" . to_vector . should_equal ["B", "C", "C", "D"] + t2.at "Right X" . to_vector . should_equal [0, 1, 1, 2] + t2.at "Right A" . to_vector . should_equal ["B", "C", "C", "D"] - t3 = t1.join t1 join_kind=Join_Kind.Full on=(Join_Condition.Equals left="X" right="Y") |> materialize |> _.order_by ["X", "Y", "Right_X"] - expect_column_names ["X", "Y", "A", "Right_X", "Right_Y", "Right_A"] t3 + t3 = t1.join t1 join_kind=Join_Kind.Full on=(Join_Condition.Equals left="X" right="Y") |> materialize |> _.order_by ["X", "Y", "Right X"] + expect_column_names ["X", "Y", "A", "Right X", "Right Y", "Right A"] t3 t3.at "X" . to_vector . should_equal [Nothing, Nothing, 0, 1, 2, 2, 3] - t3.at "Right_Y" . to_vector . should_equal [100, 4, Nothing, 1, 2, 2, 3] + t3.at "Right Y" . to_vector . should_equal [100, 4, Nothing, 1, 2, 2, 3] t3.at "Y" . to_vector . should_equal [Nothing, Nothing, 1, 2, 3, 100, 4] t3.at "A" . to_vector . should_equal [Nothing, Nothing, "B", "C", "D", "X", "E"] - t3.at "Right_X" . to_vector . should_equal [2, 3, Nothing, 0, 1, 1, 2] - t3.at "Right_A" . to_vector . should_equal ["X", "E", Nothing, "B", "C", "C", "D"] + t3.at "Right X" . to_vector . should_equal [2, 3, Nothing, 0, 1, 1, 2] + t3.at "Right A" . to_vector . should_equal ["X", "E", Nothing, "B", "C", "C", "D"] t4 = table_builder [["X", [Nothing, "a", "B"]], ["Y", ["ą", "b", Nothing]], ["Z", [1, 2, 3]]] - t5 = t4.join t4 on=(Join_Condition.Equals_Ignore_Case left="Y" right="X") |> materialize |> _.order_by ["Y"] - expect_column_names ["X", "Y", "Z", "Right_X", "Right_Y", "Right_Z"] t5 + t5 = t4.join t4 join_kind=Join_Kind.Inner on=(Join_Condition.Equals_Ignore_Case left="Y" right="X") |> materialize |> _.order_by ["Y"] + expect_column_names ["X", "Y", "Z", "Right X", "Right Y", "Right Z"] t5 # TODO enable once we handle nothing properly # t5.at "Y" . to_vector . should_equal [Nothing, "b"] - # t5.at "Right_X" . to_vector . should_equal [Nothing, "B"] + # t5.at "Right X" . to_vector . should_equal [Nothing, "B"] # t5.at "X" . to_vector . should_equal ["B", "a"] # t5.at "Z" . to_vector . should_equal [3, 2] - # t5.at "Right_Y" . to_vector . should_equal ["ą", Nothing] - # t5.at "Right_Z" . to_vector . should_equal [1, 3] + # t5.at "Right Y" . to_vector . should_equal ["ą", Nothing] + # t5.at "Right Z" . to_vector . should_equal [1, 3] Test.specify "should gracefully handle unmatched columns in Join_Conditions" <| t1 = table_builder [["X", [1, 2]], ["Y", [3, 4]]] t2 = table_builder [["Z", [2, 1]], ["W", [5, 6]]] + # Report error if the default fails - the right table does not have a column with same name as first column of left one: + r1 = t1.join t2 + r1.should_fail_with Missing_Input_Columns + r1.catch.criteria.should_equal ["X"] + r1.catch.to_display_text.should_equal "The criteria [X] did not match any columns in the right table." + conditions = [Join_Condition.Equals "foo" 42, Join_Condition.Equals "X" -3, Join_Condition.Equals -1 "baz"] - r1 = t1.join t2 on=conditions on_problems=Problem_Behavior.Ignore + r2 = t1.join t2 on=conditions on_problems=Problem_Behavior.Ignore ## We have both - Column_Indexes_Out_Of_Range.Error [42, -3] - Missing_Input_Columns.Error ["foo", "baz"] here, but we can throw only one error. I think column names error will be more useful, so I'd prioritize it. - r1.should_fail_with Missing_Input_Columns - r1.catch.criteria.should_equal ["foo", "baz"] + r2.should_fail_with Missing_Input_Columns + r2.catch.criteria.should_equal ["foo"] + r2.catch.to_display_text.should_equal "The criteria [foo] did not match any columns in the left table." - r2 = t1.join t2 on=[Join_Condition.Equals 42 0] on_problems=Problem_Behavior.Ignore - r2.should_fail_with Column_Indexes_Out_Of_Range - r2.catch.indexes.should_equal [42] + r3 = t1.join t2 on=[Join_Condition.Equals 42 0] on_problems=Problem_Behavior.Ignore + r3.should_fail_with Column_Indexes_Out_Of_Range + r3.catch.indexes.should_equal [42] Test.specify "should report Invalid_Value_Type if non-text columns are provided to Equals_Ignore_Case" <| t1 = table_builder [["X", ["1", "2", "c"]], ["Y", [1, 2, 3]]] @@ -317,7 +325,7 @@ spec setup = Test.specify "should report Invalid_Value_Type if incompatible types are correlated" <| t1 = table_builder [["X", ["1", "2", "c"]]] - t2 = table_builder [["Y", [1, 2, 3]]] + t2 = table_builder [["X", [1, 2, 3]]] r1 = t1.join t2 on_problems=Problem_Behavior.Ignore r1.should_fail_with Invalid_Value_Type @@ -334,7 +342,7 @@ spec setup = t1 = table_builder [["X", [1.5, 2.0, 2.00000000001]], ["Y", [10, 20, 30]]] t2 = table_builder [["Z", [2.0, 1.5, 2.0]], ["W", [1, 2, 3]]] - action1 = t1.join t2 on=(Join_Condition.Equals "X" "Z") on_problems=_ + action1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "Z") on_problems=_ tester1 table = expect_column_names ["X", "Y", "Z", "W"] table t1 = table.order_by ["Y", "W"] @@ -345,7 +353,7 @@ spec setup = problems1 = [Floating_Point_Equality.Error "X", Floating_Point_Equality.Error "Z"] Problems.test_problem_handling action1 problems1 tester1 - action2 = t1.join t2 on=(Join_Condition.Equals "X" "W") on_problems=_ + action2 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "W") on_problems=_ tester2 table = expect_column_names ["X", "Y", "Z", "W"] table t1 = table.order_by ["Y", "W"] @@ -363,7 +371,7 @@ spec setup = if setup.supports_custom_objects then t1 = table_builder [["X", [My_Type.Value 1 2, 2.0, 2]], ["Y", [10, 20, 30]]] t2 = table_builder [["Z", [2.0, 1.5, 2.0]], ["W", [1, 2, 3]]] - action3 = t1.join t2 on=(Join_Condition.Equals "X" "Z") on_problems=_ + action3 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "Z") on_problems=_ tester3 table = expect_column_names ["X", "Y", "Z", "W"] table t1 = table.order_by ["Y", "W"] @@ -378,7 +386,7 @@ spec setup = t1 = table_builder [["X", ["A", Nothing, "a", Nothing, "ą"]], ["Y", [0, 1, 2, 3, 4]]] t2 = table_builder [["X", ["a", Nothing, Nothing]], ["Z", [10, 20, 30]]] - r1 = t1.join t2 |> materialize |> _.order_by ["Y"] + r1 = t1.join t2 join_kind=Join_Kind.Inner |> materialize |> _.order_by ["Y"] expect_column_names ["X", "Y", "Z"] r1 r1.at "X" . to_vector . should_equal [Nothing, Nothing, "a", Nothing, Nothing] r1.at "Y" . to_vector . should_equal [1, 1, 2, 3, 3] @@ -388,10 +396,10 @@ spec setup = t1 = table_builder [["X", ["A", Nothing, "a", Nothing, "ą"]], ["Y", [0, 1, 2, 3, 4]]] t2 = table_builder [["X", ["a", Nothing, Nothing]], ["Z", [10, 20, 30]]] - r1 = t1.join t2 on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Y"] - expect_column_names ["X", "Y", "Right_X", "Z"] r1 + r1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals_Ignore_Case "X") |> materialize |> _.order_by ["Y"] + expect_column_names ["X", "Y", "Right X", "Z"] r1 r1.at "X" . to_vector . should_equal ["A", Nothing, Nothing, "a", Nothing, Nothing] - r1.at "Right_X" . to_vector . should_equal ["a", Nothing, Nothing, "a", Nothing, Nothing] + r1.at "Right X" . to_vector . should_equal ["a", Nothing, Nothing, "a", Nothing, Nothing] r1.at "Y" . to_vector . should_equal [0, 1, 1, 2, 3, 3] r1.at "Z" . to_vector . should_equal [10, 20, 30, 10, 20, 30] @@ -399,7 +407,7 @@ spec setup = t1 = table_builder [["X", [1, Nothing, 2, Nothing]], ["Y", [0, 1, 2, 3]]] t2 = table_builder [["l", [Nothing, 0, 1]], ["u", [100, 10, Nothing]], ["Z", [10, 20, 30]]] - r1 = t1.join t2 on=(Join_Condition.Between "X" "l" "u") |> materialize |> _.order_by ["Y"] + r1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Between "X" "l" "u") |> materialize |> _.order_by ["Y"] expect_column_names ["X", "Y", "l", "u", "Z"] r1 r1.at "X" . to_vector . should_equal [1, 2] r1.at "Y" . to_vector . should_equal [0, 2] @@ -408,51 +416,55 @@ spec setup = r1.at "Z" . to_vector . should_equal [20, 20] Test.specify "should rename columns of the right table to avoid duplicates" <| - t1 = table_builder [["X", [1, 2]], ["Y", [3, 4]], ["Right_Y", [5, 6]]] + t1 = table_builder [["X", [1, 2]], ["Y", [3, 4]], ["Right Y", [5, 6]]] t2 = table_builder [["X", [2, 1]], ["Y", [2, 2]]] - t3 = t1.join t2 on=(Join_Condition.Equals "X" "Y") |> materialize |> _.order_by ["Right_X"] - Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right_Y"]] - expect_column_names ["X", "Y", "Right_Y", "Right_X", "Right_Y_1"] t3 + t3 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "Y") |> materialize |> _.order_by ["Right X"] + Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right Y"]] + t3.column_names.should_equal ["X", "Y", "Right Y", "Right X", "Right Y 1"] t3.at "X" . to_vector . should_equal [2, 2] t3.at "Y" . to_vector . should_equal [4, 4] - t3.at "Right_Y" . to_vector . should_equal [6, 6] - t3.at "Right_X" . to_vector . should_equal [1, 2] - t3.at "Right_Y_1" . to_vector . should_equal [2, 2] + t3.at "Right Y" . to_vector . should_equal [6, 6] + t3.at "Right X" . to_vector . should_equal [1, 2] + t3.at "Right Y 1" . to_vector . should_equal [2, 2] - err1 = t1.join t2 on=(Join_Condition.Equals "X" "Y") on_problems=Problem_Behavior.Report_Error + err1 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "Y") on_problems=Problem_Behavior.Report_Error err1.should_fail_with Duplicate_Output_Column_Names - err1.catch.column_names . should_equal ["Right_Y"] + err1.catch.column_names . should_equal ["Right Y"] - t4 = table_builder [["Right_X", [1, 1]], ["X", [1, 2]], ["Y", [3, 4]], ["Right_Y_2", [2, 2]]] - t5 = table_builder [["Right_X", [2, 1]], ["X", [2, 2]], ["Y", [2, 2]], ["Right_Y", [2, 2]], ["Right_Y_1", [2, 2]], ["Right_Y_4", [2, 2]]] + t4 = table_builder [["Right X", [1, 1]], ["X", [1, 2]], ["Y", [3, 4]], ["Right Y 2", [2, 2]]] + t5 = table_builder [["Right X", [2, 1]], ["X", [2, 2]], ["Y", [2, 2]], ["Right Y", [2, 2]], ["Right Y 1", [2, 2]], ["Right Y 4", [2, 2]]] t6 = t4.join t5 on=(Join_Condition.Equals "X" "Y") - expect_column_names ["Right_X", "X", "Y", "Right_Y_2"]+["Right_Right_X", "Right_X_1", "Right_Y_3", "Right_Y", "Right_Y_1", "Right_Y_4"] t6 + t6.column_names.should_equal ["Right X", "X", "Y", "Right Y 2"]+["Right Right X", "Right X 1", "Right Y 3", "Right Y", "Right Y 1", "Right Y 4"] action = t1.join t2 right_prefix="" on_problems=_ - tester = expect_column_names ["X", "Y", "Right_Y", "Y_1"] - problems = [Duplicate_Output_Column_Names.Error ["Y"]] + tester = expect_column_names ["X", "Y", "Right Y", "X 1", "Y 1"] + problems = [Duplicate_Output_Column_Names.Error ["X", "Y"]] Problems.test_problem_handling action problems tester - t8 = t1.join t2 right_prefix="P" - expect_column_names ["X", "Y", "Right_Y", "PY"] t8 + action_2 = t1.join t2 join_kind=Join_Kind.Inner right_prefix="" on_problems=_ + tester_2 = expect_column_names ["X", "Y", "Right Y", "Y 1"] + problems_2 = [Duplicate_Output_Column_Names.Error ["Y"]] + Problems.test_problem_handling action_2 problems_2 tester_2 + + t8 = t1.join t2 join_kind=Join_Kind.Inner right_prefix="P" + t8.column_names.should_equal ["X", "Y", "Right Y", "PY"] Test.specify "should warn about renamed columns" <| t1 = table_builder [["X", [1, 2]], ["Y", [3, 4]]] - t2 = table_builder [["X", [2, 1]], ["Y", [2, 2]], ["Right_Y", [2, 44]]] + t2 = table_builder [["X", [2, 1]], ["Y", [2, 2]], ["Right Y", [2, 44]]] action1 = t1.join t2 on=(Join_Condition.Equals "X" "Y") on_problems=_ tester1 table = - expect_column_names ["X", "Y", "Right_X", "Right_Y_1", "Right_Y"] table - problems1 = [Duplicate_Output_Column_Names.Error ["Right_Y"]] + expect_column_names ["X", "Y", "Right X", "Right Y 1", "Right Y"] table + problems1 = [Duplicate_Output_Column_Names.Error ["Right Y"]] Problems.test_problem_handling action1 problems1 tester1 - - action2 = t1.join t2 on=(Join_Condition.Equals "X" "X") on_problems=_ + action2 = t1.join t2 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "X" "X") on_problems=_ tester2 table = - expect_column_names ["X", "Y", "Right_Y_1", "Right_Y"] table - problems2 = [Duplicate_Output_Column_Names.Error ["Right_Y"]] + expect_column_names ["X", "Y", "Right Y 1", "Right Y"] table + problems2 = [Duplicate_Output_Column_Names.Error ["Right Y"]] Problems.test_problem_handling action2 problems2 tester2 Test.specify "should pass dataflow errors through" <| @@ -527,13 +539,13 @@ spec setup = t7 = table_builder [["A", [Nothing, 2]], ["B", [Nothing, 3]]] t8 = table_builder [["C", [2, 3]], ["D", [4, 5]]] - t9 = t7.join t8 join_kind=Join_Kind.Inner + t9 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Inner r9 = materialize t9 . order_by ["A", "B", "D"] . rows . map .to_vector within_table t9 <| r9.length . should_equal 1 r9.at 0 . should_equal [2, 3, 2, 4] - t10 = t7.join t8 join_kind=Join_Kind.Full + t10 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Full r10 = materialize t10 . order_by ["A", "C"] . rows . map .to_vector within_table t10 <| r10.length . should_equal 3 @@ -541,27 +553,27 @@ spec setup = r10.at 1 . should_equal [Nothing, Nothing, 3, 5] r10.at 2 . should_equal [2, 3, 2, 4] - t10_2 = t7.join t8 join_kind=Join_Kind.Left_Outer + t10_2 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Left_Outer r10_2 = materialize t10_2 . order_by ["A", "C"] . rows . map .to_vector within_table t10_2 <| r10_2.length . should_equal 2 r10_2.at 0 . should_equal [Nothing, Nothing, Nothing, Nothing] r10_2.at 1 . should_equal [2, 3, 2, 4] - t10_3 = t7.join t8 join_kind=Join_Kind.Right_Outer + t10_3 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Right_Outer r10_3 = materialize t10_3 . order_by ["A", "C"] . rows . map .to_vector within_table t10_3 <| r10_3.length . should_equal 2 r10_3.at 0 . should_equal [Nothing, Nothing, 3, 5] r10_3.at 1 . should_equal [2, 3, 2, 4] - t11 = t7.join t8 join_kind=Join_Kind.Left_Exclusive + t11 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Left_Exclusive r11 = materialize t11 . rows . map .to_vector within_table t11 <| r11.length . should_equal 1 r11.at 0 . should_equal [Nothing, Nothing] - t12 = t7.join t8 join_kind=Join_Kind.Right_Exclusive + t12 = t7.join t8 on=[Join_Condition.Equals "A" "C"] join_kind=Join_Kind.Right_Exclusive r12 = materialize t12 . rows . map .to_vector within_table t12 <| r12.length . should_equal 1 @@ -585,18 +597,18 @@ spec setup = t1_2 = t1.set "10*[X]+1" new_name="A" t1_3 = t1.set "[X]+20" new_name="B" - t2 = t1_2.join t1_3 on=(Join_Condition.Equals "A" "B") + t2 = t1_2.join t1_3 join_kind=Join_Kind.Inner on=(Join_Condition.Equals "A" "B") t2.at "A" . to_vector . should_equal [21] t2.at "X" . to_vector . should_equal [2] t2.at "B" . to_vector . should_equal [21] - t2.at "Right_X" . to_vector . should_equal [1] + t2.at "Right X" . to_vector . should_equal [1] t4 = table_builder [["X", [1, 2, 3]], ["Y", [10, 20, 30]]] t5 = table_builder [["X", [5, 7, 1]], ["Z", [100, 200, 300]]] t4_2 = t4.set "2*[X]+1" new_name="C" t6 = t4_2.join t5 on=(Join_Condition.Equals "C" "X") join_kind=Join_Kind.Inner - expect_column_names ["X", "Y", "C", "Right_X", "Z"] t6 + expect_column_names ["X", "Y", "C", "Right X", "Z"] t6 r2 = materialize t6 . order_by ["Y"] . rows . map .to_vector r2.length . should_equal 2 r2.at 0 . should_equal [2, 20, 5, 5, 100] @@ -607,7 +619,7 @@ spec setup = t2 = table_builder [["X", ["Ć", "A", "b"]], ["Z", [100, 200, 300]]] t3 = t1.join t2 on=(Join_Condition.Equals_Ignore_Case "X") join_kind=Join_Kind.Full - expect_column_names ["X", "Y", "Right_X", "Z"] t3 + expect_column_names ["X", "Y", "Right X", "Z"] t3 r = materialize t3 . order_by ["Y"] . rows . map .to_vector r.length . should_equal 4 r.at 0 . should_equal [Nothing, Nothing, "Ć", 100] @@ -620,7 +632,7 @@ spec setup = t4_2 = t4.set "2*[X]+1" new_name="C" t6 = t4_2.join t5 on=(Join_Condition.Equals "C" "X") join_kind=Join_Kind.Full - expect_column_names ["X", "Y", "C", "Right_X", "Z"] t6 + expect_column_names ["X", "Y", "C", "Right X", "Z"] t6 r2 = materialize t6 . order_by ["Y"] . rows . map .to_vector r2.length . should_equal 4 r2.at 0 . should_equal [Nothing, Nothing, Nothing, 1, 300] @@ -632,8 +644,8 @@ spec setup = t4_4 = t4_3.set (t4_3.at "X" . fill_nothing 7) new_name="C" t7 = t4_4.join t5 on=(Join_Condition.Equals "C" "X") join_kind=Join_Kind.Full within_table t7 <| - expect_column_names ["X", "Y", "C", "Right_X", "Z"] t7 - r3 = materialize t7 . order_by ["Y", "Right_X"] . rows . map .to_vector + expect_column_names ["X", "Y", "C", "Right X", "Z"] t7 + r3 = materialize t7 . order_by ["Y", "Right X"] . rows . map .to_vector r3.length . should_equal 5 r3.at 0 . should_equal [Nothing, Nothing, Nothing, 1, 300] r3.at 1 . should_equal [Nothing, Nothing, Nothing, 5, 100] diff --git a/test/Table_Tests/src/Common_Table_Operations/Join/Zip_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Join/Zip_Spec.enso index b186cbe73a9f..e8fb5c328fee 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Join/Zip_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Join/Zip_Spec.enso @@ -148,33 +148,33 @@ spec setup = t3.at "W" . to_vector . should_equal ['b', Nothing, Nothing] Test.specify "should rename columns of the right table to avoid duplicates" <| - t1 = table_builder [["X", [1, 2]], ["Y", [5, 6]], ["Right_Y", [7, 8]]] + t1 = table_builder [["X", [1, 2]], ["Y", [5, 6]], ["Right Y", [7, 8]]] t2 = table_builder [["X", ['a']], ["Y", ['d']]] t3 = t1.zip t2 keep_unmatched=True - expect_column_names ["X", "Y", "Right_Y", "Right_X", "Right_Y_1"] t3 - Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right_Y"]] + expect_column_names ["X", "Y", "Right Y", "Right X", "Right Y 1"] t3 + Problems.get_attached_warnings t3 . should_equal [Duplicate_Output_Column_Names.Error ["Right Y"]] t3.row_count . should_equal 2 t3.at "X" . to_vector . should_equal [1, 2] t3.at "Y" . to_vector . should_equal [5, 6] - t3.at "Right_Y" . to_vector . should_equal [7, 8] - t3.at "Right_X" . to_vector . should_equal ['a', Nothing] - t3.at "Right_Y_1" . to_vector . should_equal ['d', Nothing] + t3.at "Right Y" . to_vector . should_equal [7, 8] + t3.at "Right X" . to_vector . should_equal ['a', Nothing] + t3.at "Right Y 1" . to_vector . should_equal ['d', Nothing] t1.zip t2 keep_unmatched=False on_problems=Problem_Behavior.Report_Error . should_fail_with Duplicate_Output_Column_Names - expect_column_names ["X", "Y", "Right_Y", "X_1", "Y_1"] (t1.zip t2 right_prefix="") + expect_column_names ["X", "Y", "Right Y", "X 1", "Y 1"] (t1.zip t2 right_prefix="") - t4 = table_builder [["X", [1]], ["Right_X", [5]]] - expect_column_names ["X", "Y", "Right_Y", "Right_X_1", "Right_X"] (t1.zip t4) - expect_column_names ["X", "Right_X", "Right_X_1", "Y", "Right_Y"] (t4.zip t1) + t4 = table_builder [["X", [1]], ["Right X", [5]]] + expect_column_names ["X", "Y", "Right Y", "Right X 1", "Right X"] (t1.zip t4) + expect_column_names ["X", "Right X", "Right X 1", "Y", "Right Y"] (t4.zip t1) Test.specify "should report both row count mismatch and duplicate column warnings at the same time" <| - t1 = table_builder [["X", [1, 2]], ["Right_X", [5, 6]]] + t1 = table_builder [["X", [1, 2]], ["Right X", [5, 6]]] t2 = table_builder [["X", ['a']], ["Z", ['d']]] t3 = t1.zip t2 - expected_problems = [Row_Count_Mismatch.Error 2 1, Duplicate_Output_Column_Names.Error ["Right_X"]] + expected_problems = [Row_Count_Mismatch.Error 2 1, Duplicate_Output_Column_Names.Error ["Right X"]] Problems.get_attached_warnings t3 . should_contain_the_same_elements_as expected_problems Test.specify "should allow to zip the table with itself" <| @@ -183,12 +183,12 @@ spec setup = the Database backend. t1 = table_builder [["X", [1, 2]], ["Y", [4, 5]]] t2 = t1.zip t1 - expect_column_names ["X", "Y", "Right_X", "Right_Y"] t2 + expect_column_names ["X", "Y", "Right X", "Right Y"] t2 t2.row_count . should_equal 2 t2.at "X" . to_vector . should_equal [1, 2] t2.at "Y" . to_vector . should_equal [4, 5] - t2.at "Right_X" . to_vector . should_equal [1, 2] - t2.at "Right_Y" . to_vector . should_equal [4, 5] + t2.at "Right X" . to_vector . should_equal [1, 2] + t2.at "Right Y" . to_vector . should_equal [4, 5] if setup.is_database.not then Test.specify "should correctly pad/truncate all kinds of column types" <| diff --git a/test/Table_Tests/src/Common_Table_Operations/Select_Columns_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Select_Columns_Spec.enso index 55fdc51974a5..b79d762f1b8c 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Select_Columns_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Select_Columns_Spec.enso @@ -19,8 +19,8 @@ spec setup = col1 = ["foo", [1,2,3]] col2 = ["bar", [4,5,6]] col3 = ["Baz", [7,8,9]] - col4 = ["foo_1", [10,11,12]] - col5 = ["foo_2", [13,14,15]] + col4 = ["foo 1", [10,11,12]] + col5 = ["foo 2", [13,14,15]] col6 = ["ab.+123", [16,17,18]] col7 = ["abcd123", [19,20,21]] table_builder [col1, col2, col3, col4, col5, col6, col7] @@ -28,7 +28,7 @@ spec setup = Test.group prefix+"Table.select_columns" <| Test.specify "should work as shown in the doc examples" <| expect_column_names ["foo", "bar"] <| table.select_columns ["bar", "foo"] - expect_column_names ["bar", "Baz", "foo_1", "foo_2"] <| table.select_columns [By_Name "foo.+" use_regex=True, By_Name "b.*" use_regex=True] + expect_column_names ["bar", "Baz", "foo 1", "foo 2"] <| table.select_columns [By_Name "foo.+" use_regex=True, By_Name "b.*" use_regex=True] expect_column_names ["abcd123", "foo", "bar"] <| table.select_columns [-1, 0, 1] reorder=True Test.specify "should allow to reorder columns if asked to" <| @@ -45,13 +45,13 @@ spec setup = expect_column_names ["abcd123"] <| table.select_columns [By_Name "abcd123" Case_Sensitivity.Sensitive use_regex=True] Test.specify "should allow negative indices" <| - expect_column_names ["foo", "bar", "foo_2"] <| table.select_columns [-3, 0, 1] + expect_column_names ["foo", "bar", "foo 2"] <| table.select_columns [-3, 0, 1] Test.specify "should allow mixed names and indexes" <| - expect_column_names ["foo", "bar", "foo_2"] <| table.select_columns [-3, "bar", 0] - expect_column_names ["foo_2", "bar", "foo"] <| table.select_columns [-3, "bar", 0] reorder=True - expect_column_names ["foo", "bar", "foo_1", "foo_2", "abcd123"] <| table.select_columns [-1, "bar", By_Name "foo.*" Case_Sensitivity.Sensitive use_regex=True] - expect_column_names ["foo", "foo_1", "foo_2", "bar", "abcd123"] <| table.select_columns [By_Name "foo.*" Case_Sensitivity.Sensitive use_regex=True, "bar", "foo", -1] reorder=True + expect_column_names ["foo", "bar", "foo 2"] <| table.select_columns [-3, "bar", 0] + expect_column_names ["foo 2", "bar", "foo"] <| table.select_columns [-3, "bar", 0] reorder=True + expect_column_names ["foo", "bar", "foo 1", "foo 2", "abcd123"] <| table.select_columns [-1, "bar", By_Name "foo.*" Case_Sensitivity.Sensitive use_regex=True] + expect_column_names ["foo", "foo 1", "foo 2", "bar", "abcd123"] <| table.select_columns [By_Name "foo.*" Case_Sensitivity.Sensitive use_regex=True, "bar", "foo", -1] reorder=True if test_selection.supports_case_sensitive_columns then Test.specify "should correctly handle exact matches matching multiple names due to case insensitivity" <| @@ -63,8 +63,8 @@ spec setup = expect_column_names ["bar", "Bar"] <| table.select_columns [By_Name "bar"] Test.specify "should correctly handle regexes matching multiple names" <| - expect_column_names ["foo", "bar", "foo_1", "foo_2"] <| table.select_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] - expect_column_names ["bar", "foo", "foo_1", "foo_2"] <| table.select_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] reorder=True + expect_column_names ["foo", "bar", "foo 1", "foo 2"] <| table.select_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] + expect_column_names ["bar", "foo", "foo 1", "foo 2"] <| table.select_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] reorder=True Test.specify "should correctly handle problems: out of bounds indices" <| selector = [1, 0, 100, -200, 300] @@ -142,21 +142,21 @@ spec setup = Test.group prefix+"Table.remove_columns" <| Test.specify "should work as shown in the doc examples" <| - expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] <| table.remove_columns ["bar", "foo"] + expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] <| table.remove_columns ["bar", "foo"] expect_column_names ["foo", "ab.+123", "abcd123"] <| table.remove_columns [By_Name "foo.+" Case_Sensitivity.Insensitive use_regex=True, By_Name "b.*" Case_Sensitivity.Insensitive use_regex=True] - expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123"] <| table.remove_columns [-1, 0, 1] + expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123"] <| table.remove_columns [-1, 0, 1] Test.specify "should correctly handle regex matching" <| last_ones = table.columns.drop 1 . map .name expect_column_names last_ones <| table.remove_columns [By_Name "foo" Case_Sensitivity.Sensitive use_regex=True] - first_ones = ["foo", "bar", "Baz", "foo_1", "foo_2"] + first_ones = ["foo", "bar", "Baz", "foo 1", "foo 2"] expect_column_names first_ones <| table.remove_columns [By_Name "a.*" Case_Sensitivity.Sensitive use_regex=True] expect_column_names first_ones <| table.remove_columns [By_Name "ab.+123" Case_Sensitivity.Sensitive use_regex=True] expect_column_names first_ones+["abcd123"] <| table.remove_columns [By_Name "ab.+123"] expect_column_names first_ones+["ab.+123"] <| table.remove_columns [By_Name "abcd123" Case_Sensitivity.Sensitive use_regex=True] Test.specify "should allow negative indices" <| - expect_column_names ["Baz", "foo_1", "ab.+123"] <| table.remove_columns [-1, -3, 0, 1] + expect_column_names ["Baz", "foo 1", "ab.+123"] <| table.remove_columns [-1, -3, 0, 1] if test_selection.supports_case_sensitive_columns then Test.specify "should correctly handle exact matches matching multiple names due to case insensitivity" <| @@ -173,7 +173,7 @@ spec setup = Test.specify "should correctly handle problems: out of bounds indices" <| selector = [1, 0, 100, -200, 300] action = table.remove_columns selector on_problems=_ - tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] + tester = expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] problems = [Column_Indexes_Out_Of_Range.Error [100, -200, 300]] Problems.test_problem_handling action problems tester @@ -183,28 +183,28 @@ spec setup = Test.specify "should correctly handle edge-cases: duplicate indices" <| selector = [0, 0, 0] t = table.remove_columns selector on_problems=Problem_Behavior.Report_Error - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] t + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] t Test.specify "should correctly handle edge-cases: aliased indices" <| selector = [0, -7, -6, 1] t = table.remove_columns selector on_problems=Problem_Behavior.Report_Error - expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] t + expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] t Test.specify "should correctly handle edge-cases: duplicate names" <| selector = ["foo", "foo"] t = table.remove_columns selector on_problems=Problem_Behavior.Report_Error - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] t + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] t Test.specify "should correctly handle edge-cases: duplicate matches due to case insensitivity" <| selector = [By_Name "FOO", By_Name "foo"] t = table.remove_columns selector on_problems=Problem_Behavior.Report_Error - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] t + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] t Test.specify "should correctly handle problems: unmatched names" <| weird_name = '.*?-!@#!"' selector = ["foo", "hmm", weird_name] action = table.remove_columns selector on_problems=_ - tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] + tester = expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] problems = [Missing_Input_Columns.Error ["hmm", weird_name]] Problems.test_problem_handling action problems tester @@ -223,22 +223,22 @@ spec setup = Test.group prefix+"Table.reorder_columns" <| Test.specify "should work as shown in the doc examples" <| - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns "foo" Position.After_Other_Columns - expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo", "bar"] <| table.reorder_columns ["foo", "bar"] Position.After_Other_Columns - expect_column_names ["foo_1", "foo_2", "bar", "Baz", "foo", "ab.+123", "abcd123"] <| table.reorder_columns [By_Name "foo.+" Case_Sensitivity.Insensitive use_regex=True, By_Name "b.*" Case_Sensitivity.Insensitive use_regex=True] - expect_column_names ["bar", "foo", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] <| table.reorder_columns [1, 0] Position.Before_Other_Columns - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns [0] Position.After_Other_Columns + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns "foo" Position.After_Other_Columns + expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo", "bar"] <| table.reorder_columns ["foo", "bar"] Position.After_Other_Columns + expect_column_names ["foo 1", "foo 2", "bar", "Baz", "foo", "ab.+123", "abcd123"] <| table.reorder_columns [By_Name "foo.+" Case_Sensitivity.Insensitive use_regex=True, By_Name "b.*" Case_Sensitivity.Insensitive use_regex=True] + expect_column_names ["bar", "foo", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] <| table.reorder_columns [1, 0] Position.Before_Other_Columns + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns [0] Position.After_Other_Columns Test.specify "should correctly handle regex matching" <| - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns [By_Name "foo" Case_Sensitivity.Sensitive use_regex=True] Position.After_Other_Columns - rest = ["foo", "bar", "Baz", "foo_1", "foo_2"] + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns [By_Name "foo" Case_Sensitivity.Sensitive use_regex=True] Position.After_Other_Columns + rest = ["foo", "bar", "Baz", "foo 1", "foo 2"] expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns [By_Name "a.*" Case_Sensitivity.Sensitive use_regex=True] expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns [By_Name "ab.+123" Case_Sensitivity.Sensitive use_regex=True] expect_column_names ["ab.+123"]+rest+["abcd123"] <| table.reorder_columns ["ab.+123"] expect_column_names ["abcd123"]+rest+["ab.+123"] <| table.reorder_columns [By_Name "abcd123" Case_Sensitivity.Sensitive use_regex=True] Test.specify "should allow negative indices" <| - expect_column_names ["abcd123", "foo_2", "foo", "bar", "Baz", "foo_1", "ab.+123"] <| table.reorder_columns [-1, -3, 0, 1] + expect_column_names ["abcd123", "foo 2", "foo", "bar", "Baz", "foo 1", "ab.+123"] <| table.reorder_columns [-1, -3, 0, 1] if test_selection.supports_case_sensitive_columns then Test.specify "should correctly handle exact matches matching multiple names due to case insensitivity" <| @@ -250,12 +250,12 @@ spec setup = expect_column_names ["bar", "Bar", "foo"] <| table.reorder_columns [By_Name "bar"] Test.specify "should correctly handle regexes matching multiple names" <| - expect_column_names ["bar", "foo", "foo_1", "foo_2", "Baz", "ab.+123", "abcd123"] <| table.reorder_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] + expect_column_names ["bar", "foo", "foo 1", "foo 2", "Baz", "ab.+123", "abcd123"] <| table.reorder_columns [By_Name "b.*" Case_Sensitivity.Sensitive use_regex=True, By_Name "f.+" Case_Sensitivity.Sensitive use_regex=True] Test.specify "should correctly handle problems: out of bounds indices" <| selector = [1, 0, 100, -200, 300] action = table.reorder_columns selector on_problems=_ - tester = expect_column_names ["bar", "foo", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] + tester = expect_column_names ["bar", "foo", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123"] problems = [Column_Indexes_Out_Of_Range.Error [100, -200, 300]] Problems.test_problem_handling action problems tester @@ -265,23 +265,23 @@ spec setup = Test.specify "should correctly handle edge-cases: duplicate indices" <| selector = [0, 0, 0] t = table.reorder_columns selector Position.After_Other_Columns on_problems=Problem_Behavior.Report_Error - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] t + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] t Test.specify "should correctly handle edge-cases: aliased indices" <| selector = [0, -7, -6, 1] t = table.reorder_columns selector Position.After_Other_Columns on_problems=Problem_Behavior.Report_Error - expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo", "bar"] t + expect_column_names ["Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo", "bar"] t Test.specify "should correctly handle edge-cases: duplicate names" <| selector = ["foo", "foo"] t = table.reorder_columns selector Position.After_Other_Columns on_problems=Problem_Behavior.Report_Error - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] t + expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] t Test.specify "should correctly handle problems: unmatched names" <| weird_name = '.*?-!@#!"' selector = ["foo", "hmm", weird_name] action = table.reorder_columns selector Position.After_Other_Columns on_problems=_ - tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] + tester = expect_column_names ["bar", "Baz", "foo 1", "foo 2", "ab.+123", "abcd123", "foo"] problems = [Missing_Input_Columns.Error ["hmm", weird_name]] Problems.test_problem_handling action problems tester @@ -290,31 +290,31 @@ spec setup = Test.group prefix+"Table.sort_columns" <| table = - col1 = ["foo_21", [1,2,3]] - col2 = ["foo_100", [4,5,6]] - col3 = ["foo_1", [7,8,9]] - col4 = ["Foo_2", [10,11,12]] - col5 = ["foo_3", [13,14,15]] - col6 = ["foo_001", [16,17,18]] + col1 = ["foo 21", [1,2,3]] + col2 = ["foo 100", [4,5,6]] + col3 = ["foo 1", [7,8,9]] + col4 = ["Foo 2", [10,11,12]] + col5 = ["foo 3", [13,14,15]] + col6 = ["foo 001", [16,17,18]] col7 = ["bar", [19,20,21]] table_builder [col1, col2, col3, col4, col5, col6, col7] Test.specify "should work as shown in the doc examples" <| sorted = table.sort_columns - expect_column_names ["Foo_2", "bar", "foo_001", "foo_1", "foo_100", "foo_21", "foo_3"] sorted + expect_column_names ["Foo 2", "bar", "foo 001", "foo 1", "foo 100", "foo 21", "foo 3"] sorted sorted.columns.first.to_vector . should_equal [10,11,12] - expect_column_names ["bar", "foo_001", "foo_1", "Foo_2", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering.Case_Insensitive sort_digits_as_numbers=True) - expect_column_names ["foo_3", "foo_21", "foo_100", "foo_1", "foo_001", "bar", "Foo_2"] <| table.sort_columns Sort_Direction.Descending + expect_column_names ["bar", "foo 001", "foo 1", "Foo 2", "foo 3", "foo 21", "foo 100"] <| table.sort_columns text_ordering=(Text_Ordering.Case_Insensitive sort_digits_as_numbers=True) + expect_column_names ["foo 3", "foo 21", "foo 100", "foo 1", "foo 001", "bar", "Foo 2"] <| table.sort_columns Sort_Direction.Descending Test.specify "should correctly handle case-insensitive sorting" <| - expect_column_names ["bar", "foo_001", "foo_1", "foo_100", "Foo_2", "foo_21", "foo_3"] <| table.sort_columns text_ordering=(Text_Ordering.Case_Insensitive) + expect_column_names ["bar", "foo 001", "foo 1", "foo 100", "Foo 2", "foo 21", "foo 3"] <| table.sort_columns text_ordering=(Text_Ordering.Case_Insensitive) Test.specify "should correctly handle natural order sorting" <| - expect_column_names ["Foo_2", "bar", "foo_001", "foo_1", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering.Default sort_digits_as_numbers=True) + expect_column_names ["Foo 2", "bar", "foo 001", "foo 1", "foo 3", "foo 21", "foo 100"] <| table.sort_columns text_ordering=(Text_Ordering.Default sort_digits_as_numbers=True) Test.specify "should correctly handle various combinations of options" <| - expect_column_names ["foo_100", "foo_21", "foo_3", "Foo_2", "foo_1", "foo_001", "bar"] <| table.sort_columns Sort_Direction.Descending text_ordering=(Text_Ordering.Case_Insensitive sort_digits_as_numbers=True) + expect_column_names ["foo 100", "foo 21", "foo 3", "Foo 2", "foo 1", "foo 001", "bar"] <| table.sort_columns Sort_Direction.Descending text_ordering=(Text_Ordering.Case_Insensitive sort_digits_as_numbers=True) Test.group prefix+"Table.rename_columns" <| table = @@ -441,41 +441,41 @@ spec setup = Test.specify "should correctly handle problems: invalid names ''" <| map = Map.from_vector [[1, ""]] action = table.rename_columns map on_problems=_ - tester = expect_column_names ["alpha", "Column_1", "gamma", "delta"] + tester = expect_column_names ["alpha", "Column 1", "gamma", "delta"] problems = [Invalid_Output_Column_Names.Error [""]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: invalid names Nothing" <| map = ["alpha", Nothing] action = table.rename_columns map on_problems=_ - tester = expect_column_names ["alpha", "Column_1", "gamma", "delta"] + tester = expect_column_names ["alpha", "Column 1", "gamma", "delta"] problems = [Invalid_Output_Column_Names.Error [Nothing]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: invalid names null character" <| map = ["alpha", 'a\0b'] action = table.rename_columns map on_problems=_ - tester = expect_column_names ["alpha", "Column_1", "gamma", "delta"] + tester = expect_column_names ["alpha", "Column 1", "gamma", "delta"] problems = [Invalid_Output_Column_Names.Error ['a\0b']] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| map = ["Test", "Test", "Test", "Test"] action = table.rename_columns map on_problems=_ - tester = expect_column_names ["Test", "Test_1", "Test_2", "Test_3"] + tester = expect_column_names ["Test", "Test 1", "Test 2", "Test 3"] problems = [Duplicate_Output_Column_Names.Error ["Test", "Test", "Test"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: new name is clashing with existing name of existing column" <| map = Map.from_vector [["alpha", "beta"]] action = table.rename_columns map on_problems=_ - tester = expect_column_names ["beta", "beta_1", "gamma", "delta"] + tester = expect_column_names ["beta", "beta 1", "gamma", "delta"] problems = [Duplicate_Output_Column_Names.Error ["beta"]] Problems.test_problem_handling action problems tester map2 = Map.from_vector [["beta", "alpha"]] action2 = table.rename_columns map2 on_problems=_ - tester2 = expect_column_names ["alpha_1", "alpha", "gamma", "delta"] + tester2 = expect_column_names ["alpha 1", "alpha", "gamma", "delta"] problems2 = [Duplicate_Output_Column_Names.Error ["alpha"]] Problems.test_problem_handling action2 problems2 tester2 diff --git a/test/Table_Tests/src/Common_Table_Operations/Transpose_Spec.enso b/test/Table_Tests/src/Common_Table_Operations/Transpose_Spec.enso index 4a3d340b6739..1fa3b63e4f0e 100644 --- a/test/Table_Tests/src/Common_Table_Operations/Transpose_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Operations/Transpose_Spec.enso @@ -73,18 +73,18 @@ spec setup = Test.specify "should handle missing columns" <| t1 = table_builder [["Key", ["x", "y", "z"]], ["Value", [1, 2, 3]], ["Another", [10, Nothing, 20]]] - err1 = t1.transpose ["Key", "Missing", "Missing_2"] + err1 = t1.transpose ["Key", "Missing", "Missing 2"] err1.should_fail_with Missing_Input_Columns - err1.catch.criteria . should_equal ["Missing", "Missing_2"] + err1.catch.criteria . should_equal ["Missing", "Missing 2"] err2 = t1.transpose [0, -1, 42, -100] err2.should_fail_with Column_Indexes_Out_Of_Range err2.catch.indexes . should_equal [42, -100] - action1 = t1.transpose ["Key", "Missing", "Missing_2"] error_on_missing_columns=False on_problems=_ + action1 = t1.transpose ["Key", "Missing", "Missing 2"] error_on_missing_columns=False on_problems=_ tester1 table = table.column_names . should_equal ["Key", "Name", "Value"] - problems1 = [Missing_Input_Columns.Error ["Missing", "Missing_2"]] + problems1 = [Missing_Input_Columns.Error ["Missing", "Missing 2"]] Problems.test_problem_handling action1 problems1 tester1 action2 = t1.transpose [0, -1, 42, -100] error_on_missing_columns=False on_problems=_ @@ -98,13 +98,13 @@ spec setup = action1 = t1.transpose ["X", "Y", "Z"] name_field="Y" value_field="Z" on_problems=_ tester1 table = - table.column_names . should_equal ["X", "Y", "Z", "Y_1", "Z_1"] + table.column_names . should_equal ["X", "Y", "Z", "Y 1", "Z 1"] problems1 = [Duplicate_Output_Column_Names.Error ["Y", "Z"]] Problems.test_problem_handling action1 problems1 tester1 action2 = t1.transpose ["X"] name_field="F" value_field="F" on_problems=_ tester2 table = - table.column_names . should_equal ["X", "F", "F_1"] + table.column_names . should_equal ["X", "F", "F 1"] problems2 = [Duplicate_Output_Column_Names.Error ["F"]] Problems.test_problem_handling action2 problems2 tester2 diff --git a/test/Table_Tests/src/Database/Codegen_Spec.enso b/test/Table_Tests/src/Database/Codegen_Spec.enso index cdc4e6b8f51e..f2f12b50ec70 100644 --- a/test/Table_Tests/src/Database/Codegen_Spec.enso +++ b/test/Table_Tests/src/Database/Codegen_Spec.enso @@ -115,9 +115,9 @@ spec = Test.group "Helpers" <| Test.specify "fresh_names should provide fresh names" <| - used_names = ["A", "A_1"] + used_names = ["A", "A 1"] preferred_names = ["A", "A", "B"] - fresh_names used_names preferred_names . should_equal ["A_2", "A_3", "B"] + fresh_names used_names preferred_names . should_equal ["A 2", "A 3", "B"] Test.group "[Codegen] Aggregation" <| Test.specify "should allow to count rows" <| diff --git a/test/Table_Tests/src/Database/SQLite_Spec.enso b/test/Table_Tests/src/Database/SQLite_Spec.enso index 9702096aa2ee..615f9f4deac0 100644 --- a/test/Table_Tests/src/Database/SQLite_Spec.enso +++ b/test/Table_Tests/src/Database/SQLite_Spec.enso @@ -1,6 +1,7 @@ from Standard.Base import all import Standard.Base.Runtime.Ref.Ref import Standard.Base.Runtime.Context +import Standard.Base.Errors.File_Error.File_Error import Standard.Table.Data.Type.Value_Type.Bits from Standard.Table import Table, Value_Type @@ -154,7 +155,7 @@ sqlite_spec connection prefix = spec = enso_project.data.create_directory - file = enso_project.data / "sqlite_test.db" + file = enso_project.data / "transient" / "sqlite_test.db" file.delete_if_exists in_file_prefix = "[SQLite File] " sqlite_spec (Database.connect (SQLite file)) in_file_prefix @@ -174,11 +175,31 @@ spec = connection.execute_update 'CREATE TABLE "Dummy" ("strs" VARCHAR, "ints" INTEGER, "bools" BOOLEAN, "reals" REAL)' connection.close - Test.specify "should recognise a db file" <| - Auto_Detect.get_format (enso_project.data / "data.db") . should_be_a SQLite_Format - - Test.specify "should recognise a sqlite file" <| - Auto_Detect.get_format (enso_project.data / "data.sqlite") . should_be_a SQLite_Format + Test.specify "should recognise a SQLite database file" <| + Auto_Detect.get_reading_format file . should_be_a SQLite_Format + + Test.specify "should recognise a sqlite file by extension for writing" <| + Auto_Detect.get_writing_format (enso_project.data / "nonexistent-data.db") . should_be_a SQLite_Format + Auto_Detect.get_writing_format (enso_project.data / "nonexistent-data.sqlite") . should_be_a SQLite_Format + + Test.specify "should not recognise nonexistent or empty files for reading" <| + r1 = Data.read (enso_project.data / "nonexistent-data.db") + r1.should_fail_with File_Error + r1.catch . should_be_a File_Error.Not_Found + + empty = enso_project.data / "transient" / "empty-data.db" + "".write empty on_existing_file=Existing_File_Behavior.Overwrite . should_succeed + r2 = Data.read empty + r2.should_fail_with File_Error + r2.catch . should_be_a File_Error.Unsupported_Type + empty.delete_if_exists + + broken = enso_project.data / "transient" / "empty-data.db" + "SOME_RANDOM_DATA".write empty on_existing_file=Existing_File_Behavior.Overwrite . should_succeed + r3 = Data.read broken + r3.should_fail_with File_Error + r3.catch . should_be_a File_Error.Unsupported_Type + broken.delete_if_exists Test.specify "should connect to a db file" <| connection = Data.read file diff --git a/test/Table_Tests/src/Database/Upload_Spec.enso b/test/Table_Tests/src/Database/Upload_Spec.enso index 3e3f0bfba7b2..e3985e1f2d54 100644 --- a/test/Table_Tests/src/Database/Upload_Spec.enso +++ b/test/Table_Tests/src/Database/Upload_Spec.enso @@ -34,7 +34,7 @@ spec make_new_connection prefix persistent_connector=True = Test.group prefix+"Uploading an in-memory Table" <| in_memory_table = Table.new [["X", [1, 2, 3]], ["Y", ['a', 'b', 'c']]] Test.specify "should include the created table in the tables directory" <| - db_table = in_memory_table.create_database_table connection (Name_Generator.random_name "permanent_table_1") temporary=False + db_table = in_memory_table.create_database_table connection (Name_Generator.random_name "permanent_table 1") temporary=False Panic.with_finalizer (connection.drop_table db_table.name) <| db_table.at "X" . to_vector . should_equal [1, 2, 3] @@ -42,7 +42,7 @@ spec make_new_connection prefix persistent_connector=True = connection.query db_table.name . at "X" . to_vector . should_equal [1, 2, 3] Test.specify "should include the temporary table in the tables directory" <| - db_table = in_memory_table.create_database_table connection (Name_Generator.random_name "temporary_table_1") temporary=True + db_table = in_memory_table.create_database_table connection (Name_Generator.random_name "temporary_table 1") temporary=True db_table.at "X" . to_vector . should_equal [1, 2, 3] connection.tables.at "Name" . to_vector . should_contain db_table.name connection.query db_table.name . at "X" . to_vector . should_equal [1, 2, 3] @@ -50,7 +50,7 @@ spec make_new_connection prefix persistent_connector=True = if persistent_connector then Test.specify "should drop the temporary table after the connection is closed" <| tmp_connection = make_new_connection Nothing - db_table = in_memory_table.create_database_table tmp_connection (Name_Generator.random_name "temporary_table_2") temporary=True + db_table = in_memory_table.create_database_table tmp_connection (Name_Generator.random_name "temporary_table 2") temporary=True name = db_table.name tmp_connection.query (SQL_Query.Table_Name name) . at "X" . to_vector . should_equal [1, 2, 3] tmp_connection.close @@ -58,7 +58,7 @@ spec make_new_connection prefix persistent_connector=True = Test.specify "should preserve the regular table after the connection is closed" <| tmp_connection = make_new_connection Nothing - db_table = in_memory_table.create_database_table tmp_connection (Name_Generator.random_name "permanent_table_1") temporary=False + db_table = in_memory_table.create_database_table tmp_connection (Name_Generator.random_name "permanent_table 1") temporary=False name = db_table.name Panic.with_finalizer (connection.drop_table name) <| tmp_connection.query (SQL_Query.Table_Name name) . at "X" . to_vector . should_equal [1, 2, 3] @@ -104,14 +104,22 @@ spec make_new_connection prefix persistent_connector=True = t1 = Table.new [["X", [1, 2, 1]], ["Y", ['b', 'b', 'a']]] r1 = t1.create_database_table connection (Name_Generator.random_name "primary-key-6") temporary=True primary_key=["X"] r1.should_fail_with Non_Unique_Primary_Key + e1 = r1.catch + e1.clashing_primary_key . should_equal [1] + e1.clashing_example_row_count . should_equal 2 + e1.to_display_text . should_equal "The primary key [X] is not unique. The key [1] corresponds to 2 rows." + r2 = t1.create_database_table connection (Name_Generator.random_name "primary-key-6") temporary=True primary_key=["Y"] r2.should_fail_with Non_Unique_Primary_Key + r2.catch . clashing_primary_key . should_equal ['b'] + r3 = t1.create_database_table connection (Name_Generator.random_name "primary-key-7") temporary=True primary_key=["X", "Y"] r3.at "X" . to_vector . should_equal [1, 2, 1] t2 = Table.new [["X", [1, 2, 1]], ["Y", ['a', 'b', 'a']]] r4 = t2.create_database_table connection (Name_Generator.random_name "primary-key-7") temporary=True primary_key=["X", "Y"] r4.should_fail_with Non_Unique_Primary_Key + r4.catch . clashing_primary_key . should_equal [1, 'a'] Test.group prefix+"Persisting a Database Table (query)" <| Test.specify "should be able to create a persistent copy of a DB table" <| @@ -143,11 +151,11 @@ spec make_new_connection prefix persistent_connector=True = db_table_4 = db_table_2.join db_table_3 join_kind=Join_Kind.Left_Outer copied_table = db_table_4.create_database_table connection (Name_Generator.random_name "copied-table") temporary=True primary_key=Nothing - copied_table.column_names . should_equal ["X", "Y", "C1", "C2", "Right_X", "C3"] + copied_table.column_names . should_equal ["X", "Y", "C1", "C2", "Right X", "C3"] copied_table.at "X" . to_vector . should_equal [1, 1, 2] copied_table.at "C1" . to_vector . should_equal [101, 102, 203] copied_table.at "C2" . to_vector . should_equal ["constant_text", "constant_text", "constant_text"] - copied_table.at "Right_X" . to_vector . should_equal [Nothing, Nothing, 2] + copied_table.at "Right X" . to_vector . should_equal [Nothing, Nothing, 2] copied_table.at "C3" . to_vector . should_equal [Nothing, Nothing, 5] # We check that this is indeed querying a simple DB table and not a complex query like `db_table_4` would be, @@ -193,6 +201,22 @@ spec make_new_connection prefix persistent_connector=True = r1 = db_table.create_database_table connection (Name_Generator.random_name "copied-table") temporary=True primary_key=["X"] r1.should_fail_with Non_Unique_Primary_Key + e1 = r1.catch + e1.clashing_primary_key . should_equal [1] + e1.clashing_example_row_count . should_equal 2 + + t2 = Table.new [["X", [1, 3, 1, 2, 3, 2, 2, 2, 0]], ["Y", ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']]] + db_table_2 = t2.create_database_table connection (Name_Generator.random_name "source-table-2") temporary=True primary_key=Nothing + Problems.assume_no_problems db_table_2 + + r2 = db_table_2.create_database_table connection (Name_Generator.random_name "copied-table-2") temporary=True primary_key=["X"] + r2.should_fail_with Non_Unique_Primary_Key + e2 = r2.catch + e2.clashing_primary_key.length . should_equal 1 + x = e2.clashing_primary_key.first + [1, 2, 3].should_contain x + counts = Map.from_vector [[1, 2], [2, 4], [3, 2]] + e2.clashing_example_row_count . should_equal (counts.at x) Test.specify "will not allow to upload tables across connections" <| t = Table.new [["X", [1, 2, 1]], ["Y", ['b', 'b', 'a']]] diff --git a/test/Table_Tests/src/Helpers/Unique_Naming_Strategy_Spec.enso b/test/Table_Tests/src/Helpers/Unique_Naming_Strategy_Spec.enso index 2bc8d7f5d6cf..c9d3ef258fd1 100644 --- a/test/Table_Tests/src/Helpers/Unique_Naming_Strategy_Spec.enso +++ b/test/Table_Tests/src/Helpers/Unique_Naming_Strategy_Spec.enso @@ -30,28 +30,28 @@ spec = Test.specify 'should rename duplicates names' <| strategy = Unique_Name_Strategy.new strategy.make_unique "A" . should_equal "A" - strategy.make_unique "A" . should_equal "A_1" - strategy.make_unique "A" . should_equal "A_2" + strategy.make_unique "A" . should_equal "A 1" + strategy.make_unique "A" . should_equal "A 2" strategy.renames.length . should_equal 2 strategy.invalid_names.length . should_equal 0 Test.specify 'should preserve existing suffix' <| strategy = Unique_Name_Strategy.new strategy.make_unique "A" . should_equal "A" - strategy.make_unique "A_1" . should_equal "A_1" - strategy.make_unique "A" . should_equal "A_2" - strategy.make_unique "A_1" . should_equal "A_1_1" + strategy.make_unique "A 1" . should_equal "A 1" + strategy.make_unique "A" . should_equal "A 2" + strategy.make_unique "A 1" . should_equal "A 1 1" strategy.renames.length . should_equal 2 strategy.invalid_names.length . should_equal 0 Test.specify "should always add a counter when renaming invalid names" <| strategy = Unique_Name_Strategy.new - strategy.make_unique "" . should_equal "Column_1" - strategy.make_unique "" . should_equal "Column_2" - strategy.make_unique Nothing . should_equal "Column_3" + strategy.make_unique "" . should_equal "Column 1" + strategy.make_unique "" . should_equal "Column 2" + strategy.make_unique Nothing . should_equal "Column 3" strategy.make_unique "Foo" . should_equal "Foo" strategy.make_unique "Column" . should_equal "Column" - strategy.make_unique "" . should_equal "Column_4" + strategy.make_unique "" . should_equal "Column 4" Test.specify 'should work as in examples' <| unique_name_strategy = Unique_Name_Strategy.new @@ -60,19 +60,19 @@ spec = invalid = unique_name_strategy.invalid_names duplicates.should_equal ["A"] invalid.should_equal [""] - unique_names.should_equal ["A", "B", "A_1", "Column_1"] + unique_names.should_equal ["A", "B", "A 1", "Column 1"] strategy_1 = Unique_Name_Strategy.new strategy_1.make_unique "A" . should_equal "A" - strategy_1.make_unique "A" . should_equal "A_1" + strategy_1.make_unique "A" . should_equal "A 1" Test.group "Unique_Name_Strategy.combine_with_prefix" <| Test.specify "should work as in examples" <| strategy = Unique_Name_Strategy.new first = ["A", "B", "second_A"] - second = ["A", "B", "second_A_1", "C"] + second = ["A", "B", "second_A 1", "C"] unique_second = strategy.combine_with_prefix first second "second_" - unique_second . should_equal ["second_A_2", "second_B", "second_A_1", "C"] + unique_second . should_equal ["second_A 2", "second_B", "second_A 1", "C"] strategy.invalid_names . should_equal [] strategy.renames . should_equal ["second_A"] @@ -81,7 +81,7 @@ spec = second = ["B", "A", "C"] strategy = Unique_Name_Strategy.new r = strategy.combine_with_prefix first second "" - r . should_equal ["B_1", "A_1", "C"] + r . should_equal ["B 1", "A 1", "C"] Test.specify "should work for empty input" <| Unique_Name_Strategy.new.combine_with_prefix [] [] "" . should_equal [] @@ -89,34 +89,34 @@ spec = Unique_Name_Strategy.new.combine_with_prefix [] ["a"] "" . should_equal ["a"] Test.specify "should find the first free spot" <| - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2"] ["A"] "" . should_equal ["A_3"] - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2"] ["A_4", "A_6", "A_100", "A", "A_3"] "" . should_equal ["A_4", "A_6", "A_100", "A_5", "A_3"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2"] ["A"] "" . should_equal ["A 3"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2"] ["A 4", "A 6", "A 100", "A", "A 3"] "" . should_equal ["A 4", "A 6", "A 100", "A 5", "A 3"] - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2"] ["A"] "P_" . should_equal ["P_A"] - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2", "P_A"] ["A"] "P_" . should_equal ["P_A_1"] - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2", "P_A_1"] ["A"] "P_" . should_equal ["P_A"] - Unique_Name_Strategy.new.combine_with_prefix ["A", "A_1", "A_2", "P_A_1"] ["A", "P_A", "P_A_2"] "P_" . should_equal ["P_A_3", "P_A", "P_A_2"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2"] ["A"] "P_" . should_equal ["P_A"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2", "P_A"] ["A"] "P_" . should_equal ["P_A 1"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2", "P_A 1"] ["A"] "P_" . should_equal ["P_A"] + Unique_Name_Strategy.new.combine_with_prefix ["A", "A 1", "A 2", "P_A 1"] ["A", "P_A", "P_A 2"] "P_" . should_equal ["P_A 3", "P_A", "P_A 2"] Test.specify "will add a prefix/suffix, not increment an existing counter" <| - first = ["A", "A_1", "A_2", "A_3"] - Unique_Name_Strategy.new.combine_with_prefix first ["A_2"] "P_" . should_equal ["P_A_2"] - Unique_Name_Strategy.new.combine_with_prefix first ["A_2"] "" . should_equal ["A_2_1"] - Unique_Name_Strategy.new.combine_with_prefix first+["P_A_2"] ["A_2"] "P_" . should_equal ["P_A_2_1"] + first = ["A", "A 1", "A 2", "A 3"] + Unique_Name_Strategy.new.combine_with_prefix first ["A 2"] "P_" . should_equal ["P_A 2"] + Unique_Name_Strategy.new.combine_with_prefix first ["A 2"] "" . should_equal ["A 2 1"] + Unique_Name_Strategy.new.combine_with_prefix first+["P_A 2"] ["A 2"] "P_" . should_equal ["P_A 2 1"] Test.specify "should prioritize existing names when renaming conflicts and rename only ones that are clashing with the other list" <| first = ["A", "B"] - second = ["B", "A", "B_1", "C", "B_2", "B_4"] + second = ["B", "A", "B 1", "C", "B 2", "B_4"] strategy = Unique_Name_Strategy.new r = strategy.combine_with_prefix first second "" - r . should_equal ["B_3", "A_1", "B_1", "C", "B_2", "B_4"] + r . should_equal ["B 3", "A 1", "B 1", "C", "B 2", "B_4"] strategy.invalid_names . should_equal [] strategy.renames . should_equal ["B", "A"] r2 = Unique_Name_Strategy.new.combine_with_prefix first second "P_" - r2 . should_equal ["P_B", "P_A", "B_1", "C", "B_2", "B_4"] + r2 . should_equal ["P_B", "P_A", "B 1", "C", "B 2", "B_4"] - third = ["B", "A", "P_B", "X", "P_B_1", "P_B_2"] + third = ["B", "A", "P_B", "X", "P_B 1", "P_B 2"] r3 = Unique_Name_Strategy.new.combine_with_prefix first third "P_" - r3 . should_equal ["P_B_3", "P_A", "P_B", "X", "P_B_1", "P_B_2"] + r3 . should_equal ["P_B 3", "P_A", "P_B", "X", "P_B 1", "P_B 2"] main = Test_Suite.run_main spec diff --git a/test/Table_Tests/src/IO/Csv_Spec.enso b/test/Table_Tests/src/IO/Csv_Spec.enso index 7bfbf817c17c..56b8f0377d14 100644 --- a/test/Table_Tests/src/IO/Csv_Spec.enso +++ b/test/Table_Tests/src/IO/Csv_Spec.enso @@ -29,13 +29,13 @@ spec = Test.specify "should correctly infer types of varied-type columns" <| varied_column = (enso_project.data / "varied_column.csv") . read - c_1 = ["Column_1", ["2005-02-25", "2005-02-28", "4", "2005-03-02", Nothing, "2005-03-04", "2005-03-07", "2005-03-08"]] + c_1 = ["Column 1", ["2005-02-25", "2005-02-28", "4", "2005-03-02", Nothing, "2005-03-04", "2005-03-07", "2005-03-08"]] # We can re-enable this once date support is improved. - #c_2 = ["Column_2", ["2005-02-25", "2005-02-28", "2005-03-01", Nothing, "2005-03-03", "2005-03-04", "2005-03-07", "2005-03-08"]] - c_3 = ["Column_3", [1, 2, 3, 4, 5, Nothing, 7, 8]] - c_4 = ["Column_4", [1, 2, 3, 4, 5, 6, 7, 8]] - c_5 = ["Column_5", [1.0, 2.0, 3.0, 4.0, 5.0, 6.25, 7.0, 8.0]] - c_6 = ["Column_6", ['1', '2', '3', '4', '5', '6.25', '7', 'osiem']] + #c_2 = ["Column 2", ["2005-02-25", "2005-02-28", "2005-03-01", Nothing, "2005-03-03", "2005-03-04", "2005-03-07", "2005-03-08"]] + c_3 = ["Column 3", [1, 2, 3, 4, 5, Nothing, 7, 8]] + c_4 = ["Column 4", [1, 2, 3, 4, 5, 6, 7, 8]] + c_5 = ["Column 5", [1.0, 2.0, 3.0, 4.0, 5.0, 6.25, 7.0, 8.0]] + c_6 = ["Column 6", ['1', '2', '3', '4', '5', '6.25', '7', 'osiem']] expected = Table.new [c_1, c_3, c_4, c_5, c_6] varied_column.select_columns [0, 2, 3, 4, 5] . should_equal expected @@ -45,14 +45,14 @@ spec = name,x,y,x,y foo,10,20,30,20 t = Table.from csv (format = Delimited ",") - t.columns.map .name . should_equal ['name', 'x', 'y', 'x_1', 'y_1'] + t.columns.map .name . should_equal ['name', 'x', 'y', 'x 1', 'y 1'] Test.group 'Writing' <| Test.specify 'should properly serialize simple tables' <| varied_column = (enso_project.data / "varied_column.csv") . read res = Text.from varied_column format=(Delimited ",") exp = normalize_lines <| ''' - Column_1,Column_2,Column_3,Column_4,Column_5,Column_6 + Column 1,Column 2,Column 3,Column 4,Column 5,Column 6 2005-02-25,2005-02-25,1,1,1.0,1 2005-02-28,2005-02-28,2,2,2.0,2 4,2005-03-01,3,3,3.0,3 @@ -98,7 +98,7 @@ spec = out.delete_if_exists varied_column.write out exp = normalize_lines <| ''' - Column_1,Column_2,Column_3,Column_4,Column_5,Column_6 + Column 1,Column 2,Column 3,Column 4,Column 5,Column 6 2005-02-25,2005-02-25,1,1,1.0,1 2005-02-28,2005-02-28,2,2,2.0,2 4,2005-03-01,3,3,3.0,3 diff --git a/test/Table_Tests/src/IO/Delimited_Read_Spec.enso b/test/Table_Tests/src/IO/Delimited_Read_Spec.enso index f13068001b9f..6237f164c444 100644 --- a/test/Table_Tests/src/IO/Delimited_Read_Spec.enso +++ b/test/Table_Tests/src/IO/Delimited_Read_Spec.enso @@ -25,9 +25,9 @@ spec = simple_empty.should_equal expected_table Test.specify "should load a simple table without headers" <| - c_1 = ["Column_1", ['a', '1', '4', '7', '10']] - c_2 = ["Column_2", ['b', '2', Nothing, '8', '11']] - c_3 = ["Column_3", ['c', Nothing, '6', '9', '12']] + c_1 = ["Column 1", ['a', '1', '4', '7', '10']] + c_2 = ["Column 2", ['b', '2', Nothing, '8', '11']] + c_3 = ["Column 3", ['c', Nothing, '6', '9', '12']] expected_table = Table.new [c_1, c_2, c_3] simple_empty = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False value_formatter=Nothing) simple_empty.should_equal expected_table @@ -35,11 +35,11 @@ spec = Test.specify "should work in presence of missing headers" <| action on_problems = Data.read (enso_project.data / "missing_header.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems tester table = - table.columns.map .name . should_equal ["a", "Column_1", "c", "Column_2", "d"] + table.columns.map .name . should_equal ["a", "Column 1", "c", "Column 2", "d"] table.at "a" . to_vector . should_equal ["1"] - table.at "Column_1" . to_vector . should_equal ["2"] + table.at "Column 1" . to_vector . should_equal ["2"] table.at "c" . to_vector . should_equal ["3"] - table.at "Column_2" . to_vector . should_equal ["4"] + table.at "Column 2" . to_vector . should_equal ["4"] table.at "d" . to_vector . should_equal ["5"] problems = [Invalid_Output_Column_Names.Error [Nothing, Nothing]] Problems.test_problem_handling action problems tester @@ -49,9 +49,9 @@ spec = t1.columns.map .name . should_equal ["Code", "Index", "Flag", "Value", "ValueWithNothing", "TextWithNothing", "Hexadecimal", "Leading0s", "QuotedNumbers", "Mixed Types"] t2 = Data.read (enso_project.data / "all_text.csv") (Delimited ",") - t2.columns.map .name . should_equal ["Column_1", "Column_2"] - t2.at "Column_1" . to_vector . should_equal ["a", "c", "e", "g"] - t2.at "Column_2" . to_vector . should_equal ["b", "d", "f", "h"] + t2.columns.map .name . should_equal ["Column 1", "Column 2"] + t2.at "Column 1" . to_vector . should_equal ["a", "c", "e", "g"] + t2.at "Column 2" . to_vector . should_equal ["b", "d", "f", "h"] t3 = Data.read (enso_project.data / "two_rows1.csv") (Delimited ",") t3.columns.map .name . should_equal ["a", "b", "c"] @@ -60,16 +60,16 @@ spec = t3.at "c" . to_vector . should_equal [Nothing] t4 = Data.read (enso_project.data / "two_rows2.csv") (Delimited ",") - t4.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] - t4.at "Column_1" . to_vector . should_equal ["a", "d"] - t4.at "Column_2" . to_vector . should_equal ["b", "e"] - t4.at "Column_3" . to_vector . should_equal ["c", "f"] + t4.columns.map .name . should_equal ["Column 1", "Column 2", "Column 3"] + t4.at "Column 1" . to_vector . should_equal ["a", "d"] + t4.at "Column 2" . to_vector . should_equal ["b", "e"] + t4.at "Column 3" . to_vector . should_equal ["c", "f"] t5 = Data.read (enso_project.data / "numbers_in_header.csv") (Delimited ",") - t5.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] - t5.at "Column_1" . to_vector . should_equal ["a", "1"] - t5.at "Column_2" . to_vector . should_equal ["b", "2"] - t5.at "Column_3" . to_vector . should_equal [0, 3] + t5.columns.map .name . should_equal ["Column 1", "Column 2", "Column 3"] + t5.at "Column 1" . to_vector . should_equal ["a", "1"] + t5.at "Column 2" . to_vector . should_equal ["b", "2"] + t5.at "Column 3" . to_vector . should_equal [0, 3] t6 = Data.read (enso_project.data / "quoted_numbers_in_header.csv") (Delimited ",") t6.columns.map .name . should_equal ["1", "x"] @@ -78,10 +78,10 @@ spec = Test.specify "should not use the first row as headers if it is the only row, unless specifically asked to" <| t1 = Data.read (enso_project.data / "one_row.csv") (Delimited ",") - t1.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] - t1.at "Column_1" . to_vector . should_equal ["x"] - t1.at "Column_2" . to_vector . should_equal ["y"] - t1.at "Column_3" . to_vector . should_equal ["z"] + t1.columns.map .name . should_equal ["Column 1", "Column 2", "Column 3"] + t1.at "Column 1" . to_vector . should_equal ["x"] + t1.at "Column 2" . to_vector . should_equal ["y"] + t1.at "Column 3" . to_vector . should_equal ["z"] t2 = Data.read (enso_project.data / "one_row.csv") (Delimited "," headers=True) t2.columns.map .name . should_equal ["x", "y", "z"] @@ -138,10 +138,10 @@ spec = format = Delimited ',' headers=False value_formatter=(Data_Formatter.Value trim_values=False) - reference_table = Table.new [["Column_1", ["a", "d", "1"]], ["Column_2", ["b", "e", "2"]], ["Column_3", ["c", "f", "3"]]] + reference_table = Table.new [["Column 1", ["a", "d", "1"]], ["Column 2", ["b", "e", "2"]], ["Column 3", ["c", "f", "3"]]] collapsed_table = Table.new <| ['a', 'b', 'c\nd', 'e', 'f\n1', 2, 3].map_with_index i-> v-> - ["Column_" + (i+1).to_text, [v]] + ["Column " + (i+1).to_text, [v]] Data.read file format . should_equal reference_table Data.read file (format.with_line_endings Line_Ending_Style.Unix) . should_equal reference_table Data.read file (format.with_line_endings Line_Ending_Style.Mac_Legacy) . should_equal collapsed_table @@ -201,9 +201,9 @@ spec = Test.specify "should handle duplicated columns" <| action on_problems = Data.read (enso_project.data / "duplicated_columns.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems tester table = - table.columns.map .name . should_equal ['a', 'b', 'c', 'a_1'] + table.columns.map .name . should_equal ['a', 'b', 'c', 'a 1'] table.at 'a' . to_vector . should_equal ['1'] - table.at 'a_1' . to_vector . should_equal ['4'] + table.at 'a 1' . to_vector . should_equal ['4'] problems = [Duplicate_Output_Column_Names.Error ['a']] Problems.test_problem_handling action problems tester @@ -337,7 +337,7 @@ spec = Test.specify "should allow to skip rows" <| t1 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 value_formatter=Nothing) - t1.at "Column_1" . to_vector . should_equal ['7', '10'] + t1.at "Column 1" . to_vector . should_equal ['7', '10'] t2 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True skip_rows=3 value_formatter=Nothing) t2.columns.map .name . should_equal ['7', '8', '9'] @@ -345,16 +345,16 @@ spec = Test.specify "should allow to set a limit of rows to read" <| t1 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False row_limit=2 value_formatter=Nothing) - t1.at "Column_1" . to_vector . should_equal ['a', '1'] + t1.at "Column 1" . to_vector . should_equal ['a', '1'] t2 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True row_limit=2 value_formatter=Nothing) t2.at "a" . to_vector . should_equal ['1', '4'] t3 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 row_limit=1 value_formatter=Nothing) - t3.at "Column_1" . to_vector . should_equal ['7'] + t3.at "Column 1" . to_vector . should_equal ['7'] t4 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False row_limit=0 value_formatter=Nothing) - t4.columns.map .name . should_equal ['Column_1', 'Column_2', 'Column_3'] + t4.columns.map .name . should_equal ['Column 1', 'Column 2', 'Column 3'] t4.row_count . should_equal 0 t5 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True row_limit=0 value_formatter=Nothing) @@ -363,7 +363,7 @@ spec = t5.row_count . should_equal 0 t6 = Data.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 row_limit=1000 value_formatter=Nothing) - t6.at "Column_1" . to_vector . should_equal ['7', '10'] + t6.at "Column 1" . to_vector . should_equal ['7', '10'] Test.specify "should check arguments" <| path = (enso_project.data / "simple_empty.csv") diff --git a/test/Table_Tests/src/IO/Delimited_Write_Spec.enso b/test/Table_Tests/src/IO/Delimited_Write_Spec.enso index 086ebc14fa1c..3f57f964d4ba 100644 --- a/test/Table_Tests/src/IO/Delimited_Write_Spec.enso +++ b/test/Table_Tests/src/IO/Delimited_Write_Spec.enso @@ -347,7 +347,7 @@ spec = with_headers = base_format . with_headers expected_table_with_headers = Table.new [["A", [1,2,33,44]], ["B", [1.0,1.5,Nothing,0]], ["C", ["x","y","a","BB"]]] - expected_table_without_headers = expected_table_with_headers.rename_columns ["Column_1", "Column_2", "Column_3"] + expected_table_without_headers = expected_table_with_headers.rename_columns ["Column 1", "Column 2", "Column 3"] test_append initial_file_format=with_headers append_format=no_headers expected_table_with_headers test_append initial_file_format=with_headers append_format=base_format expected_table_with_headers diff --git a/test/Table_Tests/src/IO/Excel_Spec.enso b/test/Table_Tests/src/IO/Excel_Spec.enso index 9daa23cf7d65..239b449363c6 100644 --- a/test/Table_Tests/src/IO/Excel_Spec.enso +++ b/test/Table_Tests/src/IO/Excel_Spec.enso @@ -47,8 +47,8 @@ spec_fmt header file read_method sheet_count=5 = Test.specify "should gracefully handle duplicate column names and formulas" <| t = read_method file (Excel (Worksheet "Duplicate Columns")) - t.columns.map .name . should_equal ['Item', 'Price', 'Quantity', 'Price_1'] - t.at 'Price_1' . to_vector . should_equal [20, 40, 0, 60, 0, 10] + t.columns.map .name . should_equal ['Item', 'Price', 'Quantity', 'Price 1'] + t.at 'Price 1' . to_vector . should_equal [20, 40, 0, 60, 0, 10] Test.specify "should allow reading with cell range specified" <| t_1 = read_method file (Excel (Cell_Range "Simple!B:C")) @@ -292,8 +292,8 @@ spec_write suffix test_sheet_name = Test.specify 'should be able to append to a range by name after deduplication of names' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['AA_1',[True, False]], ['BB_1', ['2022-01-20', '2022-01-21']]] - expected = Table.new [['AA', ['f', 'g', 'h', 'd', 'e']], ['BB',[1, 2, 3, 4, 5]], ['AA_1',[True, False, False, True, False]]] + extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['AA 1',[True, False]], ['BB 1', ['2022-01-20', '2022-01-21']]] + expected = Table.new [['AA', ['f', 'g', 'h', 'd', 'e']], ['BB',[1, 2, 3, 4, 5]], ['AA 1',[True, False, False, True, False]]] extra_another.write out (Excel (Cell_Range "Random!S3")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed written = out.read (Excel (Cell_Range "Random!S3")) . select_columns [0, 1, 2] written.should_equal expected @@ -725,10 +725,10 @@ spec = check_table (file.read (Excel (Cell_Range "Sheet1!B2"))) ["B"] [["A","B","C","D","E","F"]] Test.specify "Patchy table" <| - check_table (file.read (Excel (Cell_Range "Sheet1!D1"))) ["A", "B", "Column_1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] + check_table (file.read (Excel (Cell_Range "Sheet1!D1"))) ["A", "B", "Column 1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] check_table (file.read (Excel (Cell_Range "Sheet1!D2"))) ["D", "E", "F"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] check_table (file.read (Excel (Cell_Range "Sheet1!E"))) ["B"] [[4,4,Nothing,Nothing,Nothing,Nothing]] - check_table (file.read (Excel (Cell_Range "Sheet1!E1"))) ["B", "Column_1"] [[4,4,Nothing], [6,Nothing,6]] + check_table (file.read (Excel (Cell_Range "Sheet1!E1"))) ["B", "Column 1"] [[4,4,Nothing], [6,Nothing,6]] check_table (file.read (Excel (Cell_Range "Sheet1!E2"))) ["E", "F"] [[4,4,Nothing], [6,Nothing,6]] Test.specify "Single cell" <| @@ -739,19 +739,19 @@ spec = check_table (file.read (Excel (Cell_Range "Sheet1!J1"))) ["J", "K", "L"] [["Just"],["Some"],["Headers"]] Test.specify "Growing table" <| - check_table (file.read (Excel (Cell_Range "Sheet1!N1"))) ["A", "Full", "Table", "Column_1"] [["Hello","World",Nothing,"Extend"],[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] - check_table (file.read (Excel (Cell_Range "Sheet1!O1"))) ["Full", "Table", "Column_1"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] + check_table (file.read (Excel (Cell_Range "Sheet1!N1"))) ["A", "Full", "Table", "Column 1"] [["Hello","World",Nothing,"Extend"],[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] + check_table (file.read (Excel (Cell_Range "Sheet1!O1"))) ["Full", "Table", "Column 1"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] check_table (file.read (Excel (Cell_Range "Sheet1!O2"))) ["O", "P", "Q"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] Test.specify "Should handle invalid headers with warnings" <| action = file.read (Excel (Cell_Range "Sheet1!D1")) on_problems=_ - tester = check_table _ ["A", "B", "Column_1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] + tester = check_table _ ["A", "B", "Column 1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] problems = [Invalid_Output_Column_Names.Error [""]] Problems.test_problem_handling action problems tester Test.specify "Should handle duplicate headers with warnings" <| action = file.read (Excel (Cell_Range "Sheet1!S1")) on_problems=_ - tester = check_table _ ["DD", "DD_1"] [[1,3], [2,4]] + tester = check_table _ ["DD", "DD 1"] [[1,3], [2,4]] problems = [Duplicate_Output_Column_Names.Error ["DD"]] Problems.test_problem_handling action problems tester diff --git a/test/Table_Tests/src/In_Memory/Column_Format_Spec.enso b/test/Table_Tests/src/In_Memory/Column_Format_Spec.enso new file mode 100644 index 000000000000..95b2d4d50950 --- /dev/null +++ b/test/Table_Tests/src/In_Memory/Column_Format_Spec.enso @@ -0,0 +1,337 @@ +from Standard.Base import all +from Standard.Table.Data.Column_Format import all + +import Standard.Base.Data.Locale.Locale +import Standard.Base.Data.Time.Date.Date +import Standard.Base.Data.Time.Date_Time.Date_Time +import Standard.Base.Data.Time.Time_Of_Day.Time_Of_Day +import Standard.Base.Errors.Illegal_Argument.Illegal_Argument +import Standard.Table.Data.Type.Value_Type.Bits +import Standard.Test.Extensions + +from Standard.Table import Column, Value_Type +from Standard.Table.Errors import Invalid_Value_Type +from Standard.Test import Test, Test_Suite +from project.Util import all + +spec = + Test.group "Date Column.format, with format string" <| + Test.specify "Date column" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + expected = Column.from_vector "values" ["20201221", "20230425"] + actual = input.format "yyyyMMdd" + actual . should_equal expected + + Test.specify "Date with locale" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25] + expected_default = Column.from_vector "values" ["21. Jun 2020", "25. Apr 2023"] + expected_gb = Column.from_vector "values" ["21. Jun 2020", "25. Apr 2023"] + expected_fr = Column.from_vector "values" ["21. juin 2020", "25. avril 2023"] + input.format "d. MMMM yyyy" . should_equal expected_default + input.format "d. MMMM yyyy" (Locale.default) . should_equal expected_default + input.format "d. MMMM yyyy" (Locale.new "gb") . should_equal expected_gb + input.format "d. MMMM yyyy" (Locale.new "fr") . should_equal expected_fr + + Test.specify "Empty/Nothing format" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + expected = Column.from_vector "values" ['2020-12-21', '2023-04-25'] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25] + input.format "DDDDD" . should_fail_with Illegal_Argument + + Test.group "Date Column.format, with format Column" <| + Test.specify "Date column" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + formats = Column.from_vector "formats" ["yyyyMMdd", "dd-MM-yyyy"] + expected = Column.from_vector "values" ["20201221", "25-04-2023"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Date with locale" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25] + formats = Column.from_vector "formats" ["d. MMMM yyyy", "d-MMMM-yyyy"] + expected = Column.from_vector "values" ["21. juin 2020", "25-avril-2023"] + input.format formats (Locale.new "fr") . should_equal expected + + Test.specify "Empty/Nothing format, with format Column" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + formats = Column.from_vector "formats" ["", Nothing] + expected = Column.from_vector "values" ["2020-12-21", "2023-04-25"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25, Date.new 2023 4 26] + formats = Column.from_vector "formats" ["yyyyMMdd", "DDDDD", "FFF"] + input.format formats . should_fail_with Illegal_Argument + + Test.specify "Bad format column type" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25, Date.new 2023 4 26] + formats = Column.from_vector "formats" [3, 4, 5] + input.format formats . should_fail_with Invalid_Value_Type + + Test.specify "column length mismatch" <| + input = Column.from_vector "values" [Date.new 2020 6 21, Date.new 2023 4 25] + formats = Column.from_vector "formats" ["yyyyMMdd", "DDDDD", "w"] + input.format formats . should_fail_with Illegal_Argument + + Test.group "Date_Time Column.format, with format string" <| + Test.specify "Date_Time column" <| + input = Column.from_vector "values" [Date_Time.new 2020 12 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + expected = Column.from_vector "values" ["20201221 08.10.20", "20230425 14.25.02"] + actual = input.format "yyyyMMdd HH.mm.ss" + actual . should_equal expected + + Test.specify "Date_Time with locale" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + expected_default = Column.from_vector "values" ["21. Jun 2020 08.10.20", "25. Apr 2023 14.25.02"] + expected_gb = Column.from_vector "values" ["21. Jun 2020 08.10.20", "25. Apr 2023 14.25.02"] + expected_fr = Column.from_vector "values" ["21. juin 2020 08.10.20", "25. avril 2023 14.25.02"] + input.format "d. MMMM yyyy HH.mm.ss" . should_equal expected_default + input.format "d. MMMM yyyy HH.mm.ss" (Locale.default) . should_equal expected_default + input.format "d. MMMM yyyy HH.mm.ss" (Locale.new "gb") . should_equal expected_gb + input.format "d. MMMM yyyy HH.mm.ss" (Locale.new "fr") . should_equal expected_fr + + Test.specify "Empty/Nothing format" <| + zone = Time_Zone.parse "US/Hawaii" + input = Column.from_vector "values" [Date_Time.new 2020 12 21 8 10 20 zone=zone, Date_Time.new 2023 4 25 14 25 2 zone=zone] + expected = Column.from_vector "values" ['2020-12-21T08:10:20-10:00[US/Hawaii]', '2023-04-25T14:25:02-10:00[US/Hawaii]'] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + input.format "DDDDD" . should_fail_with Illegal_Argument + + Test.group "Date_Time Column.format, with format Column" <| + Test.specify "Date_Time column" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + formats = Column.from_vector "formats" ["yyyyMMdd HH.mm.ss", "dd-MM-yyyy HH.mm.ss"] + expected = Column.from_vector "values" ["20200621 08.10.20", "25-04-2023 14.25.02"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Date_Time with locale" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + formats = Column.from_vector "formats" ["d. MMMM yyyy HH.mm.ss", "d-MMMM-yyyy HH.mm.ss"] + expected = Column.from_vector "values" ["21. juin 2020 08.10.20", "25-avril-2023 14.25.02"] + input.format formats (Locale.new "fr") . should_equal expected + + Test.specify "Empty/Nothing format, with format Column" <| + zone = Time_Zone.parse "US/Hawaii" + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20 zone=zone, Date_Time.new 2023 4 25 14 25 2 zone=zone] + formats = Column.from_vector "formats" ["", Nothing] + expected = Column.from_vector "values" ['2020-06-21T08:10:20-10:00[US/Hawaii]', '2023-04-25T14:25:02-10:00[US/Hawaii]'] + actual = input.format formats + actual . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2, Date_Time.new 2023 4 26 3 4 5] + formats = Column.from_vector "formats" ["yyyyMMdd HH.mm.ss", "DDDDD", "FFF"] + input.format formats . should_fail_with Illegal_Argument + + Test.specify "Bad format column type" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + formats = Column.from_vector "formats" [3, 4, 5] + input.format formats . should_fail_with Invalid_Value_Type + + Test.specify "column length mismatch" <| + input = Column.from_vector "values" [Date_Time.new 2020 6 21 8 10 20, Date_Time.new 2023 4 25 14 25 2] + formats = Column.from_vector "formats" ["yyyyMMdd", "DDDDD", "w"] + input.format formats . should_fail_with Illegal_Argument + + Test.group "Time_Of_Day Column.format, with format string" <| + Test.specify "Time_Of_Day column" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + expected = Column.from_vector "values" ["08.10.20", "14.25.02"] + actual = input.format "HH.mm.ss" + actual . should_equal expected + + Test.specify "Time_Of_Day with locale" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + # Note that the results are all the same. + expected = Column.from_vector "values" ["08.10.20", "14.25.02"] + input.format "HH.mm.ss" . should_equal expected + input.format "HH.mm.ss" (Locale.default) . should_equal expected + input.format "HH.mm.ss" (Locale.new "gb") . should_equal expected + + Test.specify "Empty/Nothing format" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + expected = Column.from_vector "values" ['08:10:20', '14:25:02'] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + input.format "DDDDD" . should_fail_with Illegal_Argument + + Test.specify "Format for wrong date type" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + input.format "yyyyMMdd HH.mm.ss" . should_fail_with Illegal_Argument + + Test.group "Time_Of_Day Column.format, with format Column" <| + Test.specify "Time_Of_Day column" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + formats = Column.from_vector "formats" ["HH.mm.ss", "ss mm HH"] + expected = Column.from_vector "values" ["08.10.20", "02 25 14"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Time_Of_Day with locale" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + formats = Column.from_vector "formats" ["HH.mm.ss", "ss mm HH"] + expected = Column.from_vector "values" ["08.10.20", "02 25 14"] + input.format formats (Locale.new "fr") . should_equal expected + + Test.specify "Empty/Nothing format, with format Column" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + formats = Column.from_vector "formats" ["", Nothing] + expected = Column.from_vector "values" ["08:10:20", "14:25:02"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2, Time_Of_Day.new 3 4 5] + formats = Column.from_vector "formats" ["HH.mm.ss", "DDDDD", "FFF"] + input.format formats . should_fail_with Illegal_Argument + + Test.specify "Bad format column type" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + formats = Column.from_vector "formats" [3, 4, 5] + input.format formats . should_fail_with Invalid_Value_Type + + Test.specify "column length mismatch" <| + input = Column.from_vector "values" [Time_Of_Day.new 8 10 20, Time_Of_Day.new 14 25 2] + formats = Column.from_vector "formats" ["yyyyMMdd", "DDDDD", "w"] + input.format formats . should_fail_with Illegal_Argument + + Test.group "Boolean Column.format, with format string" <| + Test.specify "Boolean column" <| + input = Column.from_vector "values" [True, False] + expected = Column.from_vector "values" ["t", "f"] + actual = input.format "t|f" + actual . should_equal expected + + Test.specify "Empty/Nothing format" <| + input = Column.from_vector "values" [True, False] + expected = Column.from_vector "values" ["True", "False"] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [True, False] + input.format "x|y|z" . should_fail_with Illegal_Argument + + Test.group "Boolean Column.format, with format Column" <| + Test.specify "Time_Of_Day column" <| + input = Column.from_vector "values" [True, False, True, False] + formats = Column.from_vector "formats" ["True|False", "True|False", "troo|valz", "troo|valz"] + expected = Column.from_vector "values" ["True", "False", "troo", "valz"] + actual = input.format formats + actual . should_equal expected + + Test.specify "Empty/Nothing format, with format Column" <| + input = Column.from_vector "values" [True, False] + formats = Column.from_vector "formats" ["", Nothing] + expected = Column.from_vector "values" ["True", "False"] + input.format formats . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" [True, False] + formats = Column.from_vector "formats" ["True|False", "xyzzy"] + input.format formats . should_fail_with Illegal_Argument + + spec_with_numeric_type "Integer" (Value_Type.Integer Bits.Bits_64) + spec_with_numeric_type "Float" (Value_Type.Float Bits.Bits_64) + + Test.group "Integer" <| + Test.specify "Integer Column (constructing the column directly from Integers)" <| + input = Column.from_vector "values" [100000000, 2222, 3] + expected = Column.from_vector "values" ["100,000,000.00", "2,222.00", "3.00"] + input.format "#,##0.00" . should_equal expected + + Test.group "Numeric, empty/Nothing" <| + Test.specify "Integer" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse (Value_Type.Integer Bits.Bits_64) + expected = Column.from_vector "values" ["100000000", "2222", "3"] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Float" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse (Value_Type.Float Bits.Bits_64) + expected = Column.from_vector "values" ['1.0E8', '2222.0', '3.0'] + input.format . should_equal expected + input.format "" . should_equal expected + input.format Nothing . should_equal expected + + Test.specify "Integer, with format Column" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse (Value_Type.Integer Bits.Bits_64) + formats = Column.from_vector "formats" ["", Nothing, Nothing] + expected = Column.from_vector "values" ["100000000", "2222", "3"] + input.format formats . should_equal expected + + Test.specify "Float, with format Column" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse (Value_Type.Float Bits.Bits_64) + formats = Column.from_vector "formats" ["", Nothing, Nothing] + expected = Column.from_vector "values" ['1.0E8', '2222.0', '3.0'] + input.format formats . should_equal expected + + Test.group "Errors" <| + Test.specify "Unsupported column type" <| + input = Column.from_vector "values" ["100000000", "hey", "3"] + input.format "xyz" . should_fail_with Illegal_Argument + + Test.specify "Format is not text" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] + input.format 73 . should_fail_with Illegal_Argument + + Test.group "Edge cases" <| + Test.specify "empty table is ok" <| + input = Column.from_vector "values" [Date.new 2020 12 21, Date.new 2023 4 25] . take 0 + expected = Column.from_vector "values" [] + actual = input.format "yyyyMMdd" + actual . should_equal expected + +spec_with_numeric_type name numeric_type = + Test.group name <| + Test.specify "Column" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + expected = Column.from_vector "values" ["100,000,000.00", "2,222.00", "3.00"] + input.format "#,##0.00" . should_equal expected + + Test.specify "Column with locale" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + expected = Column.from_vector "values" ["100 000 000,00", "2 222,00", "3,00"] + input.format "#,##0.00" locale=(Locale.new "fr") . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + input.format "#.##0,00" . should_fail_with Illegal_Argument + + Test.group name+", with format Column" <| + Test.specify "Column" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + formats = Column.from_vector "formats" ["#,##0.00", "0.00", "0"] + expected = Column.from_vector "values" ["100,000,000.00", "2222.00", "3"] + input.format formats . should_equal expected + + Test.specify "Column with locale" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + formats = Column.from_vector "formats" ["#,##0.00", "0.00", "0"] + expected = Column.from_vector "values" ["100 000 000,00", "2222,00", "3"] + input.format formats locale=(Locale.new "fr") . should_equal expected + + Test.specify "Bad format" <| + input = Column.from_vector "values" ["100000000", "2222", "3"] . parse numeric_type + formats = Column.from_vector "formats" ["#,##0.00", "#.##0,00", "0"] + input.format formats . should_fail_with Illegal_Argument + +main = Test_Suite.run_main spec diff --git a/test/Table_Tests/src/In_Memory/Column_Spec.enso b/test/Table_Tests/src/In_Memory/Column_Spec.enso index 97426a5f9f2e..6318ad66d212 100644 --- a/test/Table_Tests/src/In_Memory/Column_Spec.enso +++ b/test/Table_Tests/src/In_Memory/Column_Spec.enso @@ -66,10 +66,10 @@ spec = Test.group "Columns" <| r.to_vector . should_equal [0, 2, 4, 5, Nothing, 30] Test.specify "should allow to count duplicate value occurences" <| - c_1 = Column.from_vector "c_1" [0, 1, 2, 2, 1, 0, 2] + c_1 = Column.from_vector "c 1" [0, 1, 2, 2, 1, 0, 2] c_1.duplicate_count.to_vector.should_equal [0, 0, 0, 1, 1, 1, 2] - c_2 = Column.from_vector "c_2" ["foo", "bar", "foo", "baz", "bar"] + c_2 = Column.from_vector "c 2" ["foo", "bar", "foo", "baz", "bar"] c_2.duplicate_count.to_vector.should_equal [0, 0, 1, 0, 1] Test.specify "should result in correct Storage if operation allows it" <| diff --git a/test/Table_Tests/src/In_Memory/Join_Performance_Spec.enso b/test/Table_Tests/src/In_Memory/Join_Performance_Spec.enso index be94acae6712..5014a25555f1 100644 --- a/test/Table_Tests/src/In_Memory/Join_Performance_Spec.enso +++ b/test/Table_Tests/src/In_Memory/Join_Performance_Spec.enso @@ -76,7 +76,7 @@ spec = t4 = r2.second . order_by "N" t4.row_count . should_equal n t4.at "X" . to_vector . should_equal lowers - t4.at "Right_X" . to_vector . should_equal uppers + t4.at "Right X" . to_vector . should_equal uppers t4.at "Z" . to_vector . should_equal <| 1.up_to n+1 . to_vector . reverse base_ms = r1.first.total_milliseconds diff --git a/test/Table_Tests/src/In_Memory/Main.enso b/test/Table_Tests/src/In_Memory/Main.enso index 5c64f9e67ea3..1a9c7a5fc294 100644 --- a/test/Table_Tests/src/In_Memory/Main.enso +++ b/test/Table_Tests/src/In_Memory/Main.enso @@ -5,6 +5,7 @@ from Standard.Test import Test_Suite import project.In_Memory.Aggregate_Column_Spec import project.In_Memory.Builders_Spec import project.In_Memory.Column_Spec +import project.In_Memory.Column_Format_Spec import project.In_Memory.Common_Spec import project.In_Memory.Join_Performance_Spec import project.In_Memory.Parse_To_Table_Spec @@ -17,6 +18,7 @@ import project.In_Memory.Table_Time_Of_Day_Spec spec = Table_Spec.spec Column_Spec.spec + Column_Format_Spec.spec Common_Spec.spec Table_Date_Spec.spec Table_Date_Time_Spec.spec diff --git a/test/Table_Tests/src/In_Memory/Split_Tokenize_Spec.enso b/test/Table_Tests/src/In_Memory/Split_Tokenize_Spec.enso index 07f866df508c..47ebbf009280 100644 --- a/test/Table_Tests/src/In_Memory/Split_Tokenize_Spec.enso +++ b/test/Table_Tests/src/In_Memory/Split_Tokenize_Spec.enso @@ -14,7 +14,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]]] t = Table.new cols expected_rows = [[0, "a", "c", Nothing], [1, "c", "d", "ef"], [2, "gh", "ij", "u"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.split_to_columns "bar" "b" t2.should_equal expected @@ -30,7 +30,7 @@ spec = cols = [["foo", [0, 1, 2, 3]], ["bar", ["abc", "cbdbef", Nothing, "ghbijbu"]]] t = Table.new cols expected_rows = [[0, "a", "c", Nothing], [1, "c", "d", "ef"], [2, Nothing, Nothing, Nothing], [3, "gh", "ij", "u"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.split_to_columns "bar" "b" t2.should_equal expected @@ -42,12 +42,20 @@ spec = t2 = t.split_to_rows "bar" "b" t2.should_equal expected + Test.specify "can do split_to_columns with one output column, no column suffix added" <| + cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]]] + t = Table.new cols + expected_rows = [[0, "abc"], [1, "cbdbef"], [2, "ghbijbu"]] + expected = Table.from_rows ["foo", "bar"] expected_rows + t2 = t.split_to_columns "bar" "q" + t2.should_equal expected + Test.group "Table.tokenize" <| Test.specify "can do tokenize_to_columns" <| cols = [["foo", [0, 1, 2]], ["bar", ["a12b34r5", "23", "2r4r55"]]] t = Table.new cols expected_rows = [[0, "12", "34", "5"], [1, "23", Nothing, Nothing], [2, "2", "4", "55"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.tokenize_to_columns "bar" "\d+" t2.should_equal expected @@ -63,7 +71,7 @@ spec = cols = [["foo", [0, 1, 2, 3]], ["bar", ["a12b34r5", Nothing, "23", "2r4r55"]]] t = Table.new cols expected_rows = [[0, "12", "34", "5"], [1, Nothing, Nothing, Nothing], [2, "23", Nothing, Nothing], [3, "2", "4", "55"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.tokenize_to_columns "bar" "\d+" t2.should_equal expected @@ -75,6 +83,14 @@ spec = t2 = t.tokenize_to_rows "bar" "\d+" t2.should_equal expected + Test.specify "can do tokenize_to_columns with one output column, no column suffix needed" <| + cols = [["foo", [0, 1, 2]], ["bar", ["a12b", "23", "2r"]]] + t = Table.new cols + expected_rows = [[0, "12"], [1, "23"], [2, "2"]] + expected = Table.from_rows ["foo", "bar"] expected_rows + t2 = t.tokenize_to_columns "bar" "\d+" + t2.should_equal expected + Test.specify "can do tokenize_to_rows with some rows that have no matches" <| cols = [["foo", [0, 1, 2, 3]], ["bar", ["a12b34r5", "23", "q", "2r4r55"]]] t = Table.new cols @@ -87,7 +103,7 @@ spec = cols = [["foo", [0, 1]], ["bar", ["r a-1, b-12,qd-50", "ab-10:bc-20c"]]] t = Table.new cols expected_rows = [[0, "a1", "b12", "d50"], [1, "b10", "c20", Nothing]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.tokenize_to_columns "bar" "([a-z]).(\d+)" t2.should_equal expected @@ -103,7 +119,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["aBqcE", "qcBr", "cCb"]]] t = Table.new cols expected_rows = [[0, "B", "c", Nothing], [1, "c", "B", Nothing], [2, "c", "C", "b"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3"] expected_rows t2 = t.tokenize_to_columns "bar" "[bc]" case_sensitivity=Case_Sensitivity.Insensitive t2.should_equal expected @@ -115,12 +131,24 @@ spec = t2 = t.tokenize_to_rows "bar" "[bc]" case_sensitivity=Case_Sensitivity.Insensitive t2.should_equal expected + Test.specify "can do tokenize_to_rows with at_least_one_row=True" <| + input = Table.from_rows ["foo", "bar"] [[0, "a12b34r5"], [1, "qqq"], [2, "2r4r55"]] + expected = Table.from_rows ["foo", "bar"] [[0, "12"], [0, "34"], [0, "5"], [1, Nothing], [2, "2"], [2, "4"], [2, "55"]] + actual = input.tokenize_to_rows "bar" "\d+" at_least_one_row=True + actual.should_equal expected + + Test.specify "can do tokenize_to_rows with at_least_one_row=True, with groups" <| + input = Table.from_rows ["foo", "bar"] [[0, "a12b34r5"], [1, "qqq"], [2, "2r44r55"], [3, Nothing]] + expected = Table.from_rows ["foo", "bar"] [[0, "12"], [0, "34"], [1, Nothing], [2, "44"], [2, "55"], [3, Nothing]] + actual = input.tokenize_to_rows "bar" "(\d)(\d)" at_least_one_row=True + actual.should_equal expected + Test.group "Table.split/tokenize column count" <| Test.specify "should generate extra empty columns if column_count is set" <| cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]]] t = Table.new cols expected_rows = [[0, "a", "c", Nothing, Nothing], [1, "c", "d", "ef", Nothing], [2, "gh", "ij", "u", Nothing]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2", "bar 3"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3", "bar 3"] expected_rows t2 = t.split_to_columns "bar" "b" column_count=4 t2.should_equal expected t2.at "bar 3" . value_type . is_text . should_be_true @@ -129,7 +157,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]]] t = Table.new cols expected_rows = [[0, "a", "c"], [1, "c", "d"], [2, "gh", "ij"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2"] expected_rows action = t.split_to_columns "bar" "b" column_count=2 on_problems=_ tester = t-> t.should_equal expected problems = [Column_Count_Exceeded.Error 2 3] @@ -139,7 +167,7 @@ spec = cols = [["foo", [0, 1]], ["bar", ["r a-1, b-12,qd-50", "ab-10:bc-20c"]]] t = Table.new cols expected_rows = [[0, "a1", "b12", "d50"], [1, "b10", "c20", Nothing]] - expected = Table.from_rows ["foo", "bar 0", "bar 1"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2"] expected_rows action = t.tokenize_to_columns "bar" "([a-z]).(\d+)" column_count=2 on_problems=_ tester = t-> t.should_equal expected problems = [Column_Count_Exceeded.Error 2 3] @@ -149,7 +177,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["ghbijbu", "cbdbef", "abc"]]] t = Table.new cols expected_rows = [[0, "gh", "ij", "u", Nothing], [1, "c", "d", "ef", Nothing], [2, "a", "c", Nothing, Nothing]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2", "bar 3"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3", "bar 3"] expected_rows t2 = t.split_to_columns "bar" "b" column_count=4 t2.should_equal expected t2.at "bar 3" . value_type . is_text . should_be_true @@ -186,7 +214,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]], ["bar 1", ["a", "b", "c"]]] t = Table.new cols expected_rows = [[0, "a", "c", Nothing, "a"], [1, "c", "d", "ef", "b"], [2, "gh", "ij", "u", "c"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1_1", "bar 2", "bar 1"] expected_rows + expected = Table.from_rows ["foo", "bar 1 1", "bar 2", "bar 3", "bar 1"] expected_rows action = t.split_to_columns "bar" "b" on_problems=_ tester = t-> t.should_equal expected problems = [Duplicate_Output_Column_Names.Error ["bar 1"]] @@ -196,7 +224,7 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["a12b34r5", "23", "2r4r55"]], ["bar 1", ["a", "b", "c"]]] t = Table.new cols expected_rows = [[0, "12", "34", "5", "a"], [1, "23", Nothing, Nothing, "b"], [2, "2", "4", "55", "c"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1_1", "bar 2", "bar 1"] expected_rows + expected = Table.from_rows ["foo", "bar 1 1", "bar 2", "bar 3", "bar 1"] expected_rows action = t.tokenize_to_columns "bar" "\d+" on_problems=_ tester = t-> t.should_equal expected problems = [Duplicate_Output_Column_Names.Error ["bar 1"]] @@ -207,14 +235,14 @@ spec = cols = [["foo", [0, 1, 2]], ["bar", ["abc", "cbdbef", "ghbijbu"]], ["baz", [1, 2, 3]]] t = Table.new cols expected_rows = [[0, "a", "c", Nothing, 1], [1, "c", "d", "ef", 2], [2, "gh", "ij", "u", 3]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2", "baz"] expected_rows + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3", "baz"] expected_rows t2 = t.split_to_columns "bar" "b" t2.should_equal expected Test.group "Table.parse_to_columns" <| Test.specify "can parse to columns" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "12 34p q56", "y"], ["xx", "a48 59b", "yy"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "baz"] [["x", 1, 2, "y"], ["x", 3, 4, "y"], ["x", 5, 6, "y"], ["xx", 4, 8, "yy"], ["xx", 5, 9, "yy"]] + expected = Table.from_rows ["foo", "bar 1", "bar 2", "baz"] [["x", 1, 2, "y"], ["x", 3, 4, "y"], ["x", 5, 6, "y"], ["xx", 4, 8, "yy"], ["xx", 5, 9, "yy"]] actual = t.parse_to_columns "bar" "(\d)(\d)" actual.should_equal expected @@ -232,31 +260,31 @@ spec = Test.specify "non-participating groups" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "q1", "y"], ["xx", "qp", "yy"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "bar 2", "baz"] [["x", "1", 1, Nothing, "y"], ["xx", "p", Nothing, "p", "yy"]] + expected = Table.from_rows ["foo", "bar 1", "bar 2", "bar 3", "baz"] [["x", "1", 1, Nothing, "y"], ["xx", "p", Nothing, "p", "yy"]] actual = t.parse_to_columns "bar" "q((\d)|([a-z]))" actual.should_equal expected Test.specify "case-insensitive" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "qq", "y"], ["xx", "qQ", "yy"]] - expected = Table.from_rows ["foo", "bar 0", "baz"] [["x", "q", "y"], ["xx", "Q", "yy"]] + expected = Table.from_rows ["foo", "bar 1", "baz"] [["x", "q", "y"], ["xx", "Q", "yy"]] actual = t.parse_to_columns "bar" "q(q)" case_sensitivity=Case_Sensitivity.Insensitive actual.should_equal expected Test.specify "no post-parsing" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "12 34p q56", "y"], ["xx", "a48 59b", "yy"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "baz"] [["x", "1", "2", "y"], ["x", "3", "4", "y"], ["x", "5", "6", "y"], ["xx", "4", "8", "yy"], ["xx", "5", "9", "yy"]] + expected = Table.from_rows ["foo", "bar 1", "bar 2", "baz"] [["x", "1", "2", "y"], ["x", "3", "4", "y"], ["x", "5", "6", "y"], ["xx", "4", "8", "yy"], ["xx", "5", "9", "yy"]] actual = t.parse_to_columns "bar" "(\d)(\d)" parse_values=False actual.should_equal expected Test.specify "column name clash" <| t = Table.from_rows ["foo", "bar", "bar 1"] [["x", "12 34p q56", "y"], ["xx", "a48 59b", "yy"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1_1", "bar 1"] [["x", 1, 2, "y"], ["x", 3, 4, "y"], ["x", 5, 6, "y"], ["xx", 4, 8, "yy"], ["xx", 5, 9, "yy"]] + expected = Table.from_rows ["foo", "bar 1 1", "bar 2", "bar 1"] [["x", 1, 2, "y"], ["x", 3, 4, "y"], ["x", 5, 6, "y"], ["xx", 4, 8, "yy"], ["xx", 5, 9, "yy"]] actual = t.parse_to_columns "bar" "(\d)(\d)" actual.should_equal expected Test.specify "column and group name clash" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "123", "y"]] - expected = Table.from_rows ["foo", "bar", "baz_1", "quux", "baz"] [["x", 1, 2, 3, "y"]] + expected = Table.from_rows ["foo", "bar", "baz 1", "quux", "baz"] [["x", 1, 2, 3, "y"]] actual = t.parse_to_columns "bar" "(?\d)(?\d)(?\d)" actual.should_equal expected @@ -268,13 +296,13 @@ spec = Test.specify "empty table, with regex groups" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "a", "y"]] . take 0 - expected = Table.from_rows ["foo", "bar 0", "bar 1", "baz"] [["x", "a", "a", "y"]] . take 0 + expected = Table.from_rows ["foo", "bar 1", "bar 2", "baz"] [["x", "a", "a", "y"]] . take 0 actual = t.parse_to_columns "bar" "(\d)(\d)" actual.should_equal expected Test.specify "empty table, with named and unnamed regex groups" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "a", "y"]] . take 0 - expected = Table.from_rows ["foo", "quux", "bar 0", "foo_1", "bar 1", "baz"] [["x", "a", "a", "a", "a", "y"]] . take 0 + expected = Table.from_rows ["foo", "quux", "bar 1", "foo 1", "bar 2", "baz"] [["x", "a", "a", "a", "a", "y"]] . take 0 actual = t.parse_to_columns "bar" "(?)(\d)(?\d)(\d)" actual.should_equal expected @@ -286,13 +314,13 @@ spec = Test.specify "input with no matches, with regex groups" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "a", "y"]] - expected = Table.from_rows ["foo", "bar 0", "bar 1", "baz"] [] + expected = Table.from_rows ["foo", "bar 1", "bar 2", "baz"] [] actual = t.parse_to_columns "bar" "(\d)(\d)" actual.should_equal expected Test.specify "input with no matches, with named and unnamed regex groups" <| t = Table.from_rows ["foo", "bar", "baz"] [["x", "a", "y"]] - expected = Table.from_rows ["foo", "quux", "bar 0", "foo_1", "bar 1", "baz"] [] + expected = Table.from_rows ["foo", "quux", "bar 1", "foo 1", "bar 2", "baz"] [] actual = t.parse_to_columns "bar" "(?)(\d)(?\d)(\d)" actual.should_equal expected diff --git a/test/Table_Tests/src/In_Memory/Table_Spec.enso b/test/Table_Tests/src/In_Memory/Table_Spec.enso index a6af3f7d817e..43384190d364 100644 --- a/test/Table_Tests/src/In_Memory/Table_Spec.enso +++ b/test/Table_Tests/src/In_Memory/Table_Spec.enso @@ -541,7 +541,7 @@ spec = c_4 = ['Z', [True, False, True]] table = Table.new [c_0, c_1, c_2, c_3, c_4] action = table.use_first_row_as_names on_problems=_ - tester = expect_column_names ["Column_1", "1980-01-01", "1", "5.3", "True"] + tester = expect_column_names ["Column 1", "1980-01-01", "1", "5.3", "True"] problems = [Invalid_Output_Column_Names.Error [""]] Problems.test_problem_handling action problems tester @@ -553,7 +553,7 @@ spec = c_4 = ['Z', [True, False, True]] table = Table.new [c_0, c_1, c_2, c_3, c_4] action = table.use_first_row_as_names on_problems=_ - tester = expect_column_names ["A", "1980-01-01", "Column_1", "5.3", "True"] + tester = expect_column_names ["A", "1980-01-01", "Column 1", "5.3", "True"] problems = [Invalid_Output_Column_Names.Error [Nothing]] Problems.test_problem_handling action problems tester @@ -565,7 +565,7 @@ spec = c_4 = ['Z', [True, False, True]] table = Table.new [c_0, c_1, c_2, c_3, c_4] action = table.use_first_row_as_names on_problems=_ - tester = expect_column_names ["Column_1", "1980-01-01", "Column_2", "5.3", "True"] + tester = expect_column_names ["Column 1", "1980-01-01", "Column 2", "5.3", "True"] problems = [Invalid_Output_Column_Names.Error ["", Nothing]] Problems.test_problem_handling action problems tester @@ -576,7 +576,7 @@ spec = c_3 = ['C', ["A", "B", "C"]] table = Table.new [c_0, c_1, c_2, c_3] action = table.use_first_row_as_names on_problems=_ - tester = expect_column_names ["A", "A_1", "A_2", "A_3"] + tester = expect_column_names ["A", "A 1", "A 2", "A 3"] problems = [Duplicate_Output_Column_Names.Error ["A", "A", "A"]] Problems.test_problem_handling action problems tester diff --git a/test/Table_Tests/src/Util.enso b/test/Table_Tests/src/Util.enso index aa20695bda50..3d586781b417 100644 --- a/test/Table_Tests/src/Util.enso +++ b/test/Table_Tests/src/Util.enso @@ -4,27 +4,36 @@ from Standard.Table import Table, Column from Standard.Test import Test import Standard.Test.Extensions +import Standard.Test.Test_Result.Test_Result polyglot java import org.enso.base_test_helpers.FileSystemHelper -Table.should_equal self expected = case expected of - _ : Table -> - tables_equal t0 t1 = - same_headers = (t0.columns.map .name) == (t1.columns.map .name) - same_columns = (t0.columns.map .to_vector) == (t1.columns.map .to_vector) - same_headers && same_columns - equal = tables_equal self expected - if equal.not then - msg = 'Tables differ.\nActual:\n' + self.display + '\nExpected:\n' + expected.display - Test.fail msg - _ -> Test.fail "Got a Table, but expected a "+expected.to_display_text +Table.should_equal : Any -> Integer -> Test_Result +Table.should_equal self expected frames_to_skip=0 = + loc = Meta.get_source_location 1+frames_to_skip + case expected of + _ : Table -> + tables_equal t0 t1 = + same_headers = (t0.columns.map .name) == (t1.columns.map .name) + same_columns = (t0.columns.map .to_vector) == (t1.columns.map .to_vector) + same_headers && same_columns + equal = tables_equal self expected + if equal.not then + msg = 'Tables differ at '+loc+'.\nActual:\n' + self.display + '\nExpected:\n' + expected.display + Test.fail msg + _ -> Test.fail "Got a Table, but expected a "+expected.to_display_text+' (at '+loc+').' -Column.should_equal self expected = - if self.name != expected.name then - Test.fail "Expected column name "+expected.name+", but got "+self.name+"." - if self.length != expected.length then - Test.fail "Expected column length "+expected.length.to_text+", but got "+self.length.to_text+"." - self.to_vector.should_equal expected.to_vector +Column.should_equal : Any -> Integer -> Test_Result +Column.should_equal self expected frames_to_skip=0 = + loc = Meta.get_source_location 1+frames_to_skip + case expected of + _ : Column -> + if self.name != expected.name then + Test.fail "Expected column name "+expected.name+", but got "+self.name+" (at "+loc+")." + if self.length != expected.length then + Test.fail "Expected column length "+expected.length.to_text+", but got "+self.length.to_text+" (at "+loc+")." + self.to_vector.should_equal expected.to_vector + _ -> Test.fail "Got a Column, but expected a "+expected.to_display_text+' (at '+loc+').' normalize_lines string line_separator=Line_Ending_Style.Unix.to_text newline_at_end=True = case newline_at_end of diff --git a/test/Tests/src/Data/Time/Date_Spec.enso b/test/Tests/src/Data/Time/Date_Spec.enso index edc0f589baf5..908a1a90339d 100644 --- a/test/Tests/src/Data/Time/Date_Spec.enso +++ b/test/Tests/src/Data/Time/Date_Spec.enso @@ -37,6 +37,11 @@ spec_with name create_new_date parse_date = text = create_new_date 2020 12 21 . format "yyyyMMdd" text . should_equal "20201221" + Test.specify "should format local date using provided pattern and locale" <| + d = create_new_date 2020 6 21 + d.format "d. MMMM yyyy" (Locale.new "gb") . should_equal "21. Jun 2020" + d.format "d. MMMM yyyy" (Locale.new "fr") . should_equal "21. juin 2020 + Test.specify "should format local date using default pattern" <| text = create_new_date 2020 12 21 . to_text text . should_equal "2020-12-21" @@ -229,6 +234,41 @@ spec_with name create_new_date parse_date = (create_new_date 2000 7 1).end_of Date_Period.Quarter . should_equal (Date.new 2000 9 30) (create_new_date 2000 6 30).end_of Date_Period.Quarter . should_equal (Date.new 2000 6 30) + Test.specify "should allow to compute the next Date_Period after a date" <| + create_new_date 2000 2 1 . next Date_Period.Day . should_equal <| create_new_date 2000 2 2 + create_new_date 2000 2 1 . next Date_Period.Month . should_equal <| create_new_date 2000 3 1 + create_new_date 2000 2 1 . next Date_Period.Year . should_equal <| create_new_date 2001 2 1 + + Test.specify "should allow to compute the previous Date_Period after a date" <| + create_new_date 2000 2 1 . previous Date_Period.Day . should_equal <| create_new_date 2000 1 31 + create_new_date 2000 2 1 . previous Date_Period.Month . should_equal <| create_new_date 2000 1 1 + create_new_date 2000 2 1 . previous Date_Period.Year . should_equal <| create_new_date 1999 2 1 + + Test.specify "should allow to compute the Period between two dates." <| + create_new_date 2000 2 1 . until (create_new_date 2000 2 12) . should_equal <| Period.new 0 0 11 + create_new_date 2000 2 1 . until (create_new_date 2000 12 12) . should_equal <| Period.new 0 10 11 + create_new_date 2000 2 1 . until (create_new_date 2010 2 12) . should_equal <| Period.new 10 0 11 + + create_new_date 2000 2 12 . until (create_new_date 2000 2 1) . should_equal <| Period.new 0 0 -11 + create_new_date 2000 12 12 . until (create_new_date 2000 2 1) . should_equal <| Period.new 0 -10 -11 + create_new_date 2010 2 12 . until (create_new_date 2000 2 1) . should_equal <| Period.new -10 0 -11 + + Test.specify "should allow to compute the number of days until a date" <| + create_new_date 2000 2 1 . days_until (create_new_date 2000 2 1) . should_equal 0 + create_new_date 2000 2 1 . days_until (create_new_date 2000 2 2) . should_equal 1 + create_new_date 2000 2 2 . days_until (create_new_date 2000 2 1) . should_equal -1 + create_new_date 2001 3 1 . days_until (create_new_date 2001 4 1) . should_equal 31 + create_new_date 2000 3 1 . days_until (create_new_date 2001 3 1) . should_equal 365 + create_new_date 2001 3 1 . days_until (create_new_date 2000 3 1) . should_equal -365 + + Test.specify "should allow to compute the number of days until a date including the end date" <| + create_new_date 2000 2 1 . days_until (create_new_date 2000 2 1) include_end_date=True . should_equal 1 + create_new_date 2000 2 1 . days_until (create_new_date 2000 2 2) include_end_date=True . should_equal 2 + create_new_date 2000 2 2 . days_until (create_new_date 2000 2 1) include_end_date=True . should_equal -2 + create_new_date 2001 3 1 . days_until (create_new_date 2001 4 1) include_end_date=True . should_equal 32 + create_new_date 2000 3 1 . days_until (create_new_date 2001 3 1) include_end_date=True . should_equal 366 + create_new_date 2001 3 1 . days_until (create_new_date 2000 3 1) include_end_date=True . should_equal -366 + Test.specify "should allow to compute the number of working days until a later date" <| # 2000-2-1 is a Tuesday create_new_date 2000 2 1 . work_days_until (create_new_date 2000 2 1) . should_equal 0 diff --git a/test/Tests/src/Data/Time/Date_Time_Spec.enso b/test/Tests/src/Data/Time/Date_Time_Spec.enso index b739b85e7c01..872409e77eb1 100644 --- a/test/Tests/src/Data/Time/Date_Time_Spec.enso +++ b/test/Tests/src/Data/Time/Date_Time_Spec.enso @@ -65,6 +65,11 @@ spec_with name create_new_datetime parse_datetime nanoseconds_loss_in_precision= text = create_new_datetime 1970 (zone = Time_Zone.utc) . format "yyyy-MM-dd'T'HH:mm:ss" text . should_equal "1970-01-01T00:00:00" + Test.specify "should format using provided pattern and locale" <| + d = create_new_datetime 2020 6 21 + d.format "d. MMMM yyyy" (Locale.new "gb") . should_equal "21. Jun 2020" + d.format "d. MMMM yyyy" (Locale.new "fr") . should_equal "21. juin 2020 + Test.specify "should format using default pattern" <| text = create_new_datetime 1970 (zone = Time_Zone.utc) . to_text text . should_equal "1970-01-01T00:00:00Z[UTC]" diff --git a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso index dc0aeb009a60..26b6829e683f 100644 --- a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso +++ b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso @@ -34,6 +34,13 @@ specWith name create_new_time parse_time = text = create_new_time 12 20 44 . format "HHmmss" text . should_equal "122044" + Test.specify "should format using provided pattern and locale" <| + d = create_new_time 12 20 44 + # Note that the results are all the same. + d.format "HH:mm" . should_equal "12:20" + d.format "HH:mm" (Locale.new "gb") . should_equal "12:20" + d.format "HH:mm" (Locale.new "fr") . should_equal "12:20" + Test.specify "should format local time using default pattern" <| text = create_new_time 12 20 44 . to_text text . should_equal "12:20:44" diff --git a/test/Tests/src/Data/Vector_Spec.enso b/test/Tests/src/Data/Vector_Spec.enso index 5d4a72905abe..8ba859377564 100644 --- a/test/Tests/src/Data/Vector_Spec.enso +++ b/test/Tests/src/Data/Vector_Spec.enso @@ -346,6 +346,8 @@ type_spec name alter = Test.group name <| alter [1, 2, 3, 4, 5, 6] . short_display_text max_entries=3 . should_equal "[1, 2, 3 and 3 more elements]" alter (0.up_to 100).to_vector . short_display_text max_entries=2 . should_equal "[0, 1 and 98 more elements]" + alter [1, 2] . to_display_text . should_equal "[1, 2]" + alter [] . short_display_text max_entries=0 . should_fail_with Illegal_Argument Test.specify "should define equality" <| diff --git a/test/Tests/src/Semantic/Java_Interop_Spec.enso b/test/Tests/src/Semantic/Java_Interop_Spec.enso index 9e65574dac89..a1ac2a913187 100644 --- a/test/Tests/src/Semantic/Java_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Java_Interop_Spec.enso @@ -25,7 +25,7 @@ spec = list = ArrayList.new list.add 432 list.get 0 . should_equal 432 - Test.specify "should report missing method error on Java Arrays" <| + Test.specify "should report missing method error on Java Arrays" pending="Failing due to #6609" <| list = ArrayList.new list.add 432 Test.expect_panic_with (list.asList) No_Such_Method diff --git a/test/Tests/src/System/File_Read_Spec.enso b/test/Tests/src/System/File_Read_Spec.enso index 71b7ec1f5b62..c294d5df3274 100644 --- a/test/Tests/src/System/File_Read_Spec.enso +++ b/test/Tests/src/System/File_Read_Spec.enso @@ -20,6 +20,11 @@ spec = content = sample_txt.read content.should_equal "Hello World!" + Test.specify "should raise a not-found error when reading a nonexistent file even of unknown format" <| + r1 = (File.new "nonexistent.file.of.weird-format").read + r1.should_fail_with File_Error + r1.catch.should_be_a File_Error.Not_Found + Test.group "Bytes" <| Test.specify "should be able to read a file as Bytes" <| bytes = sample_xxx.read Bytes diff --git a/test/Visualization_Tests/src/Lazy_Table_Spec.enso b/test/Visualization_Tests/src/Lazy_Table_Spec.enso index 293f2bc6465c..e61e92266a2d 100644 --- a/test/Visualization_Tests/src/Lazy_Table_Spec.enso +++ b/test/Visualization_Tests/src/Lazy_Table_Spec.enso @@ -16,8 +16,8 @@ sample_table = col1 = ["foo", [123456789,23456789,987654321]] col2 = ["bar", [4,5,6]] col3 = ["Baz", [7,8,9]] - col4 = ["foo_1", [10,11,12]] - col5 = ["foo_2", [13,14,15]] + col4 = ["foo 1", [10,11,12]] + col5 = ["foo 2", [13,14,15]] col6 = ["ab.+123", [16,17,18]] col7 = ["abcd123", ["19",20, t1]] Table.new [col1, col2, col3, col4, col5, col6, col7]