PostgreSQL has become the most popular RDBMS in the Ruby ecosystem in the last decade. It has a great set of built-in features, including a variety of versatile data types, both common and very specific.
But when we load data from the database to our application code, we're working with Ruby data types: classes from the standard library, Rails, or other gems. So while they can seem to be the same as their PostgreSQL counterparts, they are not absolutely identical, and sometimes that could lead to surprising behavior.
In this talk, I would like to explore the power of data types in PostgreSQL and Ruby and how to work with them properly to use both Ruby and PostgreSQL on 100% of their power!
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
Beyond Breakpoints: A Tour of Dynamic AnalysisC4Media
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/2dXUUTG.
Nathan Taylor provides an introduction to the dynamic analysis research space, suggesting integrating these techniques into various internal tools. Filmed at qconnewyork.com.
Nathan Taylor is a software developer currently employed at Fastly, where he works on making the Web faster through high performance content delivery. Previous gigs have included hacking on low-level systems software such as Java runtimes at Twitter and, prior to that, the Xen virtual machine monitor in grad school.
Re-checking the ReactOS project - a large reportPVS-Studio
The ReactOS project is rapidly developing. One of the developers participating in this project suggested that we re-analyzed the source code, as the code base is growing fast. We were glad to do that. We like this project, and we'll be happy if this article helps the developers to eliminate some bugs. Analysis was performed with the PVS-Studio 5.02 code analyzer.
In most of our articles about project checks, we mention that bugs are found by the PVS-Studio static code analyzer. In certain cases – when dealing with projects of a complex structure – it is this particular analyzer that is needed. However, many developers will also appreciate its lightweight version, the CppCat analyzer. In this connection, we decided to use CppCat this time, when checking the TortoiseGit project.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
Beyond Breakpoints: A Tour of Dynamic AnalysisC4Media
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/2dXUUTG.
Nathan Taylor provides an introduction to the dynamic analysis research space, suggesting integrating these techniques into various internal tools. Filmed at qconnewyork.com.
Nathan Taylor is a software developer currently employed at Fastly, where he works on making the Web faster through high performance content delivery. Previous gigs have included hacking on low-level systems software such as Java runtimes at Twitter and, prior to that, the Xen virtual machine monitor in grad school.
Re-checking the ReactOS project - a large reportPVS-Studio
The ReactOS project is rapidly developing. One of the developers participating in this project suggested that we re-analyzed the source code, as the code base is growing fast. We were glad to do that. We like this project, and we'll be happy if this article helps the developers to eliminate some bugs. Analysis was performed with the PVS-Studio 5.02 code analyzer.
In most of our articles about project checks, we mention that bugs are found by the PVS-Studio static code analyzer. In certain cases – when dealing with projects of a complex structure – it is this particular analyzer that is needed. However, many developers will also appreciate its lightweight version, the CppCat analyzer. In this connection, we decided to use CppCat this time, when checking the TortoiseGit project.
This talk will present R as a programming language suited for solving data analysis and modeling problems, MLflow as an open source project to help organizations manage their machine learning lifecycle and the intersection of both by adding support for R in MLflow. It will be highly interactive and touch on some of the technical implementation choices taken while making R available in MLflow. It will also demonstrate using MLflow tracking, projects, and models directly from R as well as reusing R models in MLflow to interoperate with other programming languages and technologies.
Performs code analysis in C, C++, C++/CLI, C++/CX, C#. Plugin for Visual Studio 2010-2015. Integration with SonarQube, QtCreator, CLion, Eclipse CDT, Anjuta DevStudio and so on. Standalone utility. Direct integration of the analyzer into the systems of build automation and the BlameNotifier utility (e-mail notification). Automatic analysis of modified files. Great scalability. Why do people need code analyzers?
[db tech showcase Tokyo 2017] A11: SQLite - The most used yet least appreciat...Insight Technology, Inc.
More instances of SQLite are used every day, by more people, than all other database engines combined. An yet, SQLite does not get much attention. Many developers hardly know anything about it. This session will review the features of SQLite, how it is different from other database engines, its strengths and its weaknesses, and when SQLite is an appropriate technology and when some other database engine might be a better choice.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
String Comparison Surprises: Did Postgres lose my data?Jeremy Schneider
Comparisons are fundamental to computing - and comparing strings is not nearly as straightforward as you might think. Come learn about the history, nuance and surprises of “putting words in order” that you never knew existed in computer science, and how that nuance impacts both general programming and SQL programming. Next, walk through a few actual scenarios and demonstrations using PostgreSQL as a user and administrator, which you can re-run yourself later for further study, including one way you could easily corrupt your self-managed PostgreSQL database if you aren't prepared. Finally we’ll dive into an explanation of the surprising behaviors we saw in PostgreSQL, and learn more about user and administrative features PostgreSQL provides related to localized string comparison.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
Node has revolutionized modern runtimes. Their async by default strategy boasts 3x the throughput of Java. And yet, the language runs 5x slower than C++ (when JS is interpreted).
This talk is an advanced intro into the world of Node where we take a closer look under the hood. What's the event loop? Why are there multiple compilers for JS in Node/V8? How many threads are actually used in Node and for what purpose? We'll answer these questions and more as we go over libuv, v8, the node core library, npm, and more.
If you're developing with Node, want to start, or are just curious about how it works, please check it out!
I've seen projects with shiny, new code render into unmaintainable big balls of mud within 2-3 years. Multiple times. But regardless of whether it's the code base as a whole that's rotten, or whether it's just the UI and User Experience that needs a major overhaul: the question on rewrite vs refactoring will come up sooner or later. Based on years of experience, and a plethora of bad decisions cumulating into epic failures, I'll share my experience on how to have a code base that stays maintainable - even after years. After this talk, you'll have more insight into whether you should refactor or rewrite, and how to do it right from now on.
Python and Ruby implementations compared by the error densityPVS-Studio
Which programming language to start learning? Python or Ruby? Which one is better? Django or Ruby on Rails? Such questions can often be found on IT forums around the world. I suggest comparing not the languages themselves, but their reference implementations: CPython and MRI. In this article, we are going to cover the errors that were found by PVS-Studio in these projects.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
This is the second and last part of the large article about analysis of the Haiku operating system. In the first article, we discussed a variety of possible errors all of which one way or another deal with conditions. In this article, we will discuss the remaining analyzer warnings I have selected for you. The bug examples are grouped into several categories.
Application Monitoring using Open Source: VictoriaMetrics - ClickHouseVictoriaMetrics
Monitoring is the key to successful operation of any software service, but commercial solutions are complex, expensive, and slow. Let us show you how to build monitoring that is simple, cost-effective, and fast using open source stacks easily accessible to any developer.
We’ll start with the elements of monitoring systems: data ingest, query engine, visualization, and alerting. We’ll then explain and contrast two implementation approaches. The first uses VictoriaMetrics, a fast growing, high performance time series database that uses PromQL for queries. The second is based on ClickHouse, a popular real-time analytics database that speaks SQL. Fast, affordable monitoring is within reach. This webinar provides designs and working code to get you there.
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo...Altinity Ltd
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHouse Webinar Slides
Monitoring is the key to the successful operation of any software service, but commercial solutions are complex, expensive, and slow. Let us show you how to build monitoring that is simple, cost-effective, and fast using open-source stacks easily accessible to any developer.
We’ll start with the elements of monitoring systems: data ingest, query engine, visualization, and alerting. We’ll then explain and contrast two implementation approaches. The first uses VictoriaMetrics, a fast-growing, high-performance time series database that uses PromQL for queries. The second is based on ClickHouse, a popular real-time analytics database that speaks SQL. Fast, affordable monitoring is within reach. This webinar provides designs and working code to get you there.
Presented by:
Roman Khavronenko, Co-Founder at VictoriaMetrics
Robert Hodges, CEO at Altinity
Beyond PHP - it's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just writing PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
MongoDB 4.2 comes GA soon delivering some amazing new features on multiple areas. In this talk, we will focus on changes related to sharded clusters. We are going to cover distributed transactions & mutable shard keys providing examples that will reveal the internals of those new features. We will provide best practices around the new sharding features and we will cover other minor changes related to it.
When you allow users to upload images to your website or app, what are the accompanying features you should have? Usually, this includes the ability to create previews (or thumbnails) of different sizes, add watermarks, crop to a specific aspect ratio, and so on.
The “classic” kind of way to do this is with an “in-house” approach. You plug in some libraries to process images (and install `imagemagick` or `libvips` to your servers or Docker images), and then create an entire pipeline to do the actual processing: configs, storage, background jobs. This is some complex machinery, but do we really need it?
Instead, enter the amazing world of image processing services that will change your life forever. 🦄 🌈 ✨
After making the switch, you'll never want to return to the “manual” way of handling thumbnails. Your applications will become more simple and reliable, UX will improve, and your hair will finally become soft and silky smooth.
Let's talk about the difficulties and dangers the “classic” approach entails, how image processing services solves them, and just how simple that is!
And, as an example of such a service, I'll tell you about imgproxy (https://imgproxy.net/), an amazing tool which I'm going to shamelessly advertise!
Сейчас контейнеризация и Kubernetes в частности — стандарт де-факто для запуска приложений «в бою». И запустить-то приложение в «кубе» несложно, но как всегда есть нюанс и не один. Обсудим, что нужно разработчику и админу учесть и сделать для того, чтобы приложение работало быстро и надёжно, не требуя к себе особого внимания. Например, посмотрим, как работают requests и limits на ресурсы, чем должны отличаться liveness и readiness пробы, и на что следует обращать внимание в мониторинге и так далее.
More Related Content
Similar to PostgreSQL as seen by Rubyists (Kaigi on Rails 2022)
This talk will present R as a programming language suited for solving data analysis and modeling problems, MLflow as an open source project to help organizations manage their machine learning lifecycle and the intersection of both by adding support for R in MLflow. It will be highly interactive and touch on some of the technical implementation choices taken while making R available in MLflow. It will also demonstrate using MLflow tracking, projects, and models directly from R as well as reusing R models in MLflow to interoperate with other programming languages and technologies.
Performs code analysis in C, C++, C++/CLI, C++/CX, C#. Plugin for Visual Studio 2010-2015. Integration with SonarQube, QtCreator, CLion, Eclipse CDT, Anjuta DevStudio and so on. Standalone utility. Direct integration of the analyzer into the systems of build automation and the BlameNotifier utility (e-mail notification). Automatic analysis of modified files. Great scalability. Why do people need code analyzers?
[db tech showcase Tokyo 2017] A11: SQLite - The most used yet least appreciat...Insight Technology, Inc.
More instances of SQLite are used every day, by more people, than all other database engines combined. An yet, SQLite does not get much attention. Many developers hardly know anything about it. This session will review the features of SQLite, how it is different from other database engines, its strengths and its weaknesses, and when SQLite is an appropriate technology and when some other database engine might be a better choice.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
String Comparison Surprises: Did Postgres lose my data?Jeremy Schneider
Comparisons are fundamental to computing - and comparing strings is not nearly as straightforward as you might think. Come learn about the history, nuance and surprises of “putting words in order” that you never knew existed in computer science, and how that nuance impacts both general programming and SQL programming. Next, walk through a few actual scenarios and demonstrations using PostgreSQL as a user and administrator, which you can re-run yourself later for further study, including one way you could easily corrupt your self-managed PostgreSQL database if you aren't prepared. Finally we’ll dive into an explanation of the surprising behaviors we saw in PostgreSQL, and learn more about user and administrative features PostgreSQL provides related to localized string comparison.
Presentation with a brief history of C, C++ and their ancestors along with an introduction to latest version C++11 and futures such as C++17. The presentation covers applications that use C++, C++11 compilers such as LLVM/Clang, some of the new language features in C++11 and C++17 and examples of modern idioms such as the new form compressions, initializer lists, lambdas, compile time type identification, improved memory management and improved standard library (threads, math, random, chrono, etc). (less == more) || (more == more)
Node has revolutionized modern runtimes. Their async by default strategy boasts 3x the throughput of Java. And yet, the language runs 5x slower than C++ (when JS is interpreted).
This talk is an advanced intro into the world of Node where we take a closer look under the hood. What's the event loop? Why are there multiple compilers for JS in Node/V8? How many threads are actually used in Node and for what purpose? We'll answer these questions and more as we go over libuv, v8, the node core library, npm, and more.
If you're developing with Node, want to start, or are just curious about how it works, please check it out!
I've seen projects with shiny, new code render into unmaintainable big balls of mud within 2-3 years. Multiple times. But regardless of whether it's the code base as a whole that's rotten, or whether it's just the UI and User Experience that needs a major overhaul: the question on rewrite vs refactoring will come up sooner or later. Based on years of experience, and a plethora of bad decisions cumulating into epic failures, I'll share my experience on how to have a code base that stays maintainable - even after years. After this talk, you'll have more insight into whether you should refactor or rewrite, and how to do it right from now on.
Python and Ruby implementations compared by the error densityPVS-Studio
Which programming language to start learning? Python or Ruby? Which one is better? Django or Ruby on Rails? Such questions can often be found on IT forums around the world. I suggest comparing not the languages themselves, but their reference implementations: CPython and MRI. In this article, we are going to cover the errors that were found by PVS-Studio in these projects.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
This is the second and last part of the large article about analysis of the Haiku operating system. In the first article, we discussed a variety of possible errors all of which one way or another deal with conditions. In this article, we will discuss the remaining analyzer warnings I have selected for you. The bug examples are grouped into several categories.
Application Monitoring using Open Source: VictoriaMetrics - ClickHouseVictoriaMetrics
Monitoring is the key to successful operation of any software service, but commercial solutions are complex, expensive, and slow. Let us show you how to build monitoring that is simple, cost-effective, and fast using open source stacks easily accessible to any developer.
We’ll start with the elements of monitoring systems: data ingest, query engine, visualization, and alerting. We’ll then explain and contrast two implementation approaches. The first uses VictoriaMetrics, a fast growing, high performance time series database that uses PromQL for queries. The second is based on ClickHouse, a popular real-time analytics database that speaks SQL. Fast, affordable monitoring is within reach. This webinar provides designs and working code to get you there.
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHo...Altinity Ltd
Application Monitoring using Open Source - VictoriaMetrics & Altinity ClickHouse Webinar Slides
Monitoring is the key to the successful operation of any software service, but commercial solutions are complex, expensive, and slow. Let us show you how to build monitoring that is simple, cost-effective, and fast using open-source stacks easily accessible to any developer.
We’ll start with the elements of monitoring systems: data ingest, query engine, visualization, and alerting. We’ll then explain and contrast two implementation approaches. The first uses VictoriaMetrics, a fast-growing, high-performance time series database that uses PromQL for queries. The second is based on ClickHouse, a popular real-time analytics database that speaks SQL. Fast, affordable monitoring is within reach. This webinar provides designs and working code to get you there.
Presented by:
Roman Khavronenko, Co-Founder at VictoriaMetrics
Robert Hodges, CEO at Altinity
Beyond PHP - it's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just writing PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
MongoDB 4.2 comes GA soon delivering some amazing new features on multiple areas. In this talk, we will focus on changes related to sharded clusters. We are going to cover distributed transactions & mutable shard keys providing examples that will reveal the internals of those new features. We will provide best practices around the new sharding features and we will cover other minor changes related to it.
When you allow users to upload images to your website or app, what are the accompanying features you should have? Usually, this includes the ability to create previews (or thumbnails) of different sizes, add watermarks, crop to a specific aspect ratio, and so on.
The “classic” kind of way to do this is with an “in-house” approach. You plug in some libraries to process images (and install `imagemagick` or `libvips` to your servers or Docker images), and then create an entire pipeline to do the actual processing: configs, storage, background jobs. This is some complex machinery, but do we really need it?
Instead, enter the amazing world of image processing services that will change your life forever. 🦄 🌈 ✨
After making the switch, you'll never want to return to the “manual” way of handling thumbnails. Your applications will become more simple and reliable, UX will improve, and your hair will finally become soft and silky smooth.
Let's talk about the difficulties and dangers the “classic” approach entails, how image processing services solves them, and just how simple that is!
And, as an example of such a service, I'll tell you about imgproxy (https://imgproxy.net/), an amazing tool which I'm going to shamelessly advertise!
Сейчас контейнеризация и Kubernetes в частности — стандарт де-факто для запуска приложений «в бою». И запустить-то приложение в «кубе» несложно, но как всегда есть нюанс и не один. Обсудим, что нужно разработчику и админу учесть и сделать для того, чтобы приложение работало быстро и надёжно, не требуя к себе особого внимания. Например, посмотрим, как работают requests и limits на ресурсы, чем должны отличаться liveness и readiness пробы, и на что следует обращать внимание в мониторинге и так далее.
How and why to monitor web applications performance.
How to build it yourself with Ruby and Prometheus.
Introducing a set of gems to avoid reinventing the wheel.
Link to the talk video (in Russian): https://youtu.be/uYKZ86l3Tv0
Какими средствами можно добиться, чтобы сообщения по вебсокетам приходили всегда, вне зависимости от качества интернета и количества разрывов соединений в секунду.
Правильная работа с часовыми поясами в Rails приложении — DevConf 2015Андрей Новиков
Презентация с рецептами по правильной работе с датой и временем в приложении на Ruby on Rails: как обрабатывать, передавать и хранить данные, чтобы избежать проблем.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
4. Martian Open Source
Yabeda:Ruby application
instrumentation framework
Lefthook:git hooks manager AnyCable:Polyglot replacement for
ActionCable server
PostCSS:A tool for transforming
CSS with JavaScript
Imgproxy:Fast and secure
standalone server for resizing and
converting remote images
Logux:Client-server communication
framework based on Optimistic UI,
CRDT, and log
Overmind:Process manager for
Procfile-based applications and
tmux
Even more at
evilmartians.com/oss
7. Example of subtle yet important difference
Are they same?
…
Left: road signconforming Vienna ConventiononRoad Signs and Signals
Right: Japanese road signper “Order onRoad Sign, Road Line, and Road Surface Marking”
8. Example of subtle yet important difference
Are they same?
NO!
Both require drivers to give a way…
European sign doesn’t have a requirement to stop or even slow down!
9. Example of subtle yet important difference
Are they same?
YES!
Stop signs around the world are mostly octagonal.
Japanese signs have “STOP” word in English after 2017, but are still pretty rare.
13. Integers
Integer
Variable length
integer
2, 4, 8 bytes signed
In ActiveModel there is validation for
databases:
Name Size Range
smallint 2 -32768 to +32767
integer 4 -2147483648 to +2147483647
bigint 8 -9223372036854775808 to
+9223372036854775807
See bignum.c in Ruby sources. See Numeric types docs
1.size # => 8 (bytes)
(256**8 - 1).size # => 8 (bytes)
(256**8).size # => 9 (bytes)
(256**40 - 1).size # => 40 (bytes)
Test.create(value: 2147483648)
# ActiveModel::RangeError: 2147483648 is out of rang
# for ActiveModel::Type::Integer with limit 4 bytes
` `
` `
` `
INSERT INTO "tests" ("value") VALUES (2147483648);
-- ERROR: integer out of range
14.
15. Oh no, I have integer primary keys! What to do?
0. Don’t panic!
1. Use pghero or Heroku pg:diagnose to detect problematic primary keys.
2. Migrate to bigint or uuid if needed (use triggers, Luke!)
3. In case of emergency, remember that all integers are signed!
You always have 2 more billions of values on the dark negative side!
Example of pkey migration from int to bigint: engineering.silverfin.com/pg-zero-downtime-bigint-migration
` ` ` `
ALTER SEQUENCE tablename_id_seq MINVALUE -2147483647 RESTART WITH -2147483647;
pghero
16. Floating point numbers
Float
8 bytes (double-precision)
real — 4 bytes
double — 8 bytes
See Ruby docs for Float More fun at 0.30000000000000004.com!
IEEE 754
0.1 + 0.2 # => 0.30000000000000004
Float::MAX # => 1.7976931348623157e+308
Float::MAX + '1e+308'.to_f # => Infinity
# BUT!
Float::MAX + '0.1'.to_f
# => 1.7976931348623157e+308 🤔
Float::MAX == (Float::MAX + '0.1'.to_f)
# => true 🤯
Float::NAN == Float::NAN # => false
SELECT 0.1::float + 0.2::float; -- 0.300000000000000
SELECT 0.1 + 0.2; -- 0.3 (but it is NOT float!)
SELECT '1.7976931348623157e+308'::float + '1e+308'::
--- ERROR: value out of range: overflow
SELECT '+inf'::double precision; -- Infinity 🤷
SELECT '1.7976931348623157e+308'::float =
('1.7976931348623157e+308'::float + '0.1'::float);
-- true ¯_(ツ)_/¯
SELECT 'NaN'::float = 'NaN'::float; -- true 🤯
0.30000000000000004.com
18. Arbitrary precision numbers
BigDecimal
Variable length
numeric
Variable length
See Ruby docs for BigDecimal Use numeric to store money!
BigDecimal("0.1") + BigDecimal("0.2") # => 0.3e0
BigDecimal("NaN") == BigDecimal("NaN") # => false
BigDecimal("1.0") / BigDecimal("0.0") #=> Infinity
# To match PostgreSQL behavior:
BigDecimal.mode(BigDecimal::EXCEPTION_OVERFLOW, tru
BigDecimal("1.0") / BigDecimal("0.0")
# Computation results in 'Infinity' (FloatDomainEr
BigDecimal("0.1") + 0.2.to_d == 0.30000000000000004
# true 🤔
SELECT 0.1 + 0.2; -- 0.3 which is decimal
SELECT 'NaN'::decimal = 'NaN'::decimal; -- true
SELECT '1.0'::decimal / '0.0'::decimal;
-- ERROR: division by zero
SELECT (0.1 + 0.2) = (0.1::float + 0.2::float);
-- false
` `
19. But there is money type, isn’t it?
BigDecimal
Variable size
money
8 byte fixed-precision number.
ActiveRecord has to parse textual representation, see
connection_adapters/postgresql/oid/money.rb
Also see issue № 31457 for lots of pain.
Both output and acceptable input format depends on
session-level lc_monetary setting!
Precision is defined by lc_monetary at database creation
time and can’t be changed!
# If the database locale setting isn't `en_US`:
# Creation may fail:
Product.create!(price: 100500.42)
# ERROR: invalid input syntax for type money: "1005
# Or it can succeed, but won't be able to be parsed
Product.last.price # => 0.0
-- on production:
SELECT 100500.42::money;
-- $100,500.42
-- on dev machine:
SELECT 100500.42::money;
-- ¥ 100,500
-- 🤯 But it should be dollars, and where are my cen
` `
` `
20. Strings and texts, lyrics and prose
String
Variable size
varchar,text
variable size, max 1 GB
Read the docs: String Read the docs: 8.3. Character Types
"こんにちは地球人!".encoding
# => #<Encoding:UTF-8>
"xe3x2ex2e".encoding
# => #<Encoding:UTF-8>
"xe3x2ex2e".valid_encoding?
# => false
"これx00やばい!".valid_encoding?
# => true
SELECT 'こんにちは地球人!';
-- こんにちは地球人!
SELECT E'xe3x2ex2e');
-- ERROR: invalid byte sequence for encoding "UTF8
SELECT E'これx00やばい!';
-- ERROR: invalid byte sequence for encoding "UTF8
21. So many string types!
1. Don’t use char(n)
It is always size of n and stores unnecessary spaces at right. Mostly for
compatibility with older applications.
2. varchar and text are effectively the same, choose whatever you like.
string in migrations is varchar in PostgreSQL.
💡Did you know?
SimpleForm gem will render multi-line HTML <textarea> tag for text type and
single-line <input type="text"> for character varying.
Convention over configuration!
See SimpleForm gem README: github.com/heartcombo/simple_form
` `
` `
` ` ` `
` ` ` `
` `
` `
23. Binary data
String
Variable size
bytea
Variable size, max 1 GB
Memory and network traffic consumption: 📈 See Binary Data Types page in the docs.
data = File.binread(“meme.png”)
# => "x89PNGrnx1A…"
data.encoding # => #<Encoding:ASCII-8BIT>
data.bytesize # => 46534
Test.last.blob
# => "x89PNGrnx1A…"
Test.last.blob_before_type_cast.bytesize
# => 46534
Test.last.blob_before_type_cast
# => "x89504e470d0a1a0a"
Test.last.blob_before_type_cast.bytesize
# => 93070
SELECT 'x89504e470d0a1a0a…'::bytea;
# Note hexadecimal format ↑
24. What if 1 GB isn’t enough?
You can’t store more in a table column (hard limit)
But you can store up 4 TB in large objects table!
And there is a gem for that:
active_storage-postgresql
Beware performance implications of TOAST →
More about it in PG docs: 70.2. TOAST
Andrey Novikov
@Envek · Follow
— PostgreSQL, did you update all these megabyte-
long JSON I gave you?
— Yes
— What did it cost?
— Everything… all the IO on the server.
Let’s talk about how PostgreSQL stores JSONB
(yep, it will be a thread about TOAST)
10:47 PM · May 18, 2022
Read the full conversation on Twitter
359 Reply Copy link
Read 4 replies
25. Dates
Date date
4 bytes
Internally stores number of days since
year 4713 BC up to infinity.
The Julianday number is inelapsed days since noon
(GreenwichMeanTime) onJanuary 1, 4713 BCE(in
the Juliancalendar).
The day count is virtually the astronomical Julian
day number.
Internally stores number of days since
year 4713 BC up to year 5874897 AD.
Inthe JulianDate system, eachday has a sequential
number, starting from JD0 (whichis sometimes
called the JulianDate). JD0 corresponds to 1
January 4713 BC inthe Juliancalendar.
See the docs for Date class. See B.7. Julian Dates in PostgreSQL docs.
26. Time and timezones
Time
AS::TimeWithZone
Two UNIX timestamps inside and tzdata also
timestamp
timestamptz
8 bytes, microsecond precision
Ruby on Rails uses UTC timezone internally. Use timestamp with time zone whenever possible!
Time.now # => 2022-10-22 13:42:42 +0900
Time.current # => Sat, 22 Oct 2022 04:42:42 UTC +00:
Time.current.time_zone
# => #<ActiveSupport::TimeZone name="UTC", @tzinfo=
Time.use_zone("Asia/Tokyo") { Time.current }
# => Sat, 22 Oct 2020 13:42:42 JST +09:00
CREATE TABLE tests (t1 timestamp, t2 timestamptz);
SET SESSION timezone TO 'Etc/UTC';
INSERT INTO tests (t1, t2) VALUES (now(), now());
SET SESSION timezone TO 'Asia/Tokyo';
INSERT INTO tests (t1, t2) VALUES (now(), now());
SET SESSION timezone TO 'Europe/Lisbon';
INSERT INTO tests (t1, t2) VALUES (now(), now());
SET SESSION timezone TO 'Asia/Tokyo';
SELECT * FROM tests;
t1 | t2
---------------------+-------------------------
2022-10-22 04:42:42 │ 2022-10-02 13:42:42+09 │
2022-10-22 13:42:42 │ 2022-10-02 13:42:42+09 │
2022-10-22 05:42:42 │ 2022-10-02 13:42:42+09 │
` `
27. How to not mess up with timezones
1. Use timezone-aware methods
Use Time.current and Date.current instead of Time.now and Date.today
2. Convert timestamps to user time zone
3. Don’t use dates in SQL, use timestamps
More tips here: thoughtbot.com/blog/its-about-time-zones
` ` ` ` ` ` ` `
Time.use_zone(user.timezone) do
# Do SQL queries, render views, …
end
# or
Time.current.in_time_zone(user.timezone)
- Posts.where(published_at: Date.today...Date.tomorrow)
+ Posts.where(published_at: Time.current.beginning_of_day..Time.current.end_of_day)
28. Time zones are hard
見る
The Problem with Time & Timezones - Computerphile
The Problem with Time & Timezones - Computerphile
共有
共有
29. Void and uncertainity
NilClass NULL
nil == nil
# => true ¯_(ツ)_/¯
SELECT NULL = NULL; -- NULL 🚨
SELECT NULL IS NULL; -- true
SELECT NULL IS DISTINCT FROM NULL; -- false
SELECT 'Ruby' = NULL; -- NULL 🚨
SELECT 'Ruby' IS NULL; -- false
SELECT 'Ruby' IS DISTINCT FROM NULL; -- true
31. JSON
Hash,Array json,jsonb
Variable length, up to 1GB
Be careful with symbols as keys
Define as_json method on your classes
to serialize them to JSON automatically.
Behavior of JSON.dump and to_json in
Rails is different!
JSON saves value as is (it is just a string)
JSONB is effective but strict: no
duplicate keys, doesn’t preserve
whitespaces, etc…
Inside: string (no null-bytes!), numeric, …
{ "foo" => "bar", foo: "baz" }.to_json
# {"foo":"baz"}
` `
` ` ` `
SELECT '{"foo": "bar","foo":"baz"}'::json;
-- {"foo": "bar","foo":"baz"}
SELECT '{"foo": "bar","foo":"baz"}'::jsonb;
-- {"foo": "baz"}
32. JSON on steroids
Use store_model gem to make powerful value objects from JSON fields.
But don’t overuse!
There is performance penalty for serialization and deserialization.
store_model gem repo
33. Ranges
Range intrange,tsrange, …
intmultirange, …
Additional methods in the facets gem. https://www.postgresql.org/docs/14/rangetypes.html
5..7 or 5...8
Time.current..1.day.from_now
# endless or beginless ranges
Time.current..
..Date.yesterday
nil.. or Range.new(nil, nil)
# Beginning is always included if possible :-(
Test.pluck("intrange(1, 5, '()')").first # 2...5
Test.pluck("tstzrange(now(), now() + '1 hour', '()
# ArgumentError: The Ruby Range object does not
# support excluding the beginning of a Range.
SELECT int8range(5, 7, '[]'); -- [5,8]
SELECT int8range(5, 8); -- [5,8)
SELECT tstzrange(now(), now() + '1 day', '()');
-- ["2022-10-22 14:42:42+09","2022-10-23 14:42:42+09
-- endless or beginless ranges
SELECT tstzrange(now(), NULL);
SELECT tstzrange(NULL, NULL);
-- PG 14: Multiranges and operators
SELECT nummultirange(numrange(1, 20))
- nummultirange(numrange(4, 6));
-- {[1,4),[6,20)}
-- and many more… (exclusion constraints!)
34. UUID
String
36 bytes
uuid
16 bytes
See Rails docs for Digest::UUID See docs for pgcrypto and uuid-ossp extensions.
Also take a look at upcoming UUIDv6, v7, and v8!
datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04
# All-random UUIDv4
SecureRandom.uuid
# => “40f15398-4b38-4e16-8b3c-ff16fc960d38”
# Determined UUIDv5 (hash-based)
Digest::UUID.uuid_v5(Digest::UUID::DNS_NAMESPACE, "n
# => "9b8edca0-90f2-5031-8e5d-3f708834696c"
CREATE EXTENSION "pgcrypto";
SELECT gen_random_uuid();
-- 2cfff962-4a24-4ef3-b2f8-35351b18bf63
CREATE EXTENSION "uuid-ossp";
SELECT uuid_generate_v5(uuid_ns_dns(), 'name');
-- 9b8edca0-90f2-5031-8e5d-3f708834696c
35. IP addresses
IPAddr inet,cidr
7 or 19 bytes both
inet works with both host and network addresses.
cidr works with network addresses only.
See IPAddr docs. See Network address types and functions and operators.
ip6 = IPAddr.new "3ffe:505:2::1"
ip4 = IPAddr.new "192.168.2.0/24"
IPAddr.new("192.168.2.0/24").mask(16)
#<IPAddr: IPv4:192.168.0.0/255.255.0.0>
SELECT '::1'::inet;
SELECT '127.0.0.1/32'::inet;
SELECT set_masklen(cidr '192.168.1.0/24', 16);
-- 192.168.0.0/16
SELECT inet_merge(inet '192.168.1.5/24', inet '192.
-- 192.168.0.0/22
` `
` `
36. Durations
ActiveSupport::Duration interval
16 bytes
Disclaimer: I added it to Rails in pull request № 16919. Supported out-of-the-box in Ruby on Rails 6.1+
Time.current + 1.year
# => Thu, 18 Jun 2021 21:00:00 MSK +03:00
100500.weeks.iso8601
# => "P100500W"
1.month.to_i
# => 2629746 (30.436875 days in seconds)
SELECT now() + ‘1 year’;
-- 2021-06-18 21:00:00+03
SELECT '100500 weeks'::interval;
-- 703500 days
SELECT EXTRACT(epoch FROM '1 month'::interval);
-- 2592000 (30.0 days in seconds)
37. Enums
String Custom enum types
4 bytes
Values are human-readable in SQL
On Rails < 7 you can use activerecord-postgres_enum gem See 8.7 Enumerated Types page in PostgreSQL docs
# In migration (Rails 7+):
create_enum :status, ["draft", "published", "archive
change_table :posts do |t|
t.enum :status, enum_type: "status", default: "dra
end
# In the application code:
class Article < ApplicationRecord
enum :status, { draft: "draft", published: "publis
end
Article.last.status #=> "draft"
Article.last.draft? #=> true
Article.last.published!
# UPDATE articles SET status = 'published' WHERE id
CREATE TYPE status AS ENUM ('draft', 'published', '
ALTER TABLE posts ADD COLUMN "status" status NOT NU
INSERT INTO posts (status) VALUES ('published');
INSERT INTO posts (status) VALUES ('draft');
SELECT id, status FROM posts;
id | status
----+------------
2 | draft
1 | published
39. Example of composite type use case
What if we want to:
1. Store products with prices in different currencies in one table
2. Work with price and currency as a whole
There is a great money gem in Ruby, but how to do it in SQL?
3. And do some calculations without having to write complex SQL queries with joins.
Before: After:
User (string currency)
has many
Product (numeric price)
User (string currency) # only as a setting!
has many
Product (true_money price (string+numeric))
40. Create custom datatype
Declare composite datatype in the database:
CREATE TYPE _true_money AS (
currency varchar,
amount numeric
);
-- type with constraints to allow:
-- - either NULL value (no price, can be forbidden by NOT NULL)
-- - or value with both currency and amount specified
CREATE DOMAIN true_money AS _true_money CHECK (
value IS NULL AND
value IS DISTINCT FROM (null, null)::_true_money OR
((value).currency IS NOT NULL AND (value).amount IS NOT NULL)
);
41. Fun fact about composite datatypes
Every table defines own datatype which can be used elsewhere
But don’t use it in reality, please!
(There are limitations)
CREATE TABLE "inner" ( v1 integer, v2 text );
CREATE TABLE "outer" (v inner);
INSERT INTO "outer" (v) VALUES ((42,'Hello world!'));
SELECT * FROM "outer";
v
-------------------
(42,"Hello world!")
42. Use composite datatype
See 8.16. Composite Types in PostgreSQL docs for more advices and caveats.
ALTER TABLE tests ADD COLUMN price true_money;
INSERT INTO tests (price) VALUES (('JPY',10000.0));
INSERT INTO tests (price) VALUES ('("JPY",100.0)');
SELECT price FROM tests; -- (JPY,10000.0),(JPY,100.0)
SELECT (price).currency, (price).amount FROM tests;
currency | amount
----------+---------
JPY | 10000.0
JPY | 100.0
43. Declare it in ActiveRecord
module ActiveRecord
module ConnectionAdapters
module PostgreSQL
module OID
class TrueMoney < Type::Value
def type
:true_money
end
# Here will be (de)serialization code
end
end
end
end
end
44. Deserialization
And "(USD,4.2)" becomes #<Money fractional:420 currency:USD> in Ruby ✨
def deserialize(value)
return nil if value.nil?
currency, amount = value.match(/A("?(w+)"?,(d+(?:.d+)?))z/).captures
::Money.from_amount(BigDecimal(amount), currency)
end
` ` ` `
45. Casting user input
Add ability to assign ready object to attribute:
def cast(value)
return nil if value.nil?
case value
when ::Money then value
when String then deserialize(value)
else
raise NotImplementedError, "Don't know how to cast #{value.class} #{value.inspect} into Money"
end
end
46. Deserialization and input casting at once
Replaces both deserialize and cast , also handles nil s.
def cast_value(value)
case value
when ::Money then value
when String
currency, amount = value.match(/A("?(w+)"?,(d+(?:.d+)?))z/).captures
::Money.from_amount(BigDecimal(amount), currency)
else
raise NotImplementedError, "Don't know how to cast #{value.class} #{value.inspect} into Money"
end
end
end
` ` ` ` ` `
47. Serialization for the database
Reuse available serialization methods for subtypes.
def serialize(value)
return nil if value.nil? # ActiveRecord will handle NULL for us
amount_t = ::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Decimal.new
currency_t = ::ActiveModel::Type::String.new
"(#{currency_t.serialize(value.currency.iso_code).inspect},#{amount_t.serialize(value.amount)})"
end
48. Register datatype in ActiveRecord
PostgreSQLAdapterWithTrueMoney = Module.new do
def initialize_type_map(m = type_map)
m.register_type "true_money" do |*_args, _sql_type|
::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::TrueMoney.new
end
m.alias_type "_true_money", "true_money"
super
end
end
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(PostgreSQLAdapterWithTrueMoney)
ActiveRecord::Type.register(
:true_money,
::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::TrueMoney,
adapter: :postgresql,
)
49. Also add it for migrations…
module SchemaStatementsWithTrueMoney
def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **)
case type.to_s
when 'true_money' then 'true_money'
else super
end
end
end
ActiveRecord::ConnectionAdapters::PostgreSQL::SchemaStatements.prepend(SchemaStatementsWithTrueMoney)
module ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnMethods
def true_money(name, options = {})
column(name, :true_money, options)
end
end
50. Ready to use!
rails g model Product title price:true_money
rails db:migrate
rails console
Product.create!(title: "Something", price: Money.from_amount(100000, “USD”))
Product.last
# => #<Product id: 1, title: "Something", price: 100000.00 USD>
51. But it is not done yet!
A lot of stuff has to be done to make a
full-featured datatype in SQL…
But then you can do a lot in SQL:
After all, one might re-invent abandoned pg-currency
CREATE FUNCTION true_money_add(a true_money, b true_
BEGIN
IF (a).currency != (b).currency THEN
RAISE EXCEPTION '% can not be added to % - cur
END IF;
RETURN ((a).currency, (a).amount + (b).amount);
END;
$$ IMMUTABLE RETURNS NULL ON NULL INPUT LANGUAGE plp
CREATE OPERATOR +(leftarg=true_money, rightarg=true
CREATE FUNCTION true_money_sum(state true_money, va
BEGIN
IF value IS NULL AND state IS NULL THEN
RETURN NULL;
END IF;
IF state IS NULL THEN
RETURN value;
END IF;
RETURN state + value;
END;
$$ IMMUTABLE LANGUAGE plpgsql;
CREATE AGGREGATE sum (true_money) (sfunc = true_mon
SELECT (price).currency AS currency, sum(price) AS total
FROM products GROUP BY currency;
52. Play with it yourself!
https://gist.github.com/Envek/780b917e72a86c123776ee763b8dd986
54. Gems for datatypes
torque-postgresql — standard datatypes not (yet) supported by Rails.
activerecord-postgis-adapter — all the power of PostGIS extension in Ruby.
activerecord-postgres_enum — support enum in migrations and schema (before
Rails 7)
55. Gems for other PostgreSQL features
Because PostgreSQL is much more than datatypes.
ActiveRecordExtended — functions for datatypes and DSL for queries
fx — make schema.rb great again with triggers
scenic — add support for views
order_query — keyset-pagination for your models
postgresql_cursor — get more data from the database efficiently
And also martian pg_trunk gem to rule them all get fx , scenic , object
dependency management and more within a single gem!
` ` ` `
structure.sql no more!
Make schema.rb great again!
`
`
`
`
pg_trunk gem