From 2d5add6dcf1a0abd1e196d591555061c08c861b0 Mon Sep 17 00:00:00 2001 From: ppvan Date: Tue, 19 Mar 2024 21:39:54 +0700 Subject: [PATCH] chore: run the formatter --- meson.options | 6 - script/formater.sh | 7 + src/application.vala | 499 ++++++++++---------- src/models/Connection.vala | 146 +++--- src/models/Query.vala | 42 +- src/models/Relation.vala | 324 ++++++------- src/models/Table.vala | 41 +- src/repositories/ConnectionRepository.vala | 306 ++++++------ src/repositories/QueryRepository.vala | 194 ++++---- src/repositories/SchemaRepository.vala | 18 +- src/services/ConnectionService.vala | 10 +- src/services/Container.vala | 62 +-- src/services/ExportService.vala | 67 +-- src/services/NavigationService.vala | 36 +- src/services/ResourceManager.vala | 15 +- src/services/SQLCompletionService.vala | 448 +++++++++--------- src/services/SQLService.vala | 290 ++++++------ src/services/SchemaService.vala | 54 +-- src/services/StorageService.vala | 86 ++-- src/ui/PreferencesWindow.vala | 163 ++++--- src/ui/Window.vala | 216 +++++---- src/ui/editor/QueryEditor.vala | 448 +++++++++--------- src/ui/schema/QueryResult.vala | 319 +++++++------ src/ui/schema/TableColumnInfo.vala | 147 +++--- src/ui/schema/TableDataView.vala | 54 +-- src/ui/schema/TableForeignKeyInfo.vala | 208 ++++---- src/ui/schema/TableIndexInfo.vala | 185 ++++---- src/ui/schema/TableStructureView.vala | 53 +-- src/ui/schema/ViewDataView.vala | 45 +- src/ui/schema/ViewStructureView.vala | 49 +- src/ui/views/ConnectionView.vala | 315 ++++++------ src/ui/views/SchemaView.vala | 196 ++++---- src/ui/widgets/DataCell.vala | 141 +++--- src/ui/widgets/StyleSwitcher.vala | 105 ++-- src/utils/Event.vala | 84 ++-- src/utils/ObservableList.vala | 171 +++---- src/utils/ValueConverter.vala | 74 ++- src/utils/errors.vala | 15 +- src/utils/helpers.vala | 103 ++-- src/utils/logging.vala | 46 +- src/utils/types.vala | 73 ++- src/viewmodels/BaseViewModel.vala | 35 +- src/viewmodels/ConnectionViewModel.vala | 190 ++++---- src/viewmodels/QueryHistoryViewModel.vala | 122 ++--- src/viewmodels/QueryViewModel.vala | 47 +- src/viewmodels/SchemaViewModel.vala | 135 +++--- src/viewmodels/TableDataViewModel.vala | 114 ++--- src/viewmodels/TableStructureViewModel.vala | 192 ++++---- src/viewmodels/TableViewModel.vala | 95 ++-- src/viewmodels/ViewDataViewModel.vala | 112 ++--- src/viewmodels/ViewStructureViewModel.vala | 147 +++--- src/viewmodels/ViewViewModel.vala | 96 ++-- uncrustify.cfg | 402 ++++++++++++++++ 53 files changed, 4004 insertions(+), 3544 deletions(-) delete mode 100644 meson.options create mode 100755 script/formater.sh create mode 100644 uncrustify.cfg diff --git a/meson.options b/meson.options deleted file mode 100644 index c6273d7..0000000 --- a/meson.options +++ /dev/null @@ -1,6 +0,0 @@ -option ('profile', - type: 'combo', - value: 'development', - choices: ['release', 'development'], - description: 'The build profile for the app. If none specified, "development" is used.' -) diff --git a/script/formater.sh b/script/formater.sh new file mode 100755 index 0000000..c1c90e1 --- /dev/null +++ b/script/formater.sh @@ -0,0 +1,7 @@ +#!/usr/bin/bash +# git diff --name-only --diff-filter=ACM + +for i in $(git diff --name-only --diff-filter=ACM|grep .vala$); +do + uncrustify -l VALA -c uncrustify.cfg --replace --no-backup $i; +done \ No newline at end of file diff --git a/src/application.vala b/src/application.vala index 3cf8543..30a56bb 100644 --- a/src/application.vala +++ b/src/application.vala @@ -20,289 +20,294 @@ using Csv; namespace Psequel { - - - public enum ApplicationStyle { - SYSTEM = 0, - LIGHT, - DARK +public enum ApplicationStyle +{ + SYSTEM = 0, + LIGHT, + DARK +} + +public class Application : Adw.Application { + /* + * Static field for easy access in other places. + * If need to create many application instance (rarely happens) reconsider this approach. + */ + public static ThreadPool background; + + public int color_scheme { get; set; } + public const int MAX_COLUMNS = 128; + public const int PRE_ALLOCATED_CELL = 1024; + public const int BATCH_SIZE = 16; + + public static List tasks; + public static bool is_running = false; + + public Application() { + Object(application_id: Config.APP_ID, flags: ApplicationFlags.DEFAULT_FLAGS); } - public class Application : Adw.Application { - - /* - * Static field for easy access in other places. - * If need to create many application instance (rarely happens) reconsider this approach. - */ - public static ThreadPool background; - - public int color_scheme { get; set; } - public const int MAX_COLUMNS = 128; - public const int PRE_ALLOCATED_CELL = 1024; - public const int BATCH_SIZE = 16; - - public static List tasks; - public static bool is_running = false; - - public Application () { - Object (application_id: Config.APP_ID, flags: ApplicationFlags.DEFAULT_FLAGS); - } - - construct { - ActionEntry[] action_entries = { - { "about", this.on_about_action }, - { "preferences", this.on_preferences_action }, - { "new-window", this.on_new_window }, - { "quit", this.quit } - }; - this.add_action_entries (action_entries, this); - - this.set_accels_for_action ("app.new-window", { "n" }); - this.set_accels_for_action ("app.quit", { "q" }); - this.set_accels_for_action ("app.preferences", { "comma" }); + construct { + ActionEntry[] action_entries = { + { "about", this.on_about_action }, + { "preferences", this.on_preferences_action }, + { "new-window", this.on_new_window }, + { "quit", this.quit } + }; + this.add_action_entries(action_entries, this); - this.set_accels_for_action ("win.import", { "o" }); - this.set_accels_for_action ("win.export", { "e" }); - this.set_accels_for_action ("win.run-query", { "Return" }); + this.set_accels_for_action("app.new-window", { "n" }); + this.set_accels_for_action("app.quit", { "q" }); + this.set_accels_for_action("app.preferences", { "comma" }); - // this.set_accels_for_action ("conn.dupplicate", { "D" }); - } + this.set_accels_for_action("win.import", { "o" }); + this.set_accels_for_action("win.export", { "e" }); + this.set_accels_for_action("win.run-query", { "Return" }); - public override void activate () { - base.activate (); + // this.set_accels_for_action ("conn.dupplicate", { "D" }); + } - var window = new_window (); - window.present (); + public override void activate() { + base.activate(); + var window = new_window(); + window.present(); - // Pre-allocated widget, scheduled after window presented - DataCell.cell_pool = new List (); - var id = Idle.add (() => { - size_t empty_cells = DataCell.cell_pool.length (); - if (empty_cells < Application.PRE_ALLOCATED_CELL) { - debug ("Empty Cell: %llu", empty_cells); - for (size_t i = 0; i < Application.BATCH_SIZE; i++) { - DataCell.cell_pool.append (new DataCell()); + // Pre-allocated widget, scheduled after window presented + DataCell.cell_pool = new List (); + var id = Idle.add(() => { + size_t empty_cells = DataCell.cell_pool.length(); + if (empty_cells < Application.PRE_ALLOCATED_CELL) + { + debug("Empty Cell: %llu", empty_cells); + for (size_t i = 0; i < Application.BATCH_SIZE; i++) + { + DataCell.cell_pool.append(new DataCell()); } - } else if (empty_cells >= Application.PRE_ALLOCATED_CELL) { - return false; + } + else if (empty_cells >= Application.PRE_ALLOCATED_CELL) + { + return(false); } - return Application.is_running; + return(Application.is_running); }, Priority.DEFAULT_IDLE); - Application.tasks.append (id); - } + Application.tasks.append(id); + } - public override void startup () { - base.startup (); - GtkSource.init (); - set_up_logging (); + public override void startup() { + base.startup(); + GtkSource.init(); + set_up_logging(); - var settings = new Settings (this.application_id); - settings.bind ("color-scheme", this, "color_scheme", SettingsBindFlags.GET); - this.notify["color-scheme"].connect (update_color_scheme); + var settings = new Settings(this.application_id); + settings.bind("color-scheme", this, "color_scheme", SettingsBindFlags.GET); + this.notify["color-scheme"].connect(update_color_scheme); - var container = Container.instance (); - container.register (settings); - container.register (this); + var container = Container.instance(); + container.register(settings); + container.register(this); - Application.tasks = new List(); - this.is_running = true; + Application.tasks = new List (); + this.is_running = true; - debug ("Begin to load resources"); - try { - // Don't change the max_thread because libpq did not support many query with 1 connection. - background = new ThreadPool.with_owned_data ((worker) => { - worker.run (); + debug("Begin to load resources"); + try { + // Don't change the max_thread because libpq did not support many query with 1 connection. + background = new ThreadPool .with_owned_data((worker) => { + worker.run(); }, 1, false); - } catch (ThreadError err) { - debug (err.message); - assert_not_reached (); - } - debug ("Resources loaded"); - } - - public override void shutdown () { - base.shutdown (); - Application.is_running = false; + } catch (ThreadError err) { + debug(err.message); + assert_not_reached(); } + debug("Resources loaded"); + } - public void update_color_scheme () { - switch (this.color_scheme) { - case ApplicationStyle.SYSTEM: - style_manager.color_scheme = Adw.ColorScheme.DEFAULT; - break; - case ApplicationStyle.DARK: - style_manager.color_scheme = Adw.ColorScheme.FORCE_DARK; - break; - case ApplicationStyle.LIGHT: - style_manager.color_scheme = Adw.ColorScheme.FORCE_LIGHT; - break; - default: - assert_not_reached (); - } - } + public override void shutdown() { + base.shutdown(); + Application.is_running = false; + } - public void on_something () { - debug ("Dark: %b", style_manager.dark); - if (style_manager.dark) { - style_manager.color_scheme = Adw.ColorScheme.FORCE_LIGHT; - } else { - style_manager.color_scheme = Adw.ColorScheme.FORCE_DARK; - } + public void update_color_scheme() { + switch (this.color_scheme) + { + case ApplicationStyle.SYSTEM: + style_manager.color_scheme = Adw.ColorScheme.DEFAULT; + break; - // style_manager.dark = !style_manager.dark; - } + case ApplicationStyle.DARK: + style_manager.color_scheme = Adw.ColorScheme.FORCE_DARK; + break; - public static int main (string[] args) { - ensure_types (); - var app = new Psequel.Application (); + case ApplicationStyle.LIGHT: + style_manager.color_scheme = Adw.ColorScheme.FORCE_LIGHT; + break; - return app.run (args); + default: + assert_not_reached(); } + } - /* register needed types, allow me to ref a template inside a template */ - private static void ensure_types () { - - typeof (Psequel.StyleSwitcher).ensure (); - typeof (Psequel.DataCell).ensure (); - typeof (Psequel.ConnectionViewModel).ensure (); - typeof (Psequel.SchemaView).ensure (); - - typeof (Psequel.ConnectionRow).ensure (); - typeof (Psequel.ConnectionView).ensure (); - typeof (Psequel.QueryResults).ensure (); - typeof (Psequel.QueryEditor).ensure (); - typeof (Psequel.TableStructureView).ensure (); - typeof (Psequel.ViewStructureView).ensure (); - typeof (Psequel.TableDataView).ensure (); - typeof (Psequel.ViewDataView).ensure (); - typeof (Psequel.TableColInfo).ensure (); - typeof (Psequel.TableIndexInfo).ensure (); - typeof (Psequel.TableFKInfo).ensure (); + public void on_something() { + debug("Dark: %b", style_manager.dark); + if (style_manager.dark) + { + style_manager.color_scheme = Adw.ColorScheme.FORCE_LIGHT; } - - private void on_about_action () { - string[] developers = { "ppvan" }; - - var about = new Adw.AboutWindow () { - transient_for = this.get_active_window (), - application_name = Config.APP_NAME, - application_icon = Config.APP_ID, - developer_name = "Phạm Văn Phúc", - version = Config.VERSION, - developers = developers, - copyright = "© 2023 ppvan", - license_type = Gtk.License.GPL_3_0_ONLY, - issue_url = "https://github.com/ppvan/psequel/issues", - - developers = { - "ppvan https://ppvan.me", - }, - }; - - about.present (); + else + { + style_manager.color_scheme = Adw.ColorScheme.FORCE_DARK; } - private void on_new_window () { - var window = new_window (); - window.present (); - } + // style_manager.dark = !style_manager.dark; + } - private void on_preferences_action () { + public static int main(string[] args) { + ensure_types(); + var app = new Psequel.Application(); - var preference = new PreferencesWindow () { - transient_for = this.active_window, - modal = true, - application = this, - }; + return(app.run(args)); + } - preference.present (); - } + /* register needed types, allow me to ref a template inside a template */ + private static void ensure_types() { + typeof(Psequel.StyleSwitcher).ensure(); + typeof(Psequel.DataCell).ensure(); + typeof(Psequel.ConnectionViewModel).ensure(); + typeof(Psequel.SchemaView).ensure(); + + typeof(Psequel.ConnectionRow).ensure(); + typeof(Psequel.ConnectionView).ensure(); + typeof(Psequel.QueryResults).ensure(); + typeof(Psequel.QueryEditor).ensure(); + typeof(Psequel.TableStructureView).ensure(); + typeof(Psequel.ViewStructureView).ensure(); + typeof(Psequel.TableDataView).ensure(); + typeof(Psequel.ViewDataView).ensure(); + typeof(Psequel.TableColInfo).ensure(); + typeof(Psequel.TableIndexInfo).ensure(); + typeof(Psequel.TableFKInfo).ensure(); + } - /** - * Create a window and inject resources. - * - * Because child widget is created before window, signals can only be connect when window is init. - * This result to another event to notify window is ready and widget should setup signals - */ - private Window new_window () { + private void on_about_action() { + string[] developers = { "ppvan" }; + + var about = new Adw.AboutWindow() { + transient_for = this.get_active_window(), + application_name = Config.APP_NAME, + application_icon = Config.APP_ID, + developer_name = "Phạm Văn Phúc", + version = Config.VERSION, + developers = developers, + copyright = "© 2023 ppvan", + license_type = Gtk.License.GPL_3_0_ONLY, + issue_url = "https://github.com/ppvan/psequel/issues", + + developers = { + "ppvan https://ppvan.me", + }, + }; + + about.present(); + } - // give temp access because window is not created yet - create_viewmodels (); - var window = new Window (this); + private void on_new_window() { + var window = new_window(); + window.present(); + } - return window; - } + private void on_preferences_action() { + var preference = new PreferencesWindow(){ + transient_for = this.active_window, + modal = true, + application = this, + }; - private Container create_viewmodels () { - var container = Container.instance (); - var app_data_dir = Path.build_filename (GLib.Environment.get_user_data_dir (), Config.APP_ID); - DirUtils.create_with_parents (app_data_dir, 0777); - - var db_file = File.new_for_path (Path.build_filename (app_data_dir, "database.sqlite3")); - - // services - var storage_service = new StorageService (db_file.get_path ()); - container.register (storage_service); - - - var sql_service = new SQLService (Application.background); - var schema_service = new SchemaService (sql_service); - var connection_repo = new ConnectionRepository (); - var query_repo = new QueryRepository (); - var navigation = new NavigationService (); - var export = new ExportService (); - var completer = new CompleterService (sql_service); - - // viewmodels - var conn_vm = new ConnectionViewModel (connection_repo, sql_service, navigation); - var sche_vm = new SchemaViewModel (schema_service); - var table_vm = new TableViewModel (sql_service); - var view_vm = new ViewViewModel (sql_service); - var table_structure_vm = new TableStructureViewModel (sql_service); - var view_structure_vm = new ViewStructureViewModel (sql_service); - var table_data_vm = new TableDataViewModel (sql_service); - var view_data_vm = new ViewDataViewModel (sql_service); - var query_history_vm = new QueryHistoryViewModel (sql_service, query_repo); - var query_vm = new QueryViewModel (query_history_vm); - - container.register (sql_service); - container.register (completer); - container.register (schema_service); - container.register (export); - container.register (connection_repo); - container.register (navigation); - container.register (conn_vm); - container.register (sche_vm); - container.register (table_vm); - container.register (view_vm); - container.register (table_structure_vm); - container.register (view_structure_vm); - container.register (table_data_vm); - container.register (view_data_vm); - container.register (query_history_vm); - container.register (query_vm); - - // events - conn_vm.subcribe (Event.ACTIVE_CONNECTION, sche_vm); - - sche_vm.subcribe (Event.SCHEMA_CHANGED, completer); - sche_vm.subcribe (Event.SCHEMA_CHANGED, table_vm); - sche_vm.subcribe (Event.SCHEMA_CHANGED, view_vm); - sche_vm.subcribe (Event.SCHEMA_CHANGED, table_structure_vm); - sche_vm.subcribe (Event.SCHEMA_CHANGED, view_structure_vm); - - table_vm.subcribe (Event.SELECTED_TABLE_CHANGED, table_structure_vm); - table_vm.subcribe (Event.SELECTED_TABLE_CHANGED, table_data_vm); - - view_vm.subcribe (Event.SELECTED_VIEW_CHANGED, view_structure_vm); - view_vm.subcribe (Event.SELECTED_VIEW_CHANGED, view_data_vm); - - - return container; - } + preference.present(); + } + + /** + * Create a window and inject resources. + * + * Because child widget is created before window, signals can only be connect when window is init. + * This result to another event to notify window is ready and widget should setup signals + */ + private Window new_window() { + // give temp access because window is not created yet + create_viewmodels(); + var window = new Window(this); + + return(window); + } + + private Container create_viewmodels() { + var container = Container.instance(); + var app_data_dir = Path.build_filename(GLib.Environment.get_user_data_dir(), Config.APP_ID); + DirUtils.create_with_parents(app_data_dir, 0777); + + var db_file = File.new_for_path(Path.build_filename(app_data_dir, "database.sqlite3")); + + // services + var storage_service = new StorageService(db_file.get_path()); + container.register(storage_service); + + + var sql_service = new SQLService(Application.background); + var schema_service = new SchemaService(sql_service); + var connection_repo = new ConnectionRepository(); + var query_repo = new QueryRepository(); + var navigation = new NavigationService(); + var export = new ExportService(); + var completer = new CompleterService(sql_service); + + // viewmodels + var conn_vm = new ConnectionViewModel(connection_repo, sql_service, navigation); + var sche_vm = new SchemaViewModel(schema_service); + var table_vm = new TableViewModel(sql_service); + var view_vm = new ViewViewModel(sql_service); + var table_structure_vm = new TableStructureViewModel(sql_service); + var view_structure_vm = new ViewStructureViewModel(sql_service); + var table_data_vm = new TableDataViewModel(sql_service); + var view_data_vm = new ViewDataViewModel(sql_service); + var query_history_vm = new QueryHistoryViewModel(sql_service, query_repo); + var query_vm = new QueryViewModel(query_history_vm); + + container.register(sql_service); + container.register(completer); + container.register(schema_service); + container.register(export); + container.register(connection_repo); + container.register(navigation); + container.register(conn_vm); + container.register(sche_vm); + container.register(table_vm); + container.register(view_vm); + container.register(table_structure_vm); + container.register(view_structure_vm); + container.register(table_data_vm); + container.register(view_data_vm); + container.register(query_history_vm); + container.register(query_vm); + + // events + conn_vm.subcribe(Event.ACTIVE_CONNECTION, sche_vm); + + sche_vm.subcribe(Event.SCHEMA_CHANGED, completer); + sche_vm.subcribe(Event.SCHEMA_CHANGED, table_vm); + sche_vm.subcribe(Event.SCHEMA_CHANGED, view_vm); + sche_vm.subcribe(Event.SCHEMA_CHANGED, table_structure_vm); + sche_vm.subcribe(Event.SCHEMA_CHANGED, view_structure_vm); + + table_vm.subcribe(Event.SELECTED_TABLE_CHANGED, table_structure_vm); + table_vm.subcribe(Event.SELECTED_TABLE_CHANGED, table_data_vm); + + view_vm.subcribe(Event.SELECTED_VIEW_CHANGED, view_structure_vm); + view_vm.subcribe(Event.SELECTED_VIEW_CHANGED, view_data_vm); + + + return(container); } -} \ No newline at end of file +} +} diff --git a/src/models/Connection.vala b/src/models/Connection.vala index b350fe2..656f332 100644 --- a/src/models/Connection.vala +++ b/src/models/Connection.vala @@ -19,100 +19,98 @@ */ namespace Psequel { +/** + * Connection info. Have basic infomation to establish a connection to server. + */ +public class Connection : Object, Json.Serializable { + public const string DEFAULT = ""; + public const string SCHEME = "postgresql"; - /** - * Connection info. Have basic infomation to establish a connection to server. - */ - public class Connection : Object, Json.Serializable { + public int64 id { get; set; default = 0; } + public string name { get; set; default = DEFAULT; } + public string host { get; set; default = "localhost"; } + public string port { get; set; default = "5432"; } + public string user { get; set; default = "postgres"; } + public string password { get; set; default = "postgres"; } + public string database { get; set; default = "postgres"; } + public bool use_ssl { get; set; default = false; } - public const string DEFAULT = ""; - public const string SCHEME = "postgresql"; + public string options { get; set; default = DEFAULT; } - public int64 id {get; set; default = 0;} - public string name { get; set; default = DEFAULT; } - public string host { get; set; default = "localhost"; } - public string port { get; set; default = "5432"; } - public string user { get; set; default = "postgres"; } - public string password { get; set; default = "postgres"; } - public string database { get; set; default = "postgres"; } - public bool use_ssl { get; set; default = false; } - public string options { get; set; default = DEFAULT; } + public Connection(string name = "New Connection") { + this._name = name; + } + /** + * build the postgres url from properties. + * + * Format = postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...] + */ + public string url_form() { + // postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...] - public Connection (string name = "New Connection") { - this._name = name; + var parsed_port = 5432; + if (!int.try_parse(port, out parsed_port, null, 10)) + { + debug("Parse port error: defautl to 5432"); } - /** - * build the postgres url from properties. - * - * Format = postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...] - */ - public string url_form () { - // postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...] - - var parsed_port = 5432; - if (!int.try_parse (port, out parsed_port, null, 10)) { - debug ("Parse port error: defautl to 5432"); - } + var safe_user = user != DEFAULT ? user : "postgres"; + var safe_password = password != DEFAULT ? password : "postgres"; + var safe_host = host != DEFAULT ? host : "localhost"; // TODO IPv6 check + var safe_port = port != DEFAULT ? parsed_port : 5432; + var safe_db = database != DEFAULT ? @"/$database" : "/postgres"; - var safe_user = user != DEFAULT ? user : "postgres"; - var safe_password = password != DEFAULT ? password : "postgres"; - var safe_host = host != DEFAULT ? host : "localhost"; // TODO IPv6 check - var safe_port = port != DEFAULT ? parsed_port : 5432; - var safe_db = database != DEFAULT ? @"/$database" : "/postgres"; - - var safe_options = use_ssl ? "sslmode=required" : "sslmode=disable"; - if (options != DEFAULT) { - safe_options = @"$safe_options&$options"; - } - - - var url = Uri.join_with_user (UriFlags.NONE, SCHEME, safe_user, safe_password, null, safe_host, safe_port, safe_db, safe_options, null); - - return url.to_string (); + var safe_options = use_ssl ? "sslmode=required" : "sslmode=disable"; + if (options != DEFAULT) + { + safe_options = @"$safe_options&$options"; } - public string connection_string (int connection_timeout, int query_timeout) { - var ssl_mode = use_ssl ? "required" : "disable"; - var options=@"\'-c statement_timeout=$(query_timeout * 1000)\'"; - var base_str = @"user=$user password=$password port=$port host=$host dbname=$database application_name=$(Config.APP_NAME) sslmode=$ssl_mode connect_timeout=$connection_timeout options=$options"; + var url = Uri.join_with_user(UriFlags.NONE, SCHEME, safe_user, safe_password, null, safe_host, safe_port, safe_db, safe_options, null); + return(url.to_string()); + } - return base_str; - } + public string connection_string(int connection_timeout, int query_timeout) { + var ssl_mode = use_ssl ? "required" : "disable"; + var options = @"\'-c statement_timeout=$(query_timeout * 1000)\'"; + var base_str = @"user=$user password=$password port=$port host=$host dbname=$database application_name=$(Config.APP_NAME) sslmode=$ssl_mode connect_timeout=$connection_timeout options=$options"; - /** - * Make a deep copy of Connection - */ - public Connection clone () { - return (Connection) Json.gobject_deserialize (typeof (Connection), Json.gobject_serialize (this)); - } - /** - * Parse Connection from a json string. - */ - public static Connection ? deserialize (string json) { + return(base_str); + } + + /** + * Make a deep copy of Connection + */ + public Connection clone() { + return((Connection)Json.gobject_deserialize(typeof(Connection), Json.gobject_serialize(this))); + } - try { - var conn = (Connection) Json.gobject_from_data (typeof (Connection), json); + /** + * Parse Connection from a json string. + */ + public static Connection ? deserialize(string json) { + try { + var conn = (Connection)Json.gobject_from_data(typeof(Connection), json); - return conn; - } catch (Error err) { - debug (err.message); + return(conn); + } catch (Error err) { + debug(err.message); - return null; - } + return(null); } + } - /** - * Create a json representation of Connection. - */ - public static string serialize (Connection conn) { - return Json.gobject_to_data (conn, null); - } + /** + * Create a json representation of Connection. + */ + public static string serialize(Connection conn) { + return(Json.gobject_to_data(conn, null)); } -} \ No newline at end of file +} +} diff --git a/src/models/Query.vala b/src/models/Query.vala index e56b5df..dd7cb33 100644 --- a/src/models/Query.vala +++ b/src/models/Query.vala @@ -1,30 +1,28 @@ namespace Psequel { - public class Query : Object, Json.Serializable { +public class Query : Object, Json.Serializable { + // Properties must be public, get, set inorder to Json.Serializable works + public int64 id { get; set; default = 0; } + public string sql { get; set; } - // Properties must be public, get, set inorder to Json.Serializable works - public int64 id {get; set; default = 0;} - public string sql { get; set; } + public List params { get; owned set; default = new List (); } + public List param_types { get; owned set; default = new List (); } - public List params {get; owned set; default = new List();} - public List param_types { get; owned set; default = new List();} - - public static Regex DDL_REG = /^(CREATE | DROP | RENAME | ALTER | INSERT | UPDATE | DELETE).*$/i; - - public Query (string sql) { - base (); - this.sql = sql; - } + public Query(string sql) { + base(); + this.sql = sql; + } - public Query.with_params (string sql, string[] params) { - this(sql); + public Query.with_params(string sql, string[] params) { + this(sql); - for(int i = 0; i < params.length; i++) { - this.params.append ((owned)params[i]); - } + for (int i = 0; i < params.length; i++) + { + this.params.append((owned)params[i]); } + } - public Query clone () { - return (Query) Json.gobject_deserialize (typeof (Query), Json.gobject_serialize (this)); - } + public Query clone() { + return((Query)Json.gobject_deserialize(typeof(Query), Json.gobject_serialize(this))); } -} \ No newline at end of file +} +} diff --git a/src/models/Relation.vala b/src/models/Relation.vala index db81a53..7794e95 100644 --- a/src/models/Relation.vala +++ b/src/models/Relation.vala @@ -1,201 +1,205 @@ using Postgres; namespace Psequel { +public delegate Relation.Row TransFormsFunc(Relation.Row row); + +/** + * Relation class represent database "table". + * + * Not to confuse with Table class hold table info, this can hold any data return from database. + */ +public class Relation : Object { + public int rows { get; private set; } + public int cols { get; private set; } + /** Time of query created this relation in us */ + public int64 fetch_time { get; construct; } + + public string row_affected { get; private set; default = ""; } + + private List data; + private List headers; + private List cols_type; + + public Relation(owned Result res) { + Object(fetch_time: 0); + load_data((owned)res); + } - public delegate Relation.Row TransFormsFunc (Relation.Row row); - - /** - * Relation class represent database "table". - * - * Not to confuse with Table class hold table info, this can hold any data return from database. - */ - public class Relation : Object { - - public int rows { get; private set; } - public int cols { get; private set; } - /** Time of query created this relation in us */ - public int64 fetch_time {get; construct;} - - public string row_affected { get; private set; default = ""; } - - private List data; - private List headers; - private List cols_type; - - public Relation (owned Result res) { - Object (fetch_time: 0); - load_data ((owned) res); - } - - public Relation.with_fetch_time (owned Result res, int64 fetch_time) { - Object (fetch_time: fetch_time); - load_data ((owned) res); - } + public Relation.with_fetch_time(owned Result res, int64 fetch_time) { + Object(fetch_time: fetch_time); + load_data((owned)res); + } - public Relation.raw(owned List headers, owned List data) { - Object (fetch_time: 0); - this.rows = (int)data.length (); - this.cols = (int)headers.length (); - this.headers = (owned) headers; - this.data = (owned) data; - } + public Relation.raw(owned List headers, owned List data) { + Object(fetch_time: 0); + this.rows = (int)data.length(); + this.cols = (int)headers.length(); + this.headers = (owned)headers; + this.data = (owned)data; + } - public Type get_column_type (int index) { - return this.cols_type.nth_data ((uint) index); - } + public Type get_column_type(int index) { + return(this.cols_type.nth_data((uint)index)); + } - private void load_data (owned Result result) { - assert_nonnull (result); - - rows = result.get_n_tuples (); - cols = result.get_n_fields (); - row_affected = result.get_cmd_tuples (); - - this.headers = new List (); - this.cols_type = new List (); - for (int i = 0; i < cols; i++) { - - // Oid, should have enum for value type in VAPI but no. - switch ((uint) result.get_field_type (i)) { - case 20, 21, 23: - // int - this.cols_type.append (Type.INT64); - break; - case 16: - // bool - this.cols_type.append (Type.BOOLEAN); - break; - case 700, 701: - // real - this.cols_type.append (Type.DOUBLE); - break; - case 25, 1043, 18, 19, 1700: - // string - this.cols_type.append (Type.STRING); - break; - case 1114: - // timestamp - this.cols_type.append (Type.STRING); - break; - case 1082: - // date - this.cols_type.append (Type.STRING); - break; - - default: - debug ("Programming errors, unhandled Oid: %u", (uint) result.get_field_type (i)); - this.cols_type.append (Type.STRING); - break; - // assert_not_reached (); - } - - headers.append (result.get_field_name (i)); + private void load_data(owned Result result) { + assert_nonnull(result); + + rows = result.get_n_tuples(); + cols = result.get_n_fields(); + row_affected = result.get_cmd_tuples(); + + this.headers = new List (); + this.cols_type = new List (); + for (int i = 0; i < cols; i++) + { + // Oid, should have enum for value type in VAPI but no. + switch ((uint)result.get_field_type(i)) + { + case 20, 21, 23: + // int + this.cols_type.append(Type.INT64); + break; + + case 16: + // bool + this.cols_type.append(Type.BOOLEAN); + break; + + case 700, 701: + // real + this.cols_type.append(Type.DOUBLE); + break; + + case 25, 1043, 18, 19, 1700: + // string + this.cols_type.append(Type.STRING); + break; + + case 1114: + // timestamp + this.cols_type.append(Type.STRING); + break; + + case 1082: + // date + this.cols_type.append(Type.STRING); + break; + + default: + debug("Programming errors, unhandled Oid: %u", (uint)result.get_field_type(i)); + this.cols_type.append(Type.STRING); + break; + // assert_not_reached (); } - this.data = new List (); - - for (int i = 0; i < rows; i++) { - var row = new Row (); - for (int j = 0; j < cols; j++) { - row.add_field (result.get_value (i, j)); - } - data.append (row); - } + headers.append(result.get_field_name(i)); } - public Relation.Iterator iterator () { - return new Iterator (this); - } + this.data = new List (); - public string get_header (int index) { - if (index >= cols) { - return ""; + for (int i = 0; i < rows; i++) + { + var row = new Row(); + for (int j = 0; j < cols; j++) + { + row.add_field(result.get_value(i, j)); } - - return headers.nth_data ((uint) index); + data.append(row); } + } - public string to_string () { - return @"Table ($rows x $cols)"; - } + public Relation.Iterator iterator() { + return(new Iterator(this)); + } - public List steal() { - return (owned)this.data; + public string get_header(int index) { + if (index >= cols) + { + return(""); } - public string name { get; set; } - - public new Row @get (int index) { - return data.nth_data ((uint) index); - } + return(headers.nth_data((uint)index)); + } + public string to_string() { + return(@"Table ($rows x $cols)"); + } - public class Iterator { + public List steal() { + return((owned)this.data); + } - private Relation relation; - private int index; + public string name { get; set; } - public Iterator (Relation relation) { - this.relation = relation; - this.index = 0; - } + public new Row @get(int index) { + return(data.nth_data((uint)index)); + } - public Relation.Row? next_value () { - if (index == relation.rows) { - return null; - } + public class Iterator { + private Relation relation; + private int index; - return relation[index++]; - } + public Iterator(Relation relation) { + this.relation = relation; + this.index = 0; } - /** - * Helper class for ease of use with Relation. - */ - public class Row : Object { + public Relation.Row ?next_value() { + if (index == relation.rows) + { + return(null); + } + return(relation[index++]); + } + } - private List data; + /** + * Helper class for ease of use with Relation. + */ + public class Row : Object { + private List data; - public int size { - get { return (int) data.length (); } - } + public int size { + get { return((int)data.length()); } + } - internal Row () { - this.data = new List (); - } + internal Row() { + this.data = new List (); + } - public void add_field (string item) { - data.append (item); - } + public void add_field(string item) { + data.append(item); + } - public void insert_field (int index, string item) { - data.insert (item, index); - } + public void insert_field(int index, string item) { + data.insert(item, index); + } - public void remove_at (int index) { - assert (index < size); - assert (index >= 0); + public void remove_at(int index) { + assert(index < size); + assert(index >= 0); - data.remove (data.nth_data ((uint) index)); - } + data.remove(data.nth_data((uint)index)); + } - public new string ? @get (int index) { - if (index >= size) { - return null; - } - return data.nth_data ((uint) index); + public new string ? @get(int index) { + if (index >= size) + { + return(null); } + return(data.nth_data((uint)index)); + } - public string to_string () { - - var builder = new StringBuilder (""); - data.foreach ((item) => { - builder.append_printf ("%s\t\t", item); + public string to_string() { + var builder = new StringBuilder(""); + data.foreach((item) => { + builder.append_printf("%s\t\t", item); }); - return builder.free_and_steal (); - } + return(builder.free_and_steal()); } } -} \ No newline at end of file +} +} diff --git a/src/models/Table.vala b/src/models/Table.vala index 0fc3538..9ca1d66 100644 --- a/src/models/Table.vala +++ b/src/models/Table.vala @@ -1,30 +1,27 @@ namespace Psequel { - - public abstract class BaseTable : Object { - public Schema schema { get; construct; } - public string name { get; set; } - } +public abstract class BaseTable : Object { + public Schema schema { get; construct; } + public string name { get; set; } +} - /** Table object in database, hold meta-data about the table */ - public sealed class Table : BaseTable { +/** Table object in database, hold meta-data about the table */ +public sealed class Table : BaseTable { + public List columns { get; owned set; default = new List (); } + public List indexes { get; owned set; default = new List (); } + public List foreign_keys { get; owned set; default = new List (); } - public List columns { get; owned set; default = new List ();} - public List indexes { get; owned set; default = new List (); } - public List foreign_keys { get; owned set; default = new List ();} - - public Table (Schema schema) { - Object (schema: schema); - } + public Table(Schema schema) { + Object(schema: schema); } +} - public sealed class View : BaseTable { - - public List columns { get; owned set; default = new List ();} - public List indexes { get; owned set; default = new List ();} +public sealed class View : BaseTable { + public List columns { get; owned set; default = new List (); } + public List indexes { get; owned set; default = new List (); } - public View (Schema schema) { - Object (schema: schema); - } + public View(Schema schema) { + Object(schema: schema); } -} \ No newline at end of file +} +} diff --git a/src/repositories/ConnectionRepository.vala b/src/repositories/ConnectionRepository.vala index 0de3ce9..1626b67 100644 --- a/src/repositories/ConnectionRepository.vala +++ b/src/repositories/ConnectionRepository.vala @@ -1,10 +1,9 @@ namespace Psequel { - public class ConnectionRepository : Object { +public class ConnectionRepository : Object { + const string KEY = "connections"; + const string table_name = "connections"; - const string KEY = "connections"; - const string table_name = "connections"; - - const string DDL = """ + const string DDL = """ CREATE TABLE IF NOT EXISTS "connections" ( "id" INTEGER, "name" TEXT NOT NULL, @@ -20,186 +19,207 @@ namespace Psequel { ) """; - const string insert_sql = """ + const string insert_sql = """ INSERT INTO connections(name, host, port, user, password, database, use_ssl, options) VALUES (?, ?, ?, ?, ?, ?, ?, ?); """; - const string select_sql = """ + const string select_sql = """ SELECT id, name, host, port, user, password, database, use_ssl, options FROM connections; """; - const string update_sql = """ + const string update_sql = """ UPDATE connections SET name = ?, host = ?, port = ?, user = ?, password = ?, database = ?, use_ssl = ?, options = ? WHERE id = ?; """; - const string delete_sql = """ + const string delete_sql = """ DELETE FROM connections WHERE id = ?; """; - private Sqlite.Statement insert_stmt; - private Sqlite.Statement select_stmt; - private Sqlite.Statement update_stmt; - private Sqlite.Statement delete_stmt; + private Sqlite.Statement insert_stmt; + private Sqlite.Statement select_stmt; + private Sqlite.Statement update_stmt; + private Sqlite.Statement delete_stmt; + + private StorageService db; - private StorageService db; + public ConnectionRepository() { + base(); + this.db = autowire (); + create_table(); + this.insert_stmt = this.db.prepare(insert_sql); + this.select_stmt = this.db.prepare(select_sql); + this.update_stmt = this.db.prepare(update_sql); + this.delete_stmt = this.db.prepare(delete_sql); + find_all(); + } - public ConnectionRepository () { - base (); - this.db = autowire (); - create_table (); - this.insert_stmt = this.db.prepare (insert_sql); - this.select_stmt = this.db.prepare (select_sql); - this.update_stmt = this.db.prepare (update_sql); - this.delete_stmt = this.db.prepare (delete_sql); - find_all (); + public Connection append_connection(Connection connection) { + this.insert_stmt.reset(); + insert_stmt.bind_text(1, connection.name); + insert_stmt.bind_text(2, connection.host); + insert_stmt.bind_text(3, connection.port); + insert_stmt.bind_text(4, connection.user); + insert_stmt.bind_text(5, connection.password); + insert_stmt.bind_text(6, connection.database); + insert_stmt.bind_int(7, connection.use_ssl ? 1 : 0); + insert_stmt.bind_text(8, connection.options); + + if (insert_stmt.step() != Sqlite.DONE) + { + debug("Error: %s\n", db.err_message()); } - public Connection append_connection (Connection connection) { - this.insert_stmt.reset (); - insert_stmt.bind_text (1, connection.name); - insert_stmt.bind_text (2, connection.host); - insert_stmt.bind_text (3, connection.port); - insert_stmt.bind_text (4, connection.user); - insert_stmt.bind_text (5, connection.password); - insert_stmt.bind_text (6, connection.database); - insert_stmt.bind_int (7, connection.use_ssl ? 1 : 0); - insert_stmt.bind_text (8, connection.options); - - if (insert_stmt.step () != Sqlite.DONE) { - debug ("Error: %s\n", db.err_message ()); - } + debug("Error: %s\n", db.err_message()); - debug ("Error: %s\n", db.err_message ()); - - List f = find_all (); - f.foreach ((item) => debug ("name = %s", item.name)); + List f = find_all(); + f.foreach((item) => debug("name = %s", item.name)); - connection.id = db.last_insert_rowid(); + connection.id = db.last_insert_rowid(); - debug ("id = %lli", connection.id); + debug("id = %lli", connection.id); - return connection; - } + return(connection); + } - public void update_connection (Connection connection) { - // debug ("Update id = %lli, name = %s", connection.id, connection.name); - this.update_stmt.reset (); - update_stmt.bind_text (1, connection.name); - update_stmt.bind_text (2, connection.host); - update_stmt.bind_text (3, connection.port); - update_stmt.bind_text (4, connection.user); - update_stmt.bind_text (5, connection.password); - update_stmt.bind_text (6, connection.database); - update_stmt.bind_int (7, connection.use_ssl ? 1 : 0); - update_stmt.bind_text (8, connection.options); - update_stmt.bind_int64 (9, connection.id); - - int code = update_stmt.step (); - if (code != Sqlite.DONE) { - debug ("Error: %s\n", db.err_message ()); - } + public void update_connection(Connection connection) { + // debug ("Update id = %lli, name = %s", connection.id, connection.name); + this.update_stmt.reset(); + update_stmt.bind_text(1, connection.name); + update_stmt.bind_text(2, connection.host); + update_stmt.bind_text(3, connection.port); + update_stmt.bind_text(4, connection.user); + update_stmt.bind_text(5, connection.password); + update_stmt.bind_text(6, connection.database); + update_stmt.bind_int(7, connection.use_ssl ? 1 : 0); + update_stmt.bind_text(8, connection.options); + update_stmt.bind_int64(9, connection.id); + + int code = update_stmt.step(); + if (code != Sqlite.DONE) + { + debug("Error: %s\n", db.err_message()); } + } - public void remove_connection (Connection connection) { - this.delete_stmt.reset (); - delete_stmt.bind_int64 (1, connection.id); - - if (delete_stmt.step () != Sqlite.DONE) { - debug ("Error: %s\n", db.err_message ()); - } - } + public void remove_connection(Connection connection) { + this.delete_stmt.reset(); + delete_stmt.bind_int64(1, connection.id); - public void append_all (List items) { - items.foreach ((item) => append_connection (item)); + if (delete_stmt.step() != Sqlite.DONE) + { + debug("Error: %s\n", db.err_message()); } + } - public void save (List connections) { + public void append_all(List items) { + items.foreach((item) => append_connection(item)); + } - var exist_connections = find_all (); - var exist_ids = new List (); - var ids = new List (); - exist_connections.foreach (item => exist_ids.append ((uint32)item.id)); - connections.foreach (item => ids.append ((uint32)item.id)); + public void save(List connections) { + var exist_connections = find_all(); + var exist_ids = new List (); + var ids = new List (); + exist_connections.foreach(item => exist_ids.append((uint32)item.id)); + connections.foreach(item => ids.append((uint32)item.id)); - foreach (var connection in connections) { - if (connection.id == 0) { - append_connection (connection); - } else { - if (exist_ids.index((uint32)connection.id) > 0) { - // debug ("Update: %lli %s", connection.id, connection.name); - update_connection (connection); - } + foreach (var connection in connections) + { + if (connection.id == 0) + { + append_connection(connection); + } + else + { + if (exist_ids.index((uint32)connection.id) > 0) + { + // debug ("Update: %lli %s", connection.id, connection.name); + update_connection(connection); } } + } - foreach (var connection in exist_connections) { - if (ids.index((uint32)connection.id) < 0) { - remove_connection (connection); - } + foreach (var connection in exist_connections) + { + if (ids.index((uint32)connection.id) < 0) + { + remove_connection(connection); } } + } - public List find_all () { - select_stmt.reset (); - int cols = select_stmt.column_count (); - var list = new List (); - - while (select_stmt.step () == Sqlite.ROW) { - Connection conn = new Connection (); - for (int i = 0; i < cols; i++) { - string col_name = select_stmt.column_name (i) ?? ""; - switch (col_name) { - case "id": - conn.id = select_stmt.column_int64 (i); - break; - case "name": - conn.name = select_stmt.column_text (i); - break; - case "host": - conn.host = select_stmt.column_text (i); - break; - case "port": - conn.port = select_stmt.column_text (i); - break; - case "user": - conn.user = select_stmt.column_text (i); - break; - case "password": - conn.password = select_stmt.column_text (i); - break; - case "database": - conn.database = select_stmt.column_text (i); - break; - case "use_ssl": - conn.use_ssl = select_stmt.column_int (i) != 0 ? true : false; - break; - case "options": - conn.options = select_stmt.column_text (i); - break; - - default: - debug ("Unexpect column: %s\n", col_name); - break; - } + public List find_all() { + select_stmt.reset(); + int cols = select_stmt.column_count(); + var list = new List (); + + while (select_stmt.step() == Sqlite.ROW) + { + Connection conn = new Connection(); + for (int i = 0; i < cols; i++) + { + string col_name = select_stmt.column_name(i) ?? ""; + switch (col_name) + { + case "id": + conn.id = select_stmt.column_int64(i); + break; + + case "name": + conn.name = select_stmt.column_text(i); + break; + + case "host": + conn.host = select_stmt.column_text(i); + break; + + case "port": + conn.port = select_stmt.column_text(i); + break; + + case "user": + conn.user = select_stmt.column_text(i); + break; + + case "password": + conn.password = select_stmt.column_text(i); + break; + + case "database": + conn.database = select_stmt.column_text(i); + break; + + case "use_ssl": + conn.use_ssl = select_stmt.column_int(i) != 0 ? true : false; + break; + + case "options": + conn.options = select_stmt.column_text(i); + break; + + default: + debug("Unexpect column: %s\n", col_name); + break; } - - list.append (conn); } - return list; + list.append(conn); } - private void create_table () { - string errmsg = null; - db.exec (DDL, out errmsg); + return(list); + } - if (errmsg != null) { - debug ("Error: %s\n", errmsg); - Process.exit (1); - } + private void create_table() { + string errmsg = null; + db.exec(DDL, out errmsg); + + if (errmsg != null) + { + debug("Error: %s\n", errmsg); + Process.exit(1); } } -} \ No newline at end of file +} +} diff --git a/src/repositories/QueryRepository.vala b/src/repositories/QueryRepository.vala index 3e42828..b277a2b 100644 --- a/src/repositories/QueryRepository.vala +++ b/src/repositories/QueryRepository.vala @@ -1,10 +1,9 @@ namespace Psequel { - public class QueryRepository : Object { +public class QueryRepository : Object { + const string KEY = "queries"; - const string KEY = "queries"; - - const string DDL = """ + const string DDL = """ CREATE TABLE IF NOT EXISTS "queries" ( "id" INTEGER, "sql" TEXT NOT NULL, @@ -13,137 +12,144 @@ namespace Psequel { ); """; - const string select_sql = """ + const string select_sql = """ SELECT id, sql FROM "queries" ORDER BY create_at DESC; """; - const string insert_sql = """ + const string insert_sql = """ INSERT INTO "queries" (sql) VALUES (?); """; - const string update_sql = """ + const string update_sql = """ UPDATE "queries" SET sql = ? WHERE id = ?; """; - const string delete_sql = """ + const string delete_sql = """ DELETE FROM "queries" WHERE id = ?; """; - const string delete_all_sql = """ + const string delete_all_sql = """ DELETE FROM "queries"; """; - private Sqlite.Statement select_stmt; - private Sqlite.Statement insert_stmt; - private Sqlite.Statement update_stmt; - private Sqlite.Statement delete_stmt; - private Sqlite.Statement delete_all_stmt; - - private StorageService db; - private List _data; + private Sqlite.Statement select_stmt; + private Sqlite.Statement insert_stmt; + private Sqlite.Statement update_stmt; + private Sqlite.Statement delete_stmt; + private Sqlite.Statement delete_all_stmt; - public QueryRepository () { - base (); + private StorageService db; + private List _data; - this.db = autowire (); - create_table (); + public QueryRepository() { + base(); - select_stmt = db.prepare (select_sql); - insert_stmt = db.prepare (insert_sql); - update_stmt = db.prepare (update_sql); - delete_stmt = db.prepare (delete_sql); - delete_all_stmt = db.prepare (delete_all_sql); - } + this.db = autowire (); + create_table(); - public List get_queries () { + select_stmt = db.prepare(select_sql); + insert_stmt = db.prepare(insert_sql); + update_stmt = db.prepare(update_sql); + delete_stmt = db.prepare(delete_sql); + delete_all_stmt = db.prepare(delete_all_sql); + } - // debug ("Get query"); + public List get_queries() { + // debug ("Get query"); - return this.find_all (); - } + return(this.find_all()); + } - public void append_query (Query query) { - _data.append (query); + public void append_query(Query query) { + _data.append(query); - insert_stmt.reset (); - insert_stmt.bind_text (1, query.sql); - if (insert_stmt.step () != Sqlite.DONE) { - debug ("Error: %s", db.err_message ()); - } + insert_stmt.reset(); + insert_stmt.bind_text(1, query.sql); + if (insert_stmt.step() != Sqlite.DONE) + { + debug("Error: %s", db.err_message()); } + } - public void update_query (Query query) { - update_stmt.reset (); - update_stmt.bind_text (1, query.sql); - update_stmt.bind_int64 (2, query.id); - if (update_stmt.step () != Sqlite.DONE) { - debug ("Error: %s", db.err_message ()); - } + public void update_query(Query query) { + update_stmt.reset(); + update_stmt.bind_text(1, query.sql); + update_stmt.bind_int64(2, query.id); + if (update_stmt.step() != Sqlite.DONE) + { + debug("Error: %s", db.err_message()); } + } - public void remove_query (Query query) { - _data.remove (query); - delete_stmt.reset (); - delete_stmt.bind_int64 (1, query.id); - if (delete_stmt.step () != Sqlite.DONE) { - debug ("Error: %s", db.err_message ()); - } + public void remove_query(Query query) { + _data.remove(query); + delete_stmt.reset(); + delete_stmt.bind_int64(1, query.id); + if (delete_stmt.step() != Sqlite.DONE) + { + debug("Error: %s", db.err_message()); } + } - public List find_all () { - - select_stmt.reset (); - int cols = select_stmt.column_count (); - var list = new List (); - - while (select_stmt.step () == Sqlite.ROW) { - Query query = new Query (""); - for (int i = 0; i < cols; i++) { - string col_name = select_stmt.column_name (i) ?? ""; - switch (col_name) { - case "id": - query.id = select_stmt.column_int64 (i); - break; - case "sql": - query.sql = select_stmt.column_text (i); - break; - - default: - debug ("Unexpect column: %s\n", col_name); - break; - } + public List find_all() { + select_stmt.reset(); + int cols = select_stmt.column_count(); + var list = new List (); + + while (select_stmt.step() == Sqlite.ROW) + { + Query query = new Query(""); + for (int i = 0; i < cols; i++) + { + string col_name = select_stmt.column_name(i) ?? ""; + switch (col_name) + { + case "id": + query.id = select_stmt.column_int64(i); + break; + + case "sql": + query.sql = select_stmt.column_text(i); + break; + + default: + debug("Unexpect column: %s\n", col_name); + break; } - - // debug ("id = %lli, sql = %s", query.id, query.sql); - list.append (query); } - return list; + // debug ("id = %lli, sql = %s", query.id, query.sql); + list.append(query); } - public void append_all (List items) { - items.foreach ((item) => append_query (item)); - } + return(list); + } - public void clear () { - delete_all_stmt.reset (); - if (delete_all_stmt.step () != Sqlite.DONE) { - debug ("Error: %s", db.err_message ()); - } + public void append_all(List items) { + items.foreach((item) => append_query(item)); + } + + public void clear() { + delete_all_stmt.reset(); + if (delete_all_stmt.step() != Sqlite.DONE) + { + debug("Error: %s", db.err_message()); } + } - private void create_table () { - string errmsg = null; - db.exec (DDL, out errmsg); + private void create_table() { + string errmsg = null; + db.exec(DDL, out errmsg); - if (errmsg != null) { - debug ("Error: %s\n", errmsg); - Process.exit (1); - } + if (errmsg != null) + { + debug("Error: %s\n", errmsg); + Process.exit(1); } } -} \ No newline at end of file +} +} diff --git a/src/repositories/SchemaRepository.vala b/src/repositories/SchemaRepository.vala index 6797e2d..774e299 100644 --- a/src/repositories/SchemaRepository.vala +++ b/src/repositories/SchemaRepository.vala @@ -1,13 +1,11 @@ namespace Psequel { - public class SchemaRepository : Object { - - - public SchemaRepository () { - Object (); - } +public class SchemaRepository : Object { + public SchemaRepository() { + Object(); + } - public List load_schemas () { - return new List (); - } + public List load_schemas() { + return(new List ()); } -} \ No newline at end of file +} +} diff --git a/src/services/ConnectionService.vala b/src/services/ConnectionService.vala index e41f225..eeef4d1 100644 --- a/src/services/ConnectionService.vala +++ b/src/services/ConnectionService.vala @@ -1,8 +1,6 @@ namespace Psequel { - public class ConnectionService : Object { - - public ConnectionService() { - - } +public class ConnectionService : Object { + public ConnectionService() { } -} \ No newline at end of file +} +} diff --git a/src/services/Container.vala b/src/services/Container.vala index e3e3a4e..7938f14 100644 --- a/src/services/Container.vala +++ b/src/services/Container.vala @@ -1,40 +1,42 @@ namespace Psequel { - public class Container : Object { +public class Container : Object { + private HashTable dependencies; + private static Container ?_instance; + + public static Container instance() { + if (_instance == null) + { + _instance = new Container(); + } - private HashTable dependencies; - private static Container? _instance; + return(_instance); + } - public static Container instance() { - if (_instance == null) { - _instance = new Container(); - } + /** Manual dependency injection map */ + public Container() { + Object(); + dependencies = new HashTable (direct_hash, direct_equal); + } - return _instance; + public void register(Object obj) { + if (!dependencies.contains(obj.get_type())) + { + dependencies.replace(obj.get_type(), obj); } - - - /** Manual dependency injection map */ - public Container() { - Object (); - dependencies = new HashTable (direct_hash, direct_equal); + else + { + warning("Register type is already in the map"); } + } - public void register (Object obj) { - - if (!dependencies.contains (obj.get_type ())) { - dependencies.replace (obj.get_type (), obj); - } else { - warning ("Register type is already in the map"); - } + public Object find_type(GLib.Type type) { + if (!dependencies.contains(type)) + { + warning("Type %s not found in the map", type.name()); + assert_not_reached(); } - public Object find_type (GLib.Type type) { - if (!dependencies.contains (type)) { - warning ("Type %s not found in the map", type.name ()); - assert_not_reached (); - } - - return dependencies.lookup (type); - } + return(dependencies.lookup(type)); } -} \ No newline at end of file +} +} diff --git a/src/services/ExportService.vala b/src/services/ExportService.vala index eb42671..3394c93 100644 --- a/src/services/ExportService.vala +++ b/src/services/ExportService.vala @@ -1,44 +1,45 @@ namespace Psequel { - public class ExportService : Object { +public class ExportService : Object { + public const string DELIMETER = ","; + public const string NEWLINE = "\n"; - public const string DELIMETER = ","; - public const string NEWLINE = "\n"; - - public ExportService () { - } - - public async void export_csv (File dest, Relation relation) throws PsequelError { + public ExportService() { + } - string[] rows = new string[relation.rows + 1]; - string[] cols = new string[relation.cols]; + public async void export_csv(File dest, Relation relation) throws PsequelError { + string[] rows = new string[relation.rows + 1]; + string[] cols = new string[relation.cols]; - // headers - for (int j = 0; j < relation.cols; j++) { - cols[j] = quote (relation.get_header (j)); + // headers + for (int j = 0; j < relation.cols; j++) + { + cols[j] = quote(relation.get_header(j)); + } + rows[0] = string.joinv(DELIMETER, cols); + + for (int i = 0; i < relation.rows; i++) + { + cols = new string[relation.cols]; + var row = relation[i]; + for (int j = 0; j < relation.cols; j++) + { + cols[j] = quote(row[j]); } - rows[0] = string.joinv (DELIMETER, cols); - - for (int i = 0; i < relation.rows; i++) { - cols = new string[relation.cols]; - var row = relation[i]; - for (int j = 0; j < relation.cols; j++) { - cols[j] = quote (row[j]); - } - rows[i + 1] = string.joinv (DELIMETER, cols); - } + rows[i + 1] = string.joinv(DELIMETER, cols); + } - var bytes = new Bytes.take (string.joinv (NEWLINE, rows).data); + var bytes = new Bytes.take(string.joinv(NEWLINE, rows).data); - try { - yield dest.replace_contents_bytes_async (bytes, null, false, FileCreateFlags.PRIVATE, null, null); - } catch (GLib.Error err) { - throw new PsequelError.EXPORT_ERROR (err.message); - } + try { + yield dest.replace_contents_bytes_async(bytes, null, false, FileCreateFlags.PRIVATE, null, null); + } catch (GLib.Error err) { + throw new PsequelError.EXPORT_ERROR(err.message); } + } - private string quote (string str) { - return Csv.quote (str); - } + private string quote(string str) { + return(Csv.quote(str)); } -} \ No newline at end of file +} +} diff --git a/src/services/NavigationService.vala b/src/services/NavigationService.vala index 6af1a5d..82512b1 100644 --- a/src/services/NavigationService.vala +++ b/src/services/NavigationService.vala @@ -1,27 +1,29 @@ namespace Psequel { - public class NavigationService : Object { +public class NavigationService : Object { + public const string CONNECTION_VIEW = "connection-view"; + public const string QUERY_VIEW = "query-view"; + public const string[] VIEW_NAMES = { CONNECTION_VIEW, QUERY_VIEW }; - public const string CONNECTION_VIEW = "connection-view"; - public const string QUERY_VIEW = "query-view"; - public const string[] VIEW_NAMES = { CONNECTION_VIEW, QUERY_VIEW }; + public string current_view { get; set; default = CONNECTION_VIEW; } - public string current_view { get; set; default = CONNECTION_VIEW; } + public NavigationService() { + } - public NavigationService () { + public void navigate(string view_name) { + if (view_name == current_view) + { + return; } - public void navigate (string view_name) { - if (view_name == current_view) { + for (int i = 0; i < VIEW_NAMES.length; i++) + { + if (VIEW_NAMES[i] == view_name) + { + debug("Navigating to " + view_name); + current_view = view_name; return; } - - for (int i = 0; i < VIEW_NAMES.length; i++) { - if (VIEW_NAMES[i] == view_name) { - debug ("Navigating to " + view_name); - current_view = view_name; - return; - } - } } } -} \ No newline at end of file +} +} diff --git a/src/services/ResourceManager.vala b/src/services/ResourceManager.vala index bfbcb5a..cc47f27 100644 --- a/src/services/ResourceManager.vala +++ b/src/services/ResourceManager.vala @@ -1,9 +1,8 @@ namespace Psequel { - /** - * Keep and give access to every service in application. - * Must be initzalize before the UI class. - */ - public class ResourceManager : Object { - - } -} \ No newline at end of file +/** + * Keep and give access to every service in application. + * Must be initzalize before the UI class. + */ +public class ResourceManager : Object { +} +} diff --git a/src/services/SQLCompletionService.vala b/src/services/SQLCompletionService.vala index 509af02..6330cd7 100644 --- a/src/services/SQLCompletionService.vala +++ b/src/services/SQLCompletionService.vala @@ -1,286 +1,288 @@ namespace Psequel { - public class SQLCompletionService : Object, GtkSource.CompletionProvider { - private CompleterService completer; - private Gtk.FilterListModel model; - private Gtk.StringFilter filter; - - private SchemaContext ctx; - - - private SchemaViewModel schema_viewmodel; - public SQLCompletionService () { - base (); - this.schema_viewmodel = autowire (); - this.completer = autowire (); - this.ctx = new SchemaContext (); - - // static_candidates = new List (); - // for (int i = 0; i < PGListerals.KEYWORDS.length; i++) { - // static_candidates.append (new Candidate (PGListerals.KEYWORDS[i], "KEYWORD")); - // } - - // for (int i = 0; i < PGListerals.FUNCTIONS.length; i++) { - // static_candidates.append (new Candidate (PGListerals.FUNCTIONS[i], "FUNCTION")); - // } - - // for (int i = 0; i < PGListerals.DATATYPES.length; i++) { - // static_candidates.append (new Candidate (PGListerals.DATATYPES[i], "DATATYPE")); - // } - - // for (int i = 0; i < PGListerals.RESERVED.length; i++) { - // static_candidates.append (new Candidate (PGListerals.RESERVED[i], "RESERVED")); - // } - - // this.notify["query-viewmodel"].connect (() => { - - // dynamic_candidates = new List (); - // query_viewmodel.current_schema.tables.foreach ((table) => { - // dynamic_candidates.append (new Model (table.name, "TABLE")); - // }); - // query_viewmodel.current_schema.views.foreach ((view) => { - // dynamic_candidates.append (new Model (view.name, "VIEW")); - // }); - // }); - - var expression = new Gtk.PropertyExpression (typeof (Candidate), null, "value"); - filter = new Gtk.StringFilter (expression); - filter.match_mode = Gtk.StringFilterMatchMode.PREFIX; - - model = new Gtk.FilterListModel (null, filter); - } +public class SQLCompletionService : Object, GtkSource.CompletionProvider { + private CompleterService completer; + private Gtk.FilterListModel model; + private Gtk.StringFilter filter; + + private SchemaContext ctx; + + + private SchemaViewModel schema_viewmodel; + public SQLCompletionService() { + base(); + this.schema_viewmodel = autowire (); + this.completer = autowire (); + this.ctx = new SchemaContext(); + + // static_candidates = new List (); + // for (int i = 0; i < PGListerals.KEYWORDS.length; i++) { + // static_candidates.append (new Candidate (PGListerals.KEYWORDS[i], "KEYWORD")); + // } + + // for (int i = 0; i < PGListerals.FUNCTIONS.length; i++) { + // static_candidates.append (new Candidate (PGListerals.FUNCTIONS[i], "FUNCTION")); + // } + + // for (int i = 0; i < PGListerals.DATATYPES.length; i++) { + // static_candidates.append (new Candidate (PGListerals.DATATYPES[i], "DATATYPE")); + // } + + // for (int i = 0; i < PGListerals.RESERVED.length; i++) { + // static_candidates.append (new Candidate (PGListerals.RESERVED[i], "RESERVED")); + // } + + // this.notify["query-viewmodel"].connect (() => { + + // dynamic_candidates = new List (); + // query_viewmodel.current_schema.tables.foreach ((table) => { + // dynamic_candidates.append (new Model (table.name, "TABLE")); + // }); + // query_viewmodel.current_schema.views.foreach ((view) => { + // dynamic_candidates.append (new Model (view.name, "VIEW")); + // }); + // }); + + var expression = new Gtk.PropertyExpression(typeof(Candidate), null, "value"); + filter = new Gtk.StringFilter(expression); + filter.match_mode = Gtk.StringFilterMatchMode.PREFIX; + + model = new Gtk.FilterListModel(null, filter); + } - public void activate (GtkSource.CompletionContext context, GtkSource.CompletionProposal proposal) { - var model = (Candidate) proposal; - var buf = context.get_buffer (); - Gtk.TextIter start, end; + public void activate(GtkSource.CompletionContext context, GtkSource.CompletionProposal proposal) { + var model = (Candidate)proposal; + var buf = context.get_buffer(); + Gtk.TextIter start, end; - last_word (buf, out start, out end); + last_word(buf, out start, out end); - buf.delete_range (start, end); - buf.insert_at_cursor (model.value, model.value.length); - // buf.insert (ref iter, model.value, model.value.length); - } + buf.delete_range(start, end); + buf.insert_at_cursor(model.value, model.value.length); + // buf.insert (ref iter, model.value, model.value.length); + } - public void display (GtkSource.CompletionContext context, GtkSource.CompletionProposal proposal, GtkSource.CompletionCell cell) { - - var candidate = (Candidate) proposal; - switch (cell.column) { - // name - case GtkSource.CompletionColumn.TYPED_TEXT: - cell.text = candidate.value; - break; - - // group - case GtkSource.CompletionColumn.AFTER: - cell.text = candidate.group; - break; - // case GtkSource.CompletionColumn.DETAILS: - // cell.text = "DETAILS"; - // break; - // case GtkSource.CompletionColumn.COMMENT: - // cell.text = "COMMENT"; - // break; - // case GtkSource.CompletionColumn.ICON: - // cell.text = "ICON"; - // break; - // case GtkSource.CompletionColumn.BEFORE: - // cell.text = candidate.value; - // break; - default: break; - } + public void display(GtkSource.CompletionContext context, GtkSource.CompletionProposal proposal, GtkSource.CompletionCell cell) { + var candidate = (Candidate)proposal; + switch (cell.column) + { + // name + case GtkSource.CompletionColumn.TYPED_TEXT: + cell.text = candidate.value; + break; + + // group + case GtkSource.CompletionColumn.AFTER: + cell.text = candidate.group; + break; + + // case GtkSource.CompletionColumn.DETAILS: + // cell.text = "DETAILS"; + // break; + // case GtkSource.CompletionColumn.COMMENT: + // cell.text = "COMMENT"; + // break; + // case GtkSource.CompletionColumn.ICON: + // cell.text = "ICON"; + // break; + // case GtkSource.CompletionColumn.BEFORE: + // cell.text = candidate.value; + // break; + default: break; } + } - public async GLib.ListModel populate_async (GtkSource.CompletionContext context, GLib.Cancellable? cancellable) { - - var word = last_word (context.get_buffer ()); - var candidates = new ObservableList (); + public async GLib.ListModel populate_async(GtkSource.CompletionContext context, GLib.Cancellable ?cancellable) { + var word = last_word(context.get_buffer()); + var candidates = new ObservableList (); - candidates.append_all (completer.get_suggestions (this.ctx, word)); - model.model = candidates; + candidates.append_all(completer.get_suggestions(this.ctx, word)); + model.model = candidates; - return model; - } + return(model); + } - public void refilter (GtkSource.CompletionContext context, GLib.ListModel _model) { - var word = last_word (context.get_buffer ()); - var candidates = new ObservableList (); - candidates.append_all (completer.get_suggestions (this.ctx, word)); - model.model = candidates; - } + public void refilter(GtkSource.CompletionContext context, GLib.ListModel _model) { + var word = last_word(context.get_buffer()); + var candidates = new ObservableList (); + candidates.append_all(completer.get_suggestions(this.ctx, word)); + model.model = candidates; + } - private string last_word (GtkSource.Buffer buf, out Gtk.TextIter start = null, out Gtk.TextIter end = null) { - Gtk.TextIter iter; - buf.get_iter_at_offset (out iter, buf.cursor_position); + private string last_word(GtkSource.Buffer buf, out Gtk.TextIter start = null, out Gtk.TextIter end = null) { + Gtk.TextIter iter; + buf.get_iter_at_offset(out iter, buf.cursor_position); - start = iter; - end = iter; + start = iter; + end = iter; - start.backward_word_start (); - end.forward_word_end (); + start.backward_word_start(); + end.forward_word_end(); - return buf.get_text (start, end, false); - } + return(buf.get_text(start, end, false)); } +} - public class CompleterService : Object, Observer { - public SQLService sql_service { get; construct; } +public class CompleterService : Object, Observer { + public SQLService sql_service { get; construct; } - public List schemas {get; owned set;} - public List tables {get; owned set;} - public List columns {get; owned set;} + public List schemas { get; owned set; } + public List tables { get; owned set; } + public List columns { get; owned set; } - // public List keywords { get; owned set; } + // public List keywords { get; owned set; } - public CompleterService (SQLService sql_service) { - Object (sql_service: sql_service); - } + public CompleterService(SQLService sql_service) { + Object(sql_service: sql_service); + } - public List get_suggestions (SchemaContext context, string last_word) { - // context maybe use in the future for smart completion or something. - debug ("Lastword: %s", last_word); + public List get_suggestions(SchemaContext context, string last_word) { + // context maybe use in the future for smart completion or something. + debug("Lastword: %s", last_word); - var keywords = suggest_keywords (last_word); - var tables = suggest_tables (last_word); - var columns = suggest_columns (last_word); - var schemas = suggest_schemas (last_word); + var keywords = suggest_keywords(last_word); + var tables = suggest_tables(last_word); + var columns = suggest_columns(last_word); + var schemas = suggest_schemas(last_word); - tables.concat ((owned)columns); - schemas.concat ((owned)tables); - keywords.concat ((owned)schemas); + tables.concat((owned)columns); + schemas.concat((owned)tables); + keywords.concat((owned)schemas); - return keywords; - } + return(keywords); + } - public void update (Event event) { - if (event.type == Event.SCHEMA_CHANGED) { - var schema = (Schema) event.data; - refresh_data (schema); - } + public void update(Event event) { + if (event.type == Event.SCHEMA_CHANGED) + { + var schema = (Schema)event.data; + refresh_data(schema); } + } - private List suggest_keywords (string prefix = "") { - var candidates = new List (); + private List suggest_keywords(string prefix = "") { + var candidates = new List (); - for (int i = 0; i < PGListerals.KEYWORDS.length; i++) { - var keyword = PGListerals.KEYWORDS[i]; - if (match (keyword, prefix)) { - candidates.append (new Candidate (PGListerals.KEYWORDS[i], "keyword")); - } + for (int i = 0; i < PGListerals.KEYWORDS.length; i++) + { + var keyword = PGListerals.KEYWORDS[i]; + if (match(keyword, prefix)) + { + candidates.append(new Candidate(PGListerals.KEYWORDS[i], "keyword")); } - - return candidates; } - private List suggest_columns (string prefix = "") { + return(candidates); + } - var candidates = new List (); - columns.foreach ((item) => { - if (match (item, prefix)) { - var cand = new Candidate (item, "column"); - candidates.append (cand); + private List suggest_columns(string prefix = "") { + var candidates = new List (); + columns.foreach((item) => { + if (match(item, prefix)) + { + var cand = new Candidate(item, "column"); + candidates.append(cand); } }); - return (owned)candidates; - } - - private List suggest_schemas (string prefix = "") { + return((owned)candidates); + } - var candidates = new List (); - schemas.foreach ((item) => { - if (match (item, prefix)) { - var cand = new Candidate (item, "schema"); - candidates.append (cand); + private List suggest_schemas(string prefix = "") { + var candidates = new List (); + schemas.foreach((item) => { + if (match(item, prefix)) + { + var cand = new Candidate(item, "schema"); + candidates.append(cand); } }); - return (owned)candidates; - } - - private List suggest_tables (string prefix = "") { + return((owned)candidates); + } - var candidates = new List (); - tables.foreach ((item) => { - if (match (item, prefix)) { - var cand = new Candidate (item, "table"); - candidates.append (cand); + private List suggest_tables(string prefix = "") { + var candidates = new List (); + tables.foreach((item) => { + if (match(item, prefix)) + { + var cand = new Candidate(item, "table"); + candidates.append(cand); } }); - return (owned)candidates; - } + return((owned)candidates); + } - private bool match (string text, string needle) { - return text.up ().has_prefix (needle.up ()); - } + private bool match(string text, string needle) { + return(text.up().has_prefix(needle.up())); + } - private void refresh_data (Schema schema) { - refresh_columns (); - } + private void refresh_data(Schema schema) { + refresh_columns(); + } - private void refresh_columns () { - var query = new Query (COLUMN_LIST); - sql_service.exec_query.begin (query, (obj, res) => { + private void refresh_columns() { + var query = new Query(COLUMN_LIST); + sql_service.exec_query.begin(query, (obj, res) => { try { - var relation = sql_service.exec_query_params.end (res); + var relation = sql_service.exec_query_params.end(res); // avoid dupplicates - var tmp_schemas = new Tree ((a, b) => { return strcmp (a, b); }); - var tmp_tables = new Tree ((a, b) => { return strcmp (a, b); }); - var tmp_columns = new Tree ((a, b) => { return strcmp (a, b); }); - - foreach (var row in relation) { - tmp_schemas.insert (row[0], row[0]); - tmp_tables.insert (row[1], row[1]); - tmp_columns.insert (row[2], row[2]); + var tmp_schemas = new Tree ((a, b) => { return(strcmp(a, b)); }); + var tmp_tables = new Tree ((a, b) => { return(strcmp(a, b)); }); + var tmp_columns = new Tree ((a, b) => { return(strcmp(a, b)); }); + + foreach (var row in relation) + { + tmp_schemas.insert(row[0], row[0]); + tmp_tables.insert(row[1], row[1]); + tmp_columns.insert(row[2], row[2]); } - schemas = new List (); - tmp_schemas.foreach ((key, val) => { - schemas.append (val.dup ()); - return false; + schemas = new List (); + tmp_schemas.foreach((key, val) => { + schemas.append(val.dup()); + return(false); }); - tables = new List (); - tmp_tables.foreach ((key, val) => { - tables.append (val.dup ()); - return false; + tables = new List (); + tmp_tables.foreach((key, val) => { + tables.append(val.dup()); + return(false); }); - columns = new List (); - tmp_columns.foreach ((key, val) => { - columns.append (val.dup ()); + columns = new List (); + tmp_columns.foreach((key, val) => { + columns.append(val.dup()); - return false; + return(false); }); - } catch (PsequelError err) { - debug (err.message); + debug(err.message); } }); - } - - const string COLUMN_LIST = """SELECT table_schema, table_name, column_name - FROM information_schema.columns"""; } + const string COLUMN_LIST = """SELECT table_schema, table_name, column_name + FROM information_schema.columns"""; +} - public class Candidate : Object, GtkSource.CompletionProposal { - public string value { get; set; } - public string group { get; set; } - - public Candidate (string value, string group) { - this.value = value; - this.group = group; - } - } - - public class SchemaContext : Object { - } +public class Candidate : Object, GtkSource.CompletionProposal { + public string value { get; set; } + public string group { get; set; } - public class PGListerals { - public const string[] KEYWORDS = { "ADD", "ADD CONSTRAINT", "ALL", "ALTER", "ALTER COLUMN", "ALTER TABLE", "AND", "ANY", "AS", "ASC", "BACKUP DATABASE", "BETWEEN", "CASE", "CHECK", "COLUMN", "CONSTRAINT", "CREATE", "CREATE DATABASE", "CREATE INDEX", "CREATE OR REPLACE VIEW", "CREATE TABLE", "CREATE PROCEDURE", "CREATE UNIQUE INDEX", "CREATE VIEW", "DATABASE", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "DROP COLUMN", "DROP CONSTRAINT", "DROP DATABASE", "DROP DEFAULT", "DROP INDEX", "DROP TABLE", "DROP VIEW", "EXEC", "EXISTS", "FOREIGN KEY", "FROM", "FULL OUTER JOIN", "GROUP BY", "HAVING", "IN", "INDEX", "INNER JOIN", "INSERT INTO", "IS NULL", "IS NOT NULL", "JOIN", "LEFT JOIN", "LIKE", "LIMIT", "NOT", "NOT NULL", "OR", "ORDER BY", "OUTER JOIN", "PRIMARY KEY", "PROCEDURE", "RIGHT JOIN", "ROWNUM", "SELECT", "SELECT DISTINCT", "SELECT INTO", "SELECT TOP", "SET", "TABLE", "TOP", "TRUNCATE TABLE", "UNION", "UNION ALL", "UNIQUE", "UPDATE", "VALUES", "VIEW", "WHERE"}; - public const string[] FUNCTIONS = { "ABBREV", "ABS", "AGE", "AREA", "ARRAY_AGG", "ARRAY_APPEND", "ARRAY_CAT", "ARRAY_DIMS", "ARRAY_FILL", "ARRAY_LENGTH", "ARRAY_LOWER", "ARRAY_NDIMS", "ARRAY_POSITION", "ARRAY_POSITIONS", "ARRAY_PREPEND", "ARRAY_REMOVE", "ARRAY_REPLACE", "ARRAY_TO_STRING", "ARRAY_UPPER", "ASCII", "AVG", "BIT_AND", "BIT_LENGTH", "BIT_OR", "BOOL_AND", "BOOL_OR", "BOUND_BOX", "BOX", "BROADCAST", "BTRIM", "CARDINALITY", "CBRT", "CEIL", "CEILING", "CENTER", "CHAR_LENGTH", "CHR", "CIRCLE", "CLOCK_TIMESTAMP", "CONCAT", "CONCAT_WS", "CONVERT", "CONVERT_FROM", "CONVERT_TO", "COUNT", "CUME_DIST", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATE_PART", "DATE_TRUNC", "DECODE", "DEGREES", "DENSE_RANK", "DIAMETER", "DIV", "ENCODE", "ENUM_FIRST", "ENUM_LAST", "ENUM_RANGE", "EVERY", "EXP", "EXTRACT", "FAMILY", "FIRST_VALUE", "FLOOR", "FORMAT", "GET_BIT", "GET_BYTE", "HEIGHT", "HOST", "HOSTMASK", "INET_MERGE", "INET_SAME_FAMILY", "INITCAP", "ISCLOSED", "ISFINITE", "ISOPEN", "JUSTIFY_DAYS", "JUSTIFY_HOURS", "JUSTIFY_INTERVAL", "LAG", "LAST_VALUE", "LEAD", "LEFT", "LENGTH", "LINE", "LN", "LOCALTIME", "LOCALTIMESTAMP", "LOG", "LOG10", "LOWER", "LPAD", "LSEG", "LTRIM", "MAKE_DATE", "MAKE_INTERVAL", "MAKE_TIME", "MAKE_TIMESTAMP", "MAKE_TIMESTAMPTZ", "MASKLEN", "MAX", "MD5", "MIN", "MOD", "NETMASK", "NETWORK", "NOW", "NPOINTS", "NTH_VALUE", "NTILE", "NUM_NONNULLS", "NUM_NULLS", "OCTET_LENGTH", "OVERLAY", "PARSE_IDENT", "PATH", "PCLOSE", "PERCENT_RANK", "PG_CLIENT_ENCODING", "PI", "POINT", "POLYGON", "POPEN", "POSITION", "POWER", "QUOTE_IDENT", "QUOTE_LITERAL", "QUOTE_NULLABLE", "RADIANS", "RADIUS", "RANDOM", "RANK", "REGEXP_MATCH", "REGEXP_MATCHES", "REGEXP_REPLACE", "REGEXP_SPLIT_TO_ARRAY", "REGEXP_SPLIT_TO_TABLE", "REPEAT", "REPLACE", "REVERSE", "RIGHT", "ROUND", "ROW_NUMBER", "RPAD", "RTRIM", "SCALE", "SET_BIT", "SET_BYTE", "SET_MASKLEN", "SHA224", "SHA256", "SHA384", "SHA512", "SIGN", "SPLIT_PART", "SQRT", "STARTS_WITH", "STATEMENT_TIMESTAMP", "STRING_TO_ARRAY", "STRPOS", "SUBSTR", "SUBSTRING", "SUM", "TEXT", "TIMEOFDAY", "TO_ASCII", "TO_CHAR", "TO_DATE", "TO_HEX", "TO_NUMBER", "TO_TIMESTAMP", "TRANSACTION_TIMESTAMP", "TRANSLATE", "TRIM", "TRUNC", "UNNEST", "UPPER", "WIDTH", "WIDTH_BUCKET", "XMLAGG" }; - public const string[] DATATYPES = { "ANY", "ANYARRAY", "ANYELEMENT", "ANYENUM", "ANYNONARRAY", "ANYRANGE", "BIGINT", "BIGSERIAL", "BIT", "BIT VARYING", "BOOL", "BOOLEAN", "BOX", "BYTEA", "CHAR", "CHARACTER", "CHARACTER VARYING", "CIDR", "CIRCLE", "CSTRING", "DATE", "DECIMAL", "DOUBLE PRECISION", "EVENT_TRIGGER", "FDW_HANDLER", "FLOAT4", "FLOAT8", "INET", "INT", "INT2", "INT4", "INT8", "INTEGER", "INTERNAL", "INTERVAL", "JSON", "JSONB", "LANGUAGE_HANDLER", "LINE", "LSEG", "MACADDR", "MACADDR8", "MONEY", "NUMERIC", "OID", "OPAQUE", "PATH", "PG_LSN", "POINT", "POLYGON", "REAL", "RECORD", "REGCLASS", "REGCONFIG", "REGDICTIONARY", "REGNAMESPACE", "REGOPER", "REGOPERATOR", "REGPROC", "REGPROCEDURE", "REGROLE", "REGTYPE", "SERIAL", "SERIAL2", "SERIAL4", "SERIAL8", "SMALLINT", "SMALLSERIAL", "TEXT", "TIME", "TIMESTAMP", "TRIGGER", "TSQUERY", "TSVECTOR", "TXID_SNAPSHOT", "UUID", "VARBIT", "VARCHAR", "VOID", "XML" }; - public const string[] RESERVED = { "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC", "BOTH", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", "CURRENT_CATALOG", "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE", "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY", "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP", "NOT", "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY", "REFERENCES", "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "TABLE", "THEN", "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC", "WHEN", "WHERE", "WINDOW", "WITH", "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA", "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL", "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE" }; + public Candidate(string value, string group) { + this.value = value; + this.group = group; } -} \ No newline at end of file +} + +public class SchemaContext : Object { +} + +public class PGListerals { + public const string[] KEYWORDS = { "ADD", "ADD CONSTRAINT", "ALL", "ALTER", "ALTER COLUMN", "ALTER TABLE", "AND", "ANY", "AS", "ASC", "BACKUP DATABASE", "BETWEEN", "CASE", "CHECK", "COLUMN", "CONSTRAINT", "CREATE", "CREATE DATABASE", "CREATE INDEX", "CREATE OR REPLACE VIEW", "CREATE TABLE", "CREATE PROCEDURE", "CREATE UNIQUE INDEX", "CREATE VIEW", "DATABASE", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP", "DROP COLUMN", "DROP CONSTRAINT", "DROP DATABASE", "DROP DEFAULT", "DROP INDEX", "DROP TABLE", "DROP VIEW", "EXEC", "EXISTS", "FOREIGN KEY", "FROM", "FULL OUTER JOIN", "GROUP BY", "HAVING", "IN", "INDEX", "INNER JOIN", "INSERT INTO", "IS NULL", "IS NOT NULL", "JOIN", "LEFT JOIN", "LIKE", "LIMIT", "NOT", "NOT NULL", "OR", "ORDER BY", "OUTER JOIN", "PRIMARY KEY", "PROCEDURE", "RIGHT JOIN", "ROWNUM", "SELECT", "SELECT DISTINCT", "SELECT INTO", "SELECT TOP", "SET", "TABLE", "TOP", "TRUNCATE TABLE", "UNION", "UNION ALL", "UNIQUE", "UPDATE", "VALUES", "VIEW", "WHERE" }; + public const string[] FUNCTIONS = { "ABBREV", "ABS", "AGE", "AREA", "ARRAY_AGG", "ARRAY_APPEND", "ARRAY_CAT", "ARRAY_DIMS", "ARRAY_FILL", "ARRAY_LENGTH", "ARRAY_LOWER", "ARRAY_NDIMS", "ARRAY_POSITION", "ARRAY_POSITIONS", "ARRAY_PREPEND", "ARRAY_REMOVE", "ARRAY_REPLACE", "ARRAY_TO_STRING", "ARRAY_UPPER", "ASCII", "AVG", "BIT_AND", "BIT_LENGTH", "BIT_OR", "BOOL_AND", "BOOL_OR", "BOUND_BOX", "BOX", "BROADCAST", "BTRIM", "CARDINALITY", "CBRT", "CEIL", "CEILING", "CENTER", "CHAR_LENGTH", "CHR", "CIRCLE", "CLOCK_TIMESTAMP", "CONCAT", "CONCAT_WS", "CONVERT", "CONVERT_FROM", "CONVERT_TO", "COUNT", "CUME_DIST", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATE_PART", "DATE_TRUNC", "DECODE", "DEGREES", "DENSE_RANK", "DIAMETER", "DIV", "ENCODE", "ENUM_FIRST", "ENUM_LAST", "ENUM_RANGE", "EVERY", "EXP", "EXTRACT", "FAMILY", "FIRST_VALUE", "FLOOR", "FORMAT", "GET_BIT", "GET_BYTE", "HEIGHT", "HOST", "HOSTMASK", "INET_MERGE", "INET_SAME_FAMILY", "INITCAP", "ISCLOSED", "ISFINITE", "ISOPEN", "JUSTIFY_DAYS", "JUSTIFY_HOURS", "JUSTIFY_INTERVAL", "LAG", "LAST_VALUE", "LEAD", "LEFT", "LENGTH", "LINE", "LN", "LOCALTIME", "LOCALTIMESTAMP", "LOG", "LOG10", "LOWER", "LPAD", "LSEG", "LTRIM", "MAKE_DATE", "MAKE_INTERVAL", "MAKE_TIME", "MAKE_TIMESTAMP", "MAKE_TIMESTAMPTZ", "MASKLEN", "MAX", "MD5", "MIN", "MOD", "NETMASK", "NETWORK", "NOW", "NPOINTS", "NTH_VALUE", "NTILE", "NUM_NONNULLS", "NUM_NULLS", "OCTET_LENGTH", "OVERLAY", "PARSE_IDENT", "PATH", "PCLOSE", "PERCENT_RANK", "PG_CLIENT_ENCODING", "PI", "POINT", "POLYGON", "POPEN", "POSITION", "POWER", "QUOTE_IDENT", "QUOTE_LITERAL", "QUOTE_NULLABLE", "RADIANS", "RADIUS", "RANDOM", "RANK", "REGEXP_MATCH", "REGEXP_MATCHES", "REGEXP_REPLACE", "REGEXP_SPLIT_TO_ARRAY", "REGEXP_SPLIT_TO_TABLE", "REPEAT", "REPLACE", "REVERSE", "RIGHT", "ROUND", "ROW_NUMBER", "RPAD", "RTRIM", "SCALE", "SET_BIT", "SET_BYTE", "SET_MASKLEN", "SHA224", "SHA256", "SHA384", "SHA512", "SIGN", "SPLIT_PART", "SQRT", "STARTS_WITH", "STATEMENT_TIMESTAMP", "STRING_TO_ARRAY", "STRPOS", "SUBSTR", "SUBSTRING", "SUM", "TEXT", "TIMEOFDAY", "TO_ASCII", "TO_CHAR", "TO_DATE", "TO_HEX", "TO_NUMBER", "TO_TIMESTAMP", "TRANSACTION_TIMESTAMP", "TRANSLATE", "TRIM", "TRUNC", "UNNEST", "UPPER", "WIDTH", "WIDTH_BUCKET", "XMLAGG" }; + public const string[] DATATYPES = { "ANY", "ANYARRAY", "ANYELEMENT", "ANYENUM", "ANYNONARRAY", "ANYRANGE", "BIGINT", "BIGSERIAL", "BIT", "BIT VARYING", "BOOL", "BOOLEAN", "BOX", "BYTEA", "CHAR", "CHARACTER", "CHARACTER VARYING", "CIDR", "CIRCLE", "CSTRING", "DATE", "DECIMAL", "DOUBLE PRECISION", "EVENT_TRIGGER", "FDW_HANDLER", "FLOAT4", "FLOAT8", "INET", "INT", "INT2", "INT4", "INT8", "INTEGER", "INTERNAL", "INTERVAL", "JSON", "JSONB", "LANGUAGE_HANDLER", "LINE", "LSEG", "MACADDR", "MACADDR8", "MONEY", "NUMERIC", "OID", "OPAQUE", "PATH", "PG_LSN", "POINT", "POLYGON", "REAL", "RECORD", "REGCLASS", "REGCONFIG", "REGDICTIONARY", "REGNAMESPACE", "REGOPER", "REGOPERATOR", "REGPROC", "REGPROCEDURE", "REGROLE", "REGTYPE", "SERIAL", "SERIAL2", "SERIAL4", "SERIAL8", "SMALLINT", "SMALLSERIAL", "TEXT", "TIME", "TIMESTAMP", "TRIGGER", "TSQUERY", "TSVECTOR", "TXID_SNAPSHOT", "UUID", "VARBIT", "VARCHAR", "VOID", "XML" }; + public const string[] RESERVED = { "ALL", "ANALYSE", "ANALYZE", "AND", "ANY", "ARRAY", "AS", "ASC", "ASYMMETRIC", "BOTH", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "CONSTRAINT", "CREATE", "CURRENT_CATALOG", "CURRENT_DATE", "CURRENT_ROLE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "DEFAULT", "DEFERRABLE", "DESC", "DISTINCT", "DO", "ELSE", "END", "EXCEPT", "FALSE", "FETCH", "FOR", "FOREIGN", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INITIALLY", "INTERSECT", "INTO", "LATERAL", "LEADING", "LIMIT", "LOCALTIME", "LOCALTIMESTAMP", "NOT", "NULL", "OFFSET", "ON", "ONLY", "OR", "ORDER", "PLACING", "PRIMARY", "REFERENCES", "RETURNING", "SELECT", "SESSION_USER", "SOME", "SYMMETRIC", "TABLE", "THEN", "TO", "TRAILING", "TRUE", "UNION", "UNIQUE", "USER", "USING", "VARIADIC", "WHEN", "WHERE", "WINDOW", "WITH", "AUTHORIZATION", "BINARY", "COLLATION", "CONCURRENTLY", "CROSS", "CURRENT_SCHEMA", "FREEZE", "FULL", "ILIKE", "INNER", "IS", "ISNULL", "JOIN", "LEFT", "LIKE", "NATURAL", "NOTNULL", "OUTER", "OVERLAPS", "RIGHT", "SIMILAR", "TABLESAMPLE", "VERBOSE" }; +} +} diff --git a/src/services/SQLService.vala b/src/services/SQLService.vala index 4e23c7c..afbf6d9 100644 --- a/src/services/SQLService.vala +++ b/src/services/SQLService.vala @@ -1,190 +1,192 @@ using Postgres; namespace Psequel { - /** Main entry poit of application, exec query and return result. - * - * Do any thing relate to database, wrapper of libpq - */ - public class SQLService : Object { +/** Main entry poit of application, exec query and return result. + * + * Do any thing relate to database, wrapper of libpq + */ +public class SQLService : Object { + public int query_limit { get; set; default = 100; } + public int query_timeout { get; set; } + + private Settings settings; + + public SQLService(ThreadPool background) { + Object(); + this.background = background; + this.settings = autowire (); + + settings.bind("query-limit", this, "query-limit", SettingsBindFlags.GET); + settings.bind("query-timeout", this, "query-timeout", SettingsBindFlags.GET); + } - public int query_limit { get; set; default = 100; } - public int query_timeout { get; set; } + /** Select info from a table. */ + public async Relation select(BaseTable table, int page, int size = query_limit) throws PsequelError { + string schema_name = active_db.escape_identifier(table.schema.name); + string escape_tbname = active_db.escape_identifier(table.name); + int offset = page * size; + int limit = size; - private Settings settings; + string stmt = @"SELECT * FROM $schema_name.$escape_tbname LIMIT $limit OFFSET $offset"; + var query = new Query(stmt); + return(yield exec_query(query)); + } - public SQLService (ThreadPool background) { - Object (); - this.background = background; - this.settings = autowire (); + /** Make a connection to database and active connection. */ + public async void connect_db(Connection conn) throws PsequelError { + var connection_timeout = settings.get_int("connection-timeout"); + var query_timeout = settings.get_int("query-timeout"); + string db_url = conn.connection_string(connection_timeout, query_timeout); + debug("Connecting to %s", db_url); + TimePerf.begin(); + SourceFunc callback = connect_db.callback; + try { + var worker = new Worker("connect database", () => { + active_db = Postgres.connect_db(db_url); - settings.bind ("query-limit", this, "query-limit", SettingsBindFlags.GET); - settings.bind ("query-timeout", this, "query-timeout", SettingsBindFlags.GET); + // Jump to yield + Idle.add((owned) callback); + }); + background.add(worker); + + yield; + TimePerf.end(); + check_connection_status(); + } catch (ThreadError err) { + debug(err.message); + assert_not_reached(); } + } - /** Select info from a table. */ - public async Relation select (BaseTable table, int page, int size = query_limit) throws PsequelError { - string schema_name = active_db.escape_identifier (table.schema.name); - string escape_tbname = active_db.escape_identifier (table.name); - int offset = page * size; - int limit = size; + public async Relation exec_query(Query query) throws PsequelError { + int64 begin = GLib.get_real_time(); + var result = yield exec_query_internal(query.sql); - string stmt = @"SELECT * FROM $schema_name.$escape_tbname LIMIT $limit OFFSET $offset"; - var query = new Query (stmt); - return yield exec_query (query); - } + check_query_status(result); - /** Make a connection to database and active connection. */ - public async void connect_db (Connection conn) throws PsequelError { - var connection_timeout = settings.get_int ("connection-timeout"); - var query_timeout = settings.get_int ("query-timeout"); - string db_url = conn.connection_string (connection_timeout, query_timeout); - debug ("Connecting to %s", db_url); - TimePerf.begin (); - SourceFunc callback = connect_db.callback; - try { - var worker = new Worker ("connect database", () => { - active_db = Postgres.connect_db (db_url); + int64 end = GLib.get_real_time(); - // Jump to yield - Idle.add ((owned) callback); - }); - background.add (worker); - - yield; - TimePerf.end (); - check_connection_status (); - } catch (ThreadError err) { - debug (err.message); - assert_not_reached (); - } - } + return(new Relation.with_fetch_time((owned)result, end - begin)); + } - public async Relation exec_query (Query query) throws PsequelError { + public Relation make_empty_relation() { + var res = active_db.make_empty_result(ExecStatus.TUPLES_OK); + return(new Relation((owned)res)); + } + public async Relation exec_query_params(Query query) throws PsequelError { + assert(query.params != null); - int64 begin = GLib.get_real_time (); - var result = yield exec_query_internal (query.sql); + var result = yield exec_query_params_internal(query.sql, query.params); - check_query_status (result); + // check query status + check_query_status(result); - int64 end = GLib.get_real_time (); + var table = new Relation((owned)result); - return new Relation.with_fetch_time ((owned) result, end - begin); - } + return(table); + } - public Relation make_empty_relation () { - var res = active_db.make_empty_result (ExecStatus.TUPLES_OK); - return new Relation ((owned) res); + private void check_connection_status() throws PsequelError { + var status = active_db.get_status(); + switch (status) + { + case Postgres.ConnectionStatus.OK: + // Success + break; + + case Postgres.ConnectionStatus.BAD: + var err_msg = active_db.get_error_message(); + throw new PsequelError.CONNECTION_ERROR(err_msg); + + default: + debug("Programming error: %s not handled", status.to_string()); + assert_not_reached(); } + } - public async Relation exec_query_params (Query query) throws PsequelError { - assert (query.params != null); - - var result = yield exec_query_params_internal (query.sql, query.params); - // check query status - check_query_status (result); + private void check_query_status(Result result) throws PsequelError { + var status = result.get_status(); - var table = new Relation ((owned) result); + switch (status) + { + case ExecStatus.TUPLES_OK, ExecStatus.COMMAND_OK, ExecStatus.COPY_OUT: + // success + break; - return table; - } + case ExecStatus.FATAL_ERROR: + var err_msg = result.get_error_message(); + debug("Fatal error: %s", err_msg); + throw new PsequelError.QUERY_FAIL(err_msg.dup()); - private void check_connection_status () throws PsequelError { - var status = active_db.get_status (); - switch (status) { - case Postgres.ConnectionStatus.OK: - // Success - break; - case Postgres.ConnectionStatus.BAD: - var err_msg = active_db.get_error_message (); - throw new PsequelError.CONNECTION_ERROR (err_msg); - default: - debug ("Programming error: %s not handled", status.to_string ()); - assert_not_reached (); - } - } + case ExecStatus.EMPTY_QUERY: + debug("Empty query"); + throw new PsequelError.QUERY_FAIL("Empty query"); - private void check_query_status (Result result) throws PsequelError { - - var status = result.get_status (); - - switch (status) { - case ExecStatus.TUPLES_OK, ExecStatus.COMMAND_OK, ExecStatus.COPY_OUT: - // success - break; - case ExecStatus.FATAL_ERROR: - var err_msg = result.get_error_message (); - debug ("Fatal error: %s", err_msg); - throw new PsequelError.QUERY_FAIL (err_msg.dup ()); - case ExecStatus.EMPTY_QUERY: - debug ("Empty query"); - throw new PsequelError.QUERY_FAIL ("Empty query"); - default: - warning ("Programming error: %s not handled", status.to_string ()); - assert_not_reached (); - } + default: + warning("Programming error: %s not handled", status.to_string()); + assert_not_reached(); } + } - private async Result exec_query_internal (string query) throws PsequelError { - - debug ("Exec: %s", query); - TimePerf.begin (); + private async Result exec_query_internal(string query) throws PsequelError { + debug("Exec: %s", query); + TimePerf.begin(); - // Boilerplate - SourceFunc callback = exec_query_internal.callback; - Result result = null; - try { - // Important line. - var worker = new Worker ("exec query", () => { + // Boilerplate + SourceFunc callback = exec_query_internal.callback; + Result result = null; + try { + // Important line. + var worker = new Worker("exec query", () => { // Important line. - result = active_db.exec (query); - Idle.add ((owned) callback); + result = active_db.exec(query); + Idle.add((owned) callback); }); - background.add (worker); + background.add(worker); - yield; - TimePerf.end (); + yield; + TimePerf.end(); - return (owned) result; - } catch (ThreadError err) { - warning (err.message); - assert_not_reached (); - } + return((owned)result); + } catch (ThreadError err) { + warning(err.message); + assert_not_reached(); } + } - private async Result exec_query_params_internal (string query, List params) throws PsequelError { - - debug ("Exec Param: %s", query); - TimePerf.begin (); + private async Result exec_query_params_internal(string query, List params) throws PsequelError { + debug("Exec Param: %s", query); + TimePerf.begin(); - SourceFunc callback = exec_query_params_internal.callback; - Result result = null; - var params_array = ValueConverter.list_to_array(params); + SourceFunc callback = exec_query_params_internal.callback; + Result result = null; + var params_array = ValueConverter.list_to_array (params); - try { - var worker = new Worker ("exec query params", () => { - result = active_db.exec_params (query, (int)params.length (), null, params_array, null, null, 0); + try { + var worker = new Worker("exec query params", () => { + result = active_db.exec_params(query, (int)params.length(), null, params_array, null, null, 0); // Jump to yield - Idle.add ((owned) callback); + Idle.add((owned) callback); }); - background.add (worker); + background.add(worker); - yield; + yield; - // worker.get_result (); + // worker.get_result (); - TimePerf.end (); + TimePerf.end(); - return (owned) result; - } catch (ThreadError err) { - warning (err.message); - assert_not_reached (); - } + return((owned)result); + } catch (ThreadError err) { + warning(err.message); + assert_not_reached(); } - - private Database active_db; - private unowned ThreadPool background; } -} \ No newline at end of file + + private Database active_db; + private unowned ThreadPool background; +} +} diff --git a/src/services/SchemaService.vala b/src/services/SchemaService.vala index a82f44d..09e027f 100644 --- a/src/services/SchemaService.vala +++ b/src/services/SchemaService.vala @@ -1,38 +1,36 @@ - namespace Psequel { - - /** Class process and load {@link Schema} infomation */ - public class SchemaService : Object { - - public const string SCHEMA_LIST_SQL = """ +/** Class process and load {@link Schema} infomation */ +public class SchemaService : Object { + public const string SCHEMA_LIST_SQL = """ SELECT schema_name FROM information_schema.schemata; """; - // WHERE schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE 'information_schema' - - private SQLService sql_service; + // WHERE schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE 'information_schema' - public SchemaService (SQLService service) { - this.sql_service = service; - } + private SQLService sql_service; - /** Get the schema list. - */ - public async List schema_list () { - var list = new List (); - try { - var query = new Query (SCHEMA_LIST_SQL); - var relation = yield sql_service.exec_query (query); + public SchemaService(SQLService service) { + this.sql_service = service; + } - for (int i = 0; i < relation.rows; i++) { - var s = new Schema (relation[i][0]); - list.append (s); - } - } catch (PsequelError err) { - debug (err.message); + /** Get the schema list. + */ + public async List schema_list() { + var list = new List (); + try { + var query = new Query(SCHEMA_LIST_SQL); + var relation = yield sql_service.exec_query(query); + + for (int i = 0; i < relation.rows; i++) + { + var s = new Schema(relation[i][0]); + list.append(s); } - - return list; + } catch (PsequelError err) { + debug(err.message); } + + return(list); } -} \ No newline at end of file +} +} diff --git a/src/services/StorageService.vala b/src/services/StorageService.vala index 871d9c2..dbac1f7 100644 --- a/src/services/StorageService.vala +++ b/src/services/StorageService.vala @@ -1,66 +1,68 @@ using Sqlite; namespace Psequel { - public class StorageService: Object { +public class StorageService : Object { + private string database_path; + private Database connection; + private string errmsg = ""; - private string database_path; - private Database connection; - private string errmsg = ""; - - public StorageService(string database_path) { - Object (); - this.database_path = database_path; - int err = Database.open_v2 (this.database_path, out this.connection); - if (err != Sqlite.OK) { - stderr.printf ("Can't open database: %d: %s\n", connection.errcode (), connection.errmsg ()); - Process.exit (1); - } + public StorageService(string database_path) { + Object(); + this.database_path = database_path; + int err = Database.open_v2(this.database_path, out this.connection); + if (err != Sqlite.OK) + { + stderr.printf("Can't open database: %d: %s\n", connection.errcode(), connection.errmsg()); + Process.exit(1); } + } - public Relation exec(string sql, out string errmsg = null) { - - var rows = new List(); - List headers = null; + public Relation exec(string sql, out string errmsg = null) { + var rows = new List (); + List headers = null; - this.connection.exec(sql, (n, values, colnames) => { - if (headers == null) { - headers = new List (); - for (int i = 0; i < n; i++) { - headers.append (colnames[i]); + this.connection.exec(sql, (n, values, colnames) => { + if (headers == null) + { + headers = new List (); + for (int i = 0; i < n; i++) + { + headers.append(colnames[i]); } } var row = new Relation.Row(); - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { row.add_field(values[i]); } rows.append(row); - return 0; + return(0); }, out errmsg); - return new Relation.raw((owned)headers, (owned)rows); - } + return(new Relation.raw((owned)headers, (owned)rows)); + } + public int64 last_insert_rowid() { + return(connection.last_insert_rowid()); + } - public int64 last_insert_rowid() { - return connection.last_insert_rowid(); + public Statement ? prepare(string sql) { + Statement stmt; + int err = connection.prepare_v2(sql, sql.length, out stmt, out errmsg); + if (err != Sqlite.OK) + { + printerr(errmsg); + return(null); } - public Statement? prepare(string sql) { - Statement stmt; - int err = connection.prepare_v2(sql, sql.length, out stmt, out errmsg); - if (err != Sqlite.OK) { - printerr(errmsg); - return null; - } - - return stmt; - } + return(stmt); + } - public string err_message() { - return this.connection.errmsg(); - } + public string err_message() { + return(this.connection.errmsg()); } -} \ No newline at end of file +} +} diff --git a/src/ui/PreferencesWindow.vala b/src/ui/PreferencesWindow.vala index 32a11b7..e7a8b9b 100644 --- a/src/ui/PreferencesWindow.vala +++ b/src/ui/PreferencesWindow.vala @@ -1,102 +1,99 @@ namespace Psequel { +// valalint=skip-file +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/preferences-window.ui")] +public class PreferencesWindow : Adw.PreferencesWindow { + // const ActionEntry[] ACTION_ENTRIES = { + // { "editor-font", old_choser }, + // }; - // valalint=skip-file - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/preferences-window.ui")] - public class PreferencesWindow : Adw.PreferencesWindow { - // const ActionEntry[] ACTION_ENTRIES = { - // { "editor-font", old_choser }, - // }; + private Settings ?settings; - private Settings? settings; - - public PreferencesWindow () { - Object (); - } - - construct { - this.settings = autowire (); - setup_binding (); - defaults (); - } + public PreferencesWindow() { + Object(); + } + construct { + this.settings = autowire (); + setup_binding(); + defaults(); + } - private void defaults () { - var desc = Pango.FontDescription.from_string (settings.get_string ("editor-font")); - font_label.get_pango_context ().set_font_description (desc); - font_label.label = desc.to_string (); -// - // Application.app.add_action_entries (ACTION_ENTRIES, this); - } + private void defaults() { + var desc = Pango.FontDescription.from_string(settings.get_string("editor-font")); - private void setup_binding () { - // settings.bind_with_mapping (string key, GLib.Object object, string property, GLib.SettingsBindFlags flags, GLib.SettingsBindGetMappingShared get_mapping, GLib.SettingsBindSetMappingShared set_mapping, void* user_data, GLib.DestroyNotify? notify) - settings.bind ("query-limit", query_limit, "value", SettingsBindFlags.DEFAULT); - settings.bind ("query-timeout", query_timeout, "value", SettingsBindFlags.DEFAULT); - settings.bind ("connection-timeout", conn_timeout, "value", SettingsBindFlags.DEFAULT); + font_label.get_pango_context().set_font_description(desc); + font_label.label = desc.to_string(); +// + // Application.app.add_action_entries (ACTION_ENTRIES, this); + } - settings.changed["editor-font"].connect ((_setting, key) => { + private void setup_binding() { + // settings.bind_with_mapping (string key, GLib.Object object, string property, GLib.SettingsBindFlags flags, GLib.SettingsBindGetMappingShared get_mapping, GLib.SettingsBindSetMappingShared set_mapping, void* user_data, GLib.DestroyNotify? notify) + settings.bind("query-limit", query_limit, "value", SettingsBindFlags.DEFAULT); + settings.bind("query-timeout", query_timeout, "value", SettingsBindFlags.DEFAULT); + settings.bind("connection-timeout", conn_timeout, "value", SettingsBindFlags.DEFAULT); - var desc = Pango.FontDescription.from_string (_setting.get_string (key)); + settings.changed["editor-font"].connect((_setting, key) => { + var desc = Pango.FontDescription.from_string(_setting.get_string(key)); - font_label.get_pango_context ().set_font_description (desc); + font_label.get_pango_context().set_font_description(desc); }); - } + } - [GtkCallback] - private void on_font_chooser (Adw.ActionRow row) { - var dialog = new Gtk.FontDialog () { - modal = true, - title = _("Select Font") - }; - dialog.filter = new MonospaceFilter(); + [GtkCallback] + private void on_font_chooser(Adw.ActionRow row) { + var dialog = new Gtk.FontDialog() { + modal = true, + title = _("Select Font") + }; + dialog.filter = new MonospaceFilter(); - var current_font = Pango.FontDescription.from_string (settings.get_string ("editor-font")); + var current_font = Pango.FontDescription.from_string(settings.get_string("editor-font")); - dialog.choose_font.begin(this, current_font, null, (obj, res) => { + dialog.choose_font.begin(this, current_font, null, (obj, res) => { try { - Pango.FontDescription val = dialog.choose_font.end (res); - font_label.get_pango_context ().set_font_description (val); - font_label.label = val.to_string (); - settings.set_string ("editor-font", val.to_string ()); + Pango.FontDescription val = dialog.choose_font.end(res); + font_label.get_pango_context().set_font_description(val); + font_label.label = val.to_string(); + settings.set_string("editor-font", val.to_string()); } catch (Error err) { - debug (err.message); + debug(err.message); } }); - } - - - // private void new_choser () { - // var dialog = new Gtk.FontDialog () { - // modal = true, - // title = _("Select Font"), - // }; - - // var init = new Pango.FontDescription (); - // init.set_family ("Roboto Regular"); - // init.set_size (14); - - // dialog.choose_font.begin (this, init, null, (obj, res) => { - // try { - // var val = dialog.choose_font.end (res); - // font_label.get_pango_context ().set_font_description (val); - // font_label.label = val.get_family (); - // } catch (Error err) { - // debug (err.message); - // } - // }); - // } - - [GtkChild] - private unowned Gtk.Label font_label; - - [GtkChild] - private unowned Gtk.SpinButton conn_timeout; - - [GtkChild] - private unowned Gtk.SpinButton query_timeout; - - [GtkChild] - private unowned Gtk.SpinButton query_limit; } -} \ No newline at end of file + + // private void new_choser () { + // var dialog = new Gtk.FontDialog () { + // modal = true, + // title = _("Select Font"), + // }; + + // var init = new Pango.FontDescription (); + // init.set_family ("Roboto Regular"); + // init.set_size (14); + + // dialog.choose_font.begin (this, init, null, (obj, res) => { + // try { + // var val = dialog.choose_font.end (res); + // font_label.get_pango_context ().set_font_description (val); + // font_label.label = val.get_family (); + // } catch (Error err) { + // debug (err.message); + // } + // }); + // } + + [GtkChild] + private unowned Gtk.Label font_label; + + [GtkChild] + private unowned Gtk.SpinButton conn_timeout; + + [GtkChild] + private unowned Gtk.SpinButton query_timeout; + + [GtkChild] + private unowned Gtk.SpinButton query_limit; +} +} diff --git a/src/ui/Window.vala b/src/ui/Window.vala index c8117f4..1d72474 100644 --- a/src/ui/Window.vala +++ b/src/ui/Window.vala @@ -21,146 +21,144 @@ using GLib; namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/window.ui")] +public class Window : Adw.ApplicationWindow { + const ActionEntry[] ACTIONS = { + { "import", import_connection }, + { "export", export_connection }, - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/window.ui")] - public class Window : Adw.ApplicationWindow { + { "run-query", run_query }, + }; - const ActionEntry[] ACTIONS = { - { "import", import_connection }, - { "export", export_connection }, + public NavigationService navigation { get; private set; } + public ConnectionViewModel connection_viewmodel { get; construct; } + public QueryViewModel query_viewmodel { get; private set; } - { "run-query", run_query }, - }; - - public NavigationService navigation { get; private set; } - public ConnectionViewModel connection_viewmodel { get; construct; } - public QueryViewModel query_viewmodel { get; private set; } + private Settings ?settings; - private Settings? settings; - - public Window (Application app) { - Object ( - application: app + public Window(Application app) { + Object( + application: app ); - } - - construct { - this.navigation = autowire (); - this.connection_viewmodel = autowire (); - this.query_viewmodel = autowire (); - this.settings = autowire (); - settings.bind ("window-width", this, "default-width", SettingsBindFlags.DEFAULT); - settings.bind ("window-height", this, "default-height", SettingsBindFlags.DEFAULT); - this.add_action_entries (ACTIONS, this); - } + } - public void add_toast (Adw.Toast toast) { - overlay.add_toast (toast); - } + construct { + this.navigation = autowire (); + this.connection_viewmodel = autowire (); + this.query_viewmodel = autowire (); + this.settings = autowire (); + settings.bind("window-width", this, "default-width", SettingsBindFlags.DEFAULT); + settings.bind("window-height", this, "default-height", SettingsBindFlags.DEFAULT); + this.add_action_entries(ACTIONS, this); + } - // Actions: - public void run_query () { - if (query_viewmodel == null) { - return; - } + public void add_toast(Adw.Toast toast) { + overlay.add_toast(toast); + } - query_viewmodel.run_selected_query.begin (); + // Actions: + public void run_query() { + if (query_viewmodel == null) + { + return; } - public void import_connection () { - open_file_dialog.begin ("Import connections"); - } + query_viewmodel.run_selected_query.begin(); + } - public void export_connection () { - save_file_dialog.begin ("Export connections"); - } + public void import_connection() { + open_file_dialog.begin("Import connections"); + } - private async void open_file_dialog (string title = "Open File") { - var filter = new Gtk.FileFilter (); - filter.add_pattern ("*.json"); + public void export_connection() { + save_file_dialog.begin("Export connections"); + } - var filters = new ListStore (typeof (Gtk.FileFilter)); - filters.append (filter); + private async void open_file_dialog(string title = "Open File") { + var filter = new Gtk.FileFilter(); + filter.add_pattern("*.json"); - var window = (Window) get_parrent_window (this); + var filters = new ListStore(typeof(Gtk.FileFilter)); + filters.append(filter); - var file_dialog = new Gtk.FileDialog () { - modal = true, - initial_folder = File.new_for_path (Environment.get_home_dir ()), - title = title, - initial_name = "connections", - default_filter = filter, - filters = filters - }; + var window = (Window)get_parrent_window(this); - uint8[] contents; + var file_dialog = new Gtk.FileDialog() { + modal = true, + initial_folder = File.new_for_path(Environment.get_home_dir()), + title = title, + initial_name = "connections", + default_filter = filter, + filters = filters + }; - try { - var file = yield file_dialog.open (window, null); + uint8[] contents; - yield file.load_contents_async (null, out contents, null); + try { + var file = yield file_dialog.open(window, null); - var json_str = (string) contents; - var conns = ValueConverter.deserialize_connection (json_str); - connection_viewmodel.import_connections (conns); + yield file.load_contents_async(null, out contents, null); - var toast = new Adw.Toast (@"Loaded $(conns.length ()) connections") { - timeout = 3, - }; - window.add_toast (toast); - } catch (Error err) { - debug (err.message); + var json_str = (string)contents; + var conns = ValueConverter.deserialize_connection(json_str); + connection_viewmodel.import_connections(conns); - var toast = new Adw.Toast (err.message) { - timeout = 3, - }; - window.add_toast (toast); - } - } + var toast = new Adw.Toast(@"Loaded $(conns.length ()) connections") { + timeout = 3, + }; + window.add_toast(toast); + } catch (Error err) { + debug(err.message); - private async void save_file_dialog (string title = "Save to file") { + var toast = new Adw.Toast(err.message) { + timeout = 3, + }; + window.add_toast(toast); + } + } - var filter = new Gtk.FileFilter (); - filter.add_suffix ("json"); + private async void save_file_dialog(string title = "Save to file") { + var filter = new Gtk.FileFilter(); + filter.add_suffix("json"); - var filters = new ListStore (typeof (Gtk.FileFilter)); - filters.append (filter); + var filters = new ListStore(typeof(Gtk.FileFilter)); + filters.append(filter); - var file_dialog = new Gtk.FileDialog () { - modal = true, - initial_folder = File.new_for_path (Environment.get_home_dir ()), - title = title, - initial_name = "connections", - default_filter = filter, - filters = filters, - }; + var file_dialog = new Gtk.FileDialog() { + modal = true, + initial_folder = File.new_for_path(Environment.get_home_dir()), + title = title, + initial_name = "connections", + default_filter = filter, + filters = filters, + }; - var conns = connection_viewmodel.export_connections (); - var content = ValueConverter.serialize_connection (conns); - var bytes = new Bytes.take (content.data); // Move data to byte so it live when out scope - var window = (Window) get_parrent_window (this); + var conns = connection_viewmodel.export_connections(); + var content = ValueConverter.serialize_connection(conns); + var bytes = new Bytes.take(content.data); // Move data to byte so it live when out scope + var window = (Window)get_parrent_window(this); - try { - var file = yield file_dialog.save (window, null); + try { + var file = yield file_dialog.save(window, null); - yield file.replace_contents_bytes_async (bytes, null, false, FileCreateFlags.NONE, null, null); + yield file.replace_contents_bytes_async(bytes, null, false, FileCreateFlags.NONE, null, null); - var toast = new Adw.Toast ("Data saved successfully.") { - timeout = 2, - }; - window.add_toast (toast); - } catch (Error err) { - debug (err.message); + var toast = new Adw.Toast("Data saved successfully.") { + timeout = 2, + }; + window.add_toast(toast); + } catch (Error err) { + debug(err.message); - var toast = new Adw.Toast (err.message) { - timeout = 3, - }; - window.add_toast (toast); - } + var toast = new Adw.Toast(err.message) { + timeout = 3, + }; + window.add_toast(toast); } - - [GtkChild] - private unowned Adw.ToastOverlay overlay; } + + [GtkChild] + private unowned Adw.ToastOverlay overlay; +} } diff --git a/src/ui/editor/QueryEditor.vala b/src/ui/editor/QueryEditor.vala index 77d2dd5..4243b07 100644 --- a/src/ui/editor/QueryEditor.vala +++ b/src/ui/editor/QueryEditor.vala @@ -1,148 +1,144 @@ using GtkSource; namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/query-editor.ui")] +public class QueryEditor : Adw.Bin { + const string LIGHT_TAG = "query-block-light"; + const string DARK_TAG = "query-block-dark"; - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/query-editor.ui")] - public class QueryEditor : Adw.Bin { + delegate void ChangeStateFunc(SimpleAction action, Variant ?new_state); + public ExportService export_service { get; set; } + public QueryViewModel query_viewmodel { get; set; } - const string LIGHT_TAG = "query-block-light"; - const string DARK_TAG = "query-block-dark"; - delegate void ChangeStateFunc (SimpleAction action, Variant? new_state); + public QueryHistoryViewModel query_history_viewmodel { get; set; } + public Query ?selected_query { get; set; } - public ExportService export_service {get; set;} - public QueryViewModel query_viewmodel { get; set; } + private GLib.SimpleAction auto_uppercase; + private GLib.SimpleAction auto_exec_history; - public QueryHistoryViewModel query_history_viewmodel { get; set; } - public Query? selected_query { get; set; } + private GtkSource.Completion completion; + private SQLCompletionService provider; - private GLib.SimpleAction auto_uppercase; - private GLib.SimpleAction auto_exec_history; + private LanguageManager lang_manager; + private StyleSchemeManager style_manager; - private GtkSource.Completion completion; - private SQLCompletionService provider; + private Settings ?settings; + private Application ?app; + public class QueryEditor() { + Object(); + } - private LanguageManager lang_manager; - private StyleSchemeManager style_manager; - - private Settings? settings; - private Application? app; - - public class QueryEditor () { - Object (); - } - - construct { - this.export_service = autowire (); - this.query_viewmodel = autowire (); - this.query_history_viewmodel = autowire (); - this.settings = autowire (); - this.app = autowire (); - - default_setttings (); - selection_model.bind_property ("selected", this, "selected-query", BindingFlags.BIDIRECTIONAL, from_selected, to_selected); - spinner.bind_property ("spinning", run_query_btn, "sensitive", BindingFlags.INVERT_BOOLEAN); + construct { + this.export_service = autowire (); + this.query_viewmodel = autowire (); + this.query_history_viewmodel = autowire (); + this.settings = autowire (); + this.app = autowire (); - buffer.changed.connect (highlight_current_query); - buffer.cursor_moved.connect (highlight_current_query); + default_setttings(); + selection_model.bind_property("selected", this, "selected-query", BindingFlags.BIDIRECTIONAL, from_selected, to_selected); + spinner.bind_property("spinning", run_query_btn, "sensitive", BindingFlags.INVERT_BOOLEAN); - create_action_group (); - setup_paned (paned); - } + buffer.changed.connect(highlight_current_query); + buffer.cursor_moved.connect(highlight_current_query); + create_action_group(); + setup_paned(paned); + } - [GtkCallback] - private void run_query_cb (Gtk.Button btn) { - query_viewmodel.run_selected_query.begin (); - } - [GtkCallback] - private void on_clear_history (Gtk.Button btn) { - query_history_viewmodel.clear_history.begin (); - popover.hide (); - } + [GtkCallback] + private void run_query_cb(Gtk.Button btn) { + query_viewmodel.run_selected_query.begin(); + } - [GtkCallback] - private void on_query_history_exec (Gtk.ListView view, uint pos) { + [GtkCallback] + private void on_clear_history(Gtk.Button btn) { + query_history_viewmodel.clear_history.begin(); + popover.hide(); + } - var history_query = (Query)selection_model.get_item (pos); - debug ("History activated, exec: %s", history_query.sql); - query_history_viewmodel.exec_history.begin (history_query); + [GtkCallback] + private void on_query_history_exec(Gtk.ListView view, uint pos) { + var history_query = (Query)selection_model.get_item(pos); + debug("History activated, exec: %s", history_query.sql); + query_history_viewmodel.exec_history.begin(history_query); - var text = history_query.sql ?? ""; - clear_and_insert (buffer, text); + var text = history_query.sql ?? ""; + clear_and_insert(buffer, text); - popover.hide (); - } + popover.hide(); + } - /** Clear and insert insteal of manipulate .text to keep undo possible */ - private void clear_and_insert (Gtk.TextBuffer buf, string text) { - Gtk.TextIter iter1; - buffer.get_start_iter (out iter1); + /** Clear and insert insteal of manipulate .text to keep undo possible */ + private void clear_and_insert(Gtk.TextBuffer buf, string text) { + Gtk.TextIter iter1; + buffer.get_start_iter(out iter1); - Gtk.TextIter iter2; - buffer.get_end_iter (out iter2); + Gtk.TextIter iter2; + buffer.get_end_iter(out iter2); - buffer.delete_range (iter1, iter2); + buffer.delete_range(iter1, iter2); - // buffer.insert (ref iter1, ); - buffer.insert_at_cursor (text, text.length); - } + // buffer.insert (ref iter1, ); + buffer.insert_at_cursor(text, text.length); + } - private void default_setttings () { - - lang_manager = LanguageManager.get_default (); - style_manager = StyleSchemeManager.get_default (); - - completion = editor.get_completion (); - completion.select_on_show = true; - completion.page_size = 8; - provider = new SQLCompletionService (); - completion.add_provider (provider); - - var lang = lang_manager.get_language ("sql"); - buffer.language = lang; - - // rgba(104, 109, 224,1.0) - var light_tag = new Gtk.TextTag (LIGHT_TAG); - light_tag.background_rgba = { 237 / 255f, 255 / 255f, 255 / 255f, 0.9f }; - - // rgba(149, 175, 192,1.0) - var dark_tag = new Gtk.TextTag (DARK_TAG); - dark_tag.background_rgba = { 149 / 255f, 175 / 255f, 192 / 255f, 0.2f }; - // tag.background = "sidebar_backdrop_color"; - // rgba(52, 73, 94,1.0) - // rgb(237, 255, 255) - buffer.tag_table.add (light_tag); - buffer.tag_table.add (dark_tag); - - - app.style_manager.bind_property ("dark", buffer, "style_scheme", BindingFlags.SYNC_CREATE, (binding, from, ref to) => { - var is_dark = from.get_boolean (); - if (is_dark) { - var scheme = style_manager.get_scheme ("Adwaita-dark"); - to.set_object (scheme); - } else { - var scheme = style_manager.get_scheme ("Adwaita"); - to.set_object (scheme); + private void default_setttings() { + lang_manager = LanguageManager.get_default(); + style_manager = StyleSchemeManager.get_default(); + + completion = editor.get_completion(); + completion.select_on_show = true; + completion.page_size = 8; + provider = new SQLCompletionService(); + completion.add_provider(provider); + + var lang = lang_manager.get_language("sql"); + buffer.language = lang; + + // rgba(104, 109, 224,1.0) + var light_tag = new Gtk.TextTag(LIGHT_TAG); + light_tag.background_rgba = { 237 / 255f, 255 / 255f, 255 / 255f, 0.9f }; + + // rgba(149, 175, 192,1.0) + var dark_tag = new Gtk.TextTag(DARK_TAG); + dark_tag.background_rgba = { 149 / 255f, 175 / 255f, 192 / 255f, 0.2f }; + // tag.background = "sidebar_backdrop_color"; + // rgba(52, 73, 94,1.0) + // rgb(237, 255, 255) + buffer.tag_table.add(light_tag); + buffer.tag_table.add(dark_tag); + + + app.style_manager.bind_property("dark", buffer, "style_scheme", BindingFlags.SYNC_CREATE, (binding, from, ref to) => { + var is_dark = from.get_boolean(); + if (is_dark) + { + var scheme = style_manager.get_scheme("Adwaita-dark"); + to.set_object(scheme); + } + else + { + var scheme = style_manager.get_scheme("Adwaita"); + to.set_object(scheme); } - return true; + return(true); }); - } - - private void highlight_current_query () { - - var stmts = PGQuery.split_statement (buffer.text); - this.clear_highlight (); - stmts.foreach ((token) => { + } + private void highlight_current_query() { + var stmts = PGQuery.split_statement(buffer.text); + this.clear_highlight(); + stmts.foreach((token) => { var start = token.location; - var end = token.location + token.statement.length; + var end = token.location + token.statement.length; // debug ("[%d, %d], %s", token.location, token.end, token.value); @@ -153,159 +149,165 @@ namespace Psequel { // buffer.get_end_iter (out iter2); // buffer.remove_tag_by_name (TAG_NAME, iter1, iter2); - buffer.get_iter_at_offset (out iter1, start); - buffer.get_iter_at_offset (out iter2, end); - - if (start < buffer.cursor_position && buffer.cursor_position <= end + 1) { + buffer.get_iter_at_offset(out iter1, start); + buffer.get_iter_at_offset(out iter2, end); + if (start < buffer.cursor_position && buffer.cursor_position <= end + 1) + { // Double-check with strict mode. - string statement = buffer.get_text (iter1, iter2, false); - if (PGQuery.split_statement (statement, true) == null) { + string statement = buffer.get_text(iter1, iter2, false); + if (PGQuery.split_statement(statement, true) == null) + { return; } - if (app.style_manager.dark) { - buffer.apply_tag_by_name (DARK_TAG, iter1, iter2); - } else { - buffer.apply_tag_by_name (LIGHT_TAG, iter1, iter2); + if (app.style_manager.dark) + { + buffer.apply_tag_by_name(DARK_TAG, iter1, iter2); + } + else + { + buffer.apply_tag_by_name(LIGHT_TAG, iter1, iter2); } // Important - query_viewmodel.selected_query_changed (token.statement); - } else { - buffer.remove_tag_by_name (DARK_TAG, iter1, iter2); - buffer.remove_tag_by_name (LIGHT_TAG, iter1, iter2); + query_viewmodel.selected_query_changed(token.statement); + } + else + { + buffer.remove_tag_by_name(DARK_TAG, iter1, iter2); + buffer.remove_tag_by_name(LIGHT_TAG, iter1, iter2); } }); - } + } - private inline void clear_highlight () { - Gtk.TextIter start; - Gtk.TextIter end; + private inline void clear_highlight() { + Gtk.TextIter start; + Gtk.TextIter end; - buffer.get_start_iter (out start); - buffer.get_end_iter (out end); - buffer.remove_tag_by_name (DARK_TAG, start, end); - buffer.remove_tag_by_name (LIGHT_TAG, start, end); - } + buffer.get_start_iter(out start); + buffer.get_end_iter(out end); + buffer.remove_tag_by_name(DARK_TAG, start, end); + buffer.remove_tag_by_name(LIGHT_TAG, start, end); + } - private void create_action_group () { + private void create_action_group() { + var group = new SimpleActionGroup(); + this.insert_action_group("editor", group); - var group = new SimpleActionGroup (); - this.insert_action_group ("editor", group); + auto_uppercase = boolean_state_factory("auto-uppercase"); + auto_exec_history = boolean_state_factory("auto-exec-history"); - auto_uppercase = boolean_state_factory ("auto-uppercase"); - auto_exec_history = boolean_state_factory ("auto-exec-history"); + group.add_action((owned)auto_uppercase); + group.add_action((owned)auto_exec_history); - group.add_action ((owned)auto_uppercase); - group.add_action ((owned)auto_exec_history); + this.insert_action_group("editor", group); + } - this.insert_action_group ("editor", group); - } + private SimpleAction boolean_state_factory(string name) { + bool init = settings.get_boolean(name); + var action = new SimpleAction.stateful(name, null, new Variant.boolean(init)); + action.activate.connect(toggle_boolean); + return(action); + } - private SimpleAction boolean_state_factory (string name) { - bool init = settings.get_boolean (name); - var action = new SimpleAction.stateful (name, null, new Variant.boolean (init)); - action.activate.connect (toggle_boolean); - return action; - } + private void toggle_boolean(Action action, Variant ?parameter) { + Variant state = action.state; + bool old_state = state.get_boolean(); + bool new_state = !old_state; + action.change_state(new_state); + settings.set_boolean(action.name, new_state); + } - private void toggle_boolean (Action action, Variant? parameter) { - Variant state = action.state; - bool old_state = state.get_boolean (); - bool new_state = !old_state; - action.change_state (new_state); - settings.set_boolean (action.name, new_state); - } + private bool from_selected(Binding binding, Value from, ref Value to) { + uint pos = from.get_uint(); + if (pos != Gtk.INVALID_LIST_POSITION) + { + to.set_object(selection_model.get_item(pos)); + } - private bool from_selected (Binding binding, Value from, ref Value to) { - uint pos = from.get_uint (); + return(true); + } - if (pos != Gtk.INVALID_LIST_POSITION) { - to.set_object (selection_model.get_item (pos)); + private bool to_selected(Binding binding, Value from, ref Value to) { + Query query = (Query)from.get_object(); + for (uint i = 0; i < selection_model.get_n_items(); i++) + { + if (selection_model.get_item(i) == query) + { + to.set_uint(i); + return(true); } - - return true; } - private bool to_selected (Binding binding, Value from, ref Value to) { + to.set_uint(Gtk.INVALID_LIST_POSITION); - Query query = (Query) from.get_object (); - for (uint i = 0; i < selection_model.get_n_items (); i++) { - if (selection_model.get_item (i) == query) { - to.set_uint (i); - return true; - } - } + return(true); + } - to.set_uint (Gtk.INVALID_LIST_POSITION); + [GtkCallback] + private void on_export_csv(Gtk.Button btn) { + export_to_csv_file.begin(); + } - return true; - } + private async void export_to_csv_file(string title = "Open File") { + var filter = new Gtk.FileFilter(); + // filter.add_pattern ("*.csv"); + filter.add_mime_type("text/csv"); + var filters = new ListStore(typeof(Gtk.FileFilter)); + filters.append(filter); - [GtkCallback] - private void on_export_csv (Gtk.Button btn) { - export_to_csv_file.begin (); - } + var window = (Window)get_parrent_window(this); - private async void export_to_csv_file (string title = "Open File") { - var filter = new Gtk.FileFilter (); - // filter.add_pattern ("*.csv"); - filter.add_mime_type ("text/csv"); - var filters = new ListStore (typeof (Gtk.FileFilter)); - filters.append (filter); - - var window = (Window) get_parrent_window (this); - - var now = new GLib.DateTime.now(); - var initial_name = @"query-export-$(now).csv"; - - var file_dialog = new Gtk.FileDialog () { - modal = true, - initial_folder = GLib.File.new_for_path (Environment.get_home_dir ()), - title = title, - default_filter = filter, - filters = filters, - initial_name = initial_name, - }; + var now = new GLib.DateTime.now(); + var initial_name = @"query-export-$(now).csv"; - try { - var dest = yield file_dialog.save (window, null); - yield export_service.export_csv (dest, query_history_viewmodel.current_relation); + var file_dialog = new Gtk.FileDialog() { + modal = true, + initial_folder = GLib.File.new_for_path(Environment.get_home_dir()), + title = title, + default_filter = filter, + filters = filters, + initial_name = initial_name, + }; - } catch (GLib.Error err) { - debug (err.message); + try { + var dest = yield file_dialog.save(window, null); - var toast = new Adw.Toast (err.message) { - timeout = 3, - }; + yield export_service.export_csv(dest, query_history_viewmodel.current_relation); + } catch (GLib.Error err) { + debug(err.message); - window.add_toast (toast); - } + var toast = new Adw.Toast(err.message) { + timeout = 3, + }; + + window.add_toast(toast); } + } - [GtkChild] - private unowned GtkSource.View editor; + [GtkChild] + private unowned GtkSource.View editor; - [GtkChild] - private unowned Gtk.Button run_query_btn; + [GtkChild] + private unowned Gtk.Button run_query_btn; - [GtkChild] - private unowned Gtk.Spinner spinner; + [GtkChild] + private unowned Gtk.Spinner spinner; - [GtkChild] - private unowned GtkSource.Buffer buffer; + [GtkChild] + private unowned GtkSource.Buffer buffer; - [GtkChild] - private unowned Gtk.Paned paned; + [GtkChild] + private unowned Gtk.Paned paned; - [GtkChild] - private unowned Gtk.SingleSelection selection_model; + [GtkChild] + private unowned Gtk.SingleSelection selection_model; - [GtkChild] - private unowned Gtk.Popover popover; - } -} \ No newline at end of file + [GtkChild] + private unowned Gtk.Popover popover; +} +} diff --git a/src/ui/schema/QueryResult.vala b/src/ui/schema/QueryResult.vala index e1006ac..189a07a 100644 --- a/src/ui/schema/QueryResult.vala +++ b/src/ui/schema/QueryResult.vala @@ -1,206 +1,215 @@ namespace Psequel { - - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/query-results.ui")] - public class QueryResults : Adw.Bin { - - const string EMPTY = "empty"; - const string MAIN = "data"; - const string LOADING = "loading"; - const string ERROR = "error"; - - public string wellcome_message { get; set; } - public bool show_loading { get; set;} - - private Relation _current_relation; - public Relation current_relation { - get { - return _current_relation; - } - set { - if (value == null) { - return; - } - _current_relation = value; - on_current_relation_change (); +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/query-results.ui")] +public class QueryResults : Adw.Bin { + const string EMPTY = "empty"; + const string MAIN = "data"; + const string LOADING = "loading"; + const string ERROR = "error"; + + public string wellcome_message { get; set; } + public bool show_loading { get; set; } + + private Relation _current_relation; + public Relation current_relation { + get { + return(_current_relation); + } + set { + if (value == null) + { + return; } + _current_relation = value; + on_current_relation_change(); } - public bool is_loading { get; set; } + } + public bool is_loading { get; set; } - private string _err_msg = ""; - public string err_msg { - get { - return _err_msg; - } - set { - if (value == null) { - return; - } - _err_msg = value; - on_err_message_change (); + private string _err_msg = ""; + public string err_msg { + get { + return(_err_msg); + } + set { + if (value == null) + { + return; } + _err_msg = value; + on_err_message_change(); } + } - private ObservableList rows; - private Gtk.SortListModel sort_model; - private Gtk.SelectionModel selection_model; + private ObservableList rows; + private Gtk.SortListModel sort_model; + private Gtk.SelectionModel selection_model; - public class QueryResults (bool show_loading) { - Object (); - } + public class QueryResults(bool show_loading) { + Object(); + } + + construct { + stack.visible_child_name = EMPTY; + rows = new ObservableList (); + alloc_columns(); - construct { - stack.visible_child_name = EMPTY; - rows = new ObservableList (); - alloc_columns (); - - this.bind_property ("is-loading", stack, "visible-child-name", BindingFlags.SYNC_CREATE, (binging, from, ref to) => { - bool current_name = from.get_boolean (); - if (show_loading && current_name) { - to.set_string (LOADING); - } else { + this.bind_property("is-loading", stack, "visible-child-name", BindingFlags.SYNC_CREATE, (binging, from, ref to) => { + bool current_name = from.get_boolean(); + if (show_loading && current_name) + { + to.set_string(LOADING); + } + else + { // to.set_string (MAIN); } }); - } + } - private void on_current_relation_change () { - debug ("%d ", current_relation.rows); - stack.visible_child_name = LOADING; - load_data_to_view.begin (current_relation, (obj, res) => { - load_data_to_view.end (res); + private void on_current_relation_change() { + debug("%d ", current_relation.rows); + stack.visible_child_name = LOADING; + load_data_to_view.begin(current_relation, (obj, res) => { + load_data_to_view.end(res); stack.visible_child_name = MAIN; }); - } + } - private void on_err_message_change () { - stack.visible_child_name = ERROR; - } + private void on_err_message_change() { + stack.visible_child_name = ERROR; + } - private async void load_data_to_view (Relation relation) { - var columns = data_view.columns; - debug ("Begin add rows to views"); - for (int i = 0;; i++) { - var raw_col = columns.get_item (i); - if (raw_col == null) { - break; - } - var col = raw_col as Gtk.ColumnViewColumn; - if (i >= relation.cols) { - col.set_visible (false); - continue; - } - auto_set_sorter (col, relation.get_column_type (i), i); - col.set_title (relation.get_header (i)); - col.set_visible (true); + private async void load_data_to_view(Relation relation) { + var columns = data_view.columns; + debug("Begin add rows to views"); + for (int i = 0;; i++) + { + var raw_col = columns.get_item(i); + if (raw_col == null) + { + break; } - - this.selection_model.unselect_all (); - this.sort_model.sorter = data_view.get_sorter (); - - rows.freeze_notify (); - rows.clear (); - rows.append_all (relation.steal ()); - rows.thaw_notify (); + var col = raw_col as Gtk.ColumnViewColumn; + if (i >= relation.cols) + { + col.set_visible(false); + continue; + } + auto_set_sorter(col, relation.get_column_type(i), i); + col.set_title(relation.get_header(i)); + col.set_visible(true); } - private void alloc_columns () { - for (int i = 0; i < Application.MAX_COLUMNS; i++) { - var factory = new Gtk.SignalListItemFactory (); - factory.set_data ("index", i); + this.selection_model.unselect_all(); + this.sort_model.sorter = data_view.get_sorter(); - factory.setup.connect ((_fact, obj) => { + rows.freeze_notify(); + rows.clear(); + rows.append_all(relation.steal()); + rows.thaw_notify(); + } - var _item = (Gtk.ListItem) obj; - if (DataCell.cell_pool == null || DataCell.cell_pool.next == null) { - for (size_t j = 0; j < Application.BATCH_SIZE; j++) { - DataCell.cell_pool.append (new DataCell()); + private void alloc_columns() { + for (int i = 0; i < Application.MAX_COLUMNS; i++) + { + var factory = new Gtk.SignalListItemFactory(); + factory.set_data ("index", i); + + factory.setup.connect((_fact, obj) => { + var _item = (Gtk.ListItem)obj; + if (DataCell.cell_pool == null || DataCell.cell_pool.next == null) + { + for (size_t j = 0; j < Application.BATCH_SIZE; j++) + { + DataCell.cell_pool.append(new DataCell()); } } - var cell = DataCell.cell_pool.data; + var cell = DataCell.cell_pool.data; DataCell.cell_pool = (owned)DataCell.cell_pool.next; - _item.child = cell; + _item.child = cell; }); - factory.bind.connect ((_fact, obj) => { - var _item = (Gtk.ListItem) obj; - var row = _item.item as Relation.Row; - var cell = _item.child as Psequel.DataCell; - int index = _fact.get_data ("index"); - cell.bind_data (row, index); + factory.bind.connect((_fact, obj) => { + var _item = (Gtk.ListItem)obj; + var row = _item.item as Relation.Row; + var cell = _item.child as Psequel.DataCell; + int index = _fact.get_data ("index"); + cell.bind_data(row, index); }); - factory.unbind.connect ((obj) => { - var _item = (Gtk.ListItem) obj; - var row = _item.item as Relation.Row; - var cell = _item.child as Psequel.DataCell; - cell.unbind_data (row); + factory.unbind.connect((obj) => { + var _item = (Gtk.ListItem)obj; + var row = _item.item as Relation.Row; + var cell = _item.child as Psequel.DataCell; + cell.unbind_data(row); }); - factory.teardown.connect ((obj) => { - var _item = (Gtk.ListItem) obj; - var cell = _item.child as Psequel.DataCell; - DataCell.cell_pool.append ((owned)cell); + factory.teardown.connect((obj) => { + var _item = (Gtk.ListItem)obj; + var cell = _item.child as Psequel.DataCell; + DataCell.cell_pool.append((owned)cell); }); - Gtk.ColumnViewColumn column = new Gtk.ColumnViewColumn ("", factory); - column.set_expand (true); - // column.fixed_width = 200; - column.set_visible (false); + Gtk.ColumnViewColumn column = new Gtk.ColumnViewColumn("", factory); + column.set_expand(true); + // column.fixed_width = 200; + column.set_visible(false); - data_view.append_column (column); - } + data_view.append_column(column); + } - this.sort_model = new Gtk.SortListModel (rows, null); - this.sort_model.incremental = true; + this.sort_model = new Gtk.SortListModel(rows, null); + this.sort_model.incremental = true; - this.selection_model = new Gtk.SingleSelection (sort_model); + this.selection_model = new Gtk.SingleSelection(sort_model); - data_view.set_model (this.selection_model); - } + data_view.set_model(this.selection_model); + } - private void auto_set_sorter (Gtk.ColumnViewColumn col, Type type, int col_index) { - switch (type) { - case Type.BOOLEAN, Type.INT64, Type.FLOAT, Type.DOUBLE: - var constexprs = new Gtk.ConstantExpression (Type.INT, col_index); - var expresion = new Gtk.CClosureExpression (Type.INT64, null, { constexprs }, (Callback) get_col_by_index_int, null, null); + private void auto_set_sorter(Gtk.ColumnViewColumn col, Type type, int col_index) { + switch (type) + { + case Type.BOOLEAN, Type.INT64, Type.FLOAT, Type.DOUBLE: + var constexprs = new Gtk.ConstantExpression(Type.INT, col_index); + var expresion = new Gtk.CClosureExpression(Type.INT64, null, { constexprs }, (Callback)get_col_by_index_int, null, null); - var sorter = new Gtk.NumericSorter (expresion); + var sorter = new Gtk.NumericSorter(expresion); - col.set_sorter (sorter); - break; + col.set_sorter(sorter); + break; - default: - var constexprs = new Gtk.ConstantExpression (Type.INT, col_index); - var expresion = new Gtk.CClosureExpression (Type.STRING, null, { constexprs }, (Callback) get_col_by_index, null, null); + default: + var constexprs = new Gtk.ConstantExpression(Type.INT, col_index); + var expresion = new Gtk.CClosureExpression(Type.STRING, null, { constexprs }, (Callback)get_col_by_index, null, null); - var sorter = new Gtk.StringSorter (expresion); + var sorter = new Gtk.StringSorter(expresion); - col.set_sorter (sorter); - break; - } + col.set_sorter(sorter); + break; } + } - [GtkChild] - private unowned Gtk.Stack stack; + [GtkChild] + private unowned Gtk.Stack stack; - [GtkChild] - private unowned Gtk.ColumnView data_view; + [GtkChild] + private unowned Gtk.ColumnView data_view; - // [GtkChild] - // private unowned Gtk.Spinner spinner; + // [GtkChild] + // private unowned Gtk.Spinner spinner; - // [GtkChild] - // private unowned Gtk.Label status_label; - } + // [GtkChild] + // private unowned Gtk.Label status_label; +} - /* - */ - public string get_col_by_index (Relation.Row row, int index) { - return row[index]; - } +/* + */ +public string get_col_by_index(Relation.Row row, int index) { + return(row[index]); +} - public int64 get_col_by_index_int (Relation.Row row, int index) { - return int64.parse (row[index], 10); - } -} \ No newline at end of file +public int64 get_col_by_index_int(Relation.Row row, int index) { + return(int64.parse(row[index], 10)); +} +} diff --git a/src/ui/schema/TableColumnInfo.vala b/src/ui/schema/TableColumnInfo.vala index 33a6c66..f3cb04f 100644 --- a/src/ui/schema/TableColumnInfo.vala +++ b/src/ui/schema/TableColumnInfo.vala @@ -1,107 +1,102 @@ - - namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/table-cols.ui")] +public class TableColInfo : Adw.Bin { + // public ObservableList columns {get; set;} + public GLib.ListModel columns { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/table-cols.ui")] - public class TableColInfo : Adw.Bin { - - // public ObservableList columns {get; set;} - public GLib.ListModel columns {get; set;} - - public TableColInfo () { - Object (); - } + public TableColInfo() { + Object(); + } - construct { - setup_name_col (); - setup_datatype_col (); - setup_nullable_col (); - setup_default_col (); - } + construct { + setup_name_col(); + setup_datatype_col(); + setup_nullable_col(); + setup_default_col(); + } - private void setup_name_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { + private void setup_name_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Column; - var label = listitem.child as Gtk.Label; - label.label = item.name; + var item = listitem.item as Column; + var label = listitem.child as Gtk.Label; + label.label = item.name; }); - var col = new Gtk.ColumnViewColumn ("Column Name", factory); - col.fixed_width = 250; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Column Name", factory); + col.fixed_width = 250; + view.append_column(col); + } - private void setup_datatype_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { + private void setup_datatype_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); + var label = new Gtk.Label(null); label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Column; - var label = listitem.child as Gtk.Label; - label.label = item.column_type; + var item = listitem.item as Column; + var label = listitem.child as Gtk.Label; + label.label = item.column_type; }); - var col = new Gtk.ColumnViewColumn ("Data Type", factory); - col.fixed_width = 300; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Data Type", factory); + col.fixed_width = 300; + view.append_column(col); + } - private void setup_nullable_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); + private void setup_nullable_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Column; - var label = listitem.child as Gtk.Label; - label.label = item.nullable ? "YES" : "NO"; + var item = listitem.item as Column; + var label = listitem.child as Gtk.Label; + label.label = item.nullable ? "YES" : "NO"; }); - var col = new Gtk.ColumnViewColumn ("Nullable", factory); - col.fixed_width = 70; + var col = new Gtk.ColumnViewColumn("Nullable", factory); + col.fixed_width = 70; - view.append_column (col); - } + view.append_column(col); + } - private void setup_default_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.END; - label.margin_end = 4; + private void setup_default_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.END; + label.margin_end = 4; label.margin_start = 4; - listitem.child = label; + listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Column; - var label = listitem.child as Gtk.Label; - label.label = item.default_val; + var item = listitem.item as Column; + var label = listitem.child as Gtk.Label; + label.label = item.default_val; }); - var col = new Gtk.ColumnViewColumn ("Default Value", factory); - col.set_expand (true); - view.append_column (col); - } - - - [GtkChild] - private unowned Gtk.ColumnView view; + var col = new Gtk.ColumnViewColumn("Default Value", factory); + col.set_expand(true); + view.append_column(col); } -} \ No newline at end of file + + [GtkChild] + private unowned Gtk.ColumnView view; +} +} diff --git a/src/ui/schema/TableDataView.vala b/src/ui/schema/TableDataView.vala index a97b9b4..d953f4f 100644 --- a/src/ui/schema/TableDataView.vala +++ b/src/ui/schema/TableDataView.vala @@ -1,39 +1,37 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/table-data-view.ui")] +public class TableDataView : Gtk.Box { + public TableDataViewModel tabledata_viewmodel { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/table-data-view.ui")] - public class TableDataView : Gtk.Box { - - public TableDataViewModel tabledata_viewmodel { get; set; } - - public TableDataView () { - Object (); - } + public TableDataView() { + Object(); + } - construct { - tabledata_viewmodel = autowire (); - } + construct { + tabledata_viewmodel = autowire (); + } - [GtkCallback] - private void reload_data (Gtk.Button btn) { - btn.sensitive = false; - tabledata_viewmodel.reload_data.begin ((obj, res) => { - var window = get_parrent_window (this); - Adw.Toast toast = new Adw.Toast ("Data Reloaded") { + [GtkCallback] + private void reload_data(Gtk.Button btn) { + btn.sensitive = false; + tabledata_viewmodel.reload_data.begin((obj, res) => { + var window = get_parrent_window(this); + Adw.Toast toast = new Adw.Toast("Data Reloaded") { timeout = 1, }; - window.add_toast (toast); + window.add_toast(toast); btn.sensitive = true; }); - } + } - [GtkCallback] - private async void next_page () { - yield tabledata_viewmodel.next_page (); - } + [GtkCallback] + private async void next_page() { + yield tabledata_viewmodel.next_page(); + } - [GtkCallback] - private async void pre_page () { - yield tabledata_viewmodel.pre_page (); - } + [GtkCallback] + private async void pre_page() { + yield tabledata_viewmodel.pre_page(); } -} \ No newline at end of file +} +} diff --git a/src/ui/schema/TableForeignKeyInfo.vala b/src/ui/schema/TableForeignKeyInfo.vala index f64f91b..1d0bc34 100644 --- a/src/ui/schema/TableForeignKeyInfo.vala +++ b/src/ui/schema/TableForeignKeyInfo.vala @@ -1,142 +1,138 @@ - - namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/table-fk.ui")] +public class TableFKInfo : Adw.Bin { + public GLib.ListModel fks { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/table-fk.ui")] - public class TableFKInfo : Adw.Bin { - - public GLib.ListModel fks { get; set; } + public TableFKInfo() { + Object(); + } - public TableFKInfo () { - Object (); - } - - construct { - setup_name_col (); - setup_table_columns_col (); - setup_fk_tbname_col (); - setup_fk_table_columns_col (); - setup_on_update_col (); - setup_fk_on_delete_col (); - } + construct { + setup_name_col(); + setup_table_columns_col(); + setup_fk_tbname_col(); + setup_fk_table_columns_col(); + setup_on_update_col(); + setup_fk_on_delete_col(); + } - private void setup_name_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; + private void setup_name_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.name; + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.name; }); - var col = new Gtk.ColumnViewColumn ("Foreign Key", factory); - col.fixed_width = 250; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Foreign Key", factory); + col.fixed_width = 250; + view.append_column(col); + } - private void setup_table_columns_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; + private void setup_table_columns_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.columns; + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.columns; }); - var col = new Gtk.ColumnViewColumn ("Columns", factory); - col.fixed_width = 250; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Columns", factory); + col.fixed_width = 250; + view.append_column(col); + } - private void setup_fk_tbname_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; + private void setup_fk_tbname_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.fk_table; + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.fk_table; }); - var col = new Gtk.ColumnViewColumn ("Foreign Table", factory); - col.expand = true; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Foreign Table", factory); + col.expand = true; + view.append_column(col); + } - private void setup_fk_table_columns_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; + private void setup_fk_table_columns_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.fk_columns; + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.fk_columns; }); - var col = new Gtk.ColumnViewColumn ("Reference Columns", factory); - col.expand = true; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Reference Columns", factory); + col.expand = true; + view.append_column(col); + } - private void setup_on_update_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.CENTER; + private void setup_on_update_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.CENTER; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.on_update.to_string (); + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.on_update.to_string(); }); - var col = new Gtk.ColumnViewColumn ("On Update", factory); - col.fixed_width = 100; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("On Update", factory); + col.fixed_width = 100; + view.append_column(col); + } - private void setup_fk_on_delete_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.CENTER; + private void setup_fk_on_delete_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.CENTER; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as ForeignKey; - var label = listitem.child as Gtk.Label; - label.label = item.on_delete.to_string (); + var item = listitem.item as ForeignKey; + var label = listitem.child as Gtk.Label; + label.label = item.on_delete.to_string(); }); - var col = new Gtk.ColumnViewColumn ("On Delete", factory); - col.fixed_width = 100; - view.append_column (col); - } - - [GtkChild] - private unowned Gtk.ColumnView view; + var col = new Gtk.ColumnViewColumn("On Delete", factory); + col.fixed_width = 100; + view.append_column(col); } -} \ No newline at end of file + + [GtkChild] + private unowned Gtk.ColumnView view; +} +} diff --git a/src/ui/schema/TableIndexInfo.vala b/src/ui/schema/TableIndexInfo.vala index e9f68ca..d342277 100644 --- a/src/ui/schema/TableIndexInfo.vala +++ b/src/ui/schema/TableIndexInfo.vala @@ -1,129 +1,124 @@ - - namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/table-index.ui")] +public class TableIndexInfo : Adw.Bin { + public GLib.ListModel indexes { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/table-index.ui")] - public class TableIndexInfo : Adw.Bin { - - public GLib.ListModel indexes {get; set;} + public TableIndexInfo() { + Object(); + } - public TableIndexInfo () { - Object (); - } - - construct { - setup_name_col (); - setup_indexcolumns_col (); - setup_indextype_col (); - setup_unique_col (); - setup_indexsize_col (); - } + construct { + setup_name_col(); + setup_indexcolumns_col(); + setup_indextype_col(); + setup_unique_col(); + setup_indexsize_col(); + } - private void setup_name_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; - label.css_classes = {"table-cell"}; - listitem.child = label; + private void setup_name_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; + label.css_classes = { "table-cell" }; + listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Index; - var label = listitem.child as Gtk.Label; - label.label = item.name; + var item = listitem.item as Index; + var label = listitem.child as Gtk.Label; + label.label = item.name; }); - var col = new Gtk.ColumnViewColumn ("Index Name", factory); - col.fixed_width = 250; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Index Name", factory); + col.fixed_width = 250; + view.append_column(col); + } - private void setup_indextype_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { + private void setup_indextype_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); + var label = new Gtk.Label(null); label.halign = Gtk.Align.CENTER; listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Index; - var label = listitem.child as Gtk.Label; - label.label = item.index_type.to_string (); + var item = listitem.item as Index; + var label = listitem.child as Gtk.Label; + label.label = item.index_type.to_string(); }); - var col = new Gtk.ColumnViewColumn ("Index Type", factory); - col.fixed_width = 80; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Index Type", factory); + col.fixed_width = 80; + view.append_column(col); + } - private void setup_unique_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); + private void setup_unique_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Index; - var label = listitem.child as Gtk.Label; - label.label = item.unique ? "YES" : "NO"; + var item = listitem.item as Index; + var label = listitem.child as Gtk.Label; + label.label = item.unique ? "YES" : "NO"; }); - var col = new Gtk.ColumnViewColumn ("Unique", factory); - col.fixed_width = 70; + var col = new Gtk.ColumnViewColumn("Unique", factory); + col.fixed_width = 70; - view.append_column (col); - } + view.append_column(col); + } - private void setup_indexcolumns_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.START; - label.margin_end = 4; + private void setup_indexcolumns_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.START; + label.margin_end = 4; label.margin_start = 4; - listitem.child = label; + listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Index; - var label = listitem.child as Gtk.Label; - label.label = item.columns; + var item = listitem.item as Index; + var label = listitem.child as Gtk.Label; + label.label = item.columns; }); - var col = new Gtk.ColumnViewColumn ("Index Columns", factory); - col.expand = true; - view.append_column (col); - } + var col = new Gtk.ColumnViewColumn("Index Columns", factory); + col.expand = true; + view.append_column(col); + } - private void setup_indexsize_col () { - var factory = new Gtk.SignalListItemFactory (); - factory.setup.connect ((obj) => { - var listitem = obj as Gtk.ListItem; - var label = new Gtk.Label (null); - label.halign = Gtk.Align.END; - label.margin_end = 4; + private void setup_indexsize_col() { + var factory = new Gtk.SignalListItemFactory(); + factory.setup.connect((obj) => { + var listitem = obj as Gtk.ListItem; + var label = new Gtk.Label(null); + label.halign = Gtk.Align.END; + label.margin_end = 4; label.margin_start = 4; - listitem.child = label; + listitem.child = label; }); - factory.bind.connect ((obj) => { + factory.bind.connect((obj) => { var listitem = obj as Gtk.ListItem; - var item = listitem.item as Index; - var label = listitem.child as Gtk.Label; - label.label = item.size; + var item = listitem.item as Index; + var label = listitem.child as Gtk.Label; + label.label = item.size; }); - var col = new Gtk.ColumnViewColumn ("Index Size", factory); - col.fixed_width = 70; - view.append_column (col); - } - - - [GtkChild] - private unowned Gtk.ColumnView view; + var col = new Gtk.ColumnViewColumn("Index Size", factory); + col.fixed_width = 70; + view.append_column(col); } -} \ No newline at end of file + + [GtkChild] + private unowned Gtk.ColumnView view; +} +} diff --git a/src/ui/schema/TableStructureView.vala b/src/ui/schema/TableStructureView.vala index 436c52c..e3edc61 100644 --- a/src/ui/schema/TableStructureView.vala +++ b/src/ui/schema/TableStructureView.vala @@ -1,37 +1,36 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/table-structure-view.ui")] +public class TableStructureView : Gtk.Box { + public TableStructureViewModel tablestructure_viewmodel { get; private set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/table-structure-view.ui")] - public class TableStructureView : Gtk.Box { - public TableStructureViewModel tablestructure_viewmodel { get; private set; } + public Gtk.FilterListModel columns { get; private set; } + public Gtk.FilterListModel indexes { get; private set; } + public Gtk.FilterListModel fks { get; private set; } + public Gtk.StringFilter filter { get; private set; } - public Gtk.FilterListModel columns { get; private set; } - public Gtk.FilterListModel indexes { get; private set; } - public Gtk.FilterListModel fks { get; private set; } - public Gtk.StringFilter filter { get; private set; } - - public TableStructureView() { - Object(); - } + public TableStructureView() { + Object(); + } - construct { - this.tablestructure_viewmodel = autowire (); + construct { + this.tablestructure_viewmodel = autowire (); - this.filter = new Gtk.StringFilter (null); - filter.expression = new Gtk.PropertyExpression (typeof (BaseType), null, "table"); - filter.match_mode = Gtk.StringFilterMatchMode.EXACT; - this.columns = new Gtk.FilterListModel (this.tablestructure_viewmodel.columns, filter); - this.indexes = new Gtk.FilterListModel (this.tablestructure_viewmodel.indexes, filter); - this.fks = new Gtk.FilterListModel (this.tablestructure_viewmodel.foreign_keys, filter); - filter.search = ""; + this.filter = new Gtk.StringFilter(null); + filter.expression = new Gtk.PropertyExpression(typeof(BaseType), null, "table"); + filter.match_mode = Gtk.StringFilterMatchMode.EXACT; + this.columns = new Gtk.FilterListModel(this.tablestructure_viewmodel.columns, filter); + this.indexes = new Gtk.FilterListModel(this.tablestructure_viewmodel.indexes, filter); + this.fks = new Gtk.FilterListModel(this.tablestructure_viewmodel.foreign_keys, filter); + filter.search = ""; - tablestructure_viewmodel.notify["selected-table"].connect (() => { - var table = tablestructure_viewmodel.selected_table; + tablestructure_viewmodel.notify["selected-table"].connect(() => { + var table = tablestructure_viewmodel.selected_table; filter.search = table.name; - debug ("Notify Table: %s", table.name); - debug ("Filter: %s", filter.search); - debug ("columns: %u", columns.get_n_items ()); + debug("Notify Table: %s", table.name); + debug("Filter: %s", filter.search); + debug("columns: %u", columns.get_n_items()); }); - } } -} \ No newline at end of file +} +} diff --git a/src/ui/schema/ViewDataView.vala b/src/ui/schema/ViewDataView.vala index 365d87c..fdeb1cd 100644 --- a/src/ui/schema/ViewDataView.vala +++ b/src/ui/schema/ViewDataView.vala @@ -1,30 +1,29 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/view-data-view.ui")] +public class ViewDataView : Gtk.Box { + public ViewDataViewModel viewdata_viewmodel { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/view-data-view.ui")] - public class ViewDataView : Gtk.Box { - public ViewDataViewModel viewdata_viewmodel {get; set;} - - public ViewDataView () { - Object (); - } + public ViewDataView() { + Object(); + } - construct { - viewdata_viewmodel = autowire (); - } + construct { + viewdata_viewmodel = autowire (); + } - [GtkCallback] - private async void reload_data () { - yield viewdata_viewmodel.reload_data (); - } + [GtkCallback] + private async void reload_data() { + yield viewdata_viewmodel.reload_data(); + } - [GtkCallback] - private async void next_page () { - yield viewdata_viewmodel.next_page (); - } + [GtkCallback] + private async void next_page() { + yield viewdata_viewmodel.next_page(); + } - [GtkCallback] - private async void pre_page () { - yield viewdata_viewmodel.pre_page (); - } + [GtkCallback] + private async void pre_page() { + yield viewdata_viewmodel.pre_page(); } -} \ No newline at end of file +} +} diff --git a/src/ui/schema/ViewStructureView.vala b/src/ui/schema/ViewStructureView.vala index 71f77c6..0f72e78 100644 --- a/src/ui/schema/ViewStructureView.vala +++ b/src/ui/schema/ViewStructureView.vala @@ -1,36 +1,35 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/view-structure-view.ui")] +public class ViewStructureView : Gtk.Box { + public ViewStructureViewModel viewstructure_viewmodel { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/view-structure-view.ui")] - public class ViewStructureView : Gtk.Box { - public ViewStructureViewModel viewstructure_viewmodel {get; set;} + public Gtk.FilterListModel columns { get; set; } + public Gtk.FilterListModel indexes { get; set; } + public Gtk.StringFilter filter { get; set; } - public Gtk.FilterListModel columns {get; set;} - public Gtk.FilterListModel indexes {get; set;} - public Gtk.StringFilter filter {get; set;} + public ViewStructureView() { + Object(); + } - public ViewStructureView () { - Object (); - } + construct { + this.viewstructure_viewmodel = autowire (); - construct { - this.viewstructure_viewmodel = autowire (); - - var expresion = new Gtk.PropertyExpression (typeof(BaseType), null, "table"); - this.filter = new Gtk.StringFilter (expresion); - this.filter.match_mode = Gtk.StringFilterMatchMode.EXACT; + var expresion = new Gtk.PropertyExpression(typeof(BaseType), null, "table"); + this.filter = new Gtk.StringFilter(expresion); + this.filter.match_mode = Gtk.StringFilterMatchMode.EXACT; - columns = new Gtk.FilterListModel (viewstructure_viewmodel.columns, filter); - indexes = new Gtk.FilterListModel (viewstructure_viewmodel.indexes, filter); - filter.search = ""; + columns = new Gtk.FilterListModel(viewstructure_viewmodel.columns, filter); + indexes = new Gtk.FilterListModel(viewstructure_viewmodel.indexes, filter); + filter.search = ""; - viewstructure_viewmodel.notify["selected-view"].connect (() => { - var view = viewstructure_viewmodel.selected_view; + viewstructure_viewmodel.notify["selected-view"].connect(() => { + var view = viewstructure_viewmodel.selected_view; filter.search = view.name; - debug ("Notify View: %s", view.name); - debug ("Filter: %s", filter.search); - debug ("columns: %u", columns.get_n_items ()); + debug("Notify View: %s", view.name); + debug("Filter: %s", filter.search); + debug("columns: %u", columns.get_n_items()); }); - } } -} \ No newline at end of file +} +} diff --git a/src/ui/views/ConnectionView.vala b/src/ui/views/ConnectionView.vala index fb2b315..e50a3bd 100644 --- a/src/ui/views/ConnectionView.vala +++ b/src/ui/views/ConnectionView.vala @@ -1,202 +1,199 @@ - namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/connection-view.ui")] +public class ConnectionView : Adw.Bin { + public ConnectionViewModel viewmodel { get; private set; } + // public ObservableList connections { get; set; } + public Connection ?selected_connection { get; set; } + + BindingGroup bindings; + + const ActionEntry[] ACTION_ENTRIES = { + { "connect", on_connect_connection }, + { "dupplicate", on_dupplicate_connection }, + { "delete", on_remove_connection }, + }; + + public ConnectionView(Application app) { + Object(); + } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/connection-view.ui")] - public class ConnectionView : Adw.Bin { - - public ConnectionViewModel viewmodel { get; private set; } - // public ObservableList connections { get; set; } - public Connection? selected_connection { get; set; } - - BindingGroup bindings; - - const ActionEntry[] ACTION_ENTRIES = { - { "connect", on_connect_connection }, - { "dupplicate", on_dupplicate_connection }, - { "delete", on_remove_connection }, - }; - - public ConnectionView (Application app) { - Object (); - } - - // Connect event. - construct { - setup_paned (paned); - viewmodel = autowire (); - - var action_group = new SimpleActionGroup (); - action_group.add_action_entries (ACTION_ENTRIES, this); - this.insert_action_group ("conn", action_group); + // Connect event. + construct { + setup_paned(paned); + viewmodel = autowire (); - set_up_bindings (); - } + var action_group = new SimpleActionGroup(); + action_group.add_action_entries(ACTION_ENTRIES, this); + this.insert_action_group("conn", action_group); - // [GtkCallback] - // public void save_connections () { - // viewmodel.save_connections (); - // } + set_up_bindings(); + } - [GtkCallback] - public void add_new_connection () { - viewmodel.new_connection (); - } + // [GtkCallback] + // public void save_connections () { + // viewmodel.save_connections (); + // } - [GtkCallback] - public void active_connection (Gtk.ListView view, uint pos) { - viewmodel.active_connection.begin (viewmodel.selected_connection); - } + [GtkCallback] + public void add_new_connection() { + viewmodel.new_connection(); + } - [GtkCallback] - public void on_connect_clicked (Gtk.Button btn) { - viewmodel.active_connection.begin (viewmodel.selected_connection); - } + [GtkCallback] + public void active_connection(Gtk.ListView view, uint pos) { + viewmodel.active_connection.begin(viewmodel.selected_connection); + } - [GtkCallback] - private void on_entry_activated (Gtk.Entry entry) { - on_connect_connection (); - } + [GtkCallback] + public void on_connect_clicked(Gtk.Button btn) { + viewmodel.active_connection.begin(viewmodel.selected_connection); + } - [GtkCallback] - private void on_text_changed (Gtk.Editable editable) { - viewmodel.save_connections (); - } + [GtkCallback] + private void on_entry_activated(Gtk.Entry entry) { + on_connect_connection(); + } - [GtkCallback] - private void on_switch_changed () { - viewmodel.save_connections (); - } + [GtkCallback] + private void on_text_changed(Gtk.Editable editable) { + viewmodel.save_connections(); + } - // [GtkAction] - private void on_dupplicate_connection () { - viewmodel.dupplicate_connection (viewmodel.selected_connection); - } + [GtkCallback] + private void on_switch_changed() { + viewmodel.save_connections(); + } - // [GtkAction] - private void on_connect_connection () { - viewmodel.active_connection.begin (viewmodel.selected_connection); - } + // [GtkAction] + private void on_dupplicate_connection() { + viewmodel.dupplicate_connection(viewmodel.selected_connection); + } - // [GtkAction] - private void on_remove_connection () { - viewmodel.remove_connection (viewmodel.selected_connection); - } + // [GtkAction] + private void on_connect_connection() { + viewmodel.active_connection.begin(viewmodel.selected_connection); + } - private bool from_selected (Binding binding, Value from, ref Value to) { - uint pos = from.get_uint (); + // [GtkAction] + private void on_remove_connection() { + viewmodel.remove_connection(viewmodel.selected_connection); + } - if (pos != Gtk.INVALID_LIST_POSITION) { - to.set_object (selection_model.get_item (pos)); - } + private bool from_selected(Binding binding, Value from, ref Value to) { + uint pos = from.get_uint(); - return true; + if (pos != Gtk.INVALID_LIST_POSITION) + { + to.set_object(selection_model.get_item(pos)); } - private bool to_selected (Binding binding, Value from, ref Value to) { + return(true); + } - Connection conn = (Connection) from.get_object (); - for (uint i = 0; i < selection_model.get_n_items (); i++) { - if (selection_model.get_item (i) == conn) { - to.set_uint (i); - return true; - } + private bool to_selected(Binding binding, Value from, ref Value to) { + Connection conn = (Connection)from.get_object(); + for (uint i = 0; i < selection_model.get_n_items(); i++) + { + if (selection_model.get_item(i) == conn) + { + to.set_uint(i); + return(true); } - - to.set_uint (Gtk.INVALID_LIST_POSITION); - - return true; } - private void set_up_bindings () { + to.set_uint(Gtk.INVALID_LIST_POSITION); - // Save ref so it does not be cleaned - this.bindings = create_form_bind_group (); + return(true); + } - viewmodel.bind_property ("selected-connection", this.bindings, "source", BindingFlags.SYNC_CREATE); - viewmodel.bind_property ("is-connectting", connect_btn, "sensitive", INVERT_BOOLEAN | SYNC_CREATE); - viewmodel.notify["current-state"].connect(() => { - if (viewmodel.current_state == ConnectionViewModel.State.ERROR) { - var err_dialog = create_dialog ("Connection Failed", viewmodel.err_msg); - err_dialog.show (); + private void set_up_bindings() { + // Save ref so it does not be cleaned + this.bindings = create_form_bind_group(); + + viewmodel.bind_property("selected-connection", this.bindings, "source", BindingFlags.SYNC_CREATE); + viewmodel.bind_property("is-connectting", connect_btn, "sensitive", INVERT_BOOLEAN | SYNC_CREATE); + viewmodel.notify["current-state"].connect(() => { + if (viewmodel.current_state == ConnectionViewModel.State.ERROR) + { + var err_dialog = create_dialog("Connection Failed", viewmodel.err_msg); + err_dialog.show(); } }); - - selection_model.bind_property ("selected", viewmodel, "selected-connection", - DEFAULT | BIDIRECTIONAL, from_selected, to_selected); - password_entry.bind_property ("text", - password_entry, - "show-peek-icon", - BindingFlags.SYNC_CREATE, - (binding, from_value, ref to_value) => { - - string text = from_value.get_string (); - to_value.set_boolean (text.length > 0); - - return true; - }); - } - private BindingGroup create_form_bind_group () { + selection_model.bind_property("selected", viewmodel, "selected-connection", + DEFAULT | BIDIRECTIONAL, from_selected, to_selected); + password_entry.bind_property("text", + password_entry, + "show-peek-icon", + BindingFlags.SYNC_CREATE, + (binding, from_value, ref to_value) => { + string text = from_value.get_string(); + to_value.set_boolean(text.length > 0); + + return(true); + }); + } - var binddings = new BindingGroup (); - // debug ("set_up connection form bindings group"); - binddings.bind ("name", name_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("host", host_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("port", port_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("user", user_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("password", password_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("database", database_entry, "text", SYNC_CREATE | BIDIRECTIONAL); - binddings.bind ("use_ssl", ssl_switch, "active", SYNC_CREATE | BIDIRECTIONAL); - // debug ("set_up binddings done"); + private BindingGroup create_form_bind_group() { + var binddings = new BindingGroup(); + // debug ("set_up connection form bindings group"); + binddings.bind("name", name_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("host", host_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("port", port_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("user", user_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("password", password_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("database", database_entry, "text", SYNC_CREATE | BIDIRECTIONAL); + binddings.bind("use_ssl", ssl_switch, "active", SYNC_CREATE | BIDIRECTIONAL); + // debug ("set_up binddings done"); - return binddings; - } + return(binddings); + } - [GtkChild] - private unowned Gtk.SingleSelection selection_model; - [GtkChild] - private unowned Gtk.Paned paned; + [GtkChild] + private unowned Gtk.SingleSelection selection_model; + [GtkChild] + private unowned Gtk.Paned paned; - [GtkChild] - private unowned Gtk.Button connect_btn; + [GtkChild] + private unowned Gtk.Button connect_btn; - [GtkChild] - private unowned Gtk.Entry name_entry; + [GtkChild] + private unowned Gtk.Entry name_entry; - [GtkChild] - private unowned Gtk.Entry host_entry; - [GtkChild] - private unowned Gtk.Entry port_entry; - [GtkChild] - private unowned Gtk.Entry user_entry; - [GtkChild] - private unowned Gtk.PasswordEntry password_entry; + [GtkChild] + private unowned Gtk.Entry host_entry; + [GtkChild] + private unowned Gtk.Entry port_entry; + [GtkChild] + private unowned Gtk.Entry user_entry; + [GtkChild] + private unowned Gtk.PasswordEntry password_entry; - [GtkChild] - private unowned Gtk.Entry database_entry; + [GtkChild] + private unowned Gtk.Entry database_entry; - [GtkChild] - private unowned Gtk.Switch ssl_switch; - } + [GtkChild] + private unowned Gtk.Switch ssl_switch; +} - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/connection-row.ui")] - public class ConnectionRow : Gtk.Box { - public Connection item { get; set; } - public uint pos { get; set; } +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/connection-row.ui")] +public class ConnectionRow : Gtk.Box { + public Connection item { get; set; } + public uint pos { get; set; } - [GtkCallback] - public void on_right_clicked () { - var list_view = this.parent.parent as Gtk.ListView; - list_view.model.select_item (pos, true); + [GtkCallback] + public void on_right_clicked() { + var list_view = this.parent.parent as Gtk.ListView; + list_view.model.select_item(pos, true); - popover.popup (); - } - - [GtkChild] - private unowned Gtk.PopoverMenu popover; + popover.popup(); } -} \ No newline at end of file + + [GtkChild] + private unowned Gtk.PopoverMenu popover; +} +} diff --git a/src/ui/views/SchemaView.vala b/src/ui/views/SchemaView.vala index 453fe94..a65a50e 100644 --- a/src/ui/views/SchemaView.vala +++ b/src/ui/views/SchemaView.vala @@ -1,149 +1,145 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/schema-view.ui")] +public class SchemaView : Adw.Bin { + public SchemaViewModel schema_viewmodel { get; set; } + public TableViewModel table_viewmodel { get; set; } + public ViewViewModel view_viewmodel { get; set; } + public NavigationService navigation_service { get; set; } - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/schema-view.ui")] - public class SchemaView : Adw.Bin { - public SchemaViewModel schema_viewmodel { get; set; } - public TableViewModel table_viewmodel {get; set;} - public ViewViewModel view_viewmodel {get; set;} - public NavigationService navigation_service { get; set; } + public string view_mode { get; set; } - public string view_mode {get; set;} + public signal void request_logout(); - public signal void request_logout (); - - public SchemaView () { - Object (); - } + public SchemaView() { + Object(); + } - construct { - setup_paned (paned); - this.schema_viewmodel = autowire (); - this.table_viewmodel = autowire (); - this.view_viewmodel = autowire (); - this.navigation_service = autowire (); + construct { + setup_paned(paned); + this.schema_viewmodel = autowire (); + this.table_viewmodel = autowire (); + this.view_viewmodel = autowire (); + this.navigation_service = autowire (); - - sql_views.bind_property ("visible-child-name", this, "view-mode", DEFAULT); - dropdown.notify["selected"].connect (() => { + sql_views.bind_property("visible-child-name", this, "view-mode", DEFAULT); - if (dropdown.selected == Gtk.INVALID_LIST_POSITION) { + dropdown.notify["selected"].connect(() => { + if (dropdown.selected == Gtk.INVALID_LIST_POSITION) + { return; } - schema_viewmodel.select_index ((int)dropdown.selected); + schema_viewmodel.select_index((int)dropdown.selected); }); - table_selection.notify["selected"].connect (() => { - var table = table_selection.get_selected_item () as Table; - table_viewmodel.select_table ((Table)table); + table_selection.notify["selected"].connect(() => { + var table = table_selection.get_selected_item() as Table; + table_viewmodel.select_table((Table)table); }); - view_selection.notify["selected"].connect (() => { - var view = view_selection.get_selected_item () as View; - view_viewmodel.select_view ((View)view); + view_selection.notify["selected"].connect(() => { + var view = view_selection.get_selected_item() as View; + view_viewmodel.select_view((View)view); }); - var table_name_expression = new Gtk.PropertyExpression (typeof (Table), null, "name"); - var view_name_expression = new Gtk.PropertyExpression (typeof (View), null, "name"); - - var table_name_sorter = new Gtk.StringSorter (table_name_expression); - var view_name_sorter = new Gtk.StringSorter (view_name_expression); + var table_name_expression = new Gtk.PropertyExpression(typeof(Table), null, "name"); + var view_name_expression = new Gtk.PropertyExpression(typeof(View), null, "name"); - dropdown.expression = new Gtk.PropertyExpression (typeof (Schema), null, "name"); - table_filter.expression = new Gtk.PropertyExpression (typeof (Table), null, "name"); - table_sort_model.sorter = table_name_sorter; - view_sort_model.sorter = view_name_sorter; - view_filter.expression = new Gtk.PropertyExpression (typeof (View), null, "name"); - stack.visible_child_name = "data-view"; - } + var table_name_sorter = new Gtk.StringSorter(table_name_expression); + var view_name_sorter = new Gtk.StringSorter(view_name_expression); + dropdown.expression = new Gtk.PropertyExpression(typeof(Schema), null, "name"); + table_filter.expression = new Gtk.PropertyExpression(typeof(Table), null, "name"); + table_sort_model.sorter = table_name_sorter; + view_sort_model.sorter = view_name_sorter; + view_filter.expression = new Gtk.PropertyExpression(typeof(View), null, "name"); + stack.visible_child_name = "data-view"; + } - [GtkChild] - private unowned Gtk.Paned paned; - [GtkCallback] - private void on_table_search (Gtk.SearchEntry entry) { - table_filter.search = entry.text; - } + [GtkChild] + private unowned Gtk.Paned paned; - [GtkCallback] - private void on_view_search (Gtk.SearchEntry entry) { - view_filter.search = entry.text; - } + [GtkCallback] + private void on_table_search(Gtk.SearchEntry entry) { + table_filter.search = entry.text; + } - [GtkCallback] - private void table_search_reveal () { - search_table_entry.grab_focus (); - } + [GtkCallback] + private void on_view_search(Gtk.SearchEntry entry) { + view_filter.search = entry.text; + } - [GtkCallback] - private void view_search_reveal () { - search_views_entry.grab_focus (); - } + [GtkCallback] + private void table_search_reveal() { + search_table_entry.grab_focus(); + } - [GtkCallback] - private void reload_btn_clicked (Gtk.Button btn) { + [GtkCallback] + private void view_search_reveal() { + search_views_entry.grab_focus(); + } - btn.sensitive = false; - schema_viewmodel.reload.begin ((obj, res) => { - var window = get_parrent_window (this); + [GtkCallback] + private void reload_btn_clicked(Gtk.Button btn) { + btn.sensitive = false; + schema_viewmodel.reload.begin((obj, res) => { + var window = get_parrent_window(this); Adw.Toast toast; try { - schema_viewmodel.reload.end (res); - toast = new Adw.Toast ("Schema Reloaded") { + schema_viewmodel.reload.end(res); + toast = new Adw.Toast("Schema Reloaded") { timeout = 1, }; } catch (Psequel.PsequelError err) { - toast = new Adw.Toast (err.message) { + toast = new Adw.Toast(err.message) { timeout = 1, }; } - window.add_toast (toast); + window.add_toast(toast); btn.sensitive = true; }); - } - - [GtkCallback] - private void logout_btn_clicked (Gtk.Button btn) { - schema_viewmodel.logout.begin(); - navigation_service.navigate (NavigationService.CONNECTION_VIEW); - } + } + [GtkCallback] + private void logout_btn_clicked(Gtk.Button btn) { + schema_viewmodel.logout.begin(); + navigation_service.navigate(NavigationService.CONNECTION_VIEW); + } + [GtkChild] + private unowned Gtk.DropDown dropdown; - [GtkChild] - private unowned Gtk.DropDown dropdown; + [GtkChild] + private unowned Gtk.SearchEntry search_table_entry; - [GtkChild] - private unowned Gtk.SearchEntry search_table_entry; + [GtkChild] + private unowned Gtk.SearchEntry search_views_entry; - [GtkChild] - private unowned Gtk.SearchEntry search_views_entry; + [GtkChild] + private unowned Gtk.StringFilter table_filter; - [GtkChild] - private unowned Gtk.StringFilter table_filter; + [GtkChild] + private unowned Gtk.SortListModel table_sort_model; - [GtkChild] - private unowned Gtk.SortListModel table_sort_model; + [GtkChild] + private unowned Gtk.SortListModel view_sort_model; - [GtkChild] - private unowned Gtk.SortListModel view_sort_model; - - [GtkChild] - private unowned Gtk.StringFilter view_filter; + [GtkChild] + private unowned Gtk.StringFilter view_filter; - [GtkChild] - private unowned Gtk.SingleSelection table_selection; + [GtkChild] + private unowned Gtk.SingleSelection table_selection; - [GtkChild] - private unowned Gtk.SingleSelection view_selection; + [GtkChild] + private unowned Gtk.SingleSelection view_selection; - [GtkChild] - private unowned Adw.ViewStack sql_views; + [GtkChild] + private unowned Adw.ViewStack sql_views; - [GtkChild] - private unowned Adw.ViewStack stack; - } -} \ No newline at end of file + [GtkChild] + private unowned Adw.ViewStack stack; +} +} diff --git a/src/ui/widgets/DataCell.vala b/src/ui/widgets/DataCell.vala index e0225b8..b746123 100644 --- a/src/ui/widgets/DataCell.vala +++ b/src/ui/widgets/DataCell.vala @@ -2,102 +2,91 @@ using Gdk; using Csv; namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/datacell.ui")] +public class DataCell : Adw.Bin { + private Relation.Row current_row; + private int current_index; + public static List cell_pool; - [GtkTemplate(ui = "/me/ppvan/psequel/gtk/datacell.ui")] - public class DataCell : Adw.Bin { + const ActionEntry[] ACTION_ENTRIES = { + { "copy", on_cell_copy }, + { "edit", on_cell_edit }, + { "row-copy", on_row_copy }, + }; - private Relation.Row current_row; - private int current_index; - - public static List cell_pool; - - const ActionEntry[] ACTION_ENTRIES = { - { "copy", on_cell_copy }, - { "edit", on_cell_edit }, - { "row-copy", on_row_copy }, - }; - - - - - public DataCell() { - Object(); - } - - construct { - var action_group = new SimpleActionGroup(); - action_group.add_action_entries(ACTION_ENTRIES, this); - this.insert_action_group("schema", action_group); - } - - - public void bind_data(Psequel.Relation.Row row, int index) { - this.current_row = row; - this.current_index = index; - this.label.label = row[index]; - } - - public void unbind_data(Psequel.Relation.Row row) { - - } - - [GtkCallback] - public void on_right_clicked() { - popover.popup(); - } + public DataCell() { + Object(); + } + construct { + var action_group = new SimpleActionGroup(); + action_group.add_action_entries(ACTION_ENTRIES, this); + this.insert_action_group("schema", action_group); + } - // [GtkAction] - private void on_cell_copy () { - // viewmodel.dupplicate_connection (viewmodel.selected_connection); - debug ("on_cell_copy"); - var primary = Gdk.Display.get_default (); - var clipboard = primary.get_clipboard (); + public void bind_data(Psequel.Relation.Row row, int index) { + this.current_row = row; + this.current_index = index; + this.label.label = row[index]; + } - clipboard.set_text (this.current_row[current_index]); + public void unbind_data(Psequel.Relation.Row row) { + } - } + [GtkCallback] + public void on_right_clicked() { + popover.popup(); + } - // [GtkAction] - private void on_row_copy () { - // viewmodel.active_connection.begin (viewmodel.selected_connection); - StringBuilder builder = new StringBuilder (); + // [GtkAction] + private void on_cell_copy() { + // viewmodel.dupplicate_connection (viewmodel.selected_connection); + debug("on_cell_copy"); - for (int i = 0; i < current_row.size - 1; i++) { - var col = current_row[i]; - builder.append_printf ("%s, ", Csv.quote (col)); - } + var primary = Gdk.Display.get_default(); + var clipboard = primary.get_clipboard(); - var last_col = current_row[current_row.size - 1]; - builder.append_printf ("%s", Csv.quote (last_col)); - var row_as_csv = builder.free_and_steal (); + clipboard.set_text(this.current_row[current_index]); + } - this.clipboard_push (row_as_csv); + // [GtkAction] + private void on_row_copy() { + // viewmodel.active_connection.begin (viewmodel.selected_connection); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < current_row.size - 1; i++) + { + var col = current_row[i]; + builder.append_printf("%s, ", Csv.quote(col)); } + var last_col = current_row[current_row.size - 1]; + builder.append_printf("%s", Csv.quote(last_col)); + var row_as_csv = builder.free_and_steal(); - private void clipboard_push(string text) { - var primary = Gdk.Display.get_default (); - var clipboard = primary.get_clipboard (); + this.clipboard_push(row_as_csv); + } - clipboard.set_text (text); - } + private void clipboard_push(string text) { + var primary = Gdk.Display.get_default(); + var clipboard = primary.get_clipboard(); - private void on_cell_edit () { - // viewmodel.active_connection.begin (viewmodel.selected_connection); - debug ("on_cell_edit"); + clipboard.set_text(text); + } - } + private void on_cell_edit() { + // viewmodel.active_connection.begin (viewmodel.selected_connection); + debug("on_cell_edit"); + } - [GtkChild] - private unowned Gtk.Label label; + [GtkChild] + private unowned Gtk.Label label; - [GtkChild] - private unowned Gtk.PopoverMenu popover; - } -} \ No newline at end of file + [GtkChild] + private unowned Gtk.PopoverMenu popover; +} +} diff --git a/src/ui/widgets/StyleSwitcher.vala b/src/ui/widgets/StyleSwitcher.vala index 3576b00..d1eed78 100644 --- a/src/ui/widgets/StyleSwitcher.vala +++ b/src/ui/widgets/StyleSwitcher.vala @@ -1,60 +1,71 @@ namespace Psequel { +[GtkTemplate(ui = "/me/ppvan/psequel/gtk/style-switcher.ui")] +public class StyleSwitcher : Gtk.Widget { + [GtkChild] unowned Gtk.CheckButton system_selector; + [GtkChild] unowned Gtk.CheckButton light_selector; + [GtkChild] unowned Gtk.CheckButton dark_selector; - [GtkTemplate (ui = "/me/ppvan/psequel/gtk/style-switcher.ui")] - public class StyleSwitcher : Gtk.Widget { + public int style { get; set; } + public bool show_system { get; set; default = true; } - [GtkChild] unowned Gtk.CheckButton system_selector; - [GtkChild] unowned Gtk.CheckButton light_selector; - [GtkChild] unowned Gtk.CheckButton dark_selector; - - public int style { get; set; } - public bool show_system { get; set; default = true; } + static construct { + set_layout_manager_type(typeof(Gtk.BinLayout)); + set_css_name("themeswitcher"); + } - static construct { - set_layout_manager_type (typeof (Gtk.BinLayout)); - set_css_name ("themeswitcher"); - } + construct { + this.notify["style"].connect(this.on_style_changed); - construct { - this.notify["style"].connect (this.on_style_changed); + var s = autowire (); + s.bind("color-scheme", this, "style", GLib.SettingsBindFlags.DEFAULT); + } - var s = autowire (); - s.bind ("color-scheme", this, "style", GLib.SettingsBindFlags.DEFAULT); + private void on_style_changed() { + this.freeze_notify(); + if (this.style == ApplicationStyle.SYSTEM) + { + this.system_selector.active = true; + this.light_selector.active = false; + this.dark_selector.active = false; + } + else if (this.style == ApplicationStyle.LIGHT) + { + this.system_selector.active = false; + this.light_selector.active = true; + this.dark_selector.active = false; } + else + { + this.system_selector.active = false; + this.light_selector.active = false; + this.dark_selector.active = true; + } + this.thaw_notify(); + } - private void on_style_changed () { - this.freeze_notify (); - if (this.style == ApplicationStyle.SYSTEM) { - this.system_selector.active = true; - this.light_selector.active = false; - this.dark_selector.active = false; - } else if (this.style == ApplicationStyle.LIGHT) { - this.system_selector.active = false; - this.light_selector.active = true; - this.dark_selector.active = false; - } else { - this.system_selector.active = false; - this.light_selector.active = false; - this.dark_selector.active = true; + [GtkCallback] + private void theme_check_active_changed() { + if (this.system_selector.active) + { + if (this.style != ApplicationStyle.SYSTEM) + { + this.style = ApplicationStyle.SYSTEM; } - this.thaw_notify (); } - - [GtkCallback] - private void theme_check_active_changed () { - if (this.system_selector.active) { - if (this.style != ApplicationStyle.SYSTEM) { - this.style = ApplicationStyle.SYSTEM; - } - } else if (this.light_selector.active) { - if (this.style != ApplicationStyle.LIGHT) { - this.style = ApplicationStyle.LIGHT; - } - } else { - if (this.style != ApplicationStyle.DARK) { - this.style = ApplicationStyle.DARK; - } + else if (this.light_selector.active) + { + if (this.style != ApplicationStyle.LIGHT) + { + this.style = ApplicationStyle.LIGHT; + } + } + else + { + if (this.style != ApplicationStyle.DARK) + { + this.style = ApplicationStyle.DARK; } } } -} \ No newline at end of file +} +} diff --git a/src/utils/Event.vala b/src/utils/Event.vala index f55abc4..f37c3b2 100644 --- a/src/utils/Event.vala +++ b/src/utils/Event.vala @@ -1,53 +1,53 @@ namespace Psequel { +public class EventManager : Object { + private List targets; - public class EventManager : Object { - private List targets; - - private class EventTarget { - public string event_type; - public Observer observer; - } + private class EventTarget { + public string event_type; + public Observer observer; + } - public new void notify (string event_type, Object data) { - foreach (EventTarget target in targets) { - if (target.event_type == event_type) { - Event event = new Event (event_type, data); - target.observer.update (event); - } + public new void notify(string event_type, Object data) { + foreach (EventTarget target in targets) + { + if (target.event_type == event_type) + { + Event event = new Event(event_type, data); + target.observer.update(event); } } + } - public EventManager () { - Object(); - targets = new List(); - } - + public EventManager() { + Object(); + targets = new List (); + } - public void subcribe (string event_type, Observer observer) { - EventTarget target = new EventTarget(); - target.event_type = event_type; - target.observer = observer; + public void subcribe(string event_type, Observer observer) { + EventTarget target = new EventTarget(); + target.event_type = event_type; + target.observer = observer; - targets.append (target); - } + targets.append(target); } - - public class Event : Object { - public const string SCHEMA_CHANGED = "schema-changed"; - public const string SELECTED_TABLE_CHANGED = "selected-table-changed"; - public const string SELECTED_VIEW_CHANGED = "selected-view-changed"; - public const string ACTIVE_CONNECTION = "active-connection"; - public string type; - public Object data; - - public Event (string type, Object data) { - base(); - this.type = type; - this.data = data; - } +} + +public class Event : Object { + public const string SCHEMA_CHANGED = "schema-changed"; + public const string SELECTED_TABLE_CHANGED = "selected-table-changed"; + public const string SELECTED_VIEW_CHANGED = "selected-view-changed"; + public const string ACTIVE_CONNECTION = "active-connection"; + public string type; + public Object data; + + public Event(string type, Object data) { + base(); + this.type = type; + this.data = data; } +} - public interface Observer : Object { - public abstract void update(Event event); - } -} \ No newline at end of file +public interface Observer : Object { + public abstract void update(Event event); +} +} diff --git a/src/utils/ObservableList.vala b/src/utils/ObservableList.vala index fac127d..105d4fc 100644 --- a/src/utils/ObservableList.vala +++ b/src/utils/ObservableList.vala @@ -1,117 +1,120 @@ - namespace Psequel { - /** A list that's notify item-changed when there's changes to the list itself. */ - public class ObservableList: Object, ListModel { +/** A list that's notify item-changed when there's changes to the list itself. */ +public class ObservableList : Object, ListModel { + private ListStore _data; - private ListStore _data; + public int size { get; private set; } - public int size {get; private set;} + public delegate void ForeachFunc (T item); - public delegate void ForeachFunc (T item); - public delegate bool Predicate (T item); + public delegate bool Predicate (T item); - public ObservableList () { - base (); - this._data = new ListStore (typeof (T)); + public ObservableList() { + base(); + this._data = new ListStore(typeof(T)); - // Forward item changed event. - // this._data.items_changed.connect (this.items_changed); - this._data.items_changed.connect ((pos, removed, added) => { + // Forward item changed event. + // this._data.items_changed.connect (this.items_changed); + this._data.items_changed.connect((pos, removed, added) => { this.items_changed(pos, removed, added); - this.size = (int)this._data.get_n_items (); + this.size = (int)this._data.get_n_items(); }); - } - - public List to_list() { - List list = new List (); + } - for (uint i = 0; i < this.size; i++) { - list.append (this._data.get_item (i)); - } + public List to_list() { + List list = new List (); - return list; + for (uint i = 0; i < this.size; i++) + { + list.append(this._data.get_item(i)); } - public new T @get (int i) { - return (T)_data.get_item ((uint)i); - } + return(list); + } - public T? find (Predicate pred) { - for (uint i = 0; i < this.size; i++) { - T item = (T)_data.get_item (i); - if (pred (item)) { - return item; - } - } + public new T @get(int i) { + return((T)_data.get_item((uint)i)); + } - return null; + public T ? find(Predicate pred) { + for (uint i = 0; i < this.size; i++) + { + T item = (T)_data.get_item(i); + if (pred(item)) + { + return(item); + } } - public void clear () { - _data.remove_all (); - } + return(null); + } - public void append_all (List items) { - items.foreach ((item) => _data.append ((Object)item)); - } + public void clear() { + _data.remove_all(); + } - public void append (T item) { - _data.append ((Object)item); - } + public void append_all(List items) { + items.foreach((item) => _data.append((Object)item)); + } - public void prepend (T item) { - _data.insert (0, (Object)item); - } + public void append(T item) { + _data.append((Object)item); + } - public void extend (List items) { - items.foreach ((item) => _data.append ((Object)item)); - } + public void prepend(T item) { + _data.insert(0, (Object)item); + } - public void remove (T item) { - uint pos; - _data.find ((Object)item, out pos); + public void extend(List items) { + items.foreach((item) => _data.append((Object)item)); + } - _data.remove (pos); - } + public void remove(T item) { + uint pos; + _data.find((Object)item, out pos); - public void remove_at (uint position) { - _data.remove (position); - } + _data.remove(pos); + } - public void insert (uint pos, T conn) { - _data.insert (pos, (Object)conn); - } + public void remove_at(uint position) { + _data.remove(position); + } - public uint indexof (T conn) { - uint pos; - _data.find ((Object)conn, out pos); + public void insert(uint pos, T conn) { + _data.insert(pos, (Object)conn); + } - return pos; - } + public uint indexof(T conn) { + uint pos; + _data.find((Object)conn, out pos); - public T last () { - return _data.get_item (size - 1); - } + return(pos); + } - public void @foreach (ForeachFunc func) { - for (uint i = 0; i < this.size; i++) { - func (_data.get_item (i)); - } - } + public T last() { + return(_data.get_item(size - 1)); + } - public GLib.Object? get_item (uint position) { - return _data.get_item (position); - } - public GLib.Type get_item_type () { - return _data.get_item_type (); + public void @foreach(ForeachFunc func) { + for (uint i = 0; i < this.size; i++) + { + func(_data.get_item(i)); } + } - public uint get_n_items () { - return _data.get_n_items (); - } + public GLib.Object ?get_item(uint position) { + return(_data.get_item(position)); + } + public GLib.Type get_item_type() { + return(_data.get_item_type()); + } - public bool empty () { - return size == 0; - } + public uint get_n_items() { + return(_data.get_n_items()); + } + + public bool empty() { + return(size == 0); } -} \ No newline at end of file +} +} diff --git a/src/utils/ValueConverter.vala b/src/utils/ValueConverter.vala index e9cbbd8..c654a26 100644 --- a/src/utils/ValueConverter.vala +++ b/src/utils/ValueConverter.vala @@ -1,56 +1,54 @@ namespace Psequel { +const int64 SECOND_TO_MS = 1000; +const int64 MILISECS_TO_US = 1000; - const int64 SECOND_TO_MS = 1000; - const int64 MILISECS_TO_US = 1000; +/** Utils class to convert values. */ +public class ValueConverter { + public static List deserialize_connection(string json_data) { + var parser = new Json.Parser(); + var recent_connections = new List (); - /** Utils class to convert values. */ - public class ValueConverter { - public static List deserialize_connection (string json_data) { - var parser = new Json.Parser (); - var recent_connections = new List (); + try { + parser.load_from_data(json_data); + var root = parser.get_root(); + var conns = root.get_array(); - try { - parser.load_from_data (json_data); - var root = parser.get_root (); - var conns = root.get_array (); - - conns.foreach_element ((array, index, node) => { - var conn = (Connection) Json.gobject_deserialize (typeof (Connection), node); - recent_connections.append (conn); + conns.foreach_element((array, index, node) => { + var conn = (Connection)Json.gobject_deserialize(typeof(Connection), node); + recent_connections.append(conn); }); - } catch (Error err) { - debug (err.message); - } - - return (owned) recent_connections; + } catch (Error err) { + debug(err.message); } - public static string serialize_connection (List conns) { - - var builder = new Json.Builder (); - builder.begin_array (); + return((owned)recent_connections); + } - foreach (var conn in conns) { - builder.add_value (Json.gobject_serialize (conn)); - } - builder.end_array (); + public static string serialize_connection(List conns) { + var builder = new Json.Builder(); + builder.begin_array(); - var node = builder.get_root (); - return Json.to_string (node, true); + foreach (var conn in conns) + { + builder.add_value(Json.gobject_serialize(conn)); } + builder.end_array(); + var node = builder.get_root(); + return(Json.to_string(node, true)); + } - public static T[] list_to_array(List list) { - int len = (int) list.length (); - int i = 0; - T[] array = new T[len]; + public static T[] list_to_array (List list) { + int len = (int)list.length(); + int i = 0; + T[] array = new T[len]; - list.foreach ((item) => { + list.foreach((item) => { array[i++] = item; }); - return array; - } + return(array); } -} \ No newline at end of file +} +} diff --git a/src/utils/errors.vala b/src/utils/errors.vala index a9c27d0..5a2589d 100644 --- a/src/utils/errors.vala +++ b/src/utils/errors.vala @@ -1,8 +1,9 @@ namespace Psequel { - public errordomain PsequelError { - CONNECTION_ERROR, - QUERY_FAIL, - PARSE_ERROR, - EXPORT_ERROR - } -} \ No newline at end of file +public errordomain PsequelError +{ + CONNECTION_ERROR, + QUERY_FAIL, + PARSE_ERROR, + EXPORT_ERROR +} +} diff --git a/src/utils/helpers.vala b/src/utils/helpers.vala index b91c259..994c072 100644 --- a/src/utils/helpers.vala +++ b/src/utils/helpers.vala @@ -1,68 +1,81 @@ namespace Psequel { +public Window get_parrent_window(Gtk.Widget widget) { + var window = widget.get_root(); - public Window get_parrent_window (Gtk.Widget widget) { - var window = widget.get_root (); - - if (window is Psequel.Window) { - return (Window) window; - } else { - warning ("Widget %s root is not a window", widget.name); - assert_not_reached (); - } + if (window is Psequel.Window) + { + return((Window)window); } + else + { + warning("Widget %s root is not a window", widget.name); + assert_not_reached(); + } +} - /** Why it has to be like this? you ask. Because i don't find a way to limit paned postion that never hide it's child */ - public void setup_paned (Gtk.Paned paned) { - - paned.notify["position"].connect (() => { +/** Why it has to be like this? you ask. Because i don't find a way to limit paned postion that never hide it's child */ +public void setup_paned(Gtk.Paned paned) { + paned.notify["position"].connect(() => { var start = paned.start_child; - var end = paned.end_child; + var end = paned.end_child; - switch (paned.orientation) { + switch (paned.orientation) + { case Gtk.Orientation.HORIZONTAL: - if (paned.position < start.width_request) { + if (paned.position < start.width_request) + { paned.position = start.width_request; - } else if (paned.position > paned.get_width () - end.width_request) { - paned.position = paned.get_width () - end.width_request; + } + else if (paned.position > paned.get_width() - end.width_request) + { + paned.position = paned.get_width() - end.width_request; } break; + case Gtk.Orientation.VERTICAL: - if (paned.position < start.height_request) { + if (paned.position < start.height_request) + { paned.position = start.height_request; - } else if (paned.position > paned.get_height () - end.height_request) { - paned.position = paned.get_height () - end.height_request; + } + else if (paned.position > paned.get_height() - end.height_request) + { + paned.position = paned.get_height() - end.height_request; } break; } }); - } - - public Adw.MessageDialog create_dialog (string heading, string body) { - var app = autowire (); - var window = app.active_window; - var dialog = new Adw.MessageDialog (window, heading, body); +} - debug (body); +public Adw.MessageDialog create_dialog(string heading, string body) { + var app = autowire (); + var window = app.active_window; + var dialog = new Adw.MessageDialog(window, heading, body); - dialog.close_response = "okay"; - dialog.add_response ("okay", "OK"); + debug(body); - return dialog; - } + dialog.close_response = "okay"; + dialog.add_response("okay", "OK"); - public class MonospaceFilter : Gtk.Filter { - public override bool match (GLib.Object? item) { + return(dialog); +} - if (item is Pango.FontFace) { - var fontface = item as Pango.FontFace; - return fontface.get_family ().is_monospace (); - } else if (item is Pango.FontFamily) { - var family = item as Pango.FontFamily; - return family.is_monospace (); - } else { - debug ("Check the FontDialog docs: https://docs.gtk.org/gtk4/method.FontDialog.set_filter.html"); - assert_not_reached (); - } +public class MonospaceFilter : Gtk.Filter { + public override bool match(GLib.Object ?item) { + if (item is Pango.FontFace) + { + var fontface = item as Pango.FontFace; + return(fontface.get_family().is_monospace()); + } + else if (item is Pango.FontFamily) + { + var family = item as Pango.FontFamily; + return(family.is_monospace()); + } + else + { + debug("Check the FontDialog docs: https://docs.gtk.org/gtk4/method.FontDialog.set_filter.html"); + assert_not_reached(); } } -} \ No newline at end of file +} +} diff --git a/src/utils/logging.vala b/src/utils/logging.vala index bfa2639..ce535e6 100644 --- a/src/utils/logging.vala +++ b/src/utils/logging.vala @@ -1,27 +1,31 @@ namespace Psequel { - public void set_up_logging () { - var debug_domain = Environment.get_variable ("G_MESSAGES_DEBUG"); +public void set_up_logging() { + var debug_domain = Environment.get_variable("G_MESSAGES_DEBUG"); - switch (debug_domain) { - case Config.G_LOG_DOMAIN, "all": - Log.set_handler (Config.G_LOG_DOMAIN, LogLevelFlags.LEVEL_DEBUG | LogLevelFlags.LEVEL_WARNING, log_function); - break; - default: - break; - } + switch (debug_domain) + { + case Config.G_LOG_DOMAIN, "all": + Log.set_handler(Config.G_LOG_DOMAIN, LogLevelFlags.LEVEL_DEBUG | LogLevelFlags.LEVEL_WARNING, log_function); + break; + + default: + break; } +} + +private void log_function(string ?domain, LogLevelFlags level, string message) { + switch (level) + { + case LogLevelFlags.LEVEL_DEBUG: + print("[DEBUG] %s\n", message); + break; - private void log_function (string? domain, LogLevelFlags level, string message) { - switch (level) { - case LogLevelFlags.LEVEL_DEBUG: - print ("[DEBUG] %s\n", message); - break; - case LogLevelFlags.LEVEL_WARNING: - print ("[WARN] %s\n", message); - break; + case LogLevelFlags.LEVEL_WARNING: + print("[WARN] %s\n", message); + break; - default: - assert_not_reached (); - } + default: + assert_not_reached(); } -} \ No newline at end of file +} +} diff --git a/src/utils/types.vala b/src/utils/types.vala index 34f7fb9..a5d17b5 100644 --- a/src/utils/types.vala +++ b/src/utils/types.vala @@ -1,50 +1,49 @@ namespace Psequel { - /** - * Util class to mesure execution time than log it using debug() - */ - public class TimePerf { - private static int64 _start; - private static int64 _end; - - public static void begin () { - _start = GLib.get_real_time (); - } +/** + * Util class to mesure execution time than log it using debug() + */ +public class TimePerf { + private static int64 _start; + private static int64 _end; + + public static void begin() { + _start = GLib.get_real_time(); + } - public static void end () { - _end = GLib.get_real_time (); + public static void end() { + _end = GLib.get_real_time(); - debug (@"Elapsed: %$(int64.FORMAT) ms", (_end - _start) / 1000); - } + debug(@"Elapsed: %$(int64.FORMAT) ms", (_end - _start) / 1000); + } - public static int64 uend () { - _end = GLib.get_real_time (); + public static int64 uend() { + _end = GLib.get_real_time(); - debug (@"Elapsed: %$(int64.FORMAT) μs", (_end - _start)); + debug(@"Elapsed: %$(int64.FORMAT) μs", (_end - _start)); - return _end - _start; - } + return(_end - _start); } +} - public delegate void Job (); +public delegate void Job(); - public class Worker { - public string thread_name { private set; get; } - public Job task; +public class Worker { + public string thread_name { private set; get; } + public Job task; - public Worker (string name, owned Job task) { - this.thread_name = name; - this.task = (owned) task; - } - - public void run () { - - // Thread.usleep ((ulong)1e6); - this.task (); - } + public Worker(string name, owned Job task) { + this.thread_name = name; + this.task = (owned)task; } - public T autowire () { - var container = Container.instance (); - return (T) container.find_type (typeof (T)); + public void run() { + // Thread.usleep ((ulong)1e6); + this.task(); } -} \ No newline at end of file +} + +public T autowire () { + var container = Container.instance(); + return((T)container.find_type(typeof(T))); +} +} diff --git a/src/viewmodels/BaseViewModel.vala b/src/viewmodels/BaseViewModel.vala index be00398..b0e9dd0 100644 --- a/src/viewmodels/BaseViewModel.vala +++ b/src/viewmodels/BaseViewModel.vala @@ -1,25 +1,24 @@ namespace Psequel { - public abstract class BaseViewModel : Object { +public abstract class BaseViewModel : Object { + public const string CONNECTION_VIEW = "connection-view"; + public const string QUERY_VIEW = "query-view"; - public const string CONNECTION_VIEW = "connection-view"; - public const string QUERY_VIEW = "query-view"; + public signal void navigate_to(string view); - public signal void navigate_to (string view); + protected EventManager event_manager; - protected EventManager event_manager; - - protected BaseViewModel () { - event_manager = new EventManager (); - // debug ("BaseViewModel created"); - } + protected BaseViewModel() { + event_manager = new EventManager(); + // debug ("BaseViewModel created"); + } - public void subcribe (string event_type, Observer observer) { - event_manager.subcribe (event_type, observer); - } + public void subcribe(string event_type, Observer observer) { + event_manager.subcribe(event_type, observer); + } - protected void emit_event(string event_type, Object data) { - debug ("Emit: %s", event_type); - event_manager.notify (event_type, data); - } + protected void emit_event(string event_type, Object data) { + debug("Emit: %s", event_type); + event_manager.notify(event_type, data); } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/ConnectionViewModel.vala b/src/viewmodels/ConnectionViewModel.vala index 52c26ea..5c52ce1 100644 --- a/src/viewmodels/ConnectionViewModel.vala +++ b/src/viewmodels/ConnectionViewModel.vala @@ -1,123 +1,127 @@ namespace Psequel { - public class ConnectionViewModel : BaseViewModel { - - public enum State { - IDLE, - CONNECTING, - ERROR - } +public class ConnectionViewModel : BaseViewModel { + public enum State + { + IDLE, + CONNECTING, + ERROR + } - uint timeout_id = 0; - public ConnectionRepository repository { get; private set; } - public SQLService sql_service { get; private set; } - public NavigationService navigation_service { get; private set; } + uint timeout_id = 0; + public ConnectionRepository repository { get; private set; } + public SQLService sql_service { get; private set; } + public NavigationService navigation_service { get; private set; } - // States + // States - public State current_state {get; private set; default = State.IDLE;} - public string err_msg {get; private set; default = "hello world";} - public ObservableList connections { get; private set; default = new ObservableList (); } - public Connection? selected_connection { get; set; } + public State current_state { get; private set; default = State.IDLE; } + public string err_msg { get; private set; default = "hello world"; } + public ObservableList connections { get; private set; default = new ObservableList (); } + public Connection ?selected_connection { get; set; } - /** True when trying to establish a connection util know results. */ - public bool is_connectting { get; set; default = false; } + /** True when trying to establish a connection util know results. */ + public bool is_connectting { get; set; default = false; } - public ConnectionViewModel (ConnectionRepository repository, SQLService sql_service, NavigationService navigation_service) { - base (); - this.repository = repository; - this.sql_service = sql_service; - this.navigation_service = navigation_service; + public ConnectionViewModel(ConnectionRepository repository, SQLService sql_service, NavigationService navigation_service) { + base(); + this.repository = repository; + this.sql_service = sql_service; + this.navigation_service = navigation_service; - var loaded_conn = repository.find_all (); - connections.extend (loaded_conn); + var loaded_conn = repository.find_all(); + connections.extend(loaded_conn); - if (connections.empty ()) { - new_connection (); - } + if (connections.empty()) + { + new_connection(); + } - this.bind_property ("current-state", this, "is-connectting", SYNC_CREATE, from_state_to_connecting); + this.bind_property("current-state", this, "is-connectting", SYNC_CREATE, from_state_to_connecting); - // Auto save data each 10 secs in case app crash. - // Timeout.add_seconds (10, () => { - // repository.save (connections.to_list ()); - // return Source.CONTINUE; - // }, Priority.LOW); - } + // Auto save data each 10 secs in case app crash. + // Timeout.add_seconds (10, () => { + // repository.save (connections.to_list ()); + // return Source.CONTINUE; + // }, Priority.LOW); + } - public void new_connection () { - var conn = new Connection (); - conn = repository.append_connection (conn); - connections.append (conn); - selected_connection = conn; + public void new_connection() { + var conn = new Connection(); + conn = repository.append_connection(conn); + connections.append(conn); + selected_connection = conn; - // save_connections (); - } + // save_connections (); + } - public void dupplicate_connection (Connection conn) { - var clone = conn.clone (); - clone.name = clone.name + " (copy)"; - clone.id = 0; - repository.append_connection (clone); - connections.insert (connections.indexof (conn) + 1, clone); - selected_connection = clone; - } + public void dupplicate_connection(Connection conn) { + var clone = conn.clone(); + clone.name = clone.name + " (copy)"; + clone.id = 0; + repository.append_connection(clone); + connections.insert(connections.indexof(conn) + 1, clone); + selected_connection = clone; + } - public void remove_connection (Connection conn) { - repository.remove_connection (conn); - connections.remove (conn); + public void remove_connection(Connection conn) { + repository.remove_connection(conn); + connections.remove(conn); + } - } + public void import_connections(List connections) { + repository.append_all(connections); - public void import_connections (List connections) { - repository.append_all (connections); + this.connections.append_all(connections); + } - this.connections.append_all (connections); + public async void active_connection(Connection connection) { + this.current_state = State.CONNECTING; + try { + yield sql_service.connect_db(connection); + + this.navigation_service.navigate(NavigationService.QUERY_VIEW); + this.emit_event(Event.ACTIVE_CONNECTION, connection); + } catch (PsequelError err) { + this.err_msg = err.message.dup(); + debug("Error: %s", err.message); + this.current_state = State.ERROR; + return; } + this.current_state = State.IDLE; + } - public async void active_connection (Connection connection) { - this.current_state = State.CONNECTING; - try { - yield sql_service.connect_db (connection); - this.navigation_service.navigate (NavigationService.QUERY_VIEW); - this.emit_event (Event.ACTIVE_CONNECTION, connection); - - } catch (PsequelError err) { - this.err_msg = err.message.dup (); - debug ("Error: %s", err.message); - this.current_state = State.ERROR; - return; - } - this.current_state = State.IDLE; - } + public List export_connections() { + return(repository.find_all()); + } - public List export_connections () { - return repository.find_all (); + public void save_connections() { + if (timeout_id != 0) + { + Source.remove(timeout_id); } - public void save_connections () { - if (timeout_id != 0) { - Source.remove (timeout_id); - } - - timeout_id = Timeout.add (500, () => { + timeout_id = Timeout.add(500, () => { timeout_id = 0; - repository.save (connections.to_list()); - return Source.REMOVE; + repository.save(connections.to_list()); + return(Source.REMOVE); }); - } - - private bool from_state_to_connecting (Binding binding, Value from, ref Value to) { - ConnectionViewModel.State state = (ConnectionViewModel.State) from.get_enum (); - if (state == ConnectionViewModel.State.CONNECTING) { - to.set_boolean (true); - } else { - to.set_boolean (false); - } + } - return true; + private bool from_state_to_connecting(Binding binding, Value from, ref Value to) { + ConnectionViewModel.State state = (ConnectionViewModel.State)from.get_enum(); + if (state == ConnectionViewModel.State.CONNECTING) + { + to.set_boolean(true); } + else + { + to.set_boolean(false); + } + + return(true); } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/QueryHistoryViewModel.vala b/src/viewmodels/QueryHistoryViewModel.vala index 3a2329a..c22ee8c 100644 --- a/src/viewmodels/QueryHistoryViewModel.vala +++ b/src/viewmodels/QueryHistoryViewModel.vala @@ -1,88 +1,94 @@ namespace Psequel { - public class QueryHistoryViewModel : BaseViewModel { - const string AUTO_EXEC_HISTORY = "auto-exec-history"; +public class QueryHistoryViewModel : BaseViewModel { + const string AUTO_EXEC_HISTORY = "auto-exec-history"; - - public ObservableList query_history { get; set; default = new ObservableList (); } - public Query? selected_query { get; set; } - // SQL related result. - public bool is_loading { get; private set; } - public bool success {get; private set;} - public string err_msg { get; private set; } + public ObservableList query_history { get; set; default = new ObservableList (); } + public Query ?selected_query { get; set; } - public Relation current_relation { get; private set; } - public Relation.Row? selected_row { get; set; } + // SQL related result. + public bool is_loading { get; private set; } + public bool success { get; private set; } + public string err_msg { get; private set; } - // Status properties - public string row_affected { get; private set; } - public string query_time { get; private set; } + public Relation current_relation { get; private set; } + public Relation.Row ?selected_row { get; set; } - public SQLService sql_service { get; construct; } - public QueryRepository query_repository {get; construct;} + // Status properties + public string row_affected { get; private set; } + public string query_time { get; private set; } + public SQLService sql_service { get; construct; } + public QueryRepository query_repository { get; construct; } - public QueryHistoryViewModel (SQLService sql_service, QueryRepository query_repository) { - Object (sql_service: sql_service, query_repository: query_repository); - this.query_history.append_all (query_repository.get_queries ()); - this.notify["current-relation"].connect (() => { - success = true; + public QueryHistoryViewModel(SQLService sql_service, QueryRepository query_repository) { + Object(sql_service: sql_service, query_repository: query_repository); + + this.query_history.append_all(query_repository.get_queries()); + this.notify["current-relation"].connect(() => { + success = true; row_affected = @"$(current_relation.row_affected) row affected."; - if (current_relation.fetch_time / SECOND_TO_MS > 0) { - if (current_relation.fetch_time / SECOND_TO_MS / MILISECS_TO_US > 0) { + if (current_relation.fetch_time / SECOND_TO_MS > 0) + { + if (current_relation.fetch_time / SECOND_TO_MS / MILISECS_TO_US > 0) + { query_time = @"$(current_relation.fetch_time / SECOND_TO_MS / MILISECS_TO_US) s"; - } else { + } + else + { query_time = @"$(current_relation.fetch_time / SECOND_TO_MS) ms"; } - } else { + } + else + { query_time = @"$(current_relation.fetch_time) μs"; } }); - } - - public async void exec_query (Query query) { - yield run_query_internal (query); + } - query_history.prepend (query); - query_repository.append_query (query); - selected_query = query; - } + public async void exec_query(Query query) { + yield run_query_internal(query); - public async void exec_history (Query query) { - // if (Application.settings.get_boolean (AUTO_EXEC_HISTORY)) { - - // } + query_history.prepend(query); + query_repository.append_query(query); + selected_query = query; + } - yield run_query_internal (query); + public async void exec_history(Query query) { + // if (Application.settings.get_boolean (AUTO_EXEC_HISTORY)) { - query_history.remove (query); - query_history.prepend (query); - selected_query = query; - } + // } - public async void clear_history () { - query_history.clear (); - query_repository.clear (); - } + yield run_query_internal(query); - private inline async bool run_query_internal (Query query) { - is_loading = true; + query_history.remove(query); + query_history.prepend(query); + selected_query = query; + } - try { - current_relation = yield sql_service.exec_query (query); + public async void clear_history() { + query_history.clear(); + query_repository.clear(); + } - debug ("Rows: %d", current_relation.rows); - is_loading = false; + private inline async bool run_query_internal(Query query) { + is_loading = true; - return true; - } catch (PsequelError err) { - this.err_msg = err.message; - } + try { + current_relation = yield sql_service.exec_query(query); + debug("Rows: %d", current_relation.rows); is_loading = false; - return false; + + return(true); + } catch (PsequelError err) { + this.err_msg = err.message; } + + is_loading = false; + return(false); } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/QueryViewModel.vala b/src/viewmodels/QueryViewModel.vala index ca749e9..9340012 100644 --- a/src/viewmodels/QueryViewModel.vala +++ b/src/viewmodels/QueryViewModel.vala @@ -1,35 +1,34 @@ namespace Psequel { - public class QueryViewModel : BaseViewModel { +public class QueryViewModel : BaseViewModel { + public QueryHistoryViewModel query_history_viewmodel { get; set; } - public QueryHistoryViewModel query_history_viewmodel { get; set; } + public ObservableList queries { get; set; } + public Query ?selected_query { get; set; } - public ObservableList queries { get; set; } - public Query? selected_query { get; set; } + public Schema ?current_schema { get; construct; } + public SQLService sql_service { get; construct; } - public Schema? current_schema { get; construct; } - public SQLService sql_service { get; construct; } - - public QueryViewModel (QueryHistoryViewModel query_history_viewmodel) { - Object (query_history_viewmodel: query_history_viewmodel); - } - - public async void run_selected_query () { - if (selected_query == null || selected_query.sql == "") { - return; - } + public QueryViewModel(QueryHistoryViewModel query_history_viewmodel) { + Object(query_history_viewmodel: query_history_viewmodel); + } - yield query_history_viewmodel.exec_query (selected_query); + public async void run_selected_query() { + if (selected_query == null || selected_query.sql == "") + { + return; } - public async void run_query (Query query) { - yield query_history_viewmodel.exec_query (query); - } + yield query_history_viewmodel.exec_query(selected_query); + } + public async void run_query(Query query) { + yield query_history_viewmodel.exec_query(query); + } - public void selected_query_changed (string text) { - Query query = new Query (text); - selected_query = query; - } + public void selected_query_changed(string text) { + Query query = new Query(text); + selected_query = query; } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/SchemaViewModel.vala b/src/viewmodels/SchemaViewModel.vala index e7bfbe9..4597bba 100644 --- a/src/viewmodels/SchemaViewModel.vala +++ b/src/viewmodels/SchemaViewModel.vala @@ -1,88 +1,93 @@ namespace Psequel { - public class SchemaViewModel : BaseViewModel, Observer { +public class SchemaViewModel : BaseViewModel, Observer { + const string DEFAULT = "public"; - const string DEFAULT = "public"; + public ObservableList schemas { get; set; default = new ObservableList (); } + public Schema ?current_schema { get; set; } - public ObservableList schemas { get; set; default = new ObservableList (); } - public Schema? current_schema { get; set; } + // Needed to interact with gtk.dropdown properly. + public int current_index { get; set; } - // Needed to interact with gtk.dropdown properly. - public int current_index { get; set;} + public SchemaRepository repository; - public SchemaRepository repository; + // Services - // Services + public SchemaService schema_service { get; private set; } - public SchemaService schema_service { get; private set; } + public SchemaViewModel(SchemaService service) { + base(); + this.schema_service = service; - public SchemaViewModel (SchemaService service) { - base(); - this.schema_service = service; - - this.notify["current-schema"].connect (() => { - this.emit_event (Event.SCHEMA_CHANGED, current_schema); + this.notify["current-schema"].connect(() => { + this.emit_event(Event.SCHEMA_CHANGED, current_schema); }); - } - - public void select_index (int index) { + } - if (index < 0 || index >= schemas.size) { - return; - } - debug ("Select index %d, %s\n", index, schemas[index].name); - select_schema.begin (schemas[index]); + public void select_index(int index) { + if (index < 0 || index >= schemas.size) + { + return; } + debug("Select index %d, %s\n", index, schemas[index].name); + select_schema.begin(schemas[index]); + } - public void update (Event event) { - if (event.type == Event.ACTIVE_CONNECTION) { - // delay for ui to play animation - Timeout.add_once (300, () => { - database_connected.begin (); + public void update(Event event) { + if (event.type == Event.ACTIVE_CONNECTION) + { + // delay for ui to play animation + Timeout.add_once(300, () => { + database_connected.begin(); }); - } } + } - public async void reload () throws PsequelError { - if (current_schema == null) { - return; - } - yield select_schema (current_schema); + public async void reload() throws PsequelError { + if (current_schema == null) + { + return; } + yield select_schema(current_schema); + } - public async void logout () throws PsequelError { - current_schema = null; - schemas.clear (); - } + public async void logout() throws PsequelError { + current_schema = null; + schemas.clear(); + } - private async void database_connected () throws PsequelError { - // auto load schema list. - yield load_schemas (); - - yield select_schema (schemas.find (s => s.name == DEFAULT)); - } + private async void database_connected() throws PsequelError { + // auto load schema list. + yield load_schemas(); - /** Select current schema */ - private async void select_schema (Schema schema) throws PsequelError { - debug ("Select schema: %s", schema.name); - current_schema = schema; - } + yield select_schema(schemas.find(s => s.name == DEFAULT)); + } - /** List schema from database. */ - private async void load_schemas () throws PsequelError { - var unload_schemas = yield schema_service.schema_list (); - - var public_first_schemas = new List (); - - foreach(var s in unload_schemas) { - if (s.name == DEFAULT) { - public_first_schemas.insert (s, 0); - } else { - public_first_schemas.append (s); - } - } + /** Select current schema */ + private async void select_schema(Schema schema) throws PsequelError { + debug("Select schema: %s", schema.name); + current_schema = schema; + } - schemas.clear (); - schemas.append_all (public_first_schemas); + /** List schema from database. */ + private async void load_schemas() throws PsequelError { + var unload_schemas = yield schema_service.schema_list(); + + var public_first_schemas = new List (); + + foreach (var s in unload_schemas) + { + if (s.name == DEFAULT) + { + public_first_schemas.insert(s, 0); + } + else + { + public_first_schemas.append(s); + } } + + schemas.clear(); + schemas.append_all(public_first_schemas); } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/TableDataViewModel.vala b/src/viewmodels/TableDataViewModel.vala index 32a7b78..4f06eb2 100644 --- a/src/viewmodels/TableDataViewModel.vala +++ b/src/viewmodels/TableDataViewModel.vala @@ -1,92 +1,94 @@ namespace Psequel { +public class TableDataViewModel : BaseViewModel, Observer { + public const int MAX_FETCHED_ROW = 50; - public class TableDataViewModel : BaseViewModel, Observer { + public Table ?selected_table { get; set; } + // public View? current_view {get; set;} - public const int MAX_FETCHED_ROW = 50; + public bool has_pre_page { get; private set; default = false; } + public bool has_next_page { get; private set; default = true; } + public int current_page { get; set; } - public Table? selected_table { get; set; } - // public View? current_view {get; set;} + public string row_ranges { get; private set; default = ""; } - public bool has_pre_page { get; private set; default = false;} - public bool has_next_page { get; private set; default = true; } - public int current_page { get; set; } + public bool is_loading { get; set; } + public string err_msg { get; set; } - public string row_ranges {get; private set; default = "";} + public Relation current_relation { get; set; } + public Relation.Row ?selected_row { get; set; } - public bool is_loading { get; set; } - public string err_msg { get; set; } + public SQLService sql_service { get; construct; } - public Relation current_relation { get; set; } - public Relation.Row? selected_row { get; set; } - public SQLService sql_service { get; construct; } + public TableDataViewModel(SQLService service) { + Object(sql_service: service); - - public TableDataViewModel (SQLService service) { - Object (sql_service: service); - - this.notify["current-page"].connect (() => { - if (current_page > 0) { + this.notify["current-page"].connect(() => { + if (current_page > 0) + { has_pre_page = true; - } else { + } + else + { has_pre_page = false; } }); - this.notify["current-relation"].connect (() => { - + this.notify["current-relation"].connect(() => { int offset = MAX_FETCHED_ROW * current_page; row_ranges = @"Rows $(1 + offset) - $(offset + current_relation.rows)"; - if (current_relation.rows < MAX_FETCHED_ROW) { + if (current_relation.rows < MAX_FETCHED_ROW) + { has_next_page = false; - - } else { + } + else + { has_next_page = true; } }); - this.notify["selected-table"].connect (() => { + this.notify["selected-table"].connect(() => { current_page = 0; - reload_data.begin (); + reload_data.begin(); }); - } - - public void update (Event event) { - switch (event.type) { - case Event.SELECTED_TABLE_CHANGED: - selected_table = event.data as Table; - break; - } - } + } - public async void reload_data () { - yield load_data (selected_table, current_page); + public void update(Event event) { + switch (event.type) + { + case Event.SELECTED_TABLE_CHANGED: + selected_table = event.data as Table; + break; } + } - public async void next_page () { - current_page = current_page + 1; - yield load_data (selected_table, current_page); - } + public async void reload_data() { + yield load_data(selected_table, current_page); + } - public async void pre_page () { - current_page = current_page - 1; - yield load_data (selected_table, current_page); - } + public async void next_page() { + current_page = current_page + 1; + yield load_data(selected_table, current_page); + } - private inline async void load_data (Table table, int page) { + public async void pre_page() { + current_page = current_page - 1; + yield load_data(selected_table, current_page); + } - try { - is_loading = true; - current_relation = yield sql_service.select (table, page, MAX_FETCHED_ROW); + private inline async void load_data(Table table, int page) { + try { + is_loading = true; + current_relation = yield sql_service.select(table, page, MAX_FETCHED_ROW); - is_loading = false; - debug ("Rows: %d", current_relation.rows); - } catch (PsequelError err) { - this.err_msg = err.message; - } + is_loading = false; + debug("Rows: %d", current_relation.rows); + } catch (PsequelError err) { + this.err_msg = err.message; } } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/TableStructureViewModel.vala b/src/viewmodels/TableStructureViewModel.vala index 338c08a..e234c71 100644 --- a/src/viewmodels/TableStructureViewModel.vala +++ b/src/viewmodels/TableStructureViewModel.vala @@ -1,125 +1,127 @@ namespace Psequel { - public class TableStructureViewModel : Observer, Object { +public class TableStructureViewModel : Observer, Object { + public SQLService sql_service { get; set; } + public Table selected_table { get; set; } - public SQLService sql_service { get; set; } - public Table selected_table { get; set; } + public ObservableList columns { get; set; default = new ObservableList (); } + public ObservableList indexes { get; set; default = new ObservableList (); } + public ObservableList foreign_keys { get; set; default = new ObservableList (); } - public ObservableList columns { get; set; default = new ObservableList (); } - public ObservableList indexes { get; set; default = new ObservableList (); } - public ObservableList foreign_keys { get; set; default = new ObservableList (); } + public TableStructureViewModel(SQLService sql_service) { + base(); + // debug ("TableStructureViewModel created "); + this.sql_service = sql_service; - public TableStructureViewModel (SQLService sql_service) { - base (); - // debug ("TableStructureViewModel created "); - this.sql_service = sql_service; - - // selected_table = table; - } + // selected_table = table; + } - public void update (Event event) { - switch (event.type) { - case Event.SCHEMA_CHANGED: - var schema = event.data as Schema; - load_data.begin (schema); - break; - case Event.SELECTED_TABLE_CHANGED: - var table = event.data as Table; - selected_table = table; - break; - default: - break; - } + public void update(Event event) { + switch (event.type) + { + case Event.SCHEMA_CHANGED: + var schema = event.data as Schema; + load_data.begin(schema); + break; + + case Event.SELECTED_TABLE_CHANGED: + var table = event.data as Table; + selected_table = table; + break; + + default: + break; } + } - private async void load_data (Schema schema) { - columns.clear (); - indexes.clear (); - foreign_keys.clear (); - - columns.append_all (yield _get_columns (schema)); - indexes.append_all (yield _get_indexes (schema)); - foreign_keys.append_all (yield _get_fks (schema)); + private async void load_data(Schema schema) { + columns.clear(); + indexes.clear(); + foreign_keys.clear(); - debug ("cols: %d indx: %d fks: %d", columns.size, indexes.size, foreign_keys.size); - } + columns.append_all(yield _get_columns(schema)); + indexes.append_all(yield _get_indexes(schema)); + foreign_keys.append_all(yield _get_fks(schema)); - private async List _get_columns (Schema schema) { + debug("cols: %d indx: %d fks: %d", columns.size, indexes.size, foreign_keys.size); + } - var list = new List (); + private async List _get_columns(Schema schema) { + var list = new List (); - try { - var query = new Query.with_params (COLUMN_SQL, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + try { + var query = new Query.with_params(COLUMN_SQL, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - foreach (var row in relation) { - var col = new Column (); - col.schemaname = schema.name; - col.name = row[0]; - col.table = row[1]; - col.column_type = row[2]; - col.nullable = row[3] == "YES" ? true : false; - col.default_val = row[4]; + foreach (var row in relation) + { + var col = new Column(); + col.schemaname = schema.name; + col.name = row[0]; + col.table = row[1]; + col.column_type = row[2]; + col.nullable = row[3] == "YES" ? true : false; + col.default_val = row[4]; - list.append (col); - } - } catch (PsequelError err) { - debug (err.message); + list.append(col); } - - return list; + } catch (PsequelError err) { + debug(err.message); } - private async List _get_indexes (Schema schema) { + return(list); + } - var list = new List (); + private async List _get_indexes(Schema schema) { + var list = new List (); - try { - var query = new Query.with_params (INDEX_SQL, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + try { + var query = new Query.with_params(INDEX_SQL, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - foreach (var row in relation) { - var index = new Index (); - index.schemaname = schema.name; - index.name = row[0]; - index.table = row[1]; - index.size = row[2]; - index.indexdef = row[3]; + foreach (var row in relation) + { + var index = new Index(); + index.schemaname = schema.name; + index.name = row[0]; + index.table = row[1]; + index.size = row[2]; + index.indexdef = row[3]; - list.append (index); - } - } catch (PsequelError err) { - debug (err.message); + list.append(index); } - - return list; + } catch (PsequelError err) { + debug(err.message); } - private async List _get_fks (Schema schema) { + return(list); + } - var list = new List (); + private async List _get_fks(Schema schema) { + var list = new List (); - try { - var query = new Query.with_params (FK_SQL, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + try { + var query = new Query.with_params(FK_SQL, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - foreach (var row in relation) { - var fk = new ForeignKey (); - fk.schemaname = schema.name; - fk.name = row[0]; - fk.table = row[1]; - fk.fk_def = row[2]; + foreach (var row in relation) + { + var fk = new ForeignKey(); + fk.schemaname = schema.name; + fk.name = row[0]; + fk.table = row[1]; + fk.fk_def = row[2]; - list.append (fk); - } - } catch (PsequelError err) { - debug (err.message); + list.append(fk); } - - return list; + } catch (PsequelError err) { + debug(err.message); } - public const string COLUMN_SQL = """ + return(list); + } + + public const string COLUMN_SQL = """ SELECT column_name, table_name, case when domain_name is not null then domain_name @@ -131,12 +133,12 @@ namespace Psequel { FROM information_schema.columns WHERE table_schema = $1; """; - public const string INDEX_SQL = """ + public const string INDEX_SQL = """ SELECT indexname, tablename, pg_size_pretty(pg_relation_size(indexname::regclass)) as size, indexdef FROM pg_indexes WHERE schemaname = $1; """; - public const string FK_SQL = """ + public const string FK_SQL = """ SELECT con.conname, rel.relname, pg_catalog.pg_get_constraintdef(con.oid, true) as condef FROM pg_catalog.pg_constraint con INNER JOIN pg_catalog.pg_class rel @@ -145,5 +147,5 @@ namespace Psequel { ON nsp.oid = connamespace WHERE con.contype = 'f' AND nsp.nspname = $1; """; - } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/TableViewModel.vala b/src/viewmodels/TableViewModel.vala index 3f3b566..a67dddb 100644 --- a/src/viewmodels/TableViewModel.vala +++ b/src/viewmodels/TableViewModel.vala @@ -1,63 +1,66 @@ namespace Psequel { - public class TableViewModel : BaseViewModel, Observer { +public class TableViewModel : BaseViewModel, Observer { + public Schema schema { get; set; } + public ObservableList tables { get; set; default = new ObservableList
(); } + public Table ?selected_table { get; set; } - public Schema schema { get; set; } - public ObservableList
tables { get; set; default = new ObservableList
(); } - public Table? selected_table { get; set; } + public SQLService sql_service { get; private set; } - public SQLService sql_service {get; private set;} + // public signal void table_changed (Table table); - // public signal void table_changed (Table table); - - public TableViewModel (SQLService sql_service) { - base (); - this.sql_service = sql_service; - this.notify["selected-table"].connect (() => { - this.emit_event (Event.SELECTED_TABLE_CHANGED, selected_table); + public TableViewModel(SQLService sql_service) { + base(); + this.sql_service = sql_service; + this.notify["selected-table"].connect(() => { + this.emit_event(Event.SELECTED_TABLE_CHANGED, selected_table); }); - } - public void update (Event event) { - if (event.type == Event.SCHEMA_CHANGED) { - schema = (Schema) event.data; - tables.clear (); - load_tables.begin (schema); - } - } + } - public void select_table (Table? table) { - if (table == null) { - return; - } - debug ("selecting table %s", table.name); - selected_table = table; + public void update(Event event) { + if (event.type == Event.SCHEMA_CHANGED) + { + schema = (Schema)event.data; + tables.clear(); + load_tables.begin(schema); } + } - public void select_index (int index) { - if (tables[index] == null) { - return; - } - debug ("selecting table %s", tables[index].name); - selected_table = tables[index]; + public void select_table(Table ?table) { + if (table == null) + { + return; } + debug("selecting table %s", table.name); + selected_table = table; + } + public void select_index(int index) { + if (tables[index] == null) + { + return; + } + debug("selecting table %s", tables[index].name); + selected_table = tables[index]; + } - private async void load_tables (Schema schema) throws PsequelError { - debug ("loading tables"); - var query = new Query.with_params (TABLE_LIST, { schema.name }); - var relation = yield sql_service.exec_query_params (query); - - foreach (var item in relation) { - var table = new Table (schema); - table.name = item[0]; - tables.append (table); - } + private async void load_tables(Schema schema) throws PsequelError { + debug("loading tables"); + var query = new Query.with_params(TABLE_LIST, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - debug ("%d tables loaded", tables.size); + foreach (var item in relation) + { + var table = new Table(schema); + table.name = item[0]; + tables.append(table); } - public const string TABLE_LIST = """ + debug("%d tables loaded", tables.size); + } + + public const string TABLE_LIST = """ SELECT tablename FROM pg_tables WHERE schemaname=$1; """; - } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/ViewDataViewModel.vala b/src/viewmodels/ViewDataViewModel.vala index 1a05b55..744dd0c 100644 --- a/src/viewmodels/ViewDataViewModel.vala +++ b/src/viewmodels/ViewDataViewModel.vala @@ -1,88 +1,92 @@ namespace Psequel { - public class ViewDataViewModel : Object, Observer { - public View? selected_view { get; set; } - // public View? current_view {get; set;} +public class ViewDataViewModel : Object, Observer { + public View ?selected_view { get; set; } + // public View? current_view {get; set;} - public bool has_pre_page { get; private set; } - public bool has_next_page { get; private set; } - public int current_page { get; set; } + public bool has_pre_page { get; private set; } + public bool has_next_page { get; private set; } + public int current_page { get; set; } - public string row_ranges {get; private set; default = "";} + public string row_ranges { get; private set; default = ""; } - public bool is_loading { get; set; } - public string err_msg { get; set; } + public bool is_loading { get; set; } + public string err_msg { get; set; } - public Relation current_relation { get; set; } - public Relation.Row? selected_row { get; set; } + public Relation current_relation { get; set; } + public Relation.Row ?selected_row { get; set; } - public SQLService sql_service { get; private set; } + public SQLService sql_service { get; private set; } - public ViewDataViewModel (SQLService service) { - base (); - this.sql_service = service; + public ViewDataViewModel(SQLService service) { + base(); + this.sql_service = service; - this.notify["selected-view"].connect (() => { + this.notify["selected-view"].connect(() => { current_page = 0; - reload_data.begin (); + reload_data.begin(); }); - this.notify["current-page"].connect (() => { - if (current_page > 0) { + this.notify["current-page"].connect(() => { + if (current_page > 0) + { has_pre_page = true; - } else { + } + else + { has_pre_page = false; } }); - this.notify["current-relation"].connect (() => { - + this.notify["current-relation"].connect(() => { int offset = TableDataViewModel.MAX_FETCHED_ROW * current_page; row_ranges = @"Rows $(1 + offset) - $(offset + current_relation.rows)"; - if (current_relation.rows < TableDataViewModel.MAX_FETCHED_ROW) { + if (current_relation.rows < TableDataViewModel.MAX_FETCHED_ROW) + { has_next_page = false; - - } else { + } + else + { has_next_page = true; } }); - } - - public void update (Event event) { - switch (event.type) { - case Event.SELECTED_VIEW_CHANGED: - selected_view = event.data as View; - break; - } - } + } - public async void reload_data () { - yield load_data (selected_view, current_page); + public void update(Event event) { + switch (event.type) + { + case Event.SELECTED_VIEW_CHANGED: + selected_view = event.data as View; + break; } + } - public async void next_page () { - current_page = current_page + 1; - yield load_data (selected_view, current_page); - } + public async void reload_data() { + yield load_data(selected_view, current_page); + } - public async void pre_page () { - current_page = current_page - 1; - yield load_data (selected_view, current_page); - } + public async void next_page() { + current_page = current_page + 1; + yield load_data(selected_view, current_page); + } - private inline async void load_data (View view, int page) { + public async void pre_page() { + current_page = current_page - 1; + yield load_data(selected_view, current_page); + } - try { - is_loading = true; - current_relation = yield sql_service.select (view, page, TableDataViewModel.MAX_FETCHED_ROW); + private inline async void load_data(View view, int page) { + try { + is_loading = true; + current_relation = yield sql_service.select(view, page, TableDataViewModel.MAX_FETCHED_ROW); - is_loading = false; - debug ("Rows: %d", current_relation.rows); - } catch (PsequelError err) { - this.err_msg = err.message; - } + is_loading = false; + debug("Rows: %d", current_relation.rows); + } catch (PsequelError err) { + this.err_msg = err.message; } } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/ViewStructureViewModel.vala b/src/viewmodels/ViewStructureViewModel.vala index 059f172..b7089ea 100644 --- a/src/viewmodels/ViewStructureViewModel.vala +++ b/src/viewmodels/ViewStructureViewModel.vala @@ -1,96 +1,97 @@ namespace Psequel { - public class ViewStructureViewModel : Object, Observer { +public class ViewStructureViewModel : Object, Observer { + public SQLService sql_service { get; private set; } - public SQLService sql_service {get; private set;} + public View selected_view { get; set; } - public View selected_view { get; set; } + public ObservableList columns { get; set; default = new ObservableList (); } + public ObservableList indexes { get; set; default = new ObservableList (); } - public ObservableList columns { get; set; default = new ObservableList (); } - public ObservableList indexes { get; set; default = new ObservableList (); } - - public ViewStructureViewModel (SQLService sql_service) { - base(); - this.sql_service = sql_service; - } + public ViewStructureViewModel(SQLService sql_service) { + base(); + this.sql_service = sql_service; + } - public void update (Event event) { - switch (event.type) { - case Event.SCHEMA_CHANGED: - var schema = event.data as Schema; - load_data.begin (schema); - break; - case Event.SELECTED_VIEW_CHANGED: - var view = event.data as View; - selected_view = view; - break; - default: - break; - } + public void update(Event event) { + switch (event.type) + { + case Event.SCHEMA_CHANGED: + var schema = event.data as Schema; + load_data.begin(schema); + break; + + case Event.SELECTED_VIEW_CHANGED: + var view = event.data as View; + selected_view = view; + break; + + default: + break; } + } - private async void load_data (Schema schema) { - columns.clear (); - indexes.clear (); - - columns.append_all (yield _get_columns (schema)); - indexes.append_all (yield _get_indexes (schema)); - - debug ("cols: %d indx: %d", columns.size, indexes.size); - } + private async void load_data(Schema schema) { + columns.clear(); + indexes.clear(); + columns.append_all(yield _get_columns(schema)); + indexes.append_all(yield _get_indexes(schema)); - private async List _get_columns (Schema schema) { + debug("cols: %d indx: %d", columns.size, indexes.size); + } - var list = new List (); + private async List _get_columns(Schema schema) { + var list = new List (); - try { - var query = new Query.with_params (COLUMN_SQL, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + try { + var query = new Query.with_params(COLUMN_SQL, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - foreach (var row in relation) { - var col = new Column (); - col.schemaname = schema.name; - col.name = row[0]; - col.table = row[1]; - col.column_type = row[2]; - col.nullable = row[3] == "YES" ? true : false; - col.default_val = row[4]; + foreach (var row in relation) + { + var col = new Column(); + col.schemaname = schema.name; + col.name = row[0]; + col.table = row[1]; + col.column_type = row[2]; + col.nullable = row[3] == "YES" ? true : false; + col.default_val = row[4]; - list.append (col); - } - } catch (PsequelError err) { - debug (err.message); + list.append(col); } - - return list; + } catch (PsequelError err) { + debug(err.message); } - private async List _get_indexes (Schema schema) { + return(list); + } - var list = new List (); + private async List _get_indexes(Schema schema) { + var list = new List (); - try { - var query = new Query.with_params (INDEX_SQL, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + try { + var query = new Query.with_params(INDEX_SQL, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - foreach (var row in relation) { - var index = new Index (); - index.schemaname = schema.name; - index.name = row[0]; - index.table = row[1]; - index.size = row[2]; - index.indexdef = row[3]; + foreach (var row in relation) + { + var index = new Index(); + index.schemaname = schema.name; + index.name = row[0]; + index.table = row[1]; + index.size = row[2]; + index.indexdef = row[3]; - list.append (index); - } - } catch (PsequelError err) { - debug (err.message); + list.append(index); } - - return list; + } catch (PsequelError err) { + debug(err.message); } - public const string COLUMN_SQL = """ + return(list); + } + + public const string COLUMN_SQL = """ SELECT column_name, table_name, case when domain_name is not null then domain_name @@ -102,10 +103,10 @@ namespace Psequel { FROM information_schema.columns WHERE table_schema = $1; """; - public const string INDEX_SQL = """ + public const string INDEX_SQL = """ SELECT indexname, tablename, pg_size_pretty(pg_relation_size(indexname::regclass)) as size, indexdef FROM pg_indexes WHERE schemaname = $1; """; - } -} \ No newline at end of file +} +} diff --git a/src/viewmodels/ViewViewModel.vala b/src/viewmodels/ViewViewModel.vala index 5d6a227..9783e38 100644 --- a/src/viewmodels/ViewViewModel.vala +++ b/src/viewmodels/ViewViewModel.vala @@ -1,66 +1,68 @@ namespace Psequel { +/* View here is database view (virtual tables), not UI */ +public class ViewViewModel : BaseViewModel, Observer { + public ObservableList views { get; set; default = new ObservableList (); } + public View ?selected_view { get; set; } - /* View here is database view (virtual tables), not UI */ - public class ViewViewModel : BaseViewModel, Observer { - public ObservableList views { get; set; default = new ObservableList (); } - public View? selected_view { get; set; } + public Schema schema { get; private set; } + public SQLService sql_service { get; private set; } - public Schema schema { get; private set; } - public SQLService sql_service { get; private set; } - - public ViewViewModel (SQLService service) { - base(); - this.sql_service = service; - this.notify["selected-view"].connect (() => { - this.emit_event (Event.SELECTED_VIEW_CHANGED, selected_view); + public ViewViewModel(SQLService service) { + base(); + this.sql_service = service; + this.notify["selected-view"].connect(() => { + this.emit_event(Event.SELECTED_VIEW_CHANGED, selected_view); }); - } + } - public void update (Event event) { - if (event.type == Event.SCHEMA_CHANGED) { - schema = (Schema) event.data; - views.clear (); - load_views.begin (schema); - } + public void update(Event event) { + if (event.type == Event.SCHEMA_CHANGED) + { + schema = (Schema)event.data; + views.clear(); + load_views.begin(schema); } + } - public void select_view (View? view) { - if (view == null) { - return; - } - - - debug ("selecting view %s", view.name); - selected_view = view; + public void select_view(View ?view) { + if (view == null) + { + return; } - public void select_index (int index) { - if (index < 0 || index >= views.size) { - return; - } - debug ("selecting view %s", views[index].name); - selected_view = views[index]; - } + debug("selecting view %s", view.name); + selected_view = view; + } + public void select_index(int index) { + if (index < 0 || index >= views.size) + { + return; + } - private async void load_views (Schema schema) throws PsequelError { - debug ("loading views"); - var query = new Query.with_params (VIEW_LIST, { schema.name }); - var relation = yield sql_service.exec_query_params (query); + debug("selecting view %s", views[index].name); + selected_view = views[index]; + } - foreach (var item in relation) { - var view = new View (schema); - view.name = item[0]; - views.append (view); - } + private async void load_views(Schema schema) throws PsequelError { + debug("loading views"); + var query = new Query.with_params(VIEW_LIST, { schema.name }); + var relation = yield sql_service.exec_query_params(query); - debug ("%d views loaded", views.size); + foreach (var item in relation) + { + var view = new View(schema); + view.name = item[0]; + views.append(view); } - public const string VIEW_LIST = """ + debug("%d views loaded", views.size); + } + + public const string VIEW_LIST = """ SELECT table_name FROM INFORMATION_SCHEMA.views WHERE table_schema = $1; """; - } -} \ No newline at end of file +} +} diff --git a/uncrustify.cfg b/uncrustify.cfg new file mode 100644 index 0000000..6a2a70b --- /dev/null +++ b/uncrustify.cfg @@ -0,0 +1,402 @@ +# Uncrustify-0.72.0 + +# +# General options +# + +# The type of line endings. +# +# Default: auto +newlines = lf # lf/crlf/cr/auto + +# The original size of tabs in the input. +# +# Default: 8 +input_tab_size = 4 # unsigned number + +# The size of tabs in the output (only used if align_with_tabs=true). +# +# Default: 8 +output_tab_size = 4 # unsigned number + +# +# Spacing options +# + +# Add or remove space around non-assignment symbolic operators ('+', '/', '%', +# '<<', and so forth). +sp_arith = force # ignore/add/remove/force + +# Add or remove space around assignment operator '=', '+=', etc. +sp_assign = force # ignore/add/remove/force + +# Add or remove space around boolean operators '&&' and '||'. +sp_bool = force # ignore/add/remove/force + +# Add or remove space around compare operator '<', '>', '==', etc. +sp_compare = force # ignore/add/remove/force + +# Add or remove space inside '(' and ')'. +sp_inside_paren = remove # ignore/add/remove/force + +# Add or remove space between nested parentheses, i.e. '((' vs. ') )'. +sp_paren_paren = remove # ignore/add/remove/force + +# Add or remove space before pointer star '*'. +sp_before_ptr_star = force # ignore/add/remove/force + +# Add or remove space between pointer stars '*'. +sp_between_ptr_star = remove # ignore/add/remove/force + +# Add or remove space after pointer star '*', if followed by a word. +# +# Overrides sp_type_func. +sp_after_ptr_star = remove # ignore/add/remove/force + +# Add or remove space before a reference sign '&'. +sp_before_byref = remove # ignore/add/remove/force + +# Add or remove space before '<'. +sp_before_angle = force # ignore/add/remove/force + +# Add or remove space inside '<' and '>'. +sp_inside_angle = remove # ignore/add/remove/force + +# Add or remove space after '>'. +sp_after_angle = force # ignore/add/remove/force + +# Add or remove space before '(' of control statements ('if', 'for', 'switch', +# 'while', etc.). +sp_before_sparen = force # ignore/add/remove/force + +# Add or remove space inside '(' and ')' of control statements. +sp_inside_sparen = remove # ignore/add/remove/force + +# Add or remove space after ')' of control statements. +sp_after_sparen = force # ignore/add/remove/force + +# Add or remove space between ')' and '{' of of control statements. +sp_sparen_brace = add # ignore/add/remove/force + +# Add or remove space inside a non-empty '[' and ']'. +sp_inside_square = remove # ignore/add/remove/force + +# Add or remove space after ',', i.e. 'a,b' vs. 'a, b'. +sp_after_comma = force # ignore/add/remove/force + +# Add or remove space after C/D cast, i.e. 'cast(int)a' vs. 'cast(int) a' or +# '(int)a' vs. '(int) a'. +sp_after_cast = remove # ignore/add/remove/force + +# Add or remove space between 'sizeof' and '('. +sp_sizeof_paren = remove # ignore/add/remove/force + +# Add or remove space inside enum '{' and '}'. +sp_inside_braces_enum = force # ignore/add/remove/force + +# Add or remove space inside struct/union '{' and '}'. +sp_inside_braces_struct = force # ignore/add/remove/force + +# Add or remove space inside '{' and '}'. +sp_inside_braces = force # ignore/add/remove/force + +# Add or remove space between function name and '(' on function declaration. +sp_func_proto_paren = remove # ignore/add/remove/force + +# Add or remove space between alias name and '(' of a non-pointer function type typedef. +sp_func_def_paren = remove # ignore/add/remove/force + +# Add or remove space inside function '(' and ')'. +sp_inside_fparen = remove # ignore/add/remove/force + +# Add or remove space between ')' and '{' of function. +sp_fparen_brace = add # ignore/add/remove/force + +# Add or remove space between function name and '(' on function calls. +sp_func_call_paren = remove # ignore/add/remove/force + +# Add or remove space between a constructor/destructor and the open +# parenthesis. +sp_func_class_paren = remove # ignore/add/remove/force + +# Add or remove space between 'return' and '('. +sp_return_paren = remove # ignore/add/remove/force + +# +# Indenting options +# + +# The number of columns to indent per level. Usually 2, 3, 4, or 8. +# +# Default: 8 +indent_columns = 4 # unsigned number + +# How to use tabs when indenting code. +# +# 0: Spaces only +# 1: Indent with tabs to brace level, align with spaces (default) +# 2: Indent and align with tabs, using spaces when not on a tabstop +# +# Default: 1 +indent_with_tabs = 0 # unsigned number + +# Whether the 'class' body is indented. +indent_class = true # true/false + +# +# Newline adding and removing options +# + +# Add or remove newlines at the start of the file. +nl_start_of_file = remove # ignore/add/remove/force + +# Add or remove newline at the end of the file. +nl_end_of_file = force # ignore/add/remove/force + +# The minimum number of newlines at the end of the file (only used if +# nl_end_of_file is 'add' or 'force'). +nl_end_of_file_min = 1 # unsigned number + +# Add or remove newline between '=' and '{'. +nl_assign_brace = remove # ignore/add/remove/force + +# Add or remove newline between a function call's ')' and '{', as in +# 'list_for_each(item, &list) { }'. +nl_fcall_brace = remove # ignore/add/remove/force + +# Add or remove newline between 'enum' and '{'. +nl_enum_brace = add # ignore/add/remove/force + +# Add or remove newline between 'struct and '{'. +nl_struct_brace = add # ignore/add/remove/force + +# Add or remove newline between 'union' and '{'. +nl_union_brace = add # ignore/add/remove/force + +# Add or remove newline between 'if' and '{'. +nl_if_brace = add # ignore/add/remove/force + +# Add or remove newline between '}' and 'else'. +nl_brace_else = add # ignore/add/remove/force + +# Add or remove newline between 'else' and '{'. +nl_else_brace = add # ignore/add/remove/force + +# Add or remove newline between 'for' and '{'. +nl_for_brace = add # ignore/add/remove/force + +# Add or remove newline between 'while' and '{'. +nl_while_brace = add # ignore/add/remove/force + +# Add or remove newline between 'do' and '{'. +nl_do_brace = add # ignore/add/remove/force + +# Add or remove newline between '}' and 'while' of 'do' statement. +nl_brace_while = remove # ignore/add/remove/force + +# Add or remove newline between 'switch' and '{'. +nl_switch_brace = add # ignore/add/remove/force + +# Whether to add a newline before 'case', and a blank line before a 'case' +# statement that follows a ';' or '}'. +nl_before_case = true # true/false + +# Add or remove newline between function signature and '{'. +nl_fdef_brace = remove # ignore/add/remove/force + +# Whether to remove blanks after '#ifxx' and '#elxx', or before '#elxx' and +# '#endif'. Does not affect top-level #ifdefs. +nl_squeeze_ifdef = true # true/false + +# Whether to put a blank line after 'return' statements, unless followed by a +# close brace. +nl_after_return = true # true/false + +# +# Blank line options +# + +# The maximum number of consecutive newlines (3 = 2 blank lines). +nl_max = 4 # unsigned number + +# The number of newlines after a function prototype, if not followed by +# another function prototype. +nl_after_func_proto_group = 2 # unsigned number + +# The number of newlines after '}' of a multi-line function body. +nl_after_func_body = 2 # unsigned number + +# The minimum number of newlines before a multi-line comment. +# Doesn't apply if after a brace open or another multi-line comment. +nl_before_block_comment = 2 # unsigned number + +# Whether to remove blank lines after '{'. +eat_blanks_after_open_brace = true # true/false + +# Whether to remove blank lines before '}'. +eat_blanks_before_close_brace = true # true/false + +# +# Positioning options +# + +# The position of Boolean operators in wrapped expressions. +pos_bool = trail # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force + +# +# Code alignment options (not left column spaces/tabs) +# + +# Whether to right-align numbers. +align_number_right = true # true/false + +# The span for aligning variable definitions. +# +# 0: Don't align (default). +align_var_def_span = 1 # unsigned number + +# The threshold for aligning variable definitions. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_var_def_thresh = 12 # number + +# Whether to align the colon in struct bit fields. +align_var_def_colon = true # true/false + +# Whether to align inline struct/enum/union variable definitions. +align_var_def_inline = true # true/false + +# The span for aligning on '=' in assignments. +# +# 0: Don't align (default). +align_assign_span = 1 # unsigned number + +# The threshold for aligning on '=' in assignments. +# Use a negative number for absolute thresholds. +# +# 0: No limit (default). +align_assign_thresh = 12 # number + +# The span for aligning on '=' in enums. +# +# 0: Don't align (default). +align_enum_equ_span = 4 # unsigned number + +# The span for aligning struct/union member definitions. +# +# 0: Don't align (default). +align_var_struct_span = 99 # unsigned number + +# The span for aligning struct initializer values. +# +# 0: Don't align (default). +align_struct_init_span = 3 # unsigned number + +# The span for aligning single-line typedefs. +# +# 0: Don't align (default). +align_typedef_span = 5 # unsigned number + +# The minimum space between the type and the synonym of a typedef. +align_typedef_gap = 3 # unsigned number + +# The span for aligning comments that end lines. +# +# 0: Don't align (default). +align_right_cmt_span = 3 # unsigned number + +# Whether to align macros wrapped with a backslash and a newline. This will +# not work right if the macro contains a multi-line comment. +align_nl_cont = 1 # true/false + +# The span for aligning on '#define' bodies. +# +# =0: Don't align (default) +# >0: Number of lines (including comments) between blocks +align_pp_define_span = 3 # unsigned number + +# The minimum space between label and value of a preprocessor define. +align_pp_define_gap = 4 # unsigned number + +# +# Comment modification options +# + +# Whether to put a star on subsequent comment lines. +cmt_star_cont = true # true/false + +# +# Code modifying options (non-whitespace) +# + +# Add or remove braces on a single-line 'do' statement. +mod_full_brace_do = add # ignore/add/remove/force + +# Add or remove braces on a single-line 'for' statement. +mod_full_brace_for = add # ignore/add/remove/force + +# Add or remove braces on a single-line 'if' statement. Braces will not be +# removed if the braced statement contains an 'else'. +mod_full_brace_if = add # ignore/add/remove/force + +# Add or remove braces on single-line 'while' statement. +mod_full_brace_while = add # ignore/add/remove/force + +# Add or remove unnecessary parenthesis on 'return' statement. +mod_paren_on_return = add # ignore/add/remove/force + +# Meaning of the settings: +# Ignore - do not do any changes +# Add - makes sure there is 1 or more space/brace/newline/etc +# Force - makes sure there is exactly 1 space/brace/newline/etc, +# behaves like Add in some contexts +# Remove - removes space/brace/newline/etc +# +# +# - Token(s) can be treated as specific type(s) with the 'set' option: +# `set tokenType tokenString [tokenString...]` +# +# Example: +# `set BOOL __AND__ __OR__` +# +# tokenTypes are defined in src/token_enum.h, use them without the +# 'CT_' prefix: 'CT_BOOL' => 'BOOL' +# +# +# - Token(s) can be treated as type(s) with the 'type' option. +# `type tokenString [tokenString...]` +# +# Example: +# `type int c_uint_8 Rectangle` +# +# This can also be achieved with `set TYPE int c_uint_8 Rectangle` +# +# +# To embed whitespace in tokenStrings use the '\' escape character, or quote +# the tokenStrings. These quotes are supported: "'` +# +# +# - Support for the auto detection of languages through the file ending can be +# added using the 'file_ext' command. +# `file_ext langType langString [langString..]` +# +# Example: +# `file_ext CPP .ch .cxx .cpp.in` +# +# langTypes are defined in uncrusify_types.h in the lang_flag_e enum, use +# them without the 'LANG_' prefix: 'LANG_CPP' => 'CPP' +# +# +# - Custom macro-based indentation can be set up using 'macro-open', +# 'macro-else' and 'macro-close'. +# `(macro-open | macro-else | macro-close) tokenString` +# +# Example: +# `macro-open BEGIN_TEMPLATE_MESSAGE_MAP` +# `macro-open BEGIN_MESSAGE_MAP` +# `macro-close END_MESSAGE_MAP` +# +# +# option(s) with 'not default' value: 86 +#