Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 36 additions & 11 deletions core/crates/drivers/duckdb/src/create_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ fn build_empty(temporary: &Path, target: &Path) -> Result<(), DriverError> {
std::fs::set_permissions(temporary, std::fs::Permissions::from_mode(0o600))
.map_err(|error| file_error(error.kind(), target))?;
}
File::open(temporary)
// Windows flushes only a handle opened for writing.
OpenOptions::new()
.write(true)
.open(temporary)
.and_then(|file| file.sync_all())
.map_err(|error| file_error(error.kind(), target))
}
Expand Down Expand Up @@ -187,12 +190,31 @@ fn wal_of(path: &Path) -> PathBuf {
}

#[cfg(test)]
#[cfg(unix)]
mod tests {
use std::os::unix::fs::PermissionsExt;

use super::*;

fn tables_in(path: &Path) -> i64 {
let reopened = duckdb::Connection::open(path).unwrap();
reopened
.query_row("SELECT count(*) FROM duckdb_tables()", [], |row| row.get(0))
.unwrap()
}

#[test]
fn a_new_database_is_made_where_no_file_was() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("new.duckdb");

create_or_replace(&path, &CancellationToken::new()).unwrap();

let made: Vec<_> = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(made, [std::ffi::OsString::from("new.duckdb")]);
assert_eq!(tables_in(&path), 0);
}

#[test]
fn an_existing_file_and_its_log_are_replaced_by_an_empty_private_database() {
let directory = tempfile::tempdir().unwrap();
Expand All @@ -202,8 +224,13 @@ mod tests {

create_or_replace(&path, &CancellationToken::new()).unwrap();

let metadata = std::fs::metadata(&path).unwrap();
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;

let metadata = std::fs::metadata(&path).unwrap();
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
}
assert!(
!wal_of(&path).exists(),
"the old log would be replayed into the new database"
Expand All @@ -213,11 +240,7 @@ mod tests {
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(leftovers, [std::ffi::OsString::from("data.duckdb")]);
let reopened = duckdb::Connection::open(&path).unwrap();
let tables: i64 = reopened
.query_row("SELECT count(*) FROM duckdb_tables()", [], |row| row.get(0))
.unwrap();
assert_eq!(tables, 0);
assert_eq!(tables_in(&path), 0);
}

#[test]
Expand Down Expand Up @@ -246,6 +269,8 @@ mod tests {
);
}

// Windows lists no process's handles, so there only a claim says a file is held.
#[cfg(unix)]
#[test]
fn a_file_this_process_holds_is_not_replaced() {
let directory = tempfile::tempdir().unwrap();
Expand Down
2 changes: 2 additions & 0 deletions core/crates/drivers/duckdb/src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,8 @@ mod tests {

/// Measured against DuckDB 1.5: a missing part is passed by its text,
/// a link is followed before the `..` after it.
// Windows makes a symbolic link only in Developer Mode or with an administrator's right.
#[cfg(unix)]
#[test]
fn a_path_is_resolved_as_duckdb_opens_it() {
let root = tempfile::tempdir().unwrap();
Expand Down
10 changes: 6 additions & 4 deletions core/crates/drivers/sqlite/src/create_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,7 @@ fn file_error(kind: ErrorKind, path: &Path) -> DriverError {
}

#[cfg(test)]
#[cfg(unix)]
mod tests {
use std::os::unix::fs::PermissionsExt;

use super::*;

#[test]
Expand All @@ -92,7 +89,12 @@ mod tests {

let metadata = std::fs::metadata(&path).unwrap();
assert_eq!(metadata.len(), 0);
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;

assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
}
let leftovers: Vec<_> = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,8 @@ private async void OnNewFile(object sender, RoutedEventArgs e)
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = Strings.Get("NewDatabaseFileName"),
// A file that is there already is opened as it is, never replaced, so the picker does not ask to replace it.
ShowOverwritePrompt = false,
};
if (suffixes.Count > 0)
{
Expand All @@ -633,8 +635,8 @@ private async void OnNewFile(object sender, RoutedEventArgs e)
if (result is not null)
{
FileBox.Text = result.Path;
_createFile = true;
SetStatus(Strings.Get("NewFileOnConnect"), null);
_createFile = !File.Exists(result.Path);
SetStatus(Strings.Get(_createFile ? "NewFileOnConnect" : "NewFileExists"), null);
}
}

Expand Down
3 changes: 3 additions & 0 deletions windows/src/TablePro.App/Strings/en-US/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,9 @@
<data name="NewFileOnConnect" xml:space="preserve">
<value>The file is made when you connect</value>
</data>
<data name="NewFileExists" xml:space="preserve">
<value>This file exists, so it opens as it is</value>
</data>
<data name="Testing" xml:space="preserve">
<value>Testing...</value>
</data>
Expand Down
108 changes: 108 additions & 0 deletions windows/tests/TablePro.App.UITests/NewFileTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Definitions;
using FlaUI.Core.Input;
using FlaUI.Core.Tools;
using FlaUI.Core.WindowsAPI;

namespace TablePro.App.UITests;

public sealed partial class ShellTests
{
public static TheoryData<string, string> ThemesAndFileEngines => new()
{
{ "Light", "duckdb" },
{ "Dark", "duckdb" },
{ "Light", "sqlite" },
{ "Dark", "sqlite" },
};

[Theory]
[MemberData(nameof(ThemesAndFileEngines))]
public void ANewFileNamedInTheSavePickerIsMadeAndConnects(string theme, string engine)
{
using var app = AppSession.Launch(theme);
var file = Path.Combine(app.DataFolder, $"made.{engine}");
var name = $"New {engine} file";
app.Click(app.Find("NewConnectionCard"), () => app.HasWindow("New connection"));
var form = app.WaitForWindow("New connection");
app.Click(app.Find($"Engine_{engine}", form), () => app.TryFind("FileBox", form) is not null, form);
app.Find("NameBox", form).AsTextBox().Text = name;
app.Click(app.Find("NewFileButton", form), () => SaveDialog(app, form) is not null, form);
SaveInFileDialog(app, form, file);
// The path reaches the form after the dialog closes, with a folder typed by its 8.3 name in its long form.
var fileBox = app.Find("FileBox", form).AsTextBox();
Assert.True(
Retry.WhileFalse(() => Path.GetFileName(fileBox.Text) == Path.GetFileName(file), AppSession.Wait, throwOnTimeout: false).Success,
"The form shows " + fileBox.Text);
Assert.False(File.Exists(file), "the picker made the file before Connect");
var status = app.Find("FormStatus", form);
Assert.Equal("The file is made when you connect", AppSession.WaitForText(status, text => text.Length > 0));
app.Screenshot($"109-new-{engine}-file-named", form);

app.Find("ConnectButton", form).AsButton().Invoke();
// The status is read only while the form is still open, since a closed form's elements are gone.
if (!Retry.WhileFalse(() => !app.HasWindow("New connection"), AppSession.Wait, throwOnTimeout: false).Success)
{
Assert.Fail("The form stayed open: " + AppSession.TextOf(status));
}

Assert.True(File.Exists(file));
Assert.False(app.Find($"Rail_{name}").IsOffscreen);
app.Find("ObjectTree");
app.Screenshot($"110-new-{engine}-file-connected");
}

[Theory]
[MemberData(nameof(Themes))]
public void AnExistingFileNamedForANewOneOpensAsItIsWithoutAReplaceQuestion(string theme)
{
using var app = AppSession.Launch(theme);
var file = AppSession.SampleDatabase(app.DataFolder);
app.Click(app.Find("NewConnectionCard"), () => app.HasWindow("New connection"));
var form = app.WaitForWindow("New connection");
app.Click(app.Find("Engine_sqlite", form), () => app.TryFind("FileBox", form) is not null, form);
app.Find("NameBox", form).AsTextBox().Text = "Kept";
app.Click(app.Find("NewFileButton", form), () => SaveDialog(app, form) is not null, form);
SaveInFileDialog(app, form, file);
Assert.Equal(
"This file exists, so it opens as it is",
AppSession.WaitForText(app.Find("FormStatus", form), text => text.Length > 0));
app.Screenshot("111-new-file-exists", form);

app.Find("ConnectButton", form).AsButton().Invoke();
app.WaitForClose("New connection");
app.FindByName("Album", app.Find("ObjectTree"));
}

// The form owns its picker, so UI Automation lists it under the form, the app's window or the desktop.
private static Window? SaveDialog(AppSession app, Window form) =>
form.FindFirstChild(condition => condition.ByClassName("#32770"))?.AsWindow() ?? FileDialog(app);

// The Save dialog's File name box is control 1001, and Enter saves to the path typed there.
private static void SaveInFileDialog(AppSession app, Window form, string path)
{
var dialog = Retry.WhileNull(() => SaveDialog(app, form), AppSession.Wait, throwOnTimeout: false).Result
?? throw new InvalidOperationException("The Save dialog did not appear.");
var box = Retry.WhileNull(
() => dialog.FindFirstDescendant(condition =>
condition.ByAutomationId("1001").And(condition.ByControlType(ControlType.Edit))),
AppSession.Wait,
throwOnTimeout: false).Result
?? throw new InvalidOperationException("The Save dialog has no File name box.");
// The Save dialog keeps its suggested name when the box's value is set without typing, so the path is typed.
dialog.SetForeground();
box.Focus();
Keyboard.TypeSimultaneously(VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_A);
Keyboard.Type(path);
if (!Retry.WhileFalse(() => box.AsTextBox().Text == path, AppSession.Wait, throwOnTimeout: false).Success)
{
throw new InvalidOperationException("The Save dialog did not take the path typed.");
}

Keyboard.Type(VirtualKeyShort.RETURN);
if (!Retry.WhileFalse(() => SaveDialog(app, form) is null, AppSession.Wait, throwOnTimeout: false).Success)
{
throw new InvalidOperationException("The Save dialog did not take the path.");
}
}
}
42 changes: 42 additions & 0 deletions windows/tests/TablePro.Interop.Tests/NewFileTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace TablePro.Interop.Tests;

public sealed class NewFileTests : IDisposable
{
private readonly string _directory = Directory.CreateTempSubdirectory("tablepro-new-file-").FullName;
private readonly TableProCore _core = TableProCore.Create(new HostConfiguration("test"), new MemorySecretStore());

public void Dispose()
{
_core.Dispose();
try
{
Directory.Delete(_directory, recursive: true);
}
catch (IOException)
{
// The database closes on the core's own threads, which can still hold it here on Windows.
}
}

// As the connection form's New file does: make the file, close it, then connect to it as saved.
[Theory]
[InlineData("duckdb", "made.duckdb")]
[InlineData("sqlite", "made.sqlite")]
public async Task ANewFileIsMadeEmptyAndOpensAgainForWriting(string engine, string name)
{
var cancellationToken = TestContext.Current.CancellationToken;
var path = Path.Combine(_directory, name);

var made = await _core.OpenFileAsync(new FileOpenOptions(path, engine, Create: true), cancellationToken);
await made.DisposeAsync();

Assert.True(File.Exists(path));
Assert.DoesNotContain(Directory.GetFiles(_directory), file => Path.GetFileName(file).StartsWith('.'));
await using var session = await _core.OpenFileAsync(new FileOpenOptions(path, engine), cancellationToken);
Assert.Equal(engine, session.EngineId);
Assert.Empty(await session.RefreshObjectsAsync(ObjectScope.DefaultSchema, cancellationToken));
await using var editor = await session.OpenEditorAsync(cancellationToken);
using var run = editor.Run("CREATE TABLE notes (body TEXT)", cancellationToken: cancellationToken);
Assert.IsType<QueryOutcome.Completed>(await run.Completion);
}
}
Loading