A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: support datetime and time as seperate value types (#2714)
Myles Scolnick588b5336e2ad
diff --git a/frontend/src/components/data-table/__test__/column_formatting.test.ts b/frontend/src/components/data-table/__test__/column_formatting.test.tsindex 0761584622..55619727a0 100644--- a/frontend/src/components/data-table/__test__/column_formatting.test.ts+++ b/frontend/src/components/data-table/__test__/column_formatting.test.ts@@ -18,6 +18,18 @@ describe("applyFormat", () => {"10/1/23, 12:00:00 PM UTC",);});++ it("should format time values correctly", () => {+ const time = "12:00:00Z";+ expect(applyFormat(time, "Time", "time")).toBe("12:00:00Z");+ });++ it("should format datetime values correctly", () => {+ const datetime = "2023-10-01T12:00:00Z";+ expect(applyFormat(datetime, "Datetime", "datetime")).toBe(+ "10/1/23, 12:00:00 PM UTC",+ );+ });});describe("number formatting", () => {diff --git a/frontend/src/components/data-table/column-formatting/feature.ts b/frontend/src/components/data-table/column-formatting/feature.tsindex e195d897b7..ae0680a913 100644--- a/frontend/src/components/data-table/column-formatting/feature.ts+++ b/frontend/src/components/data-table/column-formatting/feature.ts@@ -112,6 +112,10 @@ export const applyFormat = (}// Handle date, number, string and boolean formattingswitch (dataType) {+ case "time":+ // Do nothing+ return value;+ case "datetime":case "date": {const date = new Date(value as string);switch (format) {diff --git a/frontend/src/components/data-table/column-formatting/types.ts b/frontend/src/components/data-table/column-formatting/types.tsindex 63057fadc5..491992d959 100644--- a/frontend/src/components/data-table/column-formatting/types.ts+++ b/frontend/src/components/data-table/column-formatting/types.ts@@ -6,6 +6,8 @@ import type { OnChangeFn, RowData } from "@tanstack/react-table";// define all format optionsexport const formatOptions = {date: ["Date", "Datetime", "Time"],+ datetime: ["Date", "Datetime", "Time"],+ time: [],integer: ["Auto", "Percent", "Scientific", "Integer"],number: ["Auto", "Percent", "Scientific", "Integer"],string: ["Uppercase", "Lowercase", "Capitalize", "Title"],diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsxindex daf481cb8f..6678f7cb38 100644--- a/frontend/src/components/data-table/column-header.tsx+++ b/frontend/src/components/data-table/column-header.tsx@@ -384,6 +384,17 @@ export const DropdownMenuItemFilter = <TData, TValue>({// Not implementedreturn null;}++ if (filterType === "time") {+ // Not implemented+ return null;+ }++ if (filterType === "datetime") {+ // Not implemented+ return null;+ }+if (filterType === "date") {// Not implementedreturn null;diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex 7bdb11818b..2aeb9cb354 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -215,6 +215,10 @@ function getFilterTypeForFieldType(return "number";case "date":return "date";+ case "datetime":+ return "datetime";+ case "time":+ return "time";case "boolean":return "boolean";default:diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsxindex 239dc610d5..206bd551c8 100644--- a/frontend/src/components/data-table/filter-pills.tsx+++ b/frontend/src/components/data-table/filter-pills.tsx@@ -59,6 +59,20 @@ function formatValue(value: ColumnFilterValue) {if (value.type === "date") {return formatMinMax(value.min?.toISOString(), value.max?.toISOString());}+ if (value.type === "time") {+ const formatTime = new Intl.DateTimeFormat("en-US", {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ });+ return formatMinMax(+ value.min ? formatTime.format(value.min) : undefined,+ value.max ? formatTime.format(value.max) : undefined,+ );+ }+ if (value.type === "datetime") {+ return formatMinMax(value.min?.toISOString(), value.max?.toISOString());+ }if (value.type === "boolean") {return `is ${value.value ? "True" : "False"}`;}diff --git a/frontend/src/components/data-table/filters.ts b/frontend/src/components/data-table/filters.tsindex 8cc0736fc9..9e15613695 100644--- a/frontend/src/components/data-table/filters.ts+++ b/frontend/src/components/data-table/filters.ts@@ -17,7 +17,14 @@ declare module "@tanstack/react-table" {}}-export type FilterType = "text" | "number" | "date" | "select" | "boolean";+export type FilterType =+ | "text"+ | "number"+ | "date"+ | "datetime"+ | "time"+ | "select"+ | "boolean";// Filter is a factory function that creates a filter objectexport const Filter = {@@ -39,6 +46,18 @@ export const Filter = {...opts,} as const;},+ datetime(opts: { min?: Date; max?: Date }) {+ return {+ type: "datetime",+ ...opts,+ } as const;+ },+ time(opts: { min?: Date; max?: Date }) {+ return {+ type: "time",+ ...opts,+ } as const;+ },boolean(value: boolean) {return {type: "boolean",@@ -92,6 +111,24 @@ export function filterToFilterCondition(operator: "contains",value: filter.text,};+ case "datetime": {+ const conditions: ConditionType[] = [];+ if (filter.min !== undefined) {+ conditions.push({+ column_id,+ operator: ">=",+ value: filter.min.toISOString(),+ });+ }+ if (filter.max !== undefined) {+ conditions.push({+ column_id,+ operator: "<=",+ value: filter.max.toISOString(),+ });+ }+ return conditions;+ }case "date": {const conditions: ConditionType[] = [];if (filter.min !== undefined) {@@ -110,6 +147,24 @@ export function filterToFilterCondition(}return conditions;}+ case "time": {+ const conditions: ConditionType[] = [];+ if (filter.min !== undefined) {+ conditions.push({+ column_id,+ operator: ">=",+ value: filter.min.toISOString(),+ });+ }+ if (filter.max !== undefined) {+ conditions.push({+ column_id,+ operator: "<=",+ value: filter.max.toISOString(),+ });+ }+ return conditions;+ }case "boolean":if (filter.value) {return {diff --git a/frontend/src/components/datasets/icons.tsx b/frontend/src/components/datasets/icons.tsxindex f7702994e7..d72b19e4f5 100644--- a/frontend/src/components/datasets/icons.tsx+++ b/frontend/src/components/datasets/icons.tsx@@ -8,6 +8,9 @@ import {TypeIcon,ListOrderedIcon,type LucideIcon,+ CalendarClockIcon,+ ClockIcon,+ CurlyBracesIcon,} from "lucide-react";/**@@ -16,8 +19,10 @@ import {export const DATA_TYPE_ICON: Record<DataType, LucideIcon> = {boolean: ToggleLeftIcon,date: CalendarIcon,+ time: ClockIcon,+ datetime: CalendarClockIcon,number: HashIcon,string: TypeIcon,integer: ListOrderedIcon,- unknown: TypeIcon,+ unknown: CurlyBracesIcon,};diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.tsindex 930649fd85..66019ba501 100644--- a/frontend/src/core/kernel/messages.ts+++ b/frontend/src/core/kernel/messages.ts@@ -3,6 +3,16 @@ import type { components } from "@marimo-team/marimo-api";export type schemas = components["schemas"];export type DataType = schemas["DataType"];+export const DATA_TYPES = [+ "string",+ "boolean",+ "integer",+ "number",+ "date",+ "datetime",+ "time",+ "unknown",+] as const;export type Banner = OperationMessageData<"banner">;export type DataTableColumn = schemas["DataTableColumn"];export type DataTable = schemas["DataTable"];diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsxindex 438e3ad16b..4fe73fd9b1 100644--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx@@ -15,6 +15,7 @@ import React from "react";import "./data-editor/grid.css";import "ag-grid-community/styles/ag-grid.css";import "ag-grid-community/styles/ag-theme-quartz.css";+import { DATA_TYPES } from "@/core/kernel/messages";type CsvURL = string;type TableData<T> = T[] | CsvURL;@@ -46,21 +47,7 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor")data: z.union([z.string(), z.array(z.object({}).passthrough())]),pagination: z.boolean().default(false),pageSize: z.number().default(10),- fieldTypes: z- .record(- z.tuple([- z.enum([- "boolean",- "integer",- "number",- "date",- "string",- "unknown",- ]),- z.string(),- ]),- )- .nullish(),+ fieldTypes: z.record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullish(),}),).withFunctions({})diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 31bb5dde23..99c6b0bd0e 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -40,6 +40,8 @@ import { LoadingTable } from "@/components/data-table/loading-table";import { useAsyncData } from "@/hooks/useAsyncData";import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";import { DelayMount } from "@/components/utils/delay-mount";+import { DATA_TYPES } from "@/core/kernel/messages";+type CsvURL = string;type TableData<T> = T[] | CsvURL;interface ColumnSummaries<T = unknown> {@@ -107,21 +109,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")rowHeaders: z.array(z.string()),freezeColumnsLeft: z.array(z.string()).optional(),freezeColumnsRight: z.array(z.string()).optional(),- fieldTypes: z- .record(- z.tuple([- z.enum([- "boolean",- "integer",- "number",- "date",- "string",- "unknown",- ]),- z.string(),- ]),- )- .nullish(),+ fieldTypes: z.record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullish(),}),).withFunctions<Functions>({@@ -371,6 +359,7 @@ export const LoadingDataTableComponent = memo(let errorComponent: React.ReactNode = null;if (error) {+ Logger.error(error);errorComponent = (<Alert variant="destructive" className="mb-2"><AlertTitle>Error</AlertTitle>diff --git a/frontend/src/plugins/impl/data-editor/data-editor.tsx b/frontend/src/plugins/impl/data-editor/data-editor.tsxindex eb81e509b3..0b4f4d8a91 100644--- a/frontend/src/plugins/impl/data-editor/data-editor.tsx+++ b/frontend/src/plugins/impl/data-editor/data-editor.tsx@@ -44,6 +44,8 @@ function cellEditorForDataType(dataType: DataType) {return "agCheckboxCellEditor";// TODO: not working properly// case "date":+ // case "datetime":+ // case "time":// return 'agDateCellEditor';default:return "agTextCellEditor";diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex a7a5798795..d4cdc243f4 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -24,6 +24,7 @@ import type { FieldTypesWithExternalType } from "@/components/data-table/types";import { Spinner } from "@/components/icons/spinner";import { ReadonlyCode } from "@/components/editor/code/readonly-python-code";import { isEqual } from "lodash-es";+import { DATA_TYPES } from "@/core/kernel/messages";type CsvURL = string;type TableData<T> = T[] | CsvURL;@@ -96,19 +97,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")total_rows: z.number(),row_headers: z.array(z.string()),field_types: z- .record(- z.tuple([- z.enum([- "boolean",- "integer",- "number",- "date",- "string",- "unknown",- ]),- z.string(),- ]),- )+ .record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullable(),python_code: z.string().nullish(),sql_code: z.string().nullish(),diff --git a/frontend/src/plugins/impl/data-frames/forms/form.tsx b/frontend/src/plugins/impl/data-frames/forms/form.tsxindex 02326f79b2..56da3c2deb 100644--- a/frontend/src/plugins/impl/data-frames/forms/form.tsx+++ b/frontend/src/plugins/impl/data-frames/forms/form.tsx@@ -141,6 +141,29 @@ function renderZodSchema<T extends FieldValues, S>(if (special === "column_values") {return <ColumnValuesFormField schema={schema} form={form} path={path} />;}+ if (special === "time") {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <DebouncedInput+ {...field}+ onValueChange={field.onChange}+ type="time"+ className="my-0"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ }return <StringFormField schema={schema} form={form} path={path} />;}@@ -213,6 +236,13 @@ function renderZodSchema<T extends FieldValues, S>();}if (schema instanceof z.ZodDate) {+ const inputType =+ special === "datetime"+ ? "datetime-local"+ : special === "time"+ ? "time"+ : "date";+return (<FormFieldcontrol={form.control}@@ -225,7 +255,7 @@ function renderZodSchema<T extends FieldValues, S>(<DebouncedInput{...field}onValueChange={field.onChange}- type="date"+ type={inputType}className="my-0"/></FormControl>diff --git a/frontend/src/plugins/impl/data-frames/forms/options.ts b/frontend/src/plugins/impl/data-frames/forms/options.tsindex 38a714b612..4e042f1fce 100644--- a/frontend/src/plugins/impl/data-frames/forms/options.ts+++ b/frontend/src/plugins/impl/data-frames/forms/options.ts@@ -13,7 +13,10 @@ export interface FieldOptions {| "radio_group"| "column_filter"| "text_area_multiline"- | "column_values";+ | "column_values"+ | "date"+ | "datetime"+ | "time";}// eslint-disable-next-line @typescript-eslint/no-redeclarediff --git a/frontend/src/plugins/impl/data-frames/types.ts b/frontend/src/plugins/impl/data-frames/types.tsindex fb9548c209..c391c40cae 100644--- a/frontend/src/plugins/impl/data-frames/types.ts+++ b/frontend/src/plugins/impl/data-frames/types.ts@@ -74,6 +74,7 @@ export function numpyTypeToDataType(case "bool":return "boolean";case "datetime64":+ return "datetime";case "timedelta64":return "date";default:diff --git a/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.ts b/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.tsindex e18e899b79..7f8f8db324 100644--- a/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.ts+++ b/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.ts@@ -9,6 +9,7 @@ import {DATE_OPERATORS,NUMERIC_OPERATORS,STRING_OPERATORS,+ DATETIME_OPERATORS,} from "../operators";describe("getOperatorForDtype", () => {@@ -37,6 +38,7 @@ describe("getOperatorForDtype", () => {expect(getOperatorForDtype("datetime")).toEqual(Object.keys(DATE_OPERATORS),);+ expect(getOperatorForDtype("time")).toEqual(Object.keys(DATE_OPERATORS));});it('should return STRING_OPERATORS for "object" and "string"', () => {@@ -73,7 +75,7 @@ describe("getSchemaForOperator", () => {NUMERIC_OPERATORS["=="],);expect(getSchemaForOperator("datetime64[ns]", "!=")).toEqual(- DATE_OPERATORS["!="],+ DATETIME_OPERATORS["!="],);expect(getSchemaForOperator("date", "!=")).toEqual(DATE_OPERATORS["!="]);expect(getSchemaForOperator("string", "contains")).toEqual(@@ -91,6 +93,11 @@ describe("isConditionValueValid", () => {it("should return true if the value is valid according to the schema for the given operator", () => {expect(isConditionValueValid("is_true", true)).toBe(true);expect(isConditionValueValid("==", 123)).toBe(true);+ expect(isConditionValueValid("==", "12:34")).toBe(true);+ expect(isConditionValueValid("==", "12:34:56")).toBe(true);+ expect(isConditionValueValid("==", new Date("2024-01-01T12:34:56"))).toBe(+ true,+ );expect(isConditionValueValid("contains", "test")).toBe(true);expect(isConditionValueValid("in", ["test"])).toBe(true);});diff --git a/frontend/src/plugins/impl/data-frames/utils/operators.ts b/frontend/src/plugins/impl/data-frames/utils/operators.tsindex 64ec984a12..02c6f00dd9 100644--- a/frontend/src/plugins/impl/data-frames/utils/operators.ts+++ b/frontend/src/plugins/impl/data-frames/utils/operators.ts@@ -17,7 +17,16 @@ const Schema = {.array(z.string()).min(1).describe(FieldOptions.of({ label: "Value", special: "column_values" })),- date: z.coerce.date().describe(FieldOptions.of({ label: "Value" })),+ date: z.coerce+ .date()+ .describe(FieldOptions.of({ label: "Value", special: "date" })),+ datetime: z.coerce+ .date()+ .describe(FieldOptions.of({ label: "Value", special: "datetime" })),+ time: z+ .string()+ .regex(/^\d{2}:\d{2}(:\d{2})?$/)+ .describe(FieldOptions.of({ label: "Value", special: "time" })),};export const BOOLEAN_OPERATORS = {@@ -25,27 +34,21 @@ export const BOOLEAN_OPERATORS = {is_false: [],};-export const NUMERIC_OPERATORS = {- "==": [Schema.number],- "!=": [Schema.number],- ">": [Schema.number],- ">=": [Schema.number],- "<": [Schema.number],- "<=": [Schema.number],+const createComparisonOperators = (schema: z.ZodType) => ({+ "==": [schema],+ "!=": [schema],+ ">": [schema],+ ">=": [schema],+ "<": [schema],+ "<=": [schema],is_nan: [],is_not_nan: [],-};+});-export const DATE_OPERATORS = {- "==": [Schema.date],- "!=": [Schema.date],- ">": [Schema.date],- ">=": [Schema.date],- "<": [Schema.date],- "<=": [Schema.date],- is_nan: [],- is_not_nan: [],-};+export const NUMERIC_OPERATORS = createComparisonOperators(Schema.number);+export const DATE_OPERATORS = createComparisonOperators(Schema.date);+export const TIME_OPERATORS = createComparisonOperators(Schema.time);+export const DATETIME_OPERATORS = createComparisonOperators(Schema.datetime);export const STRING_OPERATORS = {equals: [Schema.stringColumnValues],@@ -61,6 +64,8 @@ export const ALL_OPERATORS = {...BOOLEAN_OPERATORS,...NUMERIC_OPERATORS,...DATE_OPERATORS,+ ...TIME_OPERATORS,+ ...DATETIME_OPERATORS,...STRING_OPERATORS,};@@ -92,7 +97,15 @@ function numpyTypeToDataType(type: string): DataType {return "string";}- if (type.startsWith("date") || type.startsWith("time")) {+ if (type.startsWith("datetime")) {+ return "datetime";+ }++ if (type.startsWith("time")) {+ return "time";+ }++ if (type.startsWith("date")) {return "date";}@@ -121,6 +134,10 @@ export function getOperatorForDtype(return Object.keys(STRING_OPERATORS);case "date":return Object.keys(DATE_OPERATORS);+ case "datetime":+ return Object.keys(DATETIME_OPERATORS);+ case "time":+ return Object.keys(TIME_OPERATORS);case "boolean":return Object.keys(BOOLEAN_OPERATORS);case "unknown":@@ -147,6 +164,10 @@ export function getSchemaForOperator(return safeGet(STRING_OPERATORS, operator);case "date":return safeGet(DATE_OPERATORS, operator);+ case "datetime":+ return safeGet(DATETIME_OPERATORS, operator);+ case "time":+ return safeGet(TIME_OPERATORS, operator);case "boolean":return safeGet(BOOLEAN_OPERATORS, operator);case "unknown":@@ -158,6 +179,8 @@ export function isConditionValueValid(operator: string, value: unknown) {const possibleSchemas = [safeGet(BOOLEAN_OPERATORS, operator),safeGet(DATE_OPERATORS, operator),+ safeGet(TIME_OPERATORS, operator),+ safeGet(DATETIME_OPERATORS, operator),safeGet(NUMERIC_OPERATORS, operator),safeGet(STRING_OPERATORS, operator),].flat();diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.tsindex 9a8ad7be61..c716f131c8 100644--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts@@ -6,6 +6,7 @@ import {exportedForTesting,parseCsvData,} from "../loader";+import { DATA_TYPES } from "@/core/kernel/messages";const { ZERO_WIDTH_SPACE, replacePeriodsInColumnNames, uniquifyColumnNames } =exportedForTesting;@@ -101,6 +102,17 @@ yield_error,yield_center`);});+ it.each(DATA_TYPES)("should handle %s data-type", async (type) => {+ const csvData = "name,value_column\nAlice,1";+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));++ const result = await vegaLoadData(csvData, {+ type: "csv",+ parse: { value_column: type },+ });+ expect(result.length).toEqual(1);+ });+it("should parse csv data with out of bound integers", async () => {const csvData = "id\n912312851340981241284";diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.tsindex 8e2de9aed2..8e275c0645 100644--- a/frontend/src/plugins/impl/vega/loader.ts+++ b/frontend/src/plugins/impl/vega/loader.ts@@ -1,12 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import type { DataFormat } from "./types";import { isNumber } from "lodash-es";-import {- typeParsers,- createLoader,- read,- type FieldTypes,-} from "./vega-loader";+import { typeParsers, createLoader, read, type DataType } from "./vega-loader";+import { Objects } from "@/utils/objects";type Unsubscribe = () => void;type Middleware = () => Unsubscribe;@@ -150,12 +146,28 @@ export async function vegaLoadData<T = object>(csvOrJsonData = replacePeriodsInColumnNames(csvOrJsonData);}+ let parse = (format?.parse as Record<string, DataType>) || "auto";+ // Map some of our data types to Vega's data types+ // - time -> string+ // - datetime -> date+ if (typeof parse === "object") {+ parse = Objects.mapValues(parse, (value) => {+ if (value === "time") {+ return "string";+ }+ if (value === "datetime") {+ return "date";+ }+ return value;+ });+ }+// Always set parse to auto for csv data, to be able to parse dates and floatsconst results = isCsv? // csv -> jsonread(csvOrJsonData, {...format,- parse: (format?.parse as FieldTypes) || "auto",+ parse: parse,}): read(csvOrJsonData, format);diff --git a/frontend/src/plugins/impl/vega/utils.ts b/frontend/src/plugins/impl/vega/utils.tsindex 786b3527da..ad09ea4826 100644--- a/frontend/src/plugins/impl/vega/utils.ts+++ b/frontend/src/plugins/impl/vega/utils.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { Objects } from "@/utils/objects";-import type { FieldTypes } from "./vega-loader";+import type { DataType, FieldTypes, VegaDataType } from "./vega-loader";export function mergeAsArrays<T>(left: T | T[] | undefined,@@ -21,20 +21,26 @@ function toArray<T>(value: T | T[] | undefined): T[] {}export function getVegaFieldTypes(- types: FieldTypes | undefined | null,+ types: Record<string, DataType> | undefined | null,): FieldTypes | "auto" {if (!types || Object.keys(types).length === 0) {// If fieldTypes is provided, use it to parse the data// Otherwise, infer the data typesreturn "auto";}- // Convert all 'data' to 'string', because dates don't format back to+ // Convert all 'date' to 'string', because dates don't format back to// the correct formatting. For example, a date like '2024-01-01' will// be formatted to '2024-01-01T00:00:00.000Z'.- return Objects.mapValues(types, (type) => {+ return Objects.mapValues(types, (type): VegaDataType => {if (type === "date") {return "string";}+ if (type === "time") {+ return "string";+ }+ if (type === "datetime") {+ return "date";+ }return type;});}diff --git a/frontend/src/plugins/impl/vega/vega-loader.ts b/frontend/src/plugins/impl/vega/vega-loader.tsindex 0954ac1419..5a94576ccc 100644--- a/frontend/src/plugins/impl/vega/vega-loader.ts+++ b/frontend/src/plugins/impl/vega/vega-loader.ts@@ -2,7 +2,7 @@// @ts-expect-error - no typesimport * as vl from "vega-loader";import type { DataFormat } from "./types";-import type { DataType } from "@/core/kernel/messages";+import type { DataType } from "./vega-loader";// Re-export the vega-loader functions to add TypeScript types@@ -16,7 +16,7 @@ export function read<T = object>(}| {type: DataFormat["type"];- parse: FieldTypes;+ parse: Record<string, DataType>;}| undefined,): T[] {@@ -34,9 +34,17 @@ export function createLoader(): {return vl.loader();}-export type FieldTypes = Record<string, DataType>;+export type VegaDataType =+ | "boolean"+ | "integer"+ | "number"+ | "date"+ | "string"+ | "unknown";-export const typeParsers: Record<DataType, (value: string) => unknown> =+export type FieldTypes = Record<string, VegaDataType>;++export const typeParsers: Record<VegaDataType, (value: string) => unknown> =vl.typeParsers;export type { DataType } from "@/core/kernel/messages";diff --git a/marimo/_data/charts.py b/marimo/_data/charts.pyindex 4e66bd76d8..8d33a70771 100644--- a/marimo/_data/charts.py+++ b/marimo/_data/charts.py@@ -277,7 +277,11 @@ def get_chart_builder(return WrapperChartBuilder(StringChartBuilder(should_limit_to_10_items))- if column_type == "date":+ if (+ column_type == "date"+ or column_type == "datetime"+ or column_type == "time"+ ):return WrapperChartBuilder(DateChartBuilder())if column_type == "boolean":return WrapperChartBuilder(BooleanChartBuilder())diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex 307b05f490..7357cb8290 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -176,16 +176,18 @@ def _db_type_to_data_type(db_type: str) -> DataType:]:return "string"# Date and Time types+ if db_type == "date":+ return "date"+ if db_type == "time":+ return "time"if db_type in [- "date",- "time","timestamp","timestamp with time zone","timestamptz","datetime","interval",]:- return "date"+ return "datetime"# Nested typesif db_type in ["array", "list", "struct", "map", "union"]:return "unknown"diff --git a/marimo/_data/models.py b/marimo/_data/models.pyindex 995f6719a9..07b30e1c29 100644--- a/marimo/_data/models.py+++ b/marimo/_data/models.py@@ -6,7 +6,16 @@ from datetime import date, datetime, time, timedelta # noqa: TCH003from decimal import Decimalfrom typing import List, Literal, Optional, Union-DataType = Literal["string", "boolean", "integer", "number", "date", "unknown"]+DataType = Literal[+ "string",+ "boolean",+ "integer",+ "number",+ "date",+ "datetime",+ "time",+ "unknown",+]# This is the data type based on the source library# e.g. polars, pandas, numpy, etc.ExternalDataType = strdiff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex 1f855cf6cb..ebebaa3cbb 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -200,7 +200,11 @@ def _get_altair_chart(column_data = table.select_columns([request.column_name]).data# Date types don't serialize well to csv,# so we don't transform them- if column_type == "date":+ if (+ column_type == "date"+ or column_type == "datetime"+ or column_type == "time"+ ):# Default max_rows is 5_000, but we can support more.with alt.data_transformers.enable("default", max_rows=20_000):chart_json = chart_builder.altair_json(diff --git a/marimo/_data/sql_summaries.py b/marimo/_data/sql_summaries.pyindex 6ba527d44f..2d7828bed6 100644--- a/marimo/_data/sql_summaries.py+++ b/marimo/_data/sql_summaries.py@@ -33,7 +33,11 @@ def get_sql_summary(PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY "{column_name}") as p95FROM {table_name}""" # noqa: E501- elif column_type == "date":+ elif (+ column_type == "date"+ or column_type == "datetime"+ or column_type == "time"+ ):stats_query = f"""SELECTCOUNT(*) as count,@@ -97,7 +101,11 @@ def get_sql_summary(p75=p75,p95=p95,)- elif column_type == "date":+ elif (+ column_type == "date"+ or column_type == "datetime"+ or column_type == "time"+ ):count, unique, null_count, min_val, max_val = stats_resultreturn ColumnSummary(total=count,diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.pyindex f6afef659b..821557f0c7 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import datetimefrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, castfrom marimo._plugins.ui._impl.dataframes.transforms.print_code import (@@ -254,6 +255,7 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):def handle_filter_rows(df: "pl.DataFrame", transform: FilterRowsTransform) -> "pl.DataFrame":+ import polars as plfrom polars import col# Start with no filter (all rows included)@@ -262,8 +264,17 @@ class PolarsTransformHandler(TransformHandler["pl.DataFrame"]):# Iterate over all conditions and build the filter expressionfor condition in transform.where:column = col(str(condition.column_id))+ dtype = df.schema[str(condition.column_id)]value = condition.value+ # If columns type is a Datetime, we need to convert the value to a datetime+ if dtype == pl.Datetime and isinstance(value, str):+ value = datetime.datetime.fromisoformat(value)+ elif dtype == pl.Date and isinstance(value, str):+ value = datetime.date.fromisoformat(value)+ elif dtype == pl.Time and isinstance(value, str):+ value = datetime.time.fromisoformat(value)+# Build the expression based on the operatorif condition.operator == "==":condition_expr = column == valuediff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.pyindex 319d8e9416..9ba3ff9960 100644--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py@@ -191,6 +191,10 @@ class IbisTableManagerFactory(TableManagerFactory):elif dtype.is_floating():return ("number", str(dtype))elif dtype.is_timestamp():+ return ("datetime", str(dtype))+ elif dtype.is_time():+ return ("time", str(dtype))+ elif dtype.is_date():return ("date", str(dtype))else:return ("unknown", str(dtype))diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex f24669dea9..8c3ee3c152 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -152,7 +152,11 @@ class PandasTableManagerFactory(TableManagerFactory):if dtype == "bool":return ("boolean", dtype)if dtype == "datetime64[ns]":+ return ("datetime", dtype)+ if dtype == "date":return ("date", dtype)+ if dtype == "time":+ return ("time", dtype)if dtype == "timedelta64[ns]":return ("string", dtype)if dtype == "category":@@ -167,7 +171,7 @@ class PandasTableManagerFactory(TableManagerFactory):return ColumnSummary()col = self.data[column]- if col.dtype == "object":+ if col.dtype == "object" or col.dtype == "category":try:return ColumnSummary(total=col.count(),diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 9acf67cbff..882637fac1 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -65,7 +65,16 @@ class PolarsTableManagerFactory(TableManagerFactory):).arr.join(","))elif isinstance(dtype, pl.Object):- result = result.with_columns(column.cast(str))+ import warnings++ with warnings.catch_warnings(record=True):+ result = result.with_columns(+ # As of writing this, cast(pl.String) doesn't work+ # for pl.Object types, so we use map_elements+ column.map_elements(+ str, return_dtype=pl.String+ )+ )elif isinstance(dtype, pl.Duration):if dtype.time_unit == "ms":result = result.with_columns(@@ -176,7 +185,7 @@ class PolarsTableManagerFactory(TableManagerFactory):return ColumnSummary()col = self.data[column]total = len(col)- if col.dtype == pl.String:+ if col.dtype == pl.String or col.dtype == pl.Categorical:return ColumnSummary(total=total,nulls=col.null_count(),@@ -206,17 +215,23 @@ class PolarsTableManagerFactory(TableManagerFactory):max=cast(NonNestedLiteral, col.max()),mean=cast(NonNestedLiteral, col.mean()),median=cast(NonNestedLiteral, col.median()),- p5=col.quantile(0.05),- p25=col.quantile(0.25),- p75=col.quantile(0.75),- p95=col.quantile(0.95),)if col.dtype.is_(pl.Null):return ColumnSummary(total=total,nulls=col.null_count(),)- if col.dtype == pl.List:+ if col.dtype == pl.Time:+ return ColumnSummary(+ total=total,+ nulls=col.null_count(),+ )+ if (+ col.dtype == pl.List+ or col.dtype == pl.Array+ or col.dtype == pl.Object+ or col.dtype == pl.Struct+ ):return ColumnSummary(total=total,nulls=col.null_count(),@@ -265,7 +280,7 @@ class PolarsTableManagerFactory(TableManagerFactory):dtype_string = column.dtype._string_repr()except (TypeError, AttributeError):dtype_string = str(column.dtype)- if column.dtype == pl.String:+ if column.dtype == pl.String or column.dtype == pl.Categorical:return ("string", dtype_string)elif column.dtype == pl.Boolean:return ("boolean", dtype_string)@@ -273,8 +288,14 @@ class PolarsTableManagerFactory(TableManagerFactory):return ("integer", dtype_string)elif column.dtype.is_float() or column.dtype.is_numeric():return ("number", dtype_string)- elif column.dtype.is_temporal():+ elif column.dtype == pl.Date:return ("date", dtype_string)+ elif column.dtype == pl.Time:+ return ("time", dtype_string)+ elif column.dtype == pl.Datetime:+ return ("datetime", dtype_string)+ elif column.dtype.is_temporal():+ return ("datetime", dtype_string)else:return ("unknown", dtype_string)diff --git a/marimo/_smoke_tests/_polars/polars_to_csv.py b/marimo/_smoke_tests/_polars/polars_to_csv.pyindex 39f64c6774..059039161d 100644--- a/marimo/_smoke_tests/_polars/polars_to_csv.py+++ b/marimo/_smoke_tests/_polars/polars_to_csv.py@@ -29,6 +29,11 @@ def __():datetime.datetime(2021, 1, 2),datetime.datetime(2021, 1, 3),],+ "date": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 2),+ datetime.date(2021, 1, 3),+ ],"struct": [{"a": 1, "b": 2},{"a": 3, "b": 4},diff --git a/marimo/_smoke_tests/tables/complex_types.py b/marimo/_smoke_tests/tables/complex_types.pynew file mode 100644index 0000000000..fb0b4b76b8--- /dev/null+++ b/marimo/_smoke_tests/tables/complex_types.py@@ -0,0 +1,109 @@+import marimo++__generated_with = "0.9.14"+app = marimo.App(width="medium")++[email protected](hide_code=True)+def __():+ import polars as pl+ from datetime import datetime, date, time+ import marimo as mo++ df = pl.DataFrame(+ {+ # Numeric+ "integers": pl.Series("integers", [1, 2, 3], dtype=pl.Int32),+ "floats": pl.Series("floats", [1.0, 2.0, 3.0], dtype=pl.Float64),+ # String+ "strings": pl.Series("strings", ["a", "b", "c"], dtype=pl.Utf8),+ "categories": pl.Series(+ "categories", ["a", "b", "c"], dtype=pl.Categorical+ ),+ # Boolean+ "bools": pl.Series("bools", [True, False, True], dtype=pl.Boolean),+ # Temporal+ "dates": pl.Series("dates", [date(2021, 1, 1)] * 3, dtype=pl.Date),+ "times": pl.Series("times", [time(12, 0, 0)] * 3, dtype=pl.Time),+ "datetimes": pl.Series(+ "datetimes", [datetime.now()] * 3, dtype=pl.Datetime+ ),+ "durations": pl.Series(+ "durations", ["1d", "2d", "3d"], dtype=pl.Duration+ ),+ # Lists+ "lists": pl.Series(+ "lists", [[1, 2], [3, 4], [5, 6]], dtype=pl.List(pl.Int64)+ ),+ "arrays": pl.Series(+ "arrays",+ [[1, 2], [3, 4], [5, 6]],+ dtype=pl.Array(pl.Int64, shape=(2,)),+ ),+ # Objects+ "sets": pl.Series(+ "sets", [set([1, 2]), set([3, 4]), set([5, 6])], dtype=pl.Object+ ),+ "dicts": pl.Series(+ "dicts",+ [{"a": 1, "b": 2}, {"c": 3, "d": 4}, {"e": 5, "f": 6}],+ dtype=pl.Object,+ ),+ # Structs+ "structs": pl.Series(+ [{"a": 1, "b": 2}, {"c": 3, "d": 4}, {"e": 5, "f": 6}],+ dtype=pl.Struct,+ ),+ # Nulls+ "nulls": pl.Series("nulls", [None, None, None], dtype=pl.Utf8),+ # Complex+ "complex": pl.Series(+ "complex",+ [1 + 2j, 3 + 4j, 5 + 6j],+ dtype=pl.Object,+ ),+ }+ )+ df+ return date, datetime, df, mo, pl, time+++def __(df):+ pandas = df.to_pandas()+ pandas+ return (pandas,)+++def __(df):+ arrow = df.to_arrow()+ arrow+ return (arrow,)+++def __(df, mo):+ mo.ui.dataframe(df)+ return+++def __(mo):+ import pandas as pd++ pandas_with_timestamp = pd.DataFrame(+ {+ "timestamp": [+ pd.Timestamp("2021-01-01"),+ pd.Timestamp("2021-01-02"),+ pd.Timestamp("2021-01-03"),+ ]+ }+ )+ mo.ui.dataframe(pandas_with_timestamp)+ return pandas_with_timestamp, pd+++if __name__ == "__main__":+ app.run()diff --git a/openapi/api.yaml b/openapi/api.yamlindex a17078effa..35668ffd41 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -435,6 +435,8 @@ components:- integer- number- date+ - datetime+ - time- unknowntype: stringDatasets:@@ -1911,7 +1913,7 @@ components:type: objectinfo:title: marimo API- version: 0.9.6+ version: 0.9.14openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex d443f559ea..eca2825b3d 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2140,7 +2140,15 @@ export interface components {type: components["schemas"]["DataType"];};/** @enum {string} */- DataType: "string" | "boolean" | "integer" | "number" | "date" | "unknown";+ DataType:+ | "string"+ | "boolean"+ | "integer"+ | "number"+ | "date"+ | "datetime"+ | "time"+ | "unknown";Datasets: {/** @enum {string|null} */clear_channel?: "local" | "duckdb" | null;diff --git a/tests/_data/snapshots/charts.txt b/tests/_data/snapshots/charts.txtindex aeca02ec21..f7d5075f51 100644--- a/tests/_data/snapshots/charts.txt+++ b/tests/_data/snapshots/charts.txt@@ -22,6 +22,30 @@ _chart = ()_chart+# datetime+_chart = (+ alt.Chart(df)+ .mark_line(point={"filled": False, "fill": "white"})+ .encode(+ x=alt.X("some_column", type="temporal"),+ y=alt.Y("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart++# time+_chart = (+ alt.Chart(df)+ .mark_line(point={"filled": False, "fill": "white"})+ .encode(+ x=alt.X("some_column", type="temporal"),+ y=alt.Y("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart+# integer_chart = (alt.Chart(df)diff --git a/tests/_data/snapshots/charts_json.txt b/tests/_data/snapshots/charts_json.txtindex 09055d6335..99f854f5d6 100644--- a/tests/_data/snapshots/charts_json.txt+++ b/tests/_data/snapshots/charts_json.txt@@ -84,6 +84,96 @@"width": "container"}+# datetime+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "name": "data-afce120bec1de31b50bc39eae2fedbed"+ },+ "datasets": {+ "data-afce120bec1de31b50bc39eae2fedbed": [+ {+ "some_column": 1+ },+ {+ "some_column": 2+ },+ {+ "some_column": 3+ }+ ]+ },+ "encoding": {+ "x": {+ "field": "some_column",+ "type": "temporal"+ },+ "y": {+ "aggregate": "count",+ "type": "quantitative"+ }+ },+ "mark": {+ "point": {+ "fill": "white",+ "filled": false+ },+ "type": "line"+ },+ "width": "container"+}++# time+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "name": "data-afce120bec1de31b50bc39eae2fedbed"+ },+ "datasets": {+ "data-afce120bec1de31b50bc39eae2fedbed": [+ {+ "some_column": 1+ },+ {+ "some_column": 2+ },+ {+ "some_column": 3+ }+ ]+ },+ "encoding": {+ "x": {+ "field": "some_column",+ "type": "temporal"+ },+ "y": {+ "aggregate": "count",+ "type": "quantitative"+ }+ },+ "mark": {+ "point": {+ "fill": "white",+ "filled": false+ },+ "type": "line"+ },+ "width": "container"+}+# integer{"$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.pyindex 75e23b9847..c84852c304 100644--- a/tests/_data/test_charts.py+++ b/tests/_data/test_charts.py@@ -13,6 +13,8 @@ from tests.mocks import snapshotterTYPES: List[Tuple[DataType, bool]] = [("boolean", False),("date", False),+ ("datetime", False),+ ("time", False),("integer", False),("number", False),("string", False),diff --git a/tests/_data/test_get_datasets.py b/tests/_data/test_get_datasets.pyindex 1757c19f71..7bff1c02e5 100644--- a/tests/_data/test_get_datasets.py+++ b/tests/_data/test_get_datasets.py@@ -26,21 +26,120 @@ def test_get_datasets() -> None:import duckdb- duckdb.execute("CREATE TABLE cars (name TEXT, year INTEGER)")+ duckdb.execute("""+ CREATE TABLE all_types (+ col_boolean BOOLEAN,+ col_tinyint TINYINT,+ col_smallint SMALLINT,+ col_integer INTEGER,+ col_bigint BIGINT,+ col_hugeint HUGEINT,+ col_utinyint UTINYINT,+ col_usmallint USMALLINT,+ col_uinteger UINTEGER,+ col_ubigint UBIGINT,+ col_float FLOAT,+ col_double DOUBLE,+ col_decimal DECIMAL(18,3),+ col_varchar VARCHAR,+ col_date DATE,+ col_time TIME,+ col_timestamp TIMESTAMP,+ col_interval INTERVAL,+ col_blob BLOB,+ col_bit BIT,+ col_uuid UUID,+ col_json JSON+ )+ """)assert get_datasets_from_duckdb() == [DataTable(- name="memory.main.cars",+ name="memory.main.all_types",source_type="duckdb",source="memory",num_rows=None,- num_columns=2,+ num_columns=22,variable_name=None,columns=[DataTableColumn(- name="name", type="string", external_type="VARCHAR"+ name="col_boolean", type="boolean", external_type="BOOLEAN"+ ),+ DataTableColumn(+ name="col_tinyint", type="integer", external_type="TINYINT"+ ),+ DataTableColumn(+ name="col_smallint",+ type="integer",+ external_type="SMALLINT",+ ),+ DataTableColumn(+ name="col_integer", type="integer", external_type="INTEGER"+ ),+ DataTableColumn(+ name="col_bigint", type="integer", external_type="BIGINT"+ ),+ DataTableColumn(+ name="col_hugeint", type="integer", external_type="HUGEINT"+ ),+ DataTableColumn(+ name="col_utinyint",+ type="integer",+ external_type="UTINYINT",+ ),+ DataTableColumn(+ name="col_usmallint",+ type="integer",+ external_type="USMALLINT",+ ),+ DataTableColumn(+ name="col_uinteger",+ type="integer",+ external_type="UINTEGER",+ ),+ DataTableColumn(+ name="col_ubigint", type="integer", external_type="UBIGINT"+ ),+ DataTableColumn(+ name="col_float", type="number", external_type="FLOAT"+ ),+ DataTableColumn(+ name="col_double", type="number", external_type="DOUBLE"+ ),+ DataTableColumn(+ name="col_decimal",+ type="number",+ external_type="DECIMAL(18,3)",+ ),+ DataTableColumn(+ name="col_varchar", type="string", external_type="VARCHAR"+ ),+ DataTableColumn(+ name="col_date", type="date", external_type="DATE"+ ),+ DataTableColumn(+ name="col_time", type="time", external_type="TIME"+ ),+ DataTableColumn(+ name="col_timestamp",+ type="datetime",+ external_type="TIMESTAMP",+ ),+ DataTableColumn(+ name="col_interval",+ type="datetime",+ external_type="INTERVAL",+ ),+ DataTableColumn(+ name="col_blob", type="string", external_type="BLOB"+ ),+ DataTableColumn(+ name="col_bit", type="string", external_type="BIT"+ ),+ DataTableColumn(+ name="col_uuid", type="string", external_type="UUID"),DataTableColumn(- name="year", type="integer", external_type="INTEGER"+ name="col_json", type="unknown", external_type="JSON"),],)diff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex ae45c25762..da95737182 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -210,6 +210,89 @@ def test_get_column_preview_for_duckdb_date() -> None:assert result_date.chart_spec is None+ not HAS_SQL_DEPS, reason="optional dependencies not installed"+)+ sys.platform == "win32",+ reason="Windows encodes base64 differently",+)+def test_get_column_preview_for_duckdb_datetime() -> None:+ import datetime++ import duckdb++ # Test preview for a datetime column+ duckdb.execute("""+ CREATE OR REPLACE TABLE datetime_tbl AS+ SELECT TIMESTAMP '2023-01-01 00:00:00' ++ INTERVAL (range % 365) DAY ++ INTERVAL (range % 24) HOUR ++ INTERVAL (range % 60) MINUTE AS datetime_col+ FROM range(100)+ """)++ result_datetime = get_column_preview_for_sql(+ table_name="memory.main.datetime_tbl",+ column_name="datetime_col",+ )+ assert result_datetime is not None+ assert result_datetime.summary is not None+ assert result_datetime.error is None++ # Check if summary contains expected statistics for the datetime pattern+ assert result_datetime.summary.total == 100+ assert result_datetime.summary.unique == 100+ assert result_datetime.summary.nulls == 0+ assert result_datetime.summary.min == datetime.datetime(2023, 1, 1, 0, 0)+ assert result_datetime.summary.max == datetime.datetime(2023, 4, 10, 3, 39)++ # Not implemented yet+ assert result_datetime.chart_code is None+ assert result_datetime.chart_spec is None+++ not HAS_SQL_DEPS, reason="optional dependencies not installed"+)+ sys.platform == "win32",+ reason="Windows encodes base64 differently",+)+def test_get_column_preview_for_duckdb_time() -> None:+ import datetime++ import duckdb++ # Test preview for a time column+ duckdb.execute("""+ CREATE OR REPLACE TABLE time_tbl AS+ SELECT TIME '00:00:00' ++ INTERVAL (range % 24) HOUR ++ INTERVAL (range % 60) MINUTE AS time_col+ FROM range(100)+ """)++ result_time = get_column_preview_for_sql(+ table_name="memory.main.time_tbl",+ column_name="time_col",+ )+ assert result_time is not None+ assert result_time.summary is not None+ assert result_time.error is None++ # Check if summary contains expected statistics for the time pattern+ assert result_time.summary.total == 100+ assert result_time.summary.unique == 100+ assert result_time.summary.nulls == 0+ assert result_time.summary.min == datetime.time(0, 0)+ assert result_time.summary.max == datetime.time(23, 47)++ # Not implemented yet+ assert result_time.chart_code is None+ assert result_time.chart_spec is None++@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")diff --git a/tests/_data/test_sql_summaries.py b/tests/_data/test_sql_summaries.pyindex 7907a7edd9..d00a885e17 100644--- a/tests/_data/test_sql_summaries.py+++ b/tests/_data/test_sql_summaries.py@@ -27,18 +27,20 @@ def setup_test_db():age INTEGER,salary DECIMAL(10, 2),is_active BOOLEAN,- birth_date DATE+ birth_date DATE,+ time_col TIME,+ datetime_col DATETIME)""")# Insert some test dataduckdb.execute("""INSERT INTO test_table_3 VALUES- (1, 'Alice', 30, 50000.00, true, '1993-01-15'),- (2, 'Bob', 35, 60000.00, false, '1988-05-20'),- (3, 'Charlie', 28, 45000.00, true, '1995-11-30'),- (4, 'David', NULL, 55000.00, true, '1990-08-10'),- (5, 'Eve', 32, NULL, false, '1991-03-25')+ (1, 'Alice', 30, 50000.00, true, '1993-01-15', '12:30:00', '2024-01-01 12:30:00'),+ (2, 'Bob', 35, 60000.00, false, '1988-05-20', '13:45:00', '2024-02-02 13:45:00'),+ (3, 'Charlie', 28, 45000.00, true, '1995-11-30', '14:00:00', '2024-03-03 14:00:00'),+ (4, 'David', NULL, 55000.00, true, '1990-08-10', '15:15:00', '2024-04-04 15:15:00'),+ (5, 'Eve', 32, NULL, false, '1991-03-25', '16:30:00', '2024-05-05 16:30:00')""")yield duckdb@@ -106,3 +108,29 @@ def test_get_sql_summary_date(setup_test_db: Any):assert summary.nulls == 0assert summary.min == datetime.date(1988, 5, 20)assert summary.max == datetime.date(1995, 11, 30)++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_get_sql_summary_time(setup_test_db: Any):+ del setup_test_db++ summary = get_sql_summary("test_table_3", "time_col", "time")+ assert isinstance(summary, ColumnSummary)+ assert summary.total == 5+ assert summary.unique == 5+ assert summary.nulls == 0+ assert summary.min == datetime.time(12, 30)+ assert summary.max == datetime.time(16, 30)++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_get_sql_summary_datetime(setup_test_db: Any):+ del setup_test_db++ summary = get_sql_summary("test_table_3", "datetime_col", "datetime")+ assert isinstance(summary, ColumnSummary)+ assert summary.total == 5+ assert summary.unique == 5+ assert summary.nulls == 0+ assert summary.min == datetime.datetime(2024, 1, 1, 12, 30)+ assert summary.max == datetime.datetime(2024, 5, 5, 16, 30)diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.pyindex 138274fa90..6d12f366fb 100644--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py@@ -554,7 +554,7 @@ class TestTransformHandler:),(pl.DataFrame({"A": [1, 2, 3]}),- pl.exceptions.ColumnNotFoundError,+ (KeyError, pl.exceptions.ColumnNotFoundError),),(ibis.memtable({"A": [1, 2, 3]}),diff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv b/tests/_plugins/ui/_impl/tables/snapshots/ibis.csvindex 56096ef045..878da1dfaf 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv@@ -1,4 +1,4 @@-strings,bool,int,float,datetime,nulls-a,True,1,1.0,2021-01-01,-b,False,2,2.0,2021-01-02,data-c,True,3,3.0,2021-01-03,+strings,bool,int,float,date,datetime,time,nulls+a,True,1,1.0,2021-01-01,2021-01-01,01:02:03,+b,False,2,2.0,2021-01-02,2021-01-02,04:05:06,data+c,True,3,3.0,2021-01-03,2021-01-03,07:08:09,diff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.jsonindex e795788486..289de31b20 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json@@ -3,6 +3,8 @@"bool": ["boolean", "boolean"],"int": ["integer", "int64"],"float": ["number", "float64"],- "datetime": ["date", "timestamp"],+ "date": ["date", "date"],+ "datetime": ["datetime", "timestamp"],+ "time": ["time", "time"],"nulls": ["string", "string"]}diff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.json b/tests/_plugins/ui/_impl/tables/snapshots/ibis.jsonindex c10a5114d8..bf01409a78 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.json@@ -4,7 +4,9 @@"bool": true,"int": 1,"float": 1.0,+ "date": 1609459200000,"datetime": 1609459200,+ "time": "01:02:03","nulls": null},{@@ -12,7 +14,9 @@"bool": false,"int": 2,"float": 2.0,+ "date": 1609545600000,"datetime": 1609545600,+ "time": "04:05:06","nulls": "data"},{@@ -20,7 +24,9 @@"bool": true,"int": 3,"float": 3.0,+ "date": 1609632000000,"datetime": 1609632000,+ "time": "07:08:09","nulls": null}]diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv b/tests/_plugins/ui/_impl/tables/snapshots/polars.csvindex b65fb34f03..69e813ad37 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv@@ -1,4 +1,4 @@-strings,bool,int,float,datetime,struct,list,array,nulls,categorical,duration,mixed_list-a,true,1,1.0,2021-01-01T00:00:00.000000,"{""a"":1,""b"":2}","1,2","1,2,3",,cat,86400000000,"1,two"-b,false,2,2.0,2021-01-02T00:00:00.000000,"{""a"":3,""b"":4}","3,4",4,data,dog,172800000000,"3.0,0.0"-c,true,3,3.0,2021-01-03T00:00:00.000000,"{""a"":5,""b"":6}","5,6","",,mouse,259200000000,2021-01-01 00:00:00.000000+strings,bool,int,float,datetime,date,struct,list,array,nulls,category,set,imaginary,time,duration,mixed_list+a,true,1,1.0,2021-01-01T00:00:00.000000,2021-01-01,"{""a"":1,""b"":2}","1,2",1,,cat,"{1, 2}",(1+2j),12:30:00.000000000,86400000000,"1,two"+b,false,2,2.0,2021-01-02T00:00:00.000000,2021-01-02,"{""a"":3,""b"":4}","3,4",2,data,dog,"{3, 4}",(3+4j),13:45:00.000000000,172800000000,"3.0,0.0"+c,true,3,3.0,2021-01-03T00:00:00.000000,2021-01-03,"{""a"":5,""b"":6}","5,6",3,,mouse,"{5, 6}",(5+6j),14:15:00.000000000,259200000000,2021-01-01 00:00:00.000000diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.jsonindex 7c8047c5ad..8293adf855 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json@@ -3,12 +3,16 @@"bool": ["boolean", "bool"],"int": ["integer", "i64"],"float": ["number", "f64"],- "datetime": ["date", "datetime[\u03bcs]"],+ "datetime": ["datetime", "datetime[\u03bcs]"],+ "date": ["date", "date"],"struct": ["unknown", "struct[2]"],"list": ["unknown", "list[i64]"],- "array": ["unknown", "list[i64]"],+ "array": ["unknown", "array[i64, 1]"],"nulls": ["string", "str"],- "categorical": ["unknown", "cat"],- "duration": ["date", "duration[\u03bcs]"],+ "category": ["string", "cat"],+ "set": ["unknown", "object"],+ "imaginary": ["unknown", "object"],+ "time": ["time", "Time"],+ "duration": ["datetime", "duration[\u03bcs]"],"mixed_list": ["unknown", "list[str]"]}diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.jsonindex 7d5f1be8b4..9c165e5184 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.json@@ -5,11 +5,12 @@"int": 1,"float": 1.0,"datetime": "2021-01-01 00:00:00",+ "date": "2021-01-01","struct": { "a": 1, "b": 2 },"list": [1, 2],- "array": [1, 2, 3],+ "array": [1],"nulls": null,- "categorical": "cat",+ "category": "cat","duration": "PT86400S","mixed_list": ["1", "two"]},@@ -19,11 +20,12 @@"int": 2,"float": 2.0,"datetime": "2021-01-02 00:00:00",+ "date": "2021-01-02","struct": { "a": 3, "b": 4 },"list": [3, 4],- "array": [4],+ "array": [2],"nulls": "data",- "categorical": "dog",+ "category": "dog","duration": "PT172800S","mixed_list": ["3.0", "0.0"]},@@ -33,11 +35,12 @@"int": 3,"float": 3.0,"datetime": "2021-01-03 00:00:00",+ "date": "2021-01-03","struct": { "a": 5, "b": 6 },"list": [5, 6],- "array": [],+ "array": [3],"nulls": null,- "categorical": "mouse",+ "category": "mouse","duration": "PT259200S","mixed_list": [null, "2021-01-01 00:00:00.000000"]}diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.pyindex a7507f9ea1..357ecf4226 100644--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py@@ -31,11 +31,21 @@ class TestIbisTableManagerFactory(unittest.TestCase):"bool": [True, False, True],"int": [1, 2, 3],"float": [1.0, 2.0, 3.0],+ "date": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 2),+ datetime.date(2021, 1, 3),+ ],"datetime": [datetime.datetime(2021, 1, 1),datetime.datetime(2021, 1, 2),datetime.datetime(2021, 1, 3),],+ "time": [+ datetime.time(1, 2, 3),+ datetime.time(4, 5, 6),+ datetime.time(7, 8, 9),+ ],"nulls": [None, "data", None],})@@ -116,7 +126,7 @@ class TestIbisTableManagerFactory(unittest.TestCase):"B": ("string", "string"),"C": ("number", "float64"),"D": ("boolean", "boolean"),- "E": ("date", "timestamp"),+ "E": ("datetime", "timestamp"),}assert self.manager.get_field_types() == expected_field_typesdiff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex 4bc77838d7..b0888c4577 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -133,7 +133,7 @@ class TestPandasTableManager(unittest.TestCase):"B": ("string", "object"),"C": ("number", "float64"),"D": ("boolean", "bool"),- "E": ("date", "datetime64[ns]"),+ "E": ("datetime", "datetime64[ns]"),"F": ("string", "object"),}assert self.manager.get_field_types() == expected_field_types@@ -172,7 +172,7 @@ class TestPandasTableManager(unittest.TestCase):"E": ("unknown", "complex128"),"F": ("string", "object"),"G": ("string", "object"),- "H": ("date", "datetime64[ns]"),+ "H": ("datetime", "datetime64[ns]"),"I": ("string", "timedelta64[ns]"),"J": ("string", "interval[int64, right]"),}@@ -741,3 +741,32 @@ class TestPandasTableManager(unittest.TestCase):manager = self.factory.create()(df)assert manager.get_row_headers() == ["", ""]assert manager.get_num_rows() == 4++ def test_get_field_types_with_datetime(self):+ import pandas as pd++ data = pd.DataFrame(+ {+ "date_col": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 2),+ datetime.date(2021, 1, 3),+ ],+ "datetime_col": [+ datetime.datetime(2021, 1, 1),+ datetime.datetime(2021, 1, 2),+ datetime.datetime(2021, 1, 3),+ ],+ "time_col": [+ datetime.time(1, 2, 3),+ datetime.time(4, 5, 6),+ datetime.time(7, 8, 9),+ ],+ }+ )+ manager = self.factory.create()(data)+ field_types = manager.get_field_types()++ assert field_types["date_col"] == ("string", "object")+ assert field_types["datetime_col"] == ("datetime", "datetime64[ns]")+ assert field_types["time_col"] == ("string", "object")diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex 5810324e8f..5e8f80122e 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -36,25 +36,33 @@ class TestPolarsTableManagerFactory(unittest.TestCase):datetime.datetime(2021, 1, 2),datetime.datetime(2021, 1, 3),],+ "date": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 2),+ datetime.date(2021, 1, 3),+ ],"struct": [{"a": 1, "b": 2},{"a": 3, "b": 4},{"a": 5, "b": 6},],- "list": [[1, 2], [3, 4], [5, 6]],- "array": [[1, 2, 3], [4], []],- "nulls": [None, "data", None],- "categorical": pl.Series(["cat", "dog", "mouse"]).cast(- pl.Categorical+ "list": pl.Series(+ [[1, 2], [3, 4], [5, 6]], dtype=pl.List(pl.Int64)+ ),+ "array": pl.Series(+ [[1], [2], [3]], dtype=pl.Array(pl.Int64, 1)+ ),+ "nulls": pl.Series([None, "data", None]),+ "category": pl.Series(+ ["cat", "dog", "mouse"], dtype=pl.Categorical),- # raises:- # pyo3_runtime.PanicException:- # not yet implemented: Writing Time64(Nanosecond) to JSON- # "time": [- # datetime.time(12, 30),- # datetime.time(13, 45),- # datetime.time(14, 15),- # ],+ "set": [set([1, 2]), set([3, 4]), set([5, 6])],+ "imaginary": [1 + 2j, 3 + 4j, 5 + 6j],+ "time": [+ datetime.time(12, 30),+ datetime.time(13, 45),+ datetime.time(14, 15),+ ],"duration": [datetime.timedelta(days=1),datetime.timedelta(days=2),@@ -121,7 +129,14 @@ class TestPolarsTableManagerFactory(unittest.TestCase):assert isinstance(self.manager.to_json(), bytes)complex_data = self.get_complex_data()- data = complex_data.to_json()+ # pl.Time and pl.Object are not supported in JSON+ other_columns = [+ col+ for col in complex_data.get_column_names()+ if col not in ["time", "set", "imaginary"]+ ]+ manager = complex_data.select_columns(other_columns)+ data = manager.to_json()assert isinstance(data, bytes)snapshot("polars.json", data.decode("utf-8"))@@ -163,7 +178,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):"B": ("string", "str"),"C": ("number", "f64"),"D": ("boolean", "bool"),- "E": ("date", "datetime[μs]"),+ "E": ("datetime", "datetime[μs]"),}assert self.manager.get_field_types() == expected_field_types@@ -191,6 +206,16 @@ class TestPolarsTableManagerFactory(unittest.TestCase):"5-10","10-15",],+ "K": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 2),+ datetime.date(2021, 1, 3),+ ],+ "L": [+ datetime.time(1, 2, 3),+ datetime.time(4, 5, 6),+ datetime.time(7, 8, 9),+ ],})expected_field_types = {@@ -201,9 +226,11 @@ class TestPolarsTableManagerFactory(unittest.TestCase):"E": ("unknown", "object"),"F": ("unknown", "null"),"G": ("unknown", "object"),- "H": ("date", "datetime[μs]"),+ "H": ("datetime", "datetime[μs]"),"I": ("string", "str"),"J": ("string", "str"),+ "K": ("date", "date"),+ "L": ("time", "Time"),}assert (self.factory.create()(complex_data).get_field_types()@@ -308,6 +335,11 @@ class TestPolarsTableManagerFactory(unittest.TestCase):median=datetime.datetime(2021, 1, 1, 12, 0),)+ def test_summary_does_fail_on_each_column(self) -> None:+ complex_data = self.get_complex_data()+ for column in complex_data.get_column_names():+ assert complex_data.get_summary(column) is not None+def test_sort_values(self) -> None:sorted_df = self.manager.sort_values("A", descending=True).dataexpected_df = self.data.sort("A", descending=True)@@ -666,3 +698,29 @@ class TestPolarsTableManagerFactory(unittest.TestCase):manager = self.factory.create()(df)sorted_manager = manager.sort_values("A", descending=True)assert sorted_manager.data["A"].to_list() == [None, 3, 2, 1]++ def test_get_field_types_with_datetime(self):+ import polars as pl++ data = pl.DataFrame(+ {+ "date_col": [+ datetime.date(2021, 1, 1),+ datetime.date(2021, 1, 3),+ ],+ "datetime_col": [+ datetime.datetime(2021, 1, 1),+ datetime.datetime(2021, 1, 3),+ ],+ "time_col": [+ datetime.time(1, 2, 3),+ datetime.time(4, 5, 6),+ ],+ }+ )+ manager = self.factory.create()(data)+ field_types = manager.get_field_types()++ assert field_types["date_col"] == ("date", "date")+ assert field_types["datetime_col"] == ("datetime", "datetime[μs]")+ assert field_types["time_col"] == ("time", "Time")